Three Blocks

Murmuration / source

Open preview
runtime/harnesses/water-ocean.jsPlain text ↗
import * as THREE from 'three/webgpu';

export function createOceanTestBridge( {
	renderer,
	water,
	solver,
	reset: resetOcean,
	simulation: {
		settings: ui,
		floorLevel,
		fillHeight,
		tuning,
		domainSize,
		gridSize,
		fixedTimeStep,
		interactionStrength,
		waveEnergy,
		waveEnergyMax,
		interactionRadius,
		interactionImpulse,
		getSimulatedFrames,
		setParticleCount,
		stepFrame: stepSimulation,
	},
	presentation: {
		scene,
		camera,
		controls,
		waterCaustics,
		raymarchRenderer,
		raymarchFoamMesh,
		raymarchComposite,
		environment,
		bloom,
		autoQuality,
		setFoamDisplayDensity,
		setDebugFloor,
		applyRaymarchQuality,
		renderFrame: renderFrameAsync,
		animate,
	},
} ) {

	const halfToFloat = bits => {

		const sign = ( bits & 0x8000 ) ? - 1 : 1;
		const exponent = ( bits >> 10 ) & 0x1f;
		const mantissa = bits & 0x3ff;
		if ( exponent === 0 ) return sign * mantissa * 2 ** - 24;
		if ( exponent === 31 ) return mantissa ? NaN : sign * Infinity;
		return sign * ( 1 + mantissa / 1024 ) * 2 ** ( exponent - 15 );

	};

	const readTarget = async ( target, channels ) => {

		const { width, height } = target;
		const pixels = await renderer.readRenderTargetPixelsAsync( target, 0, 0, width, height );
		const decode = pixels instanceof Uint16Array ? halfToFloat : value => value;
		const rowElements = width * channels;
		const paddedBytes = Math.ceil( rowElements * pixels.BYTES_PER_ELEMENT / 256 ) * 256;
		const paddedElements = paddedBytes / pixels.BYTES_PER_ELEMENT;
		const sourceStride = pixels.length >= paddedElements * height ? paddedElements : rowElements;
		const values = new Float32Array( width * height * channels );
		let finite = true;
		for ( let row = 0; row < height; row ++ ) {

			for ( let element = 0; element < rowElements; element ++ ) {

				const value = decode( pixels[ row * sourceStride + element ] );
				values[ row * rowElements + element ] = value;
				finite &&= Number.isFinite( value );

			}

		}
		return { width, height, values, finite, arrayType: pixels.constructor.name };

	};

	// Simulation-state metrics straight from the solver's particle buffer, in
	// grid units (positions normalized [0,1], velocities in cells/s). The
	// surface tile grid quantifies visual agitation: `graininess` is the RMS
	// height difference between adjacent tiles (high-frequency noise), while
	// `heightStdev` includes coherent large-scale swell.
	const readSimStats = async ( { stride = 4, tiles = 32 } = {} ) => {

		const values = new Float32Array( await renderer.getArrayBufferAsync( solver.particleBuffer.value ) );
		const itemStride = solver.particleBuffer.value.itemSize;
		const count = Math.min( ui.particleCount, solver.particleCount );
		const interiorCeiling = floorLevel + fillHeight * 0.7;
		const tileHeights = new Float32Array( tiles * tiles ).fill( - Infinity );
		let sampled = 0;
		let finite = true;
		let speedSum = 0;
		let speedSquaredSum = 0;
		let maxSpeed = 0;
		let densitySum = 0;
		let interiorDensitySum = 0;
		let interiorCount = 0;
		let minY = Infinity;
		let maxY = - Infinity;
		for ( let index = 0; index < count; index += stride ) {

			const offset = index * itemStride;
			const x = values[ offset ];
			const y = values[ offset + 1 ];
			const z = values[ offset + 2 ];
			const vx = values[ offset + 4 ];
			const vy = values[ offset + 5 ];
			const vz = values[ offset + 6 ];
			const density = values[ offset + 7 ];
			finite &&= Number.isFinite( x ) && Number.isFinite( y ) && Number.isFinite( z ) &&
				Number.isFinite( vx ) && Number.isFinite( vy ) && Number.isFinite( vz );
			const speedSquared = vx * vx + vy * vy + vz * vz;
			const speed = Math.sqrt( speedSquared );
			sampled ++;
			speedSum += speed;
			speedSquaredSum += speedSquared;
			maxSpeed = Math.max( maxSpeed, speed );
			densitySum += density;
			minY = Math.min( minY, y );
			maxY = Math.max( maxY, y );
			if ( x > 0.15 && x < 0.85 && z > 0.15 && z < 0.85 && y > floorLevel + 0.05 && y < interiorCeiling ) {

				interiorDensitySum += density;
				interiorCount ++;

			}
			const tileX = Math.min( tiles - 1, Math.max( 0, Math.floor( x * tiles ) ) );
			const tileZ = Math.min( tiles - 1, Math.max( 0, Math.floor( z * tiles ) ) );
			const tile = tileX * tiles + tileZ;
			tileHeights[ tile ] = Math.max( tileHeights[ tile ], y );

		}
		let heightSum = 0;
		let heightSquaredSum = 0;
		let occupied = 0;
		let neighborSquaredSum = 0;
		let neighborCount = 0;
		for ( let tileX = 0; tileX < tiles; tileX ++ ) for ( let tileZ = 0; tileZ < tiles; tileZ ++ ) {

			const height = tileHeights[ tileX * tiles + tileZ ];
			if ( height === - Infinity ) continue;
			occupied ++;
			heightSum += height;
			heightSquaredSum += height * height;
			for ( const [ nx, nz ] of [ [ tileX + 1, tileZ ], [ tileX, tileZ + 1 ] ] ) {

				if ( nx >= tiles || nz >= tiles ) continue;
				const neighbor = tileHeights[ nx * tiles + nz ];
				if ( neighbor === - Infinity ) continue;
				const delta = height - neighbor;
				neighborSquaredSum += delta * delta;
				neighborCount ++;

			}

		}
		const heightMean = heightSum / Math.max( 1, occupied );
		const gridY = gridSize.y;
		const foamAlive = water.foam ? await water.foam.readAliveCount( renderer ) : 0;
		return {
			sampled,
			finite,
			meanSpeed: speedSum / Math.max( 1, sampled ),
			rmsSpeed: Math.sqrt( speedSquaredSum / Math.max( 1, sampled ) ),
			maxSpeed,
			meanDensity: densitySum / Math.max( 1, sampled ),
			interiorDensity: interiorDensitySum / Math.max( 1, interiorCount ),
			interiorCount,
			yRange: [ minY, maxY ],
			surface: {
				tiles,
				occupied,
				meanCells: heightMean * gridY,
				stdevCells: Math.sqrt( Math.max( 0, heightSquaredSum / Math.max( 1, occupied ) - heightMean * heightMean ) ) * gridY,
				graininessCells: Math.sqrt( neighborSquaredSum / Math.max( 1, neighborCount ) ) * gridY,
			},
			diagnostics: solver.getLastStepStats().diagnostics ?? null,
			whitewater: {
				alive: foamAlive,
				capacity: water.foam?.capacity ?? 0,
				displayFraction: ui.foamDisplayDensity,
				estimatedDisplayed: Math.round( foamAlive * ui.foamDisplayDensity ),
			},
			tuning,
		};

	};

	const readCausticsStats = async () => {

		if ( ! waterCaustics ) return { available: false, finite: true, meanEnergy: 0, integral: 0 };
		const target = [
			waterCaustics._currentTarget,
			waterCaustics._historyRead,
			waterCaustics._historyWrite,
		].find( candidate => candidate?.texture === waterCaustics.texture ) ?? waterCaustics._historyRead;
		const image = await readTarget( target, 4 );
		let energy = 0;
		let shadow = 0;
		let litPixels = 0;
		for ( let pixel = 0; pixel < image.width * image.height; pixel ++ ) {

			const offset = pixel * 4;
			const pixelEnergy = (
				image.values[ offset ] + image.values[ offset + 1 ] + image.values[ offset + 2 ]
			) / 3;
			energy += pixelEnergy;
			shadow += image.values[ offset + 3 ];
			if ( pixelEnergy > 1e-4 ) litPixels ++;

		}
		const pixels = image.width * image.height;
		return {
			available: true,
			finite: image.finite,
			width: image.width,
			height: image.height,
			meanEnergy: energy / Math.max( 1, pixels ),
			meanShadow: shadow / Math.max( 1, pixels ),
			integral: energy,
			litFraction: litPixels / Math.max( 1, pixels ),
			arrayType: image.arrayType,
		};

	};

	const readCompositeEnergyStats = async () => {

		const activeComposite = raymarchComposite;
		const target = new THREE.RenderTarget( 320, 180, {
			format: THREE.RGBAFormat,
			type: THREE.HalfFloatType,
			depthBuffer: false,
			stencilBuffer: false,
		} );
		const material = new THREE.NodeMaterial();
		material.name = 'OceanHarness.compositeEnergy';
		material.outputNode = activeComposite.node;
		material.depthTest = false;
		material.depthWrite = false;
		const quad = new THREE.QuadMesh( material );
		const previousTarget = renderer.getRenderTarget();
		try {

			renderer.setRenderTarget( target );
			quad.render( renderer );
			await renderer.backend.device.queue.onSubmittedWorkDone();
			const image = await readTarget( target, 4 );
			let maximum = 0;
			let excessPixels = 0;
			let waterPixels = 0;
			for ( let pixel = 0; pixel < image.width * image.height; pixel ++ ) {

				const offset = pixel * 4;
				const red = image.values[ offset ];
				const green = image.values[ offset + 1 ];
				const blue = image.values[ offset + 2 ];
				maximum = Math.max( maximum, red, green, blue );
				if ( red > 1.002 || green > 1.002 || blue > 1.002 ) excessPixels ++;
				if ( Math.abs( red - green ) > 1e-3 || Math.abs( green - blue ) > 1e-3 ) waterPixels ++;

			}
			return {
				finite: image.finite,
				maximum,
				excessPixels,
				waterPixels,
				pixelCount: image.width * image.height,
				arrayType: image.arrayType,
			};

		} finally {

			renderer.setRenderTarget( previousTarget );
			material.dispose();
			target.dispose();

		}

	};

	const harness = {
		ready: true,
		advance: async ( steps = 1, startTime = 0 ) => {

			for ( let step = 0; step < steps; step ++ ) {

				stepSimulation( fixedTimeStep, startTime + step * fixedTimeStep );

			}
			await renderer.backend.device.queue.onSubmittedWorkDone();

		},
		readSimStats,
		readCausticsStats,
		readCompositeEnergyStats,
		getState: () => ( {
			renderMode: 'Raymarched volume',
			particleCount: ui.particleCount,
			simulate: ui.simulate,
			waveEnergy: ui.waveEnergy,
			whitewater: ui.whitewater,
			foamDisplayDensity: ui.foamDisplayDensity,
			debugFloor: ui.debugFloor,
			whitewaterRenderers: {
				raymarchVisible: raymarchFoamMesh?.visible === true,
				raymarchPixelClamp: raymarchFoamMesh?.userData?.whitewaterPixelClamp ?? null,
				raymarchDepositPixelClamp: raymarchFoamMesh?.userData?.surfaceFoamPixelClamp ?? null,
				raymarchDisplayFractions: raymarchFoamMesh?.userData?.whitewaterDisplayFractions?.map( entry => entry.uniform.value ) ?? null,
				surfaceFoamPath: raymarchFoamMesh?.userData?.surfaceFoamPath ?? null,
				legacySurfaceFoam: raymarchFoamMesh?.userData?.legacySurfaceFoam ?? null,
			},
			raymarch: {
				quality: ui.raymarchQuality,
				...( raymarchRenderer.getQualitySettings?.() ?? {} ),
				textureGridMirror: raymarchRenderer.textureGridMirror ?? null,
				traceResolution: [ raymarchRenderer.width, raymarchRenderer.height ],
				foamThreshold: raymarchComposite?.uniforms?.foamThreshold?.value ?? null,
			},
			foamSources: {
				speedStampGain: water.surface.uniforms.foamGain.value,
				depositGain: water.surface.uniforms.foamDepositGain.value,
			},
			cameraUnderwater: raymarchRenderer.uniforms.cameraUnderwater.value > 0.5,
			caustics: waterCaustics ? {
				resolution: waterCaustics.resolution,
				intensity: waterCaustics.uniforms.intensity.value,
				temporal: waterCaustics.uniforms.temporal.value,
			} : null,
			camera: camera.position.toArray(),
			cameraTarget: controls.target.toArray(),
			domain: domainSize.toArray(),
			interaction: {
				trigger: 'pointermove',
				strength: interactionStrength.value,
				radius: interactionRadius,
				radiusUnits: 'world',
				impulse: interactionImpulse,
			},
			simulation: {
				solver: 'MLS-MPM/APIC',
				grid: gridSize.toArray(),
				fixedTimeStep,
				passes: solver.getLastStepStats().passes.length > 0
					? solver.getLastStepStats().passes
					: solver.passes.map( node => node.name ),
				stats: solver.getLastStepStats(),
				simulatedFrames: getSimulatedFrames(),
			},
		} ),
		setState: async ( state = {} ) => {

			if ( state.debugFloor !== undefined ) setDebugFloor( state.debugFloor );
			if ( state.raymarchQuality !== undefined ) applyRaymarchQuality( state.raymarchQuality );
			let customRaymarch = false;
			let rebuildRaymarch = false;
			if ( state.raymarchRefinement !== undefined ) {

				ui.raymarchRefinement = Math.min( 8, Math.max( 1, Math.round( Number( state.raymarchRefinement ) ) ) );
				customRaymarch = true;
				rebuildRaymarch = true;

			}
			if ( state.raymarchMaxSteps !== undefined ) {

				ui.raymarchMaxSteps = Math.min( 768, Math.max( 32, Math.round( Number( state.raymarchMaxSteps ) ) ) );
				customRaymarch = true;
				rebuildRaymarch = true;

			}
			if ( state.raymarchNormalSmoothing !== undefined ) {

				ui.raymarchNormalSmoothing = Math.min( 5, Math.max( 0, Number( state.raymarchNormalSmoothing ) ) );
				customRaymarch = true;
				rebuildRaymarch = true;

			}
			if ( state.raymarchNormalFilter !== undefined ) {

				ui.raymarchNormalFilter = Math.min( 5, Math.max( 0, Math.round( Number( state.raymarchNormalFilter ) ) ) );
				customRaymarch = true;
				rebuildRaymarch = true;

			}
			if ( state.raymarchTrilinear !== undefined ) {

				ui.raymarchTrilinear = state.raymarchTrilinear === true;
				customRaymarch = true;
				rebuildRaymarch = true;

			}
			if ( rebuildRaymarch ) raymarchRenderer.setTraceOptions( {
				maxSteps: ui.raymarchMaxSteps,
				refinementSteps: ui.raymarchRefinement,
				normalSmoothing: ui.raymarchNormalSmoothing,
				normalFilterRadius: ui.raymarchNormalFilter,
				trilinearTracing: ui.raymarchTrilinear,
			} );
			if ( state.particleCount !== undefined ) setParticleCount( state.particleCount );
			if ( state.simulate !== undefined ) ui.simulate = state.simulate === true;
			if ( state.waveEnergy !== undefined ) {

				ui.waveEnergy = Math.min( waveEnergyMax, Math.max( 0, Number( state.waveEnergy ) ) );
				waveEnergy.value = ui.waveEnergy;

			}
			if ( state.whitewater !== undefined ) {

				ui.whitewater = state.whitewater === true;
				raymarchFoamMesh.visible = ui.whitewater;

			}
			if ( state.foamDisplayDensity !== undefined ) setFoamDisplayDensity( state.foamDisplayDensity );
			if ( state.raymarchResolution !== undefined ) {

				ui.raymarchResolution = Math.min( 1, Math.max( 0.25, Number( state.raymarchResolution ) ) );
				customRaymarch = true;
				raymarchRenderer.setResolutionScale( ui.raymarchResolution );

			}
			if ( state.raymarchWhitewaterScale !== undefined ) {

				ui.raymarchWhitewaterScale = Math.min( 1, Math.max( 0.0625, Number( state.raymarchWhitewaterScale ) ) );
				customRaymarch = true;
				raymarchRenderer.setWhitewaterScale( ui.raymarchWhitewaterScale );

			}
			if ( state.raymarchStep !== undefined ) {

				ui.raymarchStep = Math.min( 2.5, Math.max( 1, Number( state.raymarchStep ) ) );
				customRaymarch = true;
				raymarchRenderer.uniforms.stepScale.value = ui.raymarchStep;

			}
			if ( state.raymarchIso !== undefined ) {

				ui.raymarchIso = Math.min( 1.5, Math.max( 0.5, Number( state.raymarchIso ) ) );
				customRaymarch = true;
				raymarchRenderer.uniforms.isoScale.value = ui.raymarchIso;

			}
			if ( state.raymarchDepthRange !== undefined ) {

				ui.raymarchDepthRange = Math.min( 2, Math.max( 0.01, Number( state.raymarchDepthRange ) ) );
				customRaymarch = true;
				raymarchRenderer.uniforms.resolveDepthRange.value = ui.raymarchDepthRange;

			}
			if ( state.raymarchThickness !== undefined ) {

				ui.raymarchThickness = Math.min( 12, Math.max( 0.25, Number( state.raymarchThickness ) ) );
				customRaymarch = true;
				raymarchRenderer.uniforms.maxThickness.value = ui.raymarchThickness;

			}
			if ( customRaymarch ) ui.raymarchQuality = 'Custom';
			if ( state.cameraPosition || state.cameraTarget ) {

				if ( state.cameraPosition ) camera.position.fromArray( state.cameraPosition );
				if ( state.cameraTarget ) controls.target.fromArray( state.cameraTarget );
				raymarchRenderer.resetHistory();

			}
			if ( state.splash ) {

				const splash = state.splash === true ? {} : state.splash;
				water.addSplash(
					splash.x ?? 0,
					splash.y ?? water.getStillWaterLevel(),
					splash.z ?? 0,
					splash.vx ?? 6,
					splash.vy ?? - 7,
					splash.vz ?? 1,
					splash.radius ?? 2.2,
					splash.strength ?? 1
				);

			}
			if ( state.pointerStroke ) {

				const stroke = state.pointerStroke === true ? {} : state.pointerStroke;
				const frames = Math.max( 1, Math.round( stroke.frames ?? 18 ) );
				const fromX = Number( stroke.fromX ?? - 3 );
				const toX = Number( stroke.toX ?? 3 );
				const fromZ = Number( stroke.fromZ ?? 0 );
				const toZ = Number( stroke.toZ ?? 0 );
				const y = Number( stroke.y ?? water.getStillWaterLevel() );
				const point = camera.position.clone();
				const startTime = Number( stroke.time ?? state.time ?? 0 );
				for ( let frame = 0; frame < frames; frame ++ ) {

					const phase = frames === 1 ? 1 : frame / ( frames - 1 );
					point.set(
						fromX + ( toX - fromX ) * phase,
						y,
						fromZ + ( toZ - fromZ ) * phase
					);
					water.setPointer( point, 1 / 0.78 );
					stepSimulation( fixedTimeStep, startTime + frame * fixedTimeStep );

				}
				water.setPointer( null );
				await renderer.backend.device.queue.onSubmittedWorkDone();

			}
			if ( state.reset === true ) resetOcean();
			await harness.render( state.time );

		},
		setLoop: enabled => renderer.setAnimationLoop( enabled ? animate : null ),
		orbit: async ( { frames = 120, time = 0 } = {} ) => {

			const frameCount = Math.max( 1, Math.round( frames ) );
			const previousAutoRotate = controls.autoRotate;
			const start = camera.position.clone();
			controls.autoRotate = true;
			try {

				for ( let frame = 0; frame < frameCount; frame ++ ) await harness.render( time + frame / 60 );

			} finally {

				controls.autoRotate = previousAutoRotate;

			}
			return {
				frames: frameCount,
				durationSeconds: frameCount / 60,
				autoRotateSpeed: controls.autoRotateSpeed,
				start: start.toArray(),
				end: camera.position.toArray(),
				travel: start.distanceTo( camera.position ),
			};

		},
		measureRenderModes: async ( {
			modes = [ 'Raymarched volume' ],
			warmupFrames = 3,
			sampleFrames = 9,
			time = 0,
		} = {} ) => {

			const median = values => values.length > 0
				? [ ...values ].sort( ( a, b ) => a - b )[ Math.floor( values.length / 2 ) ]
				: null;
			const rows = [];
			if ( ! modes.includes( 'Raymarched volume' ) ) return {
				timestampQueriesAvailable: renderer.backend.trackTimestamp === true,
				warmupFrames,
				sampleFrames,
				rows,
			};
			await harness.resolveTimestamps();
			for ( let frame = 0; frame < warmupFrames; frame ++ ) await harness.render( time + frame / 120 );
			await harness.resolveTimestamps();
			const wallSamples = [];
			const computeSamples = [];
			const renderSamples = [];
			const totalGPUSamples = [];
			for ( let frame = 0; frame < sampleFrames; frame ++ ) {

				const start = performance.now();
				await harness.render( time + ( warmupFrames + frame ) / 120 );
				wallSamples.push( performance.now() - start );
				const timestamps = await harness.resolveTimestamps();
				if ( Number.isFinite( timestamps.compute ) && timestamps.compute >= 0 ) computeSamples.push( timestamps.compute );
				if ( Number.isFinite( timestamps.render ) && timestamps.render >= 0 ) renderSamples.push( timestamps.render );
				if ( Number.isFinite( timestamps.compute ) && Number.isFinite( timestamps.render ) ) {

					totalGPUSamples.push( timestamps.compute + timestamps.render );

				}

			}
			rows.push( {
				mode: 'Raymarched volume',
				medianWallMilliseconds: median( wallSamples ),
				medianComputeMilliseconds: median( computeSamples ),
				medianRenderMilliseconds: median( renderSamples ),
				medianTotalGPUMilliseconds: median( totalGPUSamples ),
				wallSamples,
				computeSamples,
				renderSamples,
			} );
			return {
				timestampQueriesAvailable: renderer.backend.trackTimestamp === true,
				warmupFrames,
				sampleFrames,
				rows,
			};

		},
		render: async time => {

			controls.update();
			if ( ui.simulate ) stepSimulation( fixedTimeStep, time );
			await renderFrameAsync();
			await renderer.backend.device.queue.onSubmittedWorkDone();

		},
		reset: resetOcean,
		resolveTimestamps: async () => ( {
			compute: await renderer.resolveTimestampsAsync( 'compute' ),
			render: await renderer.resolveTimestampsAsync( 'render' ),
		} ),
	};
	harness.look = {
		composite: raymarchComposite,
		raymarch: raymarchRenderer,
		caustics: waterCaustics,
		environment,
		renderer,
		scene,
		camera,
		controls,
		bloom,
		autoQuality,
	};
	return harness;

}