Three Blocks

Storm sphere / source

Open preview
webgpu_simulation_water_surface/source.jsPlain text ↗
import * as THREE from 'three/webgpu';
import { registerDevtools } from 'three-blocks/devtools';
import WebGPU from 'three/addons/capabilities/WebGPU.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { createExampleGui } from '../helpers/exampleGui.js';
import { isMobileViewport } from '../helpers/mobile.js';
import { shaderCache } from 'three-blocks/shaders';
import { ao } from 'three/addons/tsl/display/GTAONode.js';
import {
	Fn,
	If,
	Loop,
	clamp,
	mx_noise_float,
	instancedArray,
	color,
	float,
	hash,
	instanceIndex,
	int,
	ivec3,
	luminance,
	min,
	mix,
	mrt,
	normalView,
	output,
	pass,
	positionWorld,
	rtt,
	smoothstep,
	texture,
	texture3D,
	textureStore,
	uniform,
	uv,
	vec2,
	vec3,
	vec4,
} from 'three/tsl';
import { bloom } from 'three/addons/tsl/display/BloomNode.js';
import {
	ComputeSphereRasterizer,
	WaterSurfaceRenderer,
	WaterVolume,
	createWaterComposite,
} from 'three-blocks/water';

import { createPlanetPointerInteraction } from './planet-interaction.js';

// A million-particle MLS-MPM ocean wrapped around a sphere — a water planet,
// after WaterBall (github.com/matsuoka-601/WaterBall). There is no tank: the
// domain box is inert scaffolding, and the fluid is shaped entirely by two
// solver hooks. Gravity points at the sphere's centre instead of down, and a
// solid core repels anything that sinks into it, so a million particles settle
// into a ~1.9 m ocean over a 7.4 m rock and every direction is "down".
//
// Nearest-surface depth comes from ComputeSphereRasterizer: the same tiled
// compute rasterizer the software-compute ocean draws its particles with, read
// here as a depth source instead of a colour pass. That replaces a hardware
// sphere splat over every particle (the usual screen-space-fluid first pass)
// with one binning + raster compute batch. Thickness comes from the solver's
// own height field, so no per-particle pass runs at all. A world-space-sigma
// narrow-range filter (Truong & Yuksel, I3D 2018) then smooths the depth
// without eroding silhouettes, and the composite shades the sheet with
// refraction, reflections, absorption and a sun shadow marched through the
// density grid — the Splash (github.com/matsuoka-601/Splash) particle-mode
// technique.
const params = new URLSearchParams( window.location.search );
const numberParam = ( name, fallback ) => {

	const value = Number( params.get( name ) );
	return params.has( name ) && Number.isFinite( value ) ? value : fallback;

};
const colorParam = ( name, fallback ) => {

	const value = Number.parseInt( String( params.get( name ) ?? '' ).replace( /^#/, '' ), 16 );
	return Number.isFinite( value ) ? value : fallback;

};
const MPM_PARTICLE_STRIDE_BYTES = 80;
const PARTICLE_COUNTS = {
	'500K': 524_288,
	'1M': 1_048_576,
};
const requestedParticleCount = Number( params.get( 'particles' ) );
let particleCapacity = Object.values( PARTICLE_COUNTS ).includes( requestedParticleCount )
	? requestedParticleCount
	: PARTICLE_COUNTS[ '500K' ];
// A cube grid and a cube domain, so normalized volume space is isotropic and
// the sphere constraint is a plain `length( position - 0.5 )` with no
// per-axis correction anywhere in the hooks.
// A cube grid wastes the ~48% of its volume that lies outside the inscribed
// sphere, so its resolution is expensive here: every clear, update and mirror
// pass pays for cells no water can ever reach. 96 cubed is 884k cells against
// 128 cubed's 2.1M for the same planet.
const GRID_SIZE = new THREE.Vector3( 96, 96, 96 );
const FIXED_TIME_STEP = 1 / 120;
const DOMAIN_SIZE = new THREE.Vector3( 20, 20, 20 );
const BOUNDARY_MARGIN = 2;
// Radii as a fraction of the domain edge. The ocean surface sits at 0.46 and
// the box wall at 0.484, so the box clamp only ever catches escapees; the
// containment sphere just inside it keeps even those on a round silhouette.
const OCEAN_RADIUS = numberParam( 'radius', 0.46 );
const CONTAINMENT_RADIUS = 0.478;
// No rock inside: the particles fill the sphere solid, so rest density is not a
// dial but a consequence — the whole ball's worth of cells shared between the
// whole particle count.
const SPHERE_CELL_COUNT = ( 4 / 3 ) * Math.PI *
	( OCEAN_RADIUS * GRID_SIZE.x ) ** 3;
const TARGET_CELL_DENSITY = numberParam( 'density', particleCapacity / SPHERE_CELL_COUNT );
const OCEAN_WORLD_RADIUS = OCEAN_RADIUS * DOMAIN_SIZE.x;
// Floor well clear of the ball, close enough that its refraction still lands
// inside the frame.
const FLOOR_Y = - OCEAN_WORLD_RADIUS * 1.55;
const WORLD_SCALE = DOMAIN_SIZE.x / 44;
const INTERACTION_RADIUS_WORLD = 1.6;
const INTERACTION_IMPULSE = 600;
// Late-afternoon sun (~33° elevation): long glitter paths, leaning density
// shadows, and a warm key against the cool water without going full sunset.
const SUN_DIRECTION = new THREE.Vector3( - 10, 7.2, 5 ).normalize();
const SUN_AZIMUTH_XZ = new THREE.Vector2( SUN_DIRECTION.x, SUN_DIRECTION.z ).normalize();
// One golden-hour palette drives the authored equirect sky, the analytic
// water reflection, and the fog so every reflective term tells the same story.
const OCEAN_SKY = {
	zenith: 0x1e5fb2,
	upper: 0x4189d6,
	low: 0xa3cce8,
	horizonCool: 0xe6efef,
	horizonWarm: 0xffd9a0,
	sunGlow: 0xffaf62,
	sunCore: 0xfff1cf,
	seaFar: 0x2e6473,
	seaDeep: 0x0d3037,
	haze: 0xcfdcdd,
};

const MPM_FORMULATION = params.get( 'formulation' ) === 'reference' ? 'reference' : 'fused';
const MPM_SORTING = params.get( 'sorting' ) === '1'
	? {
		blockSize: Math.max( 1, Number( params.get( 'blockSize' ) ) || 4 ),
		interval: Math.max( 1, Number( params.get( 'sortInterval' ) ) || 1 ),
	}
	: null;
const MPM_P2G_MODE = [ 'atomic', 'subgroup', 'auto' ].includes( params.get( 'p2gMode' ) )
	? params.get( 'p2gMode' )
	: 'atomic';

const DENSITY_PREDICTION = params.get( 'predict' ) !== '0';
const WATER_DEBUG = params.get( 'waterdebug' );
const TEMPORAL_ENABLED = params.get( 'temporal' ) !== '0';
const TUNING = {
	stiffness: numberParam( 'stiffness', 6000 ),
	restDensity: params.has( 'restdensity' ) ? numberParam( 'restdensity', 2 ) : undefined,
	viscosity: numberParam( 'viscosity', 1 ),
	substeps: Math.max( 1, Math.round( numberParam( 'substeps', 2 ) ) ),
	velocityDamping: numberParam( 'damping', 0.9995 ),
	floorFriction: numberParam( 'friction', 0.96 ),
	// World metres per second squared, pulling toward the planet centre. The
	// hooks convert it to grid cells, which is what the solver integrates in.
	// Earth-ish would let a storm this strong throw water clean off the planet;
	// a heavier world keeps the sea on its surface and makes waves break
	// instead of launch.
	gravity: numberParam( 'gravity', 14 ),
	maxVelocity: numberParam( 'maxvel', 48 ),
	// Eastward drive, in grid cells per second squared. A planet-wide current
	// that never switches off, so the ocean keeps circulating instead of
	// settling into a still skin.
	current: numberParam( 'current', 0 ),
	// Tangential wind, in grid cells per second squared. This is the storm.
	wind: numberParam( 'wind', 45 ),
	// Radial noise forcing: the swell generator. It pumps water up and down
	// against gravity, which is what actually makes waves rather than drift.
	swell: numberParam( 'swell', 15 ),
	// Finer cells move less water in bulk for the same violence, so the sea
	// stays whole while still breaking.
	noiseScale: numberParam( 'noisescale', 6.5 ),
	noiseDrift: numberParam( 'noisedrift', 0.2 ),
};
const MPM_DIAGNOSTICS = params.get( 'diag' ) === '1' ? { overflowAudit: true } : null;
const REDUCED_MOTION = window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;

// Splat radius, and so the finest feature the surface can hold: the cube root
// of the volume each particle owns inside the ball, a little over spacing so
// the sheet closes without swelling crests.
const particleSpacingFor = count =>
	Math.cbrt( ( ( 4 / 3 ) * Math.PI * OCEAN_WORLD_RADIUS ** 3 ) / count );
const splatRadiusForCount = count => numberParam( 'splat', 1.15 ) * particleSpacingFor( count );
// World metres, so it reads against the 9.2 m ocean: at 1M particles the
// solver's own spacing inside the ball is about 0.148 m, which makes these
// spheres roughly a third of a spacing wide — dots with sky between them
// rather than a closed skin.
const DEFAULT_MONOCHROME_PARTICLE_RADIUS = 0.045;
// Monochrome shading. The grey view lights the rasterizer's own nearest-hit
// normals rather than reading luminance back out of the lit scene, so these
// numbers are its whole tone curve, and the camera pose is what sets them: it
// stands about 34 degrees off the sun, so the lit hemisphere and the visible
// one nearly coincide and every term has to fight for the little contrast that
// leaves. The wrap is small and the ambient smaller, or the disc clips to a
// flat white before the shadow or the flow tint can register; the gain leaves
// headroom under the ACES shoulder. Flow speed is the grid velocity at which
// the direction tint reaches full strength; it doubles as the guard that keeps
// still water neutral, where a normalized velocity is pure noise. The probe
// steps a little inside the shell, past the empty rim where the grid update
// wrote zeroes and neither the density gradient nor the velocity is defined.
const MONOCHROME_LIGHT_WRAP = numberParam( 'monowrap', 0.1 );
const MONOCHROME_AMBIENT = numberParam( 'monoambient', 0.05 );
const MONOCHROME_GAIN = numberParam( 'monogain', 0.75 );
const MONOCHROME_FLOW_SPEED = numberParam( 'monoflow', 24 );
const MONOCHROME_FLOW_PROBE = ( DOMAIN_SIZE.x / GRID_SIZE.x ) * 1.5;
// How much of the per-sphere normal survives into the shading normal. The
// nearest-hit normal is the normal of one particle, not of the sea: every dot
// on the disc spans the same hemisphere of directions, so lighting it alone
// produces uniform stipple and no ball at all — which is what made both this
// view and the luminance-of-the-scene version it replaced read as a flat white
// coin. The swell comes from the density gradient instead, and this is the
// fraction of grain mixed back over it.
const MONOCHROME_STIPPLE = numberParam( 'monostipple', 0.35 );
// Darkest the diffuse term may go. Nothing in this view is a light source, so
// an unlit face is not black, it is water lit by everything else.
const MONOCHROME_DIFFUSE_FLOOR = numberParam( 'monofloor', 0.3 );
// And the darkest the finished tone may go, whatever the dials are set to. The
// diffuse floor stops flat unlit patches; this one stops the *product* — a
// crest that is shadowed, occluded and running away from the sun at once, with
// every slider at maximum — from bottoming out at black.
const MONOCHROME_TONE_FLOOR = numberParam( 'monotonefloor', 0.12 );
// Radial bias folded into that gradient before it is normalized: it costs the
// crests nothing, and it keeps the normal defined in the calm cells where the
// gradient collapses to zero.
const MONOCHROME_BODY_BIAS = numberParam( 'monobodybias', 0.35 );
const MONOCHROME_GRADIENT_STEP = numberParam( 'monogradstep', 3 ) / GRID_SIZE.x;
// Truong & Yuksel size the Gaussian in WORLD units, projected into texels per
// pixel. It defaults to 1.35x the splat radius, which ties smoothing to splat
// size: shrink the radius for a thin sheet and crisp silhouettes and the kernel
// shrinks with it, so per-splat lumps survive into the normal field and the sun
// lobe shatters them into specular shards. Sigma is set here in absolute world
// metres instead — several particle spacings wide regardless of radius.
const SURFACE_WORLD_SIGMA = numberParam( 'ssfsigma', 0.26 );
// Full-resolution depth, against the usual screen-space-fluid instinct. The
// block's default half-res depth has to be joint-bilateral upsampled, and that
// upsample terraces the sheet into piecewise-flat facets whose creases the sun
// lobe shatters into horizontal shards. It is also not a saving here: a million
// analytic sphere splats are primitive-bound, not raster-area-bound, so halving
// the target barely moves the splat pass while its upsample costs a full extra
// pass. Measured 8.6 ms vs 16.6 ms per frame at 1600x900 — cleaner AND faster.
const SURFACE_RESOLUTION_SCALE = Math.min( 1, Math.max( 0.25, numberParam( 'ssfres', 1 ) ) );
const SURFACE_FILTER_ITERATIONS = Math.max( 0, Math.round( numberParam( 'ssfiterations', 2 ) ) );
const SURFACE_FILTER_RADIUS = Math.max( 1, Math.round( numberParam( 'ssfradius', 10 ) ) );
// The edge-preserving filter leaves sub-kernel splat texture as piecewise-flat
// plateaus, and at grazing incidence their creases read as horizontal shards
// across the far half of the sheet. A wider range-limited Gaussian rounds them
// while real silhouettes, which sit beyond the narrow range by definition, stay
// sharp.
const SURFACE_DEPTH_SMOOTHING = Math.max( 0, Math.round( numberParam( 'ssfsmooth', 4 ) ) );
// Density-grid sun shadow: a fixed march from the reconstructed surface toward
// the sun through the solver's mass grid. Steps are world metres; the grid is
// 0.34 × 0.125 × 0.34 m per cell, so 0.3 m steps cross a cell per sample.
const SHADOW_ENABLED = params.get( 'shadow' ) !== '0';
const SHADOW_STEPS = Math.max( 4, Math.round( numberParam( 'shadowsteps', 32 ) ) );
const SHADOW_STEP_WORLD = numberParam( 'shadowstep', DOMAIN_SIZE.x / GRID_SIZE.x );
// Quarter-res threshold bloom over the HDR composite. Threshold 1 keeps it a
// light-source effect (sun disc, glints, hottest caustics), not a glow filter.
const BLOOM_ENABLED = params.get( 'bloom' ) !== '0';
const BLOOM_STRENGTH = numberParam( 'bloomstrength', 0.55 );
const BLOOM_RADIUS = numberParam( 'bloomradius', 0.25 );
const BLOOM_THRESHOLD = numberParam( 'bloomthreshold', 0.85 );
// Adaptive quality: the drawing buffer is capped at a pixel budget (every
// pass after the half-res depth splat runs at drawing-buffer resolution, so
// pixels are the strongest cost lever), and a frame-time governor walks the
// budget ladder until the machine holds a smooth rate.
const AUTO_QUALITY_ENABLED = params.get( 'autoquality' ) !== '0';
const MAX_RENDER_PIXEL_RATIO = 1;
const MAX_PIXELS_OVERRIDE = params.has( 'maxpixels' )
	? Math.max( 4e5, numberParam( 'maxpixels', 3.6e6 ) )
	: null;
const AUTO_QUALITY_LADDER = Object.freeze( [ 3.6e6, 2.6e6, 1.8e6, 1.3e6, 1.0e6 ] );
const AUTO_QUALITY_WINDOW = 32;
const AUTO_QUALITY_WARMUP_FRAMES = 150;
const AUTO_QUALITY_STEP_DOWN_MS = numberParam( 'autobudget', 22 );
const AUTO_QUALITY_STEP_UP_MS = Math.min( 12, AUTO_QUALITY_STEP_DOWN_MS * 0.5 );
const AUTO_QUALITY_CALM_WINDOWS = 5;

let container;
let renderer;
let devtools;
let scene;
let camera;
let controls;
let gui;
let water;
let solver;
let rasterizer;
let particleSurfaceBuffer;
let splatRadiusNode;
let particleRadiusRefresh;
// Closed over by the solver hooks, which are compiled once: anything tunable at
// runtime has to reach them through a uniform, not a JavaScript value.
const gravityGridNode = uniform( 0 ).setName( 'planet_gravityGrid' );
const currentNode = uniform( TUNING.current ).setName( 'planet_current' );
const windNode = uniform( TUNING.wind ).setName( 'planet_wind' );
const floorShadowNode = uniform( numberParam( 'floorshadow', 0.075 ) ).setName( 'planet_floorShadow' );
const flowContrastNode = uniform( numberParam( 'monoflowcontrast', 1 ) ).setName( 'planet_flowContrast' );
const swellNode = uniform( TUNING.swell ).setName( 'planet_swell' );
const noiseScaleNode = uniform( TUNING.noiseScale ).setName( 'planet_noiseScale' );
// Advanced on the CPU rather than read from the solver clock, so the pattern
// keeps drifting at the same rate whatever the substep schedule does.
const noisePhaseNode = uniform( 0 ).setName( 'planet_noisePhase' );
// Gathered density above which a particle counts as buried. Expressed against
// rest density, so it tracks the fluid rather than a hand-set absolute.
// Off by default: gathered density fluctuates enough between neighbouring
// particles that thresholding it culls visible ones too, tearing holes in the
// surface. Kept as a knob because the idea is sound where density is smoother.
const SURFACE_CULL_RATIO = numberParam( 'surfacecull', 0 );
const surfaceCullNode = uniform(
	SURFACE_CULL_RATIO > 0 ? TARGET_CELL_DENSITY * SURFACE_CULL_RATIO : Number.MAX_VALUE
).setName( 'planet_surfaceCull' );
// Far outside any sane view frustum: the rasterizer's projection pass drops it
// on the screen-overlap test before it can queue a tile entry.
const PARKED_POSITION = 1e7;
const floorLevelSeed = ( BOUNDARY_MARGIN + 1 ) / GRID_SIZE.y;
let surfaceRenderer;
let surfaceComposite;
let foamMesh;
let densityTexture;
let densityCopy;
let renderPipeline;
let scenePass;
let sceneColorNode;
let sceneDepthNode;
let gtaoPass;
let monochromeParticleNode;
let oceanEnvironment;
let oceanFog;
let stageFloor;
let stageMaterial;
let debugFloorNode;
let sunShadow = null;
let shadowStrengthNode;
let shadowBiasNode;
let resizeObserver;
let pointerHandlers;
let bloomNode;
let compositeColorNode;
let autoQualityTier = 0;
let autoQualityFramesSeen = 0;
let autoQualityCalmWindows = 0;
let renderPixelBudget = AUTO_QUALITY_LADDER[ 0 ];
const autoQualityDeltas = [];
let elapsed = 0;
let previousFrame = performance.now();
let fixedFrameTimeStep = null;
let simulatedFrames = 0;
let disposed = false;

const surfaceShaderResources = {
	get water() { return water; },
	get solver() { return solver; },
	get rasterizer() { return rasterizer; },
	get rasterizerInternals() { return rasterizerShaderResources(); },
	get particleSurfaceBuffer() { return particleSurfaceBuffer; },
	get splatRadiusNode() { return splatRadiusNode; },
	get surfaceCullNode() { return surfaceCullNode; },
	get surfaceRenderer() { return surfaceRenderer; },
	get surfaceComposite() { return surfaceComposite; },
	get particleRadiusRefresh() { return particleRadiusRefresh; },
	get densityCopy() { return densityCopy; },
	get scenePass() { return scenePass; },
	get gtaoPass() { return gtaoPass; },
	get renderPipeline() { return renderPipeline; },
};

function prefixSumShaderResources( prefixSum ) {

	if ( ! prefixSum ) return null;
	return {
		dataBuffer: prefixSum.dataBuffer,
		countUniform: prefixSum.countUniform,
		localStorage: prefixSum.localStorage,
		blockSumsBuffer: prefixSum.blockSumsBuffer,
		blockPrefixSum: prefixSumShaderResources( prefixSum.blockPrefixSum ),
		localScanFn: prefixSum.localScanFn,
		addBlockSumsFn: prefixSum.addBlockSumsFn,
		computeBatch: prefixSum.computeBatch,
	};

}

function rasterizerShaderResources() {

	if ( ! rasterizer ) return null;
	return {
		particles: rasterizer.particles,
		colors: rasterizer.colors,
		uniforms: rasterizer.uniforms,
		tileCounts: rasterizer._tileCounts,
		tileOffsets: rasterizer._tileOffsets,
		tileCursors: rasterizer._tileCursors,
		tileEntries: rasterizer._tileEntries,
		counters: rasterizer._counters,
		largeIds: rasterizer._largeIds,
		projected: rasterizer._projected,
		idBuffer: rasterizer._idBuffer,
		depthBuffer: rasterizer._depthBuffer,
		largeDispatch: rasterizer._largeDispatch,
		prefixSum: prefixSumShaderResources( rasterizer._prefixSum ),
		clear: rasterizer._clear,
		project: rasterizer._project,
		prepareLargeDispatch: rasterizer._prepareLargeDispatch,
		largeCount: rasterizer._largeCount,
		copyCounts: rasterizer._copyCounts,
		copyCursors: rasterizer._copyCursors,
		scatter: rasterizer._scatter,
		largeScatter: rasterizer._largeScatter,
		raster: rasterizer._raster,
	};

}

const defaultUi = {
	particleCount: particleCapacity,
	simulate: ! REDUCED_MOTION,
	monochromeParticles: params.get( 'monochrome' ) !== '0',
	debugFloor: params.get( 'stage' ) !== 'natural',
	gravity: TUNING.gravity,
	wind: TUNING.wind,
	swell: TUNING.swell,
	whitewater: params.get( 'foam' ) !== '0',
	foamDisplayDensity: Math.min( 1, Math.max( 0, numberParam( 'foamdensity', 0.45 ) ) ),
	particleRadius: DEFAULT_MONOCHROME_PARTICLE_RADIUS,
	splatRadius: splatRadiusForCount( particleCapacity ),
	shadowStrength: SHADOW_ENABLED ? Math.max( 0, numberParam( 'shadowstrength', 1.65 ) ) : 0,
	bodyShadow: Math.min( 1, Math.max( 0, numberParam( 'bodyshadow', 1 ) ) ),
	flowContrast: flowContrastNode.value,
	autoQuality: AUTO_QUALITY_ENABLED,
	autoRotate: ! REDUCED_MOTION,
};

const ui = { ...defaultUi };
let diagnosticsOptions = {};
let controlsExpanded = true;

function configureInitialState( initialState ) {

	Object.assign( ui, defaultUi );
	for ( const [ key, value ] of Object.entries( initialState ) ) {

		if ( value !== undefined && Object.hasOwn( ui, key ) ) ui[ key ] = value;

	}
	ui.particleCount = Math.min( particleCapacity, Math.max( 1, Math.round( Number( ui.particleCount ) ) ) );
	ui.debugFloor = ui.debugFloor === true;
	ui.gravity = Math.max( 0, Number( ui.gravity ) );
	ui.wind = Math.max( 0, Number( ui.wind ) );
	ui.swell = Math.max( 0, Number( ui.swell ) );
	ui.foamDisplayDensity = Math.min( 1, Math.max( 0, Number( ui.foamDisplayDensity ) ) );
	ui.particleRadius = Math.min( 0.2, Math.max( 0.02, Number( ui.particleRadius ) ) );
	ui.simulate = ui.simulate === true;
	ui.monochromeParticles = ui.monochromeParticles === true;
	ui.whitewater = ui.whitewater !== false;
	ui.autoQuality = ui.autoQuality === true;
	ui.autoRotate = ui.autoRotate === true && ! REDUCED_MOTION;
	ui.flowContrast = Math.min( 1, Math.max( 0, Number( ui.flowContrast ) ) );
	flowContrastNode.value = ui.flowContrast;

}

export async function mount( containerElement, {
	initialState = {},
	diagnostics = {},
	controlsExpanded: expandControls = true,
	fixedFrameTimeStep: requestedFrameTimeStep = null,
} = {} ) {

	container = containerElement;
	disposed = false;
	previousFrame = performance.now();
	fixedFrameTimeStep = Number.isFinite( requestedFrameTimeStep ) && requestedFrameTimeStep > 0
		? Math.min( 0.05, requestedFrameTimeStep )
		: null;
	diagnosticsOptions = { ...diagnostics };
	controlsExpanded = expandControls !== false;
	configureInitialState( initialState );
	if ( WebGPU.isAvailable() === false ) {

		container.appendChild( WebGPU.getErrorMessage() );
		throw new Error( 'No WebGPU support' );

	}
	await init();
	return createSurfaceHandle();

}

async function init() {

	const mobile = isMobileViewport();
	container.style.position = 'relative';
	container.style.overflow = 'hidden';
	container.style.touchAction = 'none';

	scene = new THREE.Scene();
	// Fades the calibration floor's far edge into the sky instead of ending it
	// on a hard line. The water composite is a fullscreen pass and never sees
	// fog, so this only ever touches the stage.
	oceanFog = new THREE.Fog(
		OCEAN_SKY.haze,
		OCEAN_WORLD_RADIUS * 4,
		OCEAN_WORLD_RADIUS * 19
	);
	scene.fog = oceanFog;

	camera = new THREE.PerspectiveCamera( 40, 1, 0.1, 200 );
	// On the SUN's side, about 45 degrees off it. The old pose sat behind the
	// ball, which put every lit thing — the glinting crests, the bright shallows,
	// the shadow on the floor — on the far side of the sphere from the viewer.
	const distance = OCEAN_WORLD_RADIUS * 4.6;
	// High enough that the checker, not the sky, is what sits behind the ball.
	// Refraction here is screen-space: it can only bend what is already drawn
	// behind the water, so from a low angle the lens has nothing to show but
	// empty sky and the ball flattens into one turquoise tone. Looking down at
	// it puts the floor across the whole backdrop, and the checker comes
	// through the water inverted and colour-graded, which is the entire point
	// of standing a lens on a calibration target.
	camera.position.set( - distance * 0.3, distance * 0.62, distance * 0.72 );

	// Prune tiers the device cannot bind before the renderer is constructed.
	const adapter = await navigator.gpu.requestAdapter( { featureLevel: 'compatibility' } );
	if ( ! adapter ) throw new Error( 'No WebGPU adapter available' );
	const maxParticleBytes = Math.min(
		adapter.limits.maxStorageBufferBindingSize,
		adapter.limits.maxBufferSize
	);
	for ( const [ label, count ] of Object.entries( PARTICLE_COUNTS ) ) {

		if ( count * MPM_PARTICLE_STRIDE_BYTES > maxParticleBytes ) delete PARTICLE_COUNTS[ label ];

	}
	particleCapacity = Math.min( particleCapacity, Math.max( ...Object.values( PARTICLE_COUNTS ) ) );
	ui.particleCount = Math.min( ui.particleCount, particleCapacity );

	renderer = new THREE.WebGPURenderer( {
		antialias: true,
		trackTimestamp: diagnosticsOptions.timestamps === true,
		requiredLimits: {
			maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
			maxBufferSize: adapter.limits.maxBufferSize,
		},
	} );
	devtools = registerDevtools( { renderer, container } );
	renderer.setPixelRatio( Math.min( window.devicePixelRatio, MAX_RENDER_PIXEL_RATIO ) );
	renderer.toneMapping = THREE.ACESFilmicToneMapping;
	renderer.toneMappingExposure = 0.96;
	container.appendChild( renderer.domElement );
	await renderer.init();
	// The first seed dispatch happens inside createSimulation(). Publish a stable,
	// getter-backed owner before that provider lookup so hydration can resolve the
	// same resources after initialization.
	shaderCache.container( 'surface/simulation-and-rendering', surfaceShaderResources );

	controls = new OrbitControls( camera, renderer.domElement );
	controls.enabled = ! mobile;
	// Framed a little low so the ball's shadow on the floor stays in shot.
	controls.target.set( 0, - OCEAN_WORLD_RADIUS * 0.12, 0 );
	controls.enableDamping = true;
	controls.dampingFactor = 0.055;
	controls.autoRotate = ui.autoRotate;
	controls.autoRotateSpeed = 0.22;
	controls.minDistance = OCEAN_WORLD_RADIUS * 1.35;
	controls.maxDistance = OCEAN_WORLD_RADIUS * 9;
	// Every latitude is worth looking at on a planet, so no polar limit.
	controls.update();
	camera.updateMatrixWorld();

	createLighting();
	await createSimulation();
	createDensityGrid();
	sunShadow = SHADOW_ENABLED ? createSunShadowSampler() : null;
	createStage();
	setGravity( ui.gravity );
	createRasterizer();
	// Size the renderer, then the rasterizer, before anything bakes
	// surfaceNodes() into a graph. The rasterizer sizes its per-pixel id and
	// depth buffers to the tile grid, and it is still holding the placeholder
	// pair it guessed at construction: the first real drawing buffer grows the
	// grid and replaces them. A graph built on the discarded pair keeps reading
	// a buffer that only ever held the cleared miss sentinel, so every pixel
	// reports "no sphere here" for the life of the page — silently, since a
	// full-screen miss shades exactly like a scene with nothing in it.
	resize();
	rasterizer.resize( renderer );
	createSurfaceWater();
	createRenderPipeline();
	pointerHandlers = createPlanetPointerInteraction( {
		renderer,
		camera,
		domainSize: DOMAIN_SIZE,
		oceanRadius: OCEAN_WORLD_RADIUS,
		interactionPosition: water.uniforms.pointerPosition,
		interactionStrength: water.uniforms.pointerStrength,
	} );
	createGUI();

	resizeObserver = new ResizeObserver( resize );
	resizeObserver.observe( container );
	resize();

	// Initialize the foam buffers before the first visible frame.
	if ( ui.simulate ) stepSimulation( FIXED_TIME_STEP, 0 );
	renderer.setAnimationLoop( animate );
	window.addEventListener( 'pagehide', dispose, { once: true } );

}

function createLighting() {

	const sun = new THREE.DirectionalLight( 0xffd9a8, 3 );
	sun.position.copy( SUN_DIRECTION ).multiplyScalar( 22 );
	scene.add( sun );
	// The rock has no ground bounce out here, so the hemisphere light is the
	// only thing keeping its night side from going flat black.
	scene.add( new THREE.HemisphereLight( 0xcfe6f5, 0x6f7f92, 1.7 ) );
	oceanEnvironment = createOceanEnvironment();
	scene.environment = oceanEnvironment;
	applyStageBackdrop();

}

function applyStageBackdrop() {

	scene.background = ui.monochromeParticles ? new THREE.Color( 0x000000 ) : oceanEnvironment;
	scene.fog = ui.monochromeParticles ? null : oceanFog;
	if ( stageFloor ) stageFloor.visible = ! ui.monochromeParticles;

}

// A small authored equirectangular sky gives grazing Fresnel something
// structured to reflect. The sky is synthesized directly into a FLOAT
// equirect: an 8-bit source quantizes the slow vertical ramp into one-code
// plateaus that a near-flat grazing reflection sweeps into contour rings.
function createOceanEnvironment() {

	const width = 1024;
	const height = 512;
	const data = new Float32Array( width * height * 4 );
	const random = seed => {

		const value = Math.sin( seed * 91.731 ) * 43758.5453;
		return value - Math.floor( value );

	};
	// three's equirect convention: u = atan2(z, x)/2π + 0.5 and
	// v = asin(y)/π + 0.5, with data row 0 read at v = 0 — so the nadir lives
	// in row 0 and the zenith in the last row.
	const rowForY = y => ( Math.asin( Math.min( 1, Math.max( - 1, y ) ) ) / Math.PI + 0.5 ) * ( height - 1 );
	const sunAzimuth = Math.atan2( SUN_DIRECTION.z, SUN_DIRECTION.x );
	const sunColumn = ( sunAzimuth / ( Math.PI * 2 ) + 0.5 ) * width;
	const sunRow = rowForY( SUN_DIRECTION.y );
	const skyKeys = [
		[ - 1, new THREE.Color( OCEAN_SKY.seaDeep ) ],
		[ - 0.08, new THREE.Color( OCEAN_SKY.seaFar ) ],
		[ 0, new THREE.Color( OCEAN_SKY.horizonCool ) ],
		[ 0.16, new THREE.Color( OCEAN_SKY.low ) ],
		[ 0.52, new THREE.Color( OCEAN_SKY.upper ) ],
		[ 1, new THREE.Color( OCEAN_SKY.zenith ) ],
	];
	const warmColor = new THREE.Color( OCEAN_SKY.horizonWarm );
	const glowColor = new THREE.Color( OCEAN_SKY.sunGlow );
	const rampColor = new THREE.Color();
	const warmTarget = new THREE.Color();
	const pixelColor = new THREE.Color();
	for ( let row = 0; row < height; row ++ ) {

		const y = Math.sin( Math.PI * ( row / ( height - 1 ) - 0.5 ) );
		let segment = 0;
		while ( segment < skyKeys.length - 2 && skyKeys[ segment + 1 ][ 0 ] < y ) segment ++;
		const [ from, fromColor ] = skyKeys[ segment ];
		const [ to, toColor ] = skyKeys[ segment + 1 ];
		const eased = 0.5 - 0.5 * Math.cos( Math.PI * Math.min( 1, Math.max( 0, ( y - from ) / ( to - from ) ) ) );
		rampColor.copy( fromColor ).lerp( toColor, eased );
		// Golden haze hugs the horizon around the sun azimuth and spills a
		// little below it, where the far sea would catch the same light.
		const altitudeEnvelope = y >= 0 ? Math.exp( - y * 7.5 ) : Math.exp( y * 16 );
		for ( let column = 0; column < width; column ++ ) {

			const azimuth = ( column / width - 0.5 ) * Math.PI * 2;
			const warmth = Math.pow( Math.max( 0, Math.cos( azimuth - sunAzimuth ) ), 5 ) * altitudeEnvelope;
			warmTarget.copy( warmColor ).lerp( glowColor, Math.min( 1, warmth * 0.75 ) );
			pixelColor.copy( rampColor ).lerp( warmTarget, Math.min( 1, warmth * 0.85 ) );
			const offset = ( row * width + column ) * 4;
			data[ offset ] = pixelColor.r;
			data[ offset + 1 ] = pixelColor.g;
			data[ offset + 2 ] = pixelColor.b;
			data[ offset + 3 ] = 1;

		}

	}

	// Screen-blend a Gaussian layer over the ramp inside its ±3σ footprint.
	const screenBlend = ( centerX, centerY, radiusX, radiusY, rotation, alpha, tint ) => {

		const cos = Math.cos( rotation );
		const sin = Math.sin( rotation );
		const extentX = Math.ceil( Math.hypot( radiusX * cos, radiusY * sin ) * 3 );
		const extentY = Math.ceil( Math.hypot( radiusX * sin, radiusY * cos ) * 3 );
		const minY = Math.max( 0, Math.floor( centerY - extentY ) );
		const maxY = Math.min( height - 1, Math.ceil( centerY + extentY ) );
		const minX = Math.floor( centerX - extentX );
		const maxX = Math.ceil( centerX + extentX );
		for ( let row = minY; row <= maxY; row ++ ) {

			for ( let column = minX; column <= maxX; column ++ ) {

				const wrapped = ( ( column % width ) + width ) % width;
				const deltaX = column - centerX;
				const deltaY = row - centerY;
				const localX = ( deltaX * cos + deltaY * sin ) / radiusX;
				const localY = ( deltaY * cos - deltaX * sin ) / radiusY;
				const coverage = alpha * Math.exp( - 0.5 * ( localX * localX + localY * localY ) );
				if ( coverage < 1e-4 ) continue;
				const offset = ( row * width + wrapped ) * 4;
				data[ offset ] += ( 1 - data[ offset ] ) * tint.r * coverage;
				data[ offset + 1 ] += ( 1 - data[ offset + 1 ] ) * tint.g * coverage;
				data[ offset + 2 ] += ( 1 - data[ offset + 2 ] ) * tint.b * coverage;

			}

		}

	};

	// Additive Gaussian deposit for the sun: the disc must exceed 1.0 in the
	// float texture so tone mapping and the bloom threshold treat it as a real
	// light source rather than a white decal.
	const addBlend = ( centerX, centerY, radiusX, radiusY, energy, tint ) => {

		const extentX = Math.ceil( radiusX * 3 );
		const extentY = Math.ceil( radiusY * 3 );
		const minY = Math.max( 0, Math.floor( centerY - extentY ) );
		const maxY = Math.min( height - 1, Math.ceil( centerY + extentY ) );
		for ( let row = minY; row <= maxY; row ++ ) {

			for ( let column = Math.floor( centerX - extentX ); column <= Math.ceil( centerX + extentX ); column ++ ) {

				const wrapped = ( ( column % width ) + width ) % width;
				const localX = ( column - centerX ) / radiusX;
				const localY = ( row - centerY ) / radiusY;
				const deposit = energy * Math.exp( - 0.5 * ( localX * localX + localY * localY ) );
				if ( deposit < 1e-4 ) continue;
				const offset = ( row * width + wrapped ) * 4;
				data[ offset ] += tint.r * deposit;
				data[ offset + 1 ] += tint.g * deposit;
				data[ offset + 2 ] += tint.b * deposit;

			}

		}

	};

	const sunCore = new THREE.Color( OCEAN_SKY.sunCore );
	const sunHalo = new THREE.Color( OCEAN_SKY.sunGlow );
	addBlend( sunColumn, sunRow, 6, 6, 3.4, sunCore );
	addBlend( sunColumn, sunRow, 22, 15, 0.5, sunHalo );
	addBlend( sunColumn, sunRow, 72, 26, 0.14, sunHalo );

	// Deterministic cloud wisps: anisotropic Gaussians riding just above the
	// horizon, catching gold near the sun azimuth and staying cool opposite.
	const wispTint = new THREE.Color( 0xe9edec );
	const warmWisp = new THREE.Color( 0xffdcb0 );
	const tintColor = new THREE.Color();
	for ( let cloud = 0; cloud < 24; cloud ++ ) {

		const x = random( cloud * 7 + 1 ) * width;
		const y = rowForY( 0.05 + random( cloud * 7 + 2 ) * 0.4 );
		const wispWidth = 46 + random( cloud * 7 + 3 ) * 118;
		const wispHeight = 3 + random( cloud * 7 + 4 ) * 9;
		const rotation = ( random( cloud * 7 + 5 ) - 0.5 ) * 0.3;
		const alpha = 0.02 + random( cloud * 7 + 6 ) * 0.05;
		const azimuth = ( x / width - 0.5 ) * Math.PI * 2;
		const sunward = Math.pow( Math.max( 0, Math.cos( azimuth - sunAzimuth ) ), 3 );
		tintColor.copy( wispTint ).lerp( warmWisp, sunward * 0.7 );
		for ( let lobe = 0; lobe < 3; lobe ++ ) {

			screenBlend(
				x + ( lobe - 1 ) * wispWidth * 0.28,
				y + ( random( cloud * 19 + lobe ) - 0.5 ) * wispHeight * 1.5,
				wispWidth * ( 0.3 + lobe * 0.08 ) * 0.65,
				wispHeight * ( 0.65 + random( cloud * 23 + lobe ) * 0.55 ) * 0.65,
				rotation,
				alpha,
				tintColor
			);

		}

	}

	// Half float: universally filterable on WebGPU (float32 filtering is an
	// optional feature) and still ~8× the effective ramp resolution of 8-bit.
	const halfData = new Uint16Array( data.length );
	for ( let index = 0; index < data.length; index ++ ) halfData[ index ] = THREE.DataUtils.toHalfFloat( data[ index ] );

	const environment = new THREE.DataTexture( halfData, width, height, THREE.RGBAFormat, THREE.HalfFloatType );
	environment.name = 'OceanEnvironment';
	environment.mapping = THREE.EquirectangularReflectionMapping;
	environment.colorSpace = THREE.LinearSRGBColorSpace;
	environment.minFilter = THREE.LinearFilter;
	environment.magFilter = THREE.LinearFilter;
	environment.generateMipmaps = false;
	environment.needsUpdate = true;
	return environment;

}

// Continuous analytic reflection used by the water composite. The scene keeps
// the authored float equirect for ordinary materials, but the reconstructed
// sheet benefits from evaluating the simple reference sky directly: no PMREM
// atlas seams or narrow texel ramps can turn small depth ripples into
// horizontal contour bars.
function sampleOceanReflection( direction, roughness ) {

	const altitude = direction.y;
	const azimuthAlignment = direction.xz.dot( vec2( SUN_AZIMUTH_XZ.x, SUN_AZIMUTH_XZ.y ) )
		.div( direction.xz.length().max( 1e-4 ) )
		.max( 0 );
	const warmFalloff = mix( float( 16 ), float( 7.5 ), smoothstep( - 0.05, 0.05, altitude ) );
	const warmth = azimuthAlignment.pow( 5 ).mul( altitude.abs().mul( warmFalloff ).negate().exp() );
	const horizonBase = mix(
		vec3( color( OCEAN_SKY.horizonCool ) ),
		mix( vec3( color( OCEAN_SKY.horizonWarm ) ), vec3( color( OCEAN_SKY.sunGlow ) ), warmth.mul( 0.75 ).min( 1 ) ),
		warmth.mul( 0.85 ).min( 1 )
	);
	const skyLow = mix( horizonBase, vec3( color( OCEAN_SKY.upper ) ), smoothstep( 0.02, 0.5, altitude ) );
	const sky = mix( skyLow, vec3( color( OCEAN_SKY.zenith ) ), smoothstep( 0.42, 0.92, altitude ) );
	// Steep splash normals reflect the lower hemisphere: distant lit sea near
	// the horizon falling toward deep teal, never ink black.
	const sea = mix(
		vec3( color( OCEAN_SKY.seaFar ) ),
		vec3( color( OCEAN_SKY.seaDeep ) ),
		smoothstep( 0.02, 0.5, altitude.negate() )
	);
	const base = mix( sea, sky, smoothstep( - 0.14, 0.12, altitude ) );
	const softened = mix(
		base,
		mix( vec3( color( OCEAN_SKY.horizonCool ) ), vec3( color( OCEAN_SKY.upper ) ), 0.5 ),
		roughness.mul( 0.38 )
	);
	const sunCosine = direction.dot( vec3( SUN_DIRECTION ) ).max( 0 );
	const discPower = mix( float( 1400 ), float( 96 ), roughness );
	const disc = sunCosine.pow( discPower ).mul( mix( float( 3 ), float( 0.6 ), roughness ) );
	const halo = sunCosine.pow( 12 ).mul( 0.42 );
	return softened
		.add( vec3( color( OCEAN_SKY.sunCore ) ).mul( disc ) )
		.add( vec3( color( OCEAN_SKY.sunGlow ) ).mul( halo ) );

}

function smoothValueNoise( coordinate ) {

	const cell = coordinate.floor();
	const fraction = coordinate.fract();
	const curve = fraction.mul( fraction ).mul( fraction.mul( - 2 ).add( 3 ) );
	const sample = point => hash( point.x.add( point.y.mul( 57.137 ) ) );
	return mix(
		mix( sample( cell ), sample( cell.add( vec2( 1, 0 ) ) ), curve.x ),
		mix( sample( cell.add( vec2( 0, 1 ) ) ), sample( cell.add( vec2( 1 ) ) ), curve.x ),
		curve.y
	);

}

// The rock the ocean lies on. It is a real mesh in the scene pass, so the water
// composite refracts and absorbs it exactly like the seabed it replaces — the
// planet reads as deep because you are looking through kilometres of water at
// something solid, not at a tinted void.
// The calibration stage from the raymarched ocean, brought over unchanged in
// spirit: four coloured quadrants on a two-metre checker, or a weathered seabed
// when the checker is switched off. The ball is a lens, and a lens is only
// legible over something with structure — this is what its refraction bends.
//
// The floor also takes the water's shadow from the same density grid the
// surface shading marches, so the shadow is the real one: soft, wavy, and
// brighter where the ball is thin, rather than a disc pasted under a sphere.
function createStage() {

	// Tiles sized against the ball so the checker stays readable next to it at
	// any planet scale.
	const tileScale = 1 / ( OCEAN_WORLD_RADIUS * 0.22 );
	const tileX = positionWorld.x.mul( tileScale ).floor();
	const tileZ = positionWorld.z.mul( tileScale ).floor();
	const checker = tileX.add( tileZ ).mod( 2 ).abs();
	const blue = vec3( color( 0x287db8 ) );
	const purple = vec3( color( 0xa663d0 ) );
	const green = vec3( color( 0x34a96b ) );
	const yellow = vec3( color( 0xd3ad4b ) );
	const negativeX = positionWorld.x.lessThan( 0 );
	const quadrant = positionWorld.z.lessThan( 0 ).select(
		negativeX.select( blue, purple ),
		negativeX.select( green, yellow )
	);
	const tileVariation = hash( tileX.mul( 0.1031 ).add( tileZ.mul( 0.11369 ) ) ).sub( 0.5 );
	const checkerColor = mix( quadrant.mul( 0.56 ), quadrant.mul( 0.9 ), checker )
		.mul( tileVariation.mul( 0.08 ).add( 1 ) );

	const seabedPosition = positionWorld.xz;
	const broadNoise = smoothValueNoise( seabedPosition.mul( 0.075 ) );
	const mediumNoise = smoothValueNoise( seabedPosition.mul( 0.31 ).add( vec2( 13.1, 7.7 ) ) );
	const fineNoise = smoothValueNoise( seabedPosition.mul( 1.15 ).add( vec2( 3.4, 19.2 ) ) );
	const stone = vec3( color( 0x315755 ) );
	const sand = vec3( color( 0x9f9573 ) );
	const naturalSeabed = mix( stone, sand, smoothstep( 0.22, 0.78, broadNoise ) )
		.mul( mediumNoise.mul( 0.2 ).add( 0.85 ) )
		.add( vec3( color( 0xb8ae8c ) ).mul( fineNoise.mul( 0.05 ) ) );

	debugFloorNode = uniform( ui.debugFloor ? 1 : 0 ).setName( 'surface_debugFloor' );
	const albedo = mix( naturalSeabed, checkerColor, debugFloorNode );

	// Walk from the floor toward the sun through the water's own density grid.
	// Wrapped in Fn: the sampler branches, and TSL control flow needs an active
	// stack — called straight from builder code the If is orphaned and the node
	// graph comes back null.
	const shadow = SHADOW_ENABLED
		? Fn( () => createBallShadowSampler()( positionWorld ) )()
		: float( 1 );
	// Water tints what it shades rather than merely darkening it, so the
	// umbra keeps the ball's own colour instead of going grey.
	const shaded = albedo.mul( mix( vec3( 0.3, 0.55, 0.72 ), vec3( 1 ), shadow.saturate() ) );

	stageMaterial = new THREE.MeshBasicNodeMaterial();
	stageMaterial.colorNode = shaded;
	stageFloor = new THREE.Mesh(
		// Wide enough that its far edge never shows: a visible edge reads as a
		// false horizon with the sky's open sea sitting behind it.
		new THREE.PlaneGeometry( OCEAN_WORLD_RADIUS * 60, OCEAN_WORLD_RADIUS * 60, 1, 1 ),
		stageMaterial
	);
	stageFloor.name = 'SurfaceCalibrationStage';
	stageFloor.rotation.x = - Math.PI / 2;
	stageFloor.position.y = FLOOR_Y;
	scene.add( stageFloor );

}

// Radial gravity plus a solid core, applied to the grid before the solver's own
// box walls run. This is the whole planet: every cell is pulled toward the
// centre, and any cell that has sunk into the rock has its inward motion removed
// and is pushed back out. Normalized domain space is a cube, so `0.5` is the
// planet centre and radii are plain lengths.
function planetGridForce( { position, velocity, dt } ) {

	const toCentre = vec3( 0.5 ).sub( position );
	const distance = toCentre.length().max( 1e-5 ).toVar( 'planetGridDistance' );
	const inward = toCentre.div( distance ).toVar( 'planetGridInward' );

	velocity.addAssign( inward.mul( gravityGridNode ).mul( dt ) );

	// Weather. A single eastward current just spins the whole ocean into one
	// slow spiral; a planet has wind cells pushing every which way, and it is
	// their collision that raises a real sea. Three noise fields give a wind
	// VECTOR rather than a wind speed, projected onto the tangent plane so it
	// blows along the surface, and a second, finer field pumps radially — that
	// radial pump is what actually makes waves, since it works against gravity
	// instead of merely sliding water sideways.
	const outward = inward.negate();
	const stormCoord = position.mul( noiseScaleNode )
		.add( vec3( noisePhaseNode.mul( 0.6 ), noisePhaseNode, noisePhaseNode.mul( - 0.4 ) ) )
		.toVar( 'planetStormCoord' );
	const wind = vec3(
		mx_noise_float( stormCoord ),
		mx_noise_float( stormCoord.add( vec3( 17.3, 5.1, 9.7 ) ) ),
		mx_noise_float( stormCoord.add( vec3( - 4.2, 11.9, 23.4 ) ) )
	).toVar( 'planetWind' );
	const tangentialWind = wind.sub( outward.mul( wind.dot( outward ) ) );
	velocity.addAssign( tangentialWind.mul( windNode ).mul( dt ) );

	// Optional coherent drift on top, off by default — a whole-planet current
	// reads as one spiral rather than as weather.
	const spin = vec3( 0, 1, 0 );
	const eastward = spin.cross( outward );
	velocity.addAssign(
		eastward.div( eastward.length().max( 1e-4 ) ).mul( currentNode ).mul( dt )
	);

	const swellNoise = mx_noise_float( stormCoord.mul( 2.3 ).add( vec3( 3.7, - 8.1, 5.4 ) ) );
	velocity.addAssign( outward.mul( swellNoise.mul( swellNode ) ).mul( dt ) );

	// Containment shell just inside the box. Without it, spray that outruns
	// gravity meets the flat box clamp and the planet grows square shoulders.
	If( distance.greaterThan( CONTAINMENT_RADIUS ), () => {

		velocity.subAssign( inward.mul( velocity.dot( inward ).min( 0 ) ) );

	} );

}

// Remap the cube seed lattice onto the ocean shell. The lattice is already a
// stratified [0,1]^3 sample, so treating its three axes as (cos latitude,
// longitude, radial fraction) lands a uniform shell rather than the clumping a
// hashed sample would give. The radial coordinate goes through a cube root
// because shell volume grows with r^3 — sampling r linearly would crowd the
// sea floor and starve the surface.
function seedOntoShell( { position } ) {

	const seedMargin = ( BOUNDARY_MARGIN + 1 ) / GRID_SIZE.x;
	const span = 1 - 2 * seedMargin;
	const u = position.x.sub( seedMargin ).div( span ).saturate();
	const w = position.z.sub( seedMargin ).div( span ).saturate();
	const t = position.y.sub( floorLevelSeed ).div( 0.9 ).saturate();

	const cosLatitude = u.mul( 2 ).sub( 1 ).toVar( 'seedCosLatitude' );
	const sinLatitude = cosLatitude.mul( cosLatitude ).oneMinus().max( 0 ).sqrt();
	const longitude = w.mul( Math.PI * 2 );
	const direction = vec3(
		sinLatitude.mul( longitude.cos() ),
		cosLatitude,
		sinLatitude.mul( longitude.sin() )
	);
	// Cube root because volume grows as r^3: sampling the radius linearly would
	// crowd the centre and starve the surface.
	const radius = t.mul( OCEAN_RADIUS ** 3 ).pow( 1 / 3 );
	// Seed the sea already running. A perfectly smooth shell released from rest
	// spends its first seconds as a glass marble, which is both the least
	// interesting thing this scene ever looks like and exactly the frame the
	// gallery captures. Warping the shell radially starts it mid-swell.
	const seedSwell = mx_noise_float( direction.mul( 5.5 ) ).mul( 0.04 ).add( 1 );
	return {
		position: vec3( 0.5 ).add( direction.mul( radius.mul( seedSwell ) ) ),
		velocity: vec3( 0 ),
	};

}

async function createSimulation() {

	// World-space sphere centres for the compute rasterizer, written by the
	// solver's own particle pass so no CPU readback or second traversal exists.
	particleSurfaceBuffer = instancedArray( particleCapacity, 'vec4' ).setName( 'surface_spheres' );
	splatRadiusNode = uniform(
		ui.monochromeParticles ? ui.particleRadius : ui.splatRadius
	).setName( 'surface_splatRadius' );
	particleRadiusRefresh = Fn( () => {

		particleSurfaceBuffer.element( instanceIndex ).w.assign( splatRadiusNode );

	} )().compute( particleCapacity, [ 256 ] ).setName( 'surface_refreshParticleRadius' );

	// The planet sits at the origin, so the domain cube is centred there too.
	const domainMatrix = new THREE.Matrix4().makeScale( DOMAIN_SIZE.x, DOMAIN_SIZE.y, DOMAIN_SIZE.z );

	water = new WaterVolume( {
		capacity: particleCapacity,
		gridSize: GRID_SIZE,
		domainSize: DOMAIN_SIZE,
		// Seeding fills the cube lattice, then the modifier below remaps it onto
		// the shell, so the fill fraction only sizes the lattice, never the water.
		fillHeight: 0.9,
		preset: 'ocean-swell',
		// Down does not exist here: the built-in constant gravity is switched off
		// and the grid hook adds a radial one instead.
		gravity: 0,
		waves: null,
		material: {
			stiffness: TUNING.stiffness,
			viscosity: TUNING.viscosity,
			// Rest density is normally derived from a box fill, which would be
			// badly wrong for a shell — over-derive it and the ocean collapses
			// into the rock, under-derive it and it boils off. State the real
			// shell density instead: particles per grid cell.
			restDensity: TUNING.restDensity ?? TARGET_CELL_DENSITY,
		},
		boundary: {
			margin: BOUNDARY_MARGIN,
			floorFriction: TUNING.floorFriction,
			velocityDamping: TUNING.velocityDamping,
			// The absorbing rim is tank logic that fades motion near the XZ walls;
			// on a planet it would eat the swell wherever the ocean happens to
			// pass a box edge.
			mode: 'reflective',
		},
		seed: {
			// Both are height-field notions: a hydrostatic column profile and an
			// analytic swell, neither of which survives being wrapped on a sphere.
			profile: false,
			waves: false,
			modifier: seedOntoShell,
		},
		pointer: { radius: INTERACTION_RADIUS_WORLD, impulse: INTERACTION_IMPULSE },
		// A top-down height field cannot describe a ball: every column has two
		// surfaces and the corners have none. Nothing here needs it — thickness
		// is analytic and the foam deposits it feeds are off.
		surfaceField: false,
		gridForce: planetGridForce,
		foam: {
			capacity: 131072,
			// Radial gravity accelerates harder than a swell ever does, so the
			// tank's windows classified the entire ocean as breaking and wrapped
			// the planet in a foam belt. These keep spray to genuine churn.
			kineticEnergyWindow: [ 110, 320 ],
			shearWindow: [ 18, 48 ],
			crestWindow: [ 6, 16 ],
			spawnRate: 2,
			trappedAirStrength: 0.9,
			crestStrength: 1.2,
			lifetime: [ 0.7, 2 ],
			// Deposits land in XZ columns, which would pile the whole planet's
			// foam onto its north pole. Spray and bubbles are particles and work
			// in any geometry, so keep those and drop the stamping.
			foamDepositRate: 0,
		},
		onParticleUpdate: ( { index, position, density } ) => {

			// Surface-only rasterization. Only the outermost couple of particle
			// layers can ever be the nearest hit — everything under them is
			// occluded ocean — yet the rasterizer would still bin all million
			// and make every covered pixel walk them. The solver already knows
			// which particles are buried: gathered density rises with depth as
			// the column compresses, so anything above the threshold is interior
			// and gets parked outside the frustum, where the projection pass
			// rejects it before it ever reaches a tile. It still simulates; it
			// just stops being drawn.
			const world = water.uniforms.volumeToWorld.mul( vec4( position, 1 ) ).xyz;
			particleSurfaceBuffer.element( index ).assign( vec4(
				density.lessThan( surfaceCullNode ).select( world, vec3( PARKED_POSITION ) ),
				splatRadiusNode
			) );

		},
		solver: {
			formulation: MPM_FORMULATION,
			densityPrediction: DENSITY_PREDICTION,
			substeps: TUNING.substeps,
			maxVelocity: TUNING.maxVelocity,
			sorting: MPM_SORTING,
			// The density shadow reads the render mirror as plain vec4 cells.
			packedGridMirror: false,
			p2gMode: MPM_P2G_MODE,
			diagnostics: MPM_DIAGNOSTICS,
		},
	} );
	water.setDomainTransform( domainMatrix );
	solver = water.solver;
	water.particleCount = ui.particleCount;
	water.seed( renderer );
	const postPasses = typeof solver.postPasses === 'function'
		? [ 0, 1 ].flatMap( frame => solver.postPasses( {
			frame,
			dt: FIXED_TIME_STEP,
			substeps: TUNING.substeps,
		} ) ?? [] )
		: solver.postPasses ?? [];
	await renderer.compileComputeAsync( [ ...new Set( [ ...solver.passes, ...postPasses ] ) ] );

}

// The solver already mirrors its grid (velocity.xyz, mass) into a storage
// buffer for renderers. One copy per frame into a filterable rgba16float 3D
// texture turns that into a trilinear density field the sun-shadow march and
// the whitewater absorption can sample with a single fetch per step.
function createDensityGrid() {

	const { x, y, z } = GRID_SIZE;
	densityTexture = new THREE.Storage3DTexture( x, y, z );
	densityTexture.name = 'SurfaceDensityGrid';
	densityTexture.format = THREE.RGBAFormat;
	densityTexture.type = THREE.HalfFloatType;
	densityTexture.minFilter = THREE.LinearFilter;
	densityTexture.magFilter = THREE.LinearFilter;
	densityTexture.generateMipmaps = false;
	densityTexture.wrapS = THREE.ClampToEdgeWrapping;
	densityTexture.wrapT = THREE.ClampToEdgeWrapping;
	densityTexture.wrapR = THREE.ClampToEdgeWrapping;
	densityTexture.needsUpdate = true;

	const gridMirror = solver.gridMirrorBuffer;
	const yz = y * z;
	densityCopy = Fn( () => {

		const pointer = instanceIndex;
		const remainder = pointer.mod( yz );
		const coordinate = ivec3(
			int( pointer.div( yz ) ),
			int( remainder.div( z ) ),
			int( remainder.mod( z ) )
		);
		textureStore( densityTexture, coordinate, gridMirror.element( pointer ) );

	} )().compute( solver.gridCellCount, [ solver.workgroupSize ] ).setName( 'surface_copyDensityGrid' );

}

// Splash-style shadow: from the reconstructed surface, march toward the sun
// through the density grid and attenuate by the mass crossed. Crests in the
// lee of other crests lose their glitter and body light; thin crests stay
// bright. The bias skips the surface's own shell so flat water is unshadowed.
// The floor's shadow needs a march tens of metres long to reach the ball at
// all, which the surface's own short self-shadow walk cannot do. Rather than
// lengthen that everywhere, intersect the ball analytically first: most floor
// pixels miss it entirely and cost nothing, and the ones that hit march only
// the chord, so the sample budget lands exactly where the shadow is.
function createBallShadowSampler() {

	const gridNode = texture3D( densityTexture );
	const worldToVolume = water.uniforms.worldToVolume;
	const toSun = vec3( SUN_DIRECTION );
	const isoMass = float( TARGET_CELL_DENSITY * 0.5 );
	const steps = 20;

	return worldPosition => {

		const shadow = float( 1 ).toVar( 'ballShadow' );
		const b = worldPosition.dot( toSun );
		const discriminant = b.mul( b )
			.sub( worldPosition.dot( worldPosition ) )
			.add( OCEAN_WORLD_RADIUS ** 2 );
		If( discriminant.greaterThan( 0 ), () => {

			const root = discriminant.sqrt();
			const enter = b.negate().sub( root ).max( 0 );
			const exit = b.negate().add( root );
			If( exit.greaterThan( enter ), () => {

				const stride = exit.sub( enter ).div( steps );
				const opticalDepth = float( 0 ).toVar( 'ballShadowDepth' );
				Loop( steps, ( { i } ) => {

					const sampleWorld = worldPosition.add(
						toSun.mul( enter.add( stride.mul( float( i ).add( 0.5 ) ) ) )
					);
					const local = worldToVolume.mul( vec4( sampleWorld, 1 ) ).xyz;
					const mass = gridNode.sample( clamp( local, vec3( 0 ), vec3( 1 ) ) ).w;
					opticalDepth.addAssign( mass.div( isoMass.max( 1e-4 ) ).min( 2 ) );

				} );
				// A whole diameter of water would extinguish everything and stamp
				// a hard black disc on the floor. This is a shadow, not an
				// eclipse: the gradient across it is the readable part.
				shadow.assign(
					opticalDepth.mul( stride ).mul( floorShadowNode ).negate().exp()
				);

			} );

		} );
		return shadow;

	};

}

function createSunShadowSampler() {

	const gridNode = texture3D( densityTexture );
	const isoMass = float( TARGET_CELL_DENSITY * 0.5 );
	const worldToVolume = water.uniforms.worldToVolume;
	const sunStep = vec3( SUN_DIRECTION.clone().multiplyScalar( SHADOW_STEP_WORLD ) );
	const sun = vec3( SUN_DIRECTION );
	shadowStrengthNode = uniform( ui.shadowStrength ).setName( 'surface_shadowStrength' );
	shadowBiasNode = uniform( numberParam( 'shadowbias', 0.45 ) ).setName( 'surface_shadowBias' );

	return worldPosition => {

		const origin = worldPosition.add( sun.mul( shadowBiasNode ) ).toVar( 'surfaceShadowOrigin' );
		const opticalDepth = float( 0 ).toVar( 'surfaceShadowOpticalDepth' );
		Loop( SHADOW_STEPS, ( { i } ) => {

			const sampleWorld = origin.add( sunStep.mul( float( i ) ) );
			const local = worldToVolume.mul( vec4( sampleWorld, 1 ) ).xyz;
			// Margin cells are empty, so clamp-to-edge sampling outside the
			// domain contributes nothing without a bounds branch.
			const mass = gridNode.sample( clamp( local, vec3( 0 ), vec3( 1 ) ) ).w;
			opticalDepth.addAssign( mass.div( isoMass.max( 1e-4 ) ).min( 2 ) );

		} );
		return opticalDepth.mul( SHADOW_STEP_WORLD ).mul( shadowStrengthNode ).negate().exp();

	};

}

// Tiled compute rasterization of the particle spheres. This is the software
// rasterizer the compute ocean renders with, used here purely as a depth
// producer: the mesh stays out of the scene and only its binning + raster
// compute batch runs, leaving a per-pixel nearest hit that the surface
// reconstruction reads in one fullscreen pass.
function createRasterizer() {

	rasterizer = new ComputeSphereRasterizer( particleSurfaceBuffer, {
		count: particleCapacity,
		entryMultiplier: 5,
		// The slice walk is the only thing that stops each pixel reading every
		// sphere queued on its tile, and a planet stacks its whole ocean into a
		// narrow depth range: more slices across that range means the front-to-
		// back walk terminates far sooner.
		depthSlices: 64,
		lodPixelRadius: 0.72,
	} );
	rasterizer.particleCount = ui.particleCount;
	rasterizer.material.color.set( 0xffffff );
	rasterizer.material.roughness = 0.3;
	rasterizer.material.metalness = 0.78;
	rasterizer.material.clearcoat = 0.55;
	rasterizer.material.clearcoatRoughness = 0.12;
	rasterizer.material.envMapIntensity = 1.2;
	rasterizer.visible = ui.monochromeParticles;
	scene.add( rasterizer );

}

// Optical thickness with no per-particle pass and no height field: the exact
// distance the eye ray travels through the shell, solved analytically against
// two spheres. Entering at the reconstructed surface, the ray either strikes the
// rock — and stops there — or slips past its limb and runs on through water to
// the far side of the planet.
//
// That second case is the one worth being exact about. A ray grazing the core is
// crossing far more water than the depth beneath it suggests, and shading it by
// radial depth leaves it barely absorbed: the bright sky behind the planet comes
// straight through and paints a white belt around the rock's silhouette that
// reads, convincingly and wrongly, as surf. Two square roots buy the truth.
function surfaceThicknessNode() {

	const nodes = rasterizer.surfaceNodes();
	const cameraWorld = rasterizer.uniforms.cameraWorldMatrix;
	const entry = cameraWorld.mul( vec4( nodes.positionView, 1 ) ).xyz;
	const eyeWorld = cameraWorld.mul( vec4( 0, 0, 0, 1 ) ).xyz;
	const direction = entry.sub( eyeWorld ).normalize();

	// |entry + t*direction|^2 = radius^2  =>  t^2 + 2bt + (r2 - radius^2) = 0.
	const b = entry.dot( direction );
	const r2 = entry.dot( entry );
	const discriminant = b.mul( b ).sub( r2 ).add( OCEAN_WORLD_RADIUS ** 2 ).max( 0 );
	// Far root: with nothing solid inside, the ray runs from the near surface
	// clean through to the far one.
	const path = b.negate().add( discriminant.sqrt() );
	return nodes.valid.select( path.max( 0 ), float( 0 ) );

}

function createSurfaceWater() {

	surfaceRenderer = new WaterSurfaceRenderer( renderer, water, {
		worldRadius: ui.splatRadius,
		worldSigma: SURFACE_WORLD_SIGMA,
		resolutionScale: SURFACE_RESOLUTION_SCALE,
		// The rasterizer indexes its per-pixel buffers by drawing-buffer pixel,
		// so every pass that reads them runs at full resolution.
		thicknessScale: 1,
		whitewaterScale: 0.5,
		filterIterations: SURFACE_FILTER_ITERATIONS,
		filterRadius: SURFACE_FILTER_RADIUS,
		depthSmoothingRadius: SURFACE_DEPTH_SMOOTHING,
		temporalBlend: TEMPORAL_ENABLED ? numberParam( 'temporalblend', 0.82 ) : 0,
		depthSource: () => {

			const nodes = rasterizer.surfaceNodes();
			return nodes.valid.select( nodes.viewDistance, float( 0 ) );

		},
		thicknessSource: surfaceThicknessNode,
	} );

}

function setFoamDisplayDensity( value ) {

	ui.foamDisplayDensity = Math.min( 1, Math.max( 0, Number( value ) || 0 ) );
	for ( const entry of foamMesh?.userData.whitewaterDisplayFractions ?? [] ) {

		entry.uniform.value = Math.min( 1, ui.foamDisplayDensity * entry.scale );

	}

}

function createRenderPipeline() {

	scenePass = pass( scene, camera );
	scenePass.setMRT( mrt( { output, normal: normalView } ) );
	sceneColorNode = scenePass.getTextureNode( 'output' );
	sceneDepthNode = scenePass.getTextureNode( 'depth' );
	const sceneNormalNode = scenePass.getTextureNode( 'normal' );
	gtaoPass = ao( sceneDepthNode, sceneNormalNode, camera );
	gtaoPass.resolutionScale = 0.5;
	gtaoPass.radius.value = 0.26;
	gtaoPass.thickness.value = 0.45;
	gtaoPass.distanceExponent.value = 1.25;
	gtaoPass.distanceFallOff.value = 0.82;
	gtaoPass.samples.value = 12;

	surfaceComposite = createWaterComposite( surfaceRenderer, {
		sceneColorNode,
		sceneDepthNode,
		worldToVolume: water.uniforms.worldToVolume,
		envNode: params.get( 'env' ) === '0'
			? null
			: params.get( 'env' ) === 'white'
				? () => vec3( 1 )
				: sampleOceanReflection,
		physicalRefraction: true,
		dispersion: params.get( 'dispersion' ) === '0' ? 0 : numberParam( 'dispersion', 0.004 ),
		glitter: params.get( 'glitter' ) === '0' ? 0 : numberParam( 'glitter', 0.42 ),
		reducedMotion: REDUCED_MOTION,
		ssr: params.get( 'ssr' ) === '0'
			? false
			: {
				steps: Math.round( numberParam( 'ssrsteps', 12 ) ),
				refine: 4,
				maxDistance: numberParam( 'ssrdistance', 42 ),
				thickness: numberParam( 'ssrthickness', 0.45 ),
			},
		detailNormals: params.get( 'detailnormal' ) === '0'
			? null
			: { micro: numberParam( 'microdetail', 0.22 ) },
		// Off by default here. Contact foam is for water meeting scene geometry;
		// this basin's floor sits metres below the sheet, so the mask finds
		// nothing to grip and instead traces thin dark seams along crest lines.
		contactFoam: params.get( 'contactfoam' ) === '1' ? numberParam( 'contactwidth', 0.22 * WORLD_SCALE ) : 0,
		sunShadowNode: sunShadow,
		uniforms: {
			// With nothing inside to hide, the ball is a lens and has to stay
			// see-through: an eye ray now crosses a whole diameter of water, so
			// the coefficients that made a shallow shell opaque would make this
			// solid black. Red still dies first, which is what turns the checker
			// beneath into turquoise.
			absorption: new THREE.Vector3( 0.55, 0.2, 0.09 ),
			// A reconstructed sheet has no volumetric scatter integral behind it,
			// so this constant IS the body colour rather than a dark floor under
			// a marched one: it has to carry the lit-turquoise depth the
			// raymarched ocean derives from sun samples.
			scatterColor: new THREE.Color( colorParam( 'bodycolor', 0x1a7a86 ) ),
			scatterTint: new THREE.Color( 0x1fbfae ),
			scatterDepth: numberParam( 'scatterdepth', 1.6 ),
			scatterShadow: ui.bodyShadow,
			refractionStrength: numberParam( 'refract', 1 ),
			refractionBlur: numberParam( 'refractblur', 0.0018 ),
			// The height field reports thickness in real metres, where the splat
			// path it replaces accumulated a small per-particle chord — the gain
			// is a fraction, not a multiplier. Left at splat scale the whole body
			// pins to the optical cap and the water flattens into one tone.
			thicknessBoost: numberParam( 'thicknessboost', 0.35 ),
			thicknessMax: 4.5,
			// Floored at a wind-blown-ocean microfacet roughness: near-mirror
			// values turn bilinear texel kinks into nested contour rings.
			baseRoughness: numberParam( 'baseroughness', 0.11 ),
			thicknessRoughness: 0.08,
			environmentIntensity: numberParam( 'envintensity', 1 ),
			reflectionFloor: new THREE.Color( 0x175a72 ),
			sunPower: 420,
			sunStrength: numberParam( 'sunstrength', 2.4 ),
			sssStrength: numberParam( 'sss', 0.14 ),
			horizonColor: new THREE.Color( 0x4a90a8 ),
			zenithColor: new THREE.Color( 0x8fc9dd ),
			sunDirection: SUN_DIRECTION,
			sunColor: new THREE.Color( 0xffb763 ),
			foamColor: new THREE.Color( 0xf6f7f2 ),
			foamThreshold: numberParam( 'foamthreshold', 0.1 ),
			foamFeather: numberParam( 'foamfeather', 0.2 ),
			foamAlbedoMax: 0.65,
			foamNoiseScale: numberParam( 'foamscale', 58 ),
			foamNormalStrength: 0.08,
			foamEdgeCutoff: numberParam( 'foamedgecutoff', 0.06 ),
			whitewaterDensity: 1.1,
			whitewaterMaxBrightness: 0.86,
			whitewaterEdgeCutoff: numberParam( 'whitewateredgecutoff', 0.055 ),
			whitewaterEdgePower: numberParam( 'whitewateredgepower', 0.72 ),
			edgeFade: 0.4,
			domainFade: numberParam( 'domainfade', 0.02 ),
			domainNormalFade: numberParam( 'domainnormalfade', 0.09 ),
			// SSF synthesizes finite side walls from a clipped depth sheet;
			// suppress their reflection so the cutaway does not flash white.
			domainWallReflection: numberParam( 'domainwallreflection', 0.24 ),
			domainWallColor: new THREE.Color( 0x0d5f6b ),
			// Nearly full authored fill on the walls. The reconstructed sheet's
			// side faces get their depth from spheres seen edge-on and their
			// thickness from a height field that assumes a downward view, so
			// shading them from that data mottles the cutaway with blotches;
			// the authored wall colour is both cleaner and more honest.
			domainWallFill: numberParam( 'domainwallfill', 0.92 ),
		},
	} );

	const group = new THREE.Group();
	group.name = 'SurfaceWhitewater';
	const diffuse = water.createFoamMesh( {
		baseSize: 0.095,
		minPixelSize: 2,
		maxPixelSize: 28,
		displayFraction: ui.foamDisplayDensity,
		surface: surfaceRenderer,
		sceneDepthNode,
		sunDirection: SUN_DIRECTION,
		worldToVolume: water.uniforms.worldToVolume,
		volumeGrid: densityTexture,
		volumeAbsorption: numberParam( 'whitewaterabsorption', 0.65 ),
	} );
	// Only the free spray and bubbles: deposited surface foam is stamped into
	// XZ columns, which on a sphere would pile every latitude's foam onto the
	// north pole.
	group.add( diffuse );
	group.userData.whitewaterDisplayFractions = [
		{ uniform: diffuse.userData.whitewaterDisplayFraction, scale: 1 },
	];
	foamMesh = group;
	foamMesh.visible = ui.whitewater;
	surfaceRenderer.setWhitewaterMesh( foamMesh );

	renderPipeline = new THREE.RenderPipeline( renderer );
	updateRenderPipeline();

}

// The grey view, shaded from the rasterizer's own nearest-hit buffers rather
// than read back as luminance out of the lit scene. Two things made the old
// shortcut a flat white coin. The nearest-hit normal is one particle's normal,
// not the sea's: every dot on the disc spans the same hemisphere of directions,
// so no arrangement of lights can carve a swell out of it — the shape has to
// come from the density grid's own gradient. And the hemisphere fill plus the
// environment map swamped the sun on a clearcoated metal, then the tone curve
// clipped whatever was left, so both shadow dials modulated a value already
// pinned at white.
//
// The camera stands about 34 degrees off the sun, which is a hard light for
// showing form: the lit hemisphere and the visible one nearly coincide, so
// there is no terminator to cross the disc and self-shadowing only reaches the
// deeper troughs. What that pose does buy is that the two things the eye can
// still read — where the swell has folded the surface, and which way the water
// is running — are exactly the density shadow and the flow tint.
function createMonochromeParticleNode() {

	const nodes = rasterizer.surfaceNodes();
	const cameraWorld = rasterizer.uniforms.cameraWorldMatrix;
	const worldPosition = cameraWorld.mul( vec4( nodes.positionView, 1 ) ).xyz;
	const worldNormal = cameraWorld.mul( vec4( nodes.normalView, 0 ) ).xyz.normalize();
	const sun = vec3( SUN_DIRECTION );
	const wrap = float( MONOCHROME_LIGHT_WRAP );
	const gridNode = texture3D( densityTexture );
	const isoMassNode = float( TARGET_CELL_DENSITY * 0.5 );
	const ambientOcclusion = mix( float( 1 ), gtaoPass.getTextureNode().r, 0.7 );

	return vec4( vec3( Fn( () => {

		const tone = float( 0 ).toVar( 'monochromeShade' );
		// Off the silhouette there is no sphere to light, and the shadow march
		// would be walking an undefined position. Whitewater spray still lands
		// in the scene pass out there, so those pixels read it back instead.
		If( nodes.valid.not(), () => {

			tone.assign( luminance( sceneColorNode.rgb ).saturate() );

		} ).Else( () => {

			// One probe point, a little inside the shell, serves the swell
			// normal and the flow direction both. On the rim itself the grid
			// update wrote zeroes into empty cells, so neither the gradient nor
			// the velocity is defined there. Step in along the planet radius
			// rather than the hit normal: the hit normal belongs to one
			// particle and swings over a whole hemisphere between neighbouring
			// pixels, which would jitter the probe by its own full offset.
			const radial = worldPosition.normalize().toVar( 'monochromeRadial' );
			const probe = water.uniforms.worldToVolume.mul( vec4(
				worldPosition.sub( radial.mul( MONOCHROME_FLOW_PROBE ) ), 1
			) ).xyz;
			const probeUv = clamp( probe, vec3( 0 ), vec3( 1 ) ).toVar( 'monochromeProbe' );
			const massAt = offset => gridNode.sample(
				clamp( probeUv.add( offset ), vec3( 0 ), vec3( 1 ) )
			).w;
			const step = float( MONOCHROME_GRADIENT_STEP );
			// Mass climbs inward, so the outward normal is the negated
			// gradient. Volume space and world space differ by one uniform
			// scale on a cube domain, which the normalize cancels.
			const gradient = vec3(
				massAt( vec3( step, 0, 0 ) ).sub( massAt( vec3( step.negate(), 0, 0 ) ) ),
				massAt( vec3( 0, step, 0 ) ).sub( massAt( vec3( 0, step.negate(), 0 ) ) ),
				massAt( vec3( 0, 0, step ) ).sub( massAt( vec3( 0, 0, step.negate() ) ) )
			).negate().div( isoMassNode );
			const bodyNormal = gradient
				.add( radial.mul( MONOCHROME_BODY_BIAS ) )
				.normalize()
				.toVar( 'monochromeBodyNormal' );
			// The swell carries the light; the particle's own normal is mixed
			// back only far enough to keep the grain.
			const shadingNormal = mix( bodyNormal, worldNormal, MONOCHROME_STIPPLE ).normalize();

			// Wrapped diffuse, and only just: the wrap keeps the steepest crest
			// faces off zero without flattening the little N·L range this
			// near-axial sun leaves to work with. The floor under it is not
			// cosmetic — a pointer stroke churns the shell into a plume whose
			// density gradient points every which way, so whole patches read
			// as facing away from the sun and drop to hard zero, and the
			// stirred water goes black exactly where it should be most
			// legible. Flooring the diffuse alone leaves the marched shadow
			// and the ambient occlusion free to darken, so crest shadows keep
			// their depth.
			const sunLight = clamp(
				shadingNormal.dot( sun ).add( wrap ).div( wrap.add( 1 ) ),
				float( MONOCHROME_DIFFUSE_FLOOR ),
				float( 1 )
			);
			// The same march the water composite uses, so crests shade the
			// troughs in their lee, scaled by the same Body shadow dial that
			// sets how far a shadow may sink the scattered body colour there.
			const marched = sunShadow ? sunShadow( worldPosition ).saturate() : float( 1 );
			const shadow = mix(
				float( 1 ),
				marched,
				surfaceComposite.uniforms.scatterShadow.saturate()
			);

			// Direction of travel, from the same grid mirror (xyz velocity,
			// w mass) the shadow march already samples. Tangential only, and
			// signed against the sun: the radial part is just the shell
			// breathing, while the tangential part is the wave actually
			// travelling. A crest running sunward lights its leading face and
			// darkens its trailing one, so the pair rides along with the crest
			// and a still frame says which way the swell is going.
			const flow = gridNode.sample( probeUv ).xyz;
			const speed = flow.length();
			const tangential = flow.sub( bodyNormal.mul( flow.dot( bodyNormal ) ) );
			const flowTone = tangential.div( speed.max( 1e-4 ) ).dot( sun )
				.mul( smoothstep( 0, MONOCHROME_FLOW_SPEED, speed ) )
				.mul( flowContrastNode );

			// Flow rides as a gain rather than a lift: added on top it would be
			// swallowed wherever the disc already sits at white, which under
			// this camera is most of it.
			tone.assign( clamp(
				sunLight
					.mul( shadow )
					.mul( ambientOcclusion )
					.mul( flowTone.add( 1 ) )
					.mul( MONOCHROME_GAIN )
					.add( MONOCHROME_AMBIENT ),
				float( MONOCHROME_TONE_FLOOR ),
				float( 1 )
			) );

		} );
		return tone;

	} )() ), 1 );

}

function updateRenderPipeline() {

	if ( ! renderPipeline ) return;
	rasterizer.visible = ui.monochromeParticles;
	applyStageBackdrop();
	if ( ui.monochromeParticles ) {

		monochromeParticleNode ??= createMonochromeParticleNode();
		renderPipeline.outputNode = monochromeParticleNode;

	} else if ( WATER_DEBUG === 'thickness' ) {

		const value = surfaceRenderer.thicknessNode.sample( uv() ).r.div( 5 ).saturate();
		renderPipeline.outputNode = vec4( vec3( value ), 1 );

	} else if ( WATER_DEBUG === 'depth' ) {

		const value = surfaceRenderer.depthNode.sample( uv() ).r.div( 60 ).saturate();
		renderPipeline.outputNode = vec4( vec3( value ), 1 );

	} else if ( WATER_DEBUG === 'normal' ) {

		const value = surfaceRenderer.normalNode.sample( uv() ).gba.mul( 0.5 ).add( 0.5 );
		renderPipeline.outputNode = vec4( value, 1 );

	} else if ( WATER_DEBUG === 'refract' ) {

		const delta = surfaceComposite.diagnostics.refractionDeltaNode;
		const magnitude = delta.length().mul( 24 ).saturate();
		renderPipeline.outputNode = vec4(
			vec3( delta.x.mul( 12 ).add( 0.5 ), delta.y.mul( 12 ).add( 0.5 ), magnitude ),
			1
		);

	} else if ( WATER_DEBUG === 'contact' ) {

		renderPipeline.outputNode = vec4( vec3( surfaceComposite.diagnostics.contactFoamMaskNode ), 1 );

	} else if ( WATER_DEBUG === 'ssr' ) {

		const value = surfaceComposite.diagnostics.ssrNode;
		renderPipeline.outputNode = vec4(
			vec3( value.r, value.g.mul( 6 ).add( 0.5 ), value.b.mul( 6 ).add( 0.5 ) ),
			1
		);

	} else if ( BLOOM_ENABLED ) {

		// The composite renders once into a half-float RTT so its HDR glints
		// survive to the bloom threshold; the output quad then adds the bloom
		// mips and applies tone mapping over the sum.
		compositeColorNode ??= rtt( surfaceComposite.node );
		if ( ! bloomNode ) {

			bloomNode = bloom( compositeColorNode, BLOOM_STRENGTH, BLOOM_RADIUS, BLOOM_THRESHOLD );
			bloomNode.setResolutionScale( 0.25 );

		}
		renderPipeline.outputNode = compositeColorNode.add( bloomNode );

	} else {

		renderPipeline.outputNode = surfaceComposite.node;

	}
	renderPipeline.needsUpdate = true;

}

// Grid cells per second squared: the solver integrates velocity in cells, and
// the domain is a cube, so one scale factor covers every axis.
function setGravity( worldGravity ) {

	ui.gravity = Math.max( 0, Number( worldGravity ) || 0 );
	gravityGridNode.value = ui.gravity * ( GRID_SIZE.x / DOMAIN_SIZE.x );

}

function setParticleCount( count ) {

	ui.particleCount = Math.min( particleCapacity, Math.max( 1, Math.round( count ) ) );
	water.particleCount = ui.particleCount;
	rasterizer.particleCount = ui.particleCount;

}

function setAutoQuality( enabled ) {

	ui.autoQuality = enabled === true;
	autoQualityDeltas.length = 0;
	autoQualityCalmWindows = 0;

}

function setMonochromeParticles( enabled ) {

	ui.monochromeParticles = enabled === true;
	refreshParticleRadius();
	surfaceRenderer?.resetHistory();
	updateRenderPipeline();

}

function refreshParticleRadius() {

	splatRadiusNode.value = ui.monochromeParticles ? ui.particleRadius : ui.splatRadius;
	renderer.compute( particleRadiusRefresh );

}

function applyAutoQualityTier( tier ) {

	const clamped = Math.min( AUTO_QUALITY_LADDER.length - 1, Math.max( 0, tier ) );
	if ( clamped === autoQualityTier ) return;
	autoQualityTier = clamped;
	renderPixelBudget = AUTO_QUALITY_LADDER[ clamped ];
	surfaceRenderer.resetHistory();
	resize();

}

// Median rAF delta over a short window: wall time covers the whole frame —
// simulation, splats, filters, composite, bloom, and presentation.
function updateAutoQuality( frameDeltaMs ) {

	if ( ! ui.autoQuality || document.hidden ) return;
	autoQualityFramesSeen ++;
	// Skip startup: pipeline compilation and the seeding beat spike wildly.
	if ( autoQualityFramesSeen < AUTO_QUALITY_WARMUP_FRAMES ) return;
	if ( ! ( frameDeltaMs > 0 ) || frameDeltaMs > 250 ) return;
	autoQualityDeltas.push( frameDeltaMs );
	if ( autoQualityDeltas.length < AUTO_QUALITY_WINDOW ) return;
	autoQualityDeltas.sort( ( a, b ) => a - b );
	const median = autoQualityDeltas[ autoQualityDeltas.length >> 1 ];
	autoQualityDeltas.length = 0;
	if ( median > AUTO_QUALITY_STEP_DOWN_MS ) {

		autoQualityCalmWindows = 0;
		const step = median > AUTO_QUALITY_STEP_DOWN_MS * 2 ? 2 : 1;
		applyAutoQualityTier( autoQualityTier + step );

	} else if ( median < AUTO_QUALITY_STEP_UP_MS && autoQualityTier > 0 ) {

		if ( ++ autoQualityCalmWindows >= AUTO_QUALITY_CALM_WINDOWS ) {

			autoQualityCalmWindows = 0;
			applyAutoQualityTier( autoQualityTier - 1 );

		}

	} else {

		autoQualityCalmWindows = 0;

	}

}

function createGUI() {

	gui = createExampleGui( 'Ocean / Fluid surface' );
	if ( container.clientWidth < 680 || ! controlsExpanded ) gui.close();
	gui.add( ui, 'particleCount', PARTICLE_COUNTS )
		.name( 'Particles' )
		.info( 'Reloads the page: particle buffers are sized once at start.' )
		.onChange( count => {

			const url = new URL( window.location.href );
			url.searchParams.set( 'particles', String( count ) );
			window.location.href = url.href;

		} );
	gui.add( ui, 'simulate' ).name( 'Run simulation' );
	gui.add( ui, 'monochromeParticles' )
		.name( 'Monochrome particles' )
		.info( 'Draws the particles directly with tiled compute rasterization, ambient occlusion, and density/body shadow.' )
		.onChange( setMonochromeParticles );
	gui.add( ui, 'particleRadius', 0.02, 0.2, 0.005 )
		.name( 'Particle radius' )
		.info( 'Fixed world radius for monochrome particles; it never scales with particle count.' )
		.onChange( () => {

			if ( ui.monochromeParticles ) refreshParticleRadius();

		} );
	gui.add( ui, 'gravity', 0, 30, 0.1 )
		.name( 'Gravity' )
		.info( 'Pull toward the planet centre. Low values let the ocean drift into a thick haze; high values pin it into a smooth skin.' )
		.onChange( setGravity );
	gui.add( ui, 'wind', 0, 60, 0.5 )
		.name( 'Wind' )
		.info( 'Storm cells blowing along the surface in every direction. Push it far enough and the sea is stripped off its floor.' )
		.onChange( value => {

			ui.wind = value;
			windNode.value = value;

		} );
	gui.add( ui, 'swell', 0, 60, 0.5 )
		.name( 'Swell' )
		.info( 'Radial pumping against gravity. This is what raises waves rather than merely sliding water sideways.' )
		.onChange( value => {

			ui.swell = value;
			swellNode.value = value;

		} );
	gui.add( ui, 'whitewater' ).name( 'Whitewater' ).onChange( enabled => {

		foamMesh.visible = enabled;

	} );
	gui.add( ui, 'foamDisplayDensity', 0, 1, 0.01 )
		.name( 'Foam display density' )
		.info( 'Stable display thinning only; the physical whitewater simulation and deposits remain intact.' )
		.onChange( setFoamDisplayDensity );
	gui.add( ui, 'debugFloor' )
		.name( 'Debug floor' )
		.info( 'Four-quadrant checker for reading refraction, depth and shadow; off swaps in a natural seabed.' )
		.onChange( value => {

			ui.debugFloor = value === true;
			debugFloorNode.value = ui.debugFloor ? 1 : 0;

		} );
	gui.add( { reset: resetOcean }, 'reset' ).name( 'Reset ocean' );
	const surface = gui.addFolder( 'Surface' );
	surface.add( ui, 'splatRadius', 0.12, 0.6, 0.01 )
		.name( 'Splat radius' )
		.info( 'World radius of each particle sphere before the narrow-range filter. Larger closes gaps; smaller keeps crests sharp.' )
		.onChange( value => {

			if ( ! ui.monochromeParticles ) refreshParticleRadius();
			surfaceRenderer.setWorldRadius( value );

		} );
	if ( SHADOW_ENABLED ) {

		surface.add( ui, 'shadowStrength', 0, 3, 0.01 )
			.name( 'Density shadow' )
			.info( 'Extinction per metre of water crossed on the march from the surface toward the sun.' )
			.onChange( value => {

				shadowStrengthNode.value = value;

			} );
		surface.add( ui, 'bodyShadow', 0, 1, 0.01 )
			.name( 'Body shadow' )
			.info( 'How much the density shadow darkens the scattered body colour, not only glints and foam.' )
			.onChange( value => {

				surfaceComposite.uniforms.scatterShadow.value = value;

			} );

	}
	surface.add( ui, 'flowContrast', 0, 1, 0.01 )
		.name( 'Flow direction' )
		.info( 'Monochrome only: tints the shell by where its velocity points, so a travelling crest reads as travelling.' )
		.onChange( value => {

			ui.flowContrast = value;
			flowContrastNode.value = value;

		} );
	const finish = gui.addFolder( 'Finish' );
	finish.add( ui, 'autoQuality' )
		.name( 'Auto quality' )
		.info( 'Holds a smooth frame rate by stepping the internal pixel budget down (and back up) as the machine allows.' )
		.onChange( setAutoQuality );
	finish.add( ui, 'autoRotate' ).name( 'Drift camera' ).onChange( enabled => {

		controls.autoRotate = enabled && ! REDUCED_MOTION;

	} );

}

function resize() {

	if ( ! renderer || ! camera ) return;
	const width = Math.max( 1, container.clientWidth );
	const height = Math.max( 1, container.clientHeight );
	const budget = MAX_PIXELS_OVERRIDE !== null
		? Math.min( renderPixelBudget, MAX_PIXELS_OVERRIDE )
		: renderPixelBudget;
	const pixelRatio = Math.max( 0.5, Math.min(
		Math.min( window.devicePixelRatio, MAX_RENDER_PIXEL_RATIO ),
		Math.sqrt( budget / Math.max( 1, width * height ) )
	) );
	camera.aspect = width / height;
	fitCameraClipping();
	renderer.setPixelRatio( pixelRatio );
	renderer.setSize( width, height );

}

function stepSimulation( delta = FIXED_TIME_STEP, time = elapsed ) {

	water.uniforms.pointerStrength.value = pointerHandlers?.consumeMove?.()
		? 1
		: water.uniforms.pointerStrength.value * 0.78;
	water.time = time;
	noisePhaseNode.value = time * TUNING.noiseDrift;
	water.step( renderer, Math.min( FIXED_TIME_STEP, Math.max( 1 / 360, delta ) ) );
	simulatedFrames ++;

}

function resetOcean() {

	simulatedFrames = 0;
	elapsed = 0;
	water.uniforms.pointerStrength.value = 0;
	water.seed( renderer );
	surfaceRenderer?.resetHistory();

}

// The rasterizer sorts spheres into logarithmic depth slices spanning the
// camera's whole near-to-far range, and that walk front-to-back is the only
// thing that lets a pixel stop early instead of testing every sphere queued on
// its tile. A default 0.1-to-200 range spreads those slices over eleven octaves
// while the planet occupies barely one of them, so almost every sphere lands in
// the same slice and the early-out never fires. Clipping tight to the planet
// puts the full slice budget across the depth that actually contains water.
function fitCameraClipping() {

	const distance = camera.position.length();
	camera.near = Math.max( 0.05, distance - OCEAN_WORLD_RADIUS * 1.35 );
	camera.far = distance + OCEAN_WORLD_RADIUS * 2.4;
	camera.updateProjectionMatrix();

}

function prepareWaterFrame() {

	// Binning projects with the camera matrices directly, so it must run after
	// controls.update() or an orbit drags a one-frame ghost.
	fitCameraClipping();
	camera.updateMatrixWorld();
	renderer.compute( densityCopy );
	rasterizer.update( renderer, camera );
	// update() re-shows the mesh every frame: for its own resolve pass that is
	// the right reflex, since the call has just proven the environment supports
	// it. Here it is a depth producer, and in the shaded view its spheres must
	// stay out of the scene — drawn, they land at the same depth as the sheet
	// they feed, so the composite reads them as geometry in front of the water
	// and the ocean turns into a ball of wet gravel.
	rasterizer.visible = rasterizer.visible && ui.monochromeParticles;
	if ( ! ui.monochromeParticles ) surfaceRenderer.update( renderer, camera );

}

async function renderFrameAsync() {

	prepareWaterFrame();
	await renderPipeline.renderAsync();

}

function animate( now ) {

	const frameDelta = now - previousFrame;
	const delta = fixedFrameTimeStep
		?? Math.min( 0.05, Math.max( 0, frameDelta ) * 0.001 );
	previousFrame = now;
	if ( ! REDUCED_MOTION ) elapsed += delta;
	updateAutoQuality( frameDelta );
	controls.update();
	if ( ui.simulate ) stepSimulation( FIXED_TIME_STEP, elapsed );
	prepareWaterFrame();
	renderPipeline.render();

}

async function waitForSubmittedWork() {

	const queue = renderer?.backend?.device?.queue;
	if ( typeof queue?.onSubmittedWorkDone === 'function' ) await queue.onSubmittedWorkDone();

}

async function stepOcean( steps = 1, startTime = elapsed ) {

	const count = Math.max( 0, Math.round( Number( steps ) || 0 ) );
	for ( let step = 0; step < count; step ++ ) {

		stepSimulation( FIXED_TIME_STEP, startTime + step * FIXED_TIME_STEP );

	}
	await waitForSubmittedWork();
	return getDiagnostics();

}

async function renderOcean() {

	controls.update();
	await renderFrameAsync();
	await waitForSubmittedWork();
	return getDiagnostics();

}

function pauseOcean() {

	ui.simulate = false;
	renderer?.setAnimationLoop( null );

}

function resumeOcean() {

	ui.simulate = true;
	previousFrame = performance.now();
	renderer?.setAnimationLoop( animate );

}

function getDiagnostics() {

	return {
		particleCount: ui.particleCount,
		particleCapacity,
		simulatedFrames,
		simulating: ui.simulate,
		monochromeParticles: ui.monochromeParticles,
		splatRadius: surfaceRenderer?.uniforms.worldRadius.value ?? ui.splatRadius,
		surface: surfaceRenderer
			? {
				width: surfaceRenderer.width,
				height: surfaceRenderer.height,
				fullWidth: surfaceRenderer.fullWidth,
				fullHeight: surfaceRenderer.fullHeight,
			}
			: null,
		shadow: {
			enabled: SHADOW_ENABLED,
			strength: ui.shadowStrength,
			bodyShadow: ui.bodyShadow,
			steps: SHADOW_STEPS,
		},
		flowContrast: ui.flowContrast,
		autoQuality: {
			enabled: ui.autoQuality,
			tier: autoQualityTier,
			pixelBudget: renderPixelBudget,
		},
		domain: DOMAIN_SIZE.toArray(),
		grid: GRID_SIZE.toArray(),
		rasterizer: rasterizer?.stats ?? null,
		solver: solver?.getLastStepStats?.() ?? null,
		timestampQueries: renderer?.backend?.trackTimestamp === true,
	};

}

function createSurfaceHandle() {

	return {
		renderer,
		solver,
		water,
		pause: pauseOcean,
		resume: resumeOcean,
		reset: resetOcean,
		step: stepOcean,
		render: renderOcean,
		getDiagnostics,
		dispose,
		simulation: {
			water,
			solver,
			settings: ui,
			particleCapacity,
			oceanRadius: OCEAN_WORLD_RADIUS,
			tuning: {
				...TUNING,
				restDensity: water.restDensity,
				densityPrediction: DENSITY_PREDICTION,
				formulation: MPM_FORMULATION,
				block: 'WaterVolume',
			},
			domainSize: DOMAIN_SIZE,
			gridSize: GRID_SIZE,
			fixedTimeStep: FIXED_TIME_STEP,
			interactionStrength: water.uniforms.pointerStrength,
			interactionRadius: INTERACTION_RADIUS_WORLD,
			interactionImpulse: INTERACTION_IMPULSE,
			getSimulatedFrames: () => simulatedFrames,
			setParticleCount,
			stepFrame: stepSimulation,
		},
		presentation: {
			scene,
			camera,
			controls,
			rasterizer,
			surfaceRenderer,
			surfaceComposite,
			foamMesh,
			densityTexture,
			environment: oceanEnvironment,
			get bloom() {

				return bloomNode;

			},
			setFoamDisplayDensity,
			setMonochromeParticles,
			renderFrame: renderFrameAsync,
			animate,
			autoQuality: {
				apply: applyAutoQualityTier,
				get enabled() {

					return ui.autoQuality;

				},
				get tier() {

					return autoQualityTier;

				},
				get pixelBudget() {

					return renderPixelBudget;

				},
			},
		},
	};

}

function dispose() {

	if ( disposed ) return;
	disposed = true;
	renderer?.setAnimationLoop( null );
	window.removeEventListener( 'pagehide', dispose );
	resizeObserver?.disconnect();
	controls?.dispose();
	gui?.destroy?.();
	if ( pointerHandlers ) {

		renderer.domElement.removeEventListener( 'pointermove', pointerHandlers.onPointerMove );
		renderer.domElement.removeEventListener( 'pointercancel', pointerHandlers.onPointerLeave );
		renderer.domElement.removeEventListener( 'pointerleave', pointerHandlers.onPointerLeave );

	}
	stageFloor?.geometry?.dispose();
	stageMaterial?.dispose();
	bloomNode?.dispose?.();
	compositeColorNode?.renderTarget?.dispose?.();
	gtaoPass?.dispose();
	rasterizer?.dispose();
	surfaceRenderer?.dispose();
	densityTexture?.dispose();
	water?.dispose();
	scenePass?.dispose?.();
	renderPipeline?.dispose();
	oceanEnvironment?.dispose();
	devtools?.dispose();
	devtools = null;
	renderer?.dispose();

}

export function unmount() {

	dispose();

}