Explorar o código

CurveModifierGPU: WebGPURenderer port. (#29453)

* curve mod

* lint

* update screenshot

* use correct constant

* use filtered texture

---------

Co-authored-by: aardgoose <angus.sawyer@email.com>
aardgoose hai 1 ano
pai
achega
d7575e406b

+ 1 - 0
examples/files.json

@@ -362,6 +362,7 @@
 		"webgpu_materialx_noise",
 		"webgpu_mesh_batch",
 		"webgpu_mirror",
+		"webgpu_modifier_curve",
 		"webgpu_morphtargets",
 		"webgpu_morphtargets_face",
 		"webgpu_mrt",

+ 233 - 0
examples/jsm/modifiers/CurveModifierGPU.js

@@ -0,0 +1,233 @@
+// Original src: https://github.com/zz85/threejs-path-flow
+const CHANNELS = 4;
+const TEXTURE_WIDTH = 1024;
+const TEXTURE_HEIGHT = 4;
+
+import {
+	DataTexture,
+	DataUtils,
+	RGBAFormat,
+	HalfFloatType,
+	RepeatWrapping,
+	Mesh,
+	InstancedMesh,
+	LinearFilter
+} from 'three';
+
+import { modelWorldMatrix, normalLocal, vec2, vec3, vec4, mat3, varyingProperty, texture, reference, Fn, select, positionLocal } from 'three/tsl';
+
+/**
+ * Make a new DataTexture to store the descriptions of the curves.
+ *
+ * @param { number } numberOfCurves the number of curves needed to be described by this texture.
+ */
+export function initSplineTexture( numberOfCurves = 1 ) {
+
+	const dataArray = new Uint16Array( TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * CHANNELS );
+	const dataTexture = new DataTexture(
+		dataArray,
+		TEXTURE_WIDTH,
+		TEXTURE_HEIGHT * numberOfCurves,
+		RGBAFormat,
+		HalfFloatType
+	);
+
+	dataTexture.wrapS = RepeatWrapping;
+	dataTexture.wrapY = RepeatWrapping;
+	dataTexture.magFilter = LinearFilter;
+	dataTexture.minFilter = LinearFilter;
+	dataTexture.needsUpdate = true;
+
+	return dataTexture;
+
+}
+
+/**
+ * Write the curve description to the data texture
+ *
+ * @param { DataTexture } texture The DataTexture to write to
+ * @param { Curve } splineCurve The curve to describe
+ * @param { number } offset Which curve slot to write to
+ */
+export function updateSplineTexture( texture, splineCurve, offset = 0 ) {
+
+	const numberOfPoints = Math.floor( TEXTURE_WIDTH * ( TEXTURE_HEIGHT / 4 ) );
+	splineCurve.arcLengthDivisions = numberOfPoints / 2;
+	splineCurve.updateArcLengths();
+	const points = splineCurve.getSpacedPoints( numberOfPoints );
+	const frenetFrames = splineCurve.computeFrenetFrames( numberOfPoints, true );
+
+	for ( let i = 0; i < numberOfPoints; i ++ ) {
+
+		const rowOffset = Math.floor( i / TEXTURE_WIDTH );
+		const rowIndex = i % TEXTURE_WIDTH;
+
+		let pt = points[ i ];
+		setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 0 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
+		pt = frenetFrames.tangents[ i ];
+		setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 1 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
+		pt = frenetFrames.normals[ i ];
+		setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 2 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
+		pt = frenetFrames.binormals[ i ];
+		setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 3 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
+
+	}
+
+	texture.needsUpdate = true;
+
+}
+
+
+function setTextureValue( texture, index, x, y, z, o ) {
+
+	const image = texture.image;
+	const { data } = image;
+	const i = CHANNELS * TEXTURE_WIDTH * o; // Row Offset
+
+	data[ index * CHANNELS + i + 0 ] = DataUtils.toHalfFloat( x );
+	data[ index * CHANNELS + i + 1 ] = DataUtils.toHalfFloat( y );
+	data[ index * CHANNELS + i + 2 ] = DataUtils.toHalfFloat( z );
+	data[ index * CHANNELS + i + 3 ] = DataUtils.toHalfFloat( 1 );
+
+}
+
+/**
+ * Create a new set of uniforms for describing the curve modifier
+ *
+ * @param { DataTexture } Texture which holds the curve description
+ */
+export function getUniforms( splineTexture ) {
+
+	return {
+		spineTexture: splineTexture,
+		pathOffset: 0, // time of path curve
+		pathSegment: 1, // fractional length of path
+		spineOffset: 161,
+		spineLength: 400,
+		flow: 1, // int
+	};
+
+}
+
+export function modifyShader( material, uniforms, numberOfCurves ) {
+
+	const spineTexture = uniforms.spineTexture;
+
+	const pathOffset = reference( 'pathOffset', 'float', uniforms );
+	const pathSegment = reference( 'pathSegment', 'float', uniforms );
+	const spineOffset = reference( 'spineOffset', 'float', uniforms );
+	const spineLength = reference( 'spineLength', 'float', uniforms );
+	const flow = reference( 'flow', 'float', uniforms );
+
+	material.positionNode = Fn( () => {
+
+		const textureStacks = TEXTURE_HEIGHT / 4;
+		const textureScale = TEXTURE_HEIGHT * numberOfCurves;
+
+		const worldPos = modelWorldMatrix.mul( vec4( positionLocal, 1 ) ).toVar();
+
+		const bend = flow.greaterThan( 0 ).toVar();
+		const xWeight = select( bend, 0, 1 ).toVar();
+
+		const spinePortion = select( bend, worldPos.x.add( spineOffset ).div( spineLength ), 0 );
+		const mt = spinePortion.mul( pathSegment ).add( pathOffset ).mul( textureStacks ).toVar();
+
+		mt.assign( mt.mod( textureStacks ) );
+
+		const rowOffset = mt.floor().toVar();
+
+		const spinePos = texture( spineTexture, vec2( mt, rowOffset.add( 0.5 ).div( textureScale ) ) ).xyz;
+
+		const a = texture( spineTexture, vec2( mt, rowOffset.add( 1.5 ).div( textureScale ) ) ).xyz;
+		const b = texture( spineTexture, vec2( mt, rowOffset.add( 2.5 ).div( textureScale ) ) ).xyz;
+		const c = texture( spineTexture, vec2( mt, rowOffset.add( 3.5 ).div( textureScale ) ) ).xyz;
+
+		const basis = mat3( a, b, c ).toVar();
+
+		varyingProperty( 'vec3', 'curveNormal' ).assign( basis.mul( normalLocal ) );
+
+		return basis.mul( vec3( worldPos.x.mul( xWeight ), worldPos.y, worldPos.z ) ).add( spinePos );
+
+	} )();
+
+	material.normalNode = varyingProperty( 'vec3', 'curveNormal' );
+
+}
+
+/**
+ * A helper class for making meshes bend aroudn curves
+ */
+export class Flow {
+
+	/**
+	 * @param {Mesh} mesh The mesh to clone and modify to bend around the curve
+	 * @param {number} numberOfCurves The amount of space that should preallocated for additional curves
+	 */
+	constructor( mesh, numberOfCurves = 1 ) {
+
+		const obj3D = mesh.clone();
+		const splineTexure = initSplineTexture( numberOfCurves );
+		const uniforms = getUniforms( splineTexure );
+
+		obj3D.traverse( function ( child ) {
+
+			if (
+				child instanceof Mesh ||
+				child instanceof InstancedMesh
+			) {
+
+				if ( Array.isArray( child.material ) ) {
+
+					const materials = [];
+
+					for ( const material of child.material ) {
+
+						const newMaterial = material.clone();
+						modifyShader( newMaterial, uniforms, numberOfCurves );
+						materials.push( newMaterial );
+
+					}
+
+					child.material = materials;
+
+				} else {
+
+					child.material = child.material.clone();
+					modifyShader( child.material, uniforms, numberOfCurves );
+
+				}
+
+			}
+
+		} );
+
+		this.curveArray = new Array( numberOfCurves );
+		this.curveLengthArray = new Array( numberOfCurves );
+
+		this.object3D = obj3D;
+		this.splineTexure = splineTexure;
+		this.uniforms = uniforms;
+
+	}
+
+	updateCurve( index, curve ) {
+
+		if ( index >= this.curveArray.length ) throw Error( 'Index out of range for Flow' );
+
+		const curveLength = curve.getLength();
+
+		this.uniforms.spineLength = curveLength;
+		this.curveLengthArray[ index ] = curveLength;
+		this.curveArray[ index ] = curve;
+
+		updateSplineTexture( this.splineTexure, curve, index );
+
+	}
+
+	moveAlongCurve( amount ) {
+
+		this.uniforms.pathOffset += amount;
+
+	}
+
+}

BIN=BIN
examples/screenshots/webgpu_modifier_curve.jpg


+ 220 - 0
examples/webgpu_modifier_curve.html

@@ -0,0 +1,220 @@
+<!DOCTYPE html>
+<html lang="en">
+	<head>
+		<title>three.js webgpu - curve modifier</title>
+		<meta charset="utf-8" />
+		<meta
+			name="viewport"
+			content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"
+		/>
+		<link type="text/css" rel="stylesheet" href="main.css" />
+	</head>
+	<body>
+		<div id="info">
+			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgpu - curve modifier
+		</div>
+
+		<script type="importmap">
+			{
+				"imports": {
+					"three": "../build/three.webgpu.js",
+					"three/tsl": "../build/three.webgpu.js",
+					"three/addons/": "./jsm/"
+				}
+			}
+		</script>
+
+		<script type="module">
+			import * as THREE from 'three';
+			import { TransformControls } from 'three/addons/controls/TransformControls.js';
+			import Stats from 'three/addons/libs/stats.module.js';
+			import { Flow } from 'three/addons/modifiers/CurveModifierGPU.js';
+			import { FontLoader } from 'three/addons/loaders/FontLoader.js';
+			import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
+
+			const ACTION_SELECT = 1, ACTION_NONE = 0;
+			const curveHandles = [];
+			const mouse = new THREE.Vector2();
+
+			let stats;
+			let scene,
+				camera,
+				renderer,
+				rayCaster,
+				control,
+				flow,
+				action = ACTION_NONE;
+
+			init();
+
+			function init() {
+
+				scene = new THREE.Scene();
+
+				camera = new THREE.PerspectiveCamera(
+					40,
+					window.innerWidth / window.innerHeight,
+					1,
+					1000
+				);
+				camera.position.set( 2, 2, 4 );
+				camera.lookAt( scene.position );
+
+				const initialPoints = [
+					{ x: 1, y: 0, z: - 1 },
+					{ x: 1, y: 0, z: 1 },
+					{ x: - 1, y: 0, z: 1 },
+					{ x: - 1, y: 0, z: - 1 },
+				];
+
+				const boxGeometry = new THREE.BoxGeometry( 0.1, 0.1, 0.1 );
+				const boxMaterial = new THREE.MeshBasicNodeMaterial();
+
+				for ( const handlePos of initialPoints ) {
+
+					const handle = new THREE.Mesh( boxGeometry, boxMaterial );
+					handle.position.copy( handlePos );
+					curveHandles.push( handle );
+					scene.add( handle );
+
+				}
+
+				const curve = new THREE.CatmullRomCurve3(
+					curveHandles.map( ( handle ) => handle.position )
+				);
+				curve.curveType = 'centripetal';
+				curve.closed = true;
+
+				const points = curve.getPoints( 50 );
+				const line = new THREE.Line(
+					new THREE.BufferGeometry().setFromPoints( points ),
+					new THREE.LineBasicMaterial( { color: 0x00ff00 } )
+				);
+
+				scene.add( line );
+
+				//
+
+				const light = new THREE.DirectionalLight( 0xffaa33, 3 );
+				light.position.set( - 10, 10, 10 );
+				scene.add( light );
+
+				const light2 = new THREE.AmbientLight( 0x003973, 3 );
+				scene.add( light2 );
+
+				//
+
+				const loader = new FontLoader();
+				loader.load( 'fonts/helvetiker_regular.typeface.json', function ( font ) {
+
+					const geometry = new TextGeometry( 'Hello three.js!', {
+						font: font,
+						size: 0.2,
+						depth: 0.05,
+						curveSegments: 12,
+						bevelEnabled: true,
+						bevelThickness: 0.02,
+						bevelSize: 0.01,
+						bevelOffset: 0,
+						bevelSegments: 5,
+					} );
+
+					geometry.rotateX( Math.PI );
+
+					const material = new THREE.MeshStandardNodeMaterial( {
+						color: 0x99ffff
+					} );
+
+					const objectToCurve = new THREE.Mesh( geometry, material );
+
+					flow = new Flow( objectToCurve );
+					flow.updateCurve( 0, curve );
+					scene.add( flow.object3D );
+
+				} );
+
+				//
+
+				renderer = new THREE.WebGPURenderer( { antialias: true } );
+				renderer.setPixelRatio( window.devicePixelRatio );
+				renderer.setSize( window.innerWidth, window.innerHeight );
+				renderer.setAnimationLoop( animate );
+				document.body.appendChild( renderer.domElement );
+
+				renderer.domElement.addEventListener( 'pointerdown', onPointerDown );
+
+				rayCaster = new THREE.Raycaster();
+				control = new TransformControls( camera, renderer.domElement );
+				control.addEventListener( 'dragging-changed', function ( event ) {
+
+					if ( ! event.value ) {
+
+						const points = curve.getPoints( 50 );
+						line.geometry.setFromPoints( points );
+						flow.updateCurve( 0, curve );
+
+					}
+
+				} );
+
+				stats = new Stats();
+				document.body.appendChild( stats.dom );
+
+				window.addEventListener( 'resize', onWindowResize );
+
+			}
+
+			function onWindowResize() {
+
+				camera.aspect = window.innerWidth / window.innerHeight;
+				camera.updateProjectionMatrix();
+
+				renderer.setSize( window.innerWidth, window.innerHeight );
+
+			}
+
+			function onPointerDown( event ) {
+
+				action = ACTION_SELECT;
+				mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
+				mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
+
+			}
+
+			function animate() {
+
+				if ( action === ACTION_SELECT ) {
+
+					rayCaster.setFromCamera( mouse, camera );
+					action = ACTION_NONE;
+					const intersects = rayCaster.intersectObjects( curveHandles, false );
+					if ( intersects.length ) {
+
+						const target = intersects[ 0 ].object;
+						control.attach( target );
+						scene.add( control.getHelper() );
+
+					}
+
+				}
+
+				if ( flow ) {
+
+					flow.moveAlongCurve( 0.001 );
+
+				}
+
+				render();
+
+			}
+
+			function render() {
+
+				renderer.render( scene, camera );
+
+				stats.update();
+
+			}
+		</script>
+	</body>
+</html>

粤ICP备19079148号