webgpu_compute_cloth.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute cloth</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <meta property="og:title" content="three.js webgpu - compute cloth">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_compute_cloth.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_compute_cloth.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  16. <div class="title-wrapper">
  17. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Compute Cloth</span>
  18. </div>
  19. <small>Simple cloth simulation with a verlet system running in compute shaders.</small>
  20. </div>
  21. <script type="importmap">
  22. {
  23. "imports": {
  24. "three": "../build/three.webgpu.js",
  25. "three/webgpu": "../build/three.webgpu.js",
  26. "three/tsl": "../build/three.tsl.js",
  27. "three/addons/": "./jsm/"
  28. }
  29. }
  30. </script>
  31. <script type="module">
  32. import * as THREE from 'three/webgpu';
  33. import { Fn, If, Return, instancedArray, instanceIndex, uniform, select, attribute, Loop, float, transformNormalToView, cross, triNoise3D, time } from 'three/tsl';
  34. import { Inspector } from 'three/addons/inspector/Inspector.js';
  35. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  36. import { UltraHDRLoader } from 'three/addons/loaders/UltraHDRLoader.js';
  37. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  38. let renderer, scene, camera, controls;
  39. const clothWidth = 1;
  40. const clothHeight = 1;
  41. const clothNumSegmentsX = 30;
  42. const clothNumSegmentsY = 30;
  43. const sphereRadius = 0.15;
  44. let vertexPositionBuffer, vertexForceBuffer, vertexParamsBuffer;
  45. let springVertexIdBuffer, springRestLengthBuffer, springForceBuffer;
  46. let springListBuffer;
  47. let computeSpringForces, computeVertexForces;
  48. let dampeningUniform, spherePositionUniform, stiffnessUniform, sphereUniform, windUniform;
  49. let vertexWireframeObject, springWireframeObject;
  50. let clothMesh, clothMaterial, sphere;
  51. let timeSinceLastStep = 0;
  52. let timestamp = 0;
  53. const verletVertices = [];
  54. const verletSprings = [];
  55. const verletVertexColumns = [];
  56. const timer = new THREE.Timer();
  57. timer.connect( document );
  58. const params = {
  59. wireframe: false,
  60. sphere: true,
  61. wind: 1.0,
  62. };
  63. const API = {
  64. color: 0x204080, // sRGB
  65. sheenColor: 0xffffff // sRGB
  66. };
  67. // TODO: Fix example with WebGL backend
  68. if ( WebGPU.isAvailable() === false ) {
  69. document.body.appendChild( WebGPU.getErrorMessage() );
  70. throw new Error( 'No WebGPU support' );
  71. }
  72. init();
  73. async function init() {
  74. renderer = new THREE.WebGPURenderer( { antialias: true, requiredLimits: { maxStorageBuffersInVertexStage: 1 } } );
  75. renderer.setPixelRatio( window.devicePixelRatio );
  76. renderer.setSize( window.innerWidth, window.innerHeight );
  77. renderer.toneMapping = THREE.NeutralToneMapping;
  78. renderer.toneMappingExposure = 1;
  79. renderer.inspector = new Inspector();
  80. document.body.appendChild( renderer.domElement );
  81. scene = new THREE.Scene();
  82. camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.01, 10 );
  83. camera.position.set( - 1.6, - 0.1, - 1.6 );
  84. controls = new OrbitControls( camera, renderer.domElement );
  85. controls.minDistance = 1;
  86. controls.maxDistance = 3;
  87. controls.target.set( 0, - 0.1, 0 );
  88. controls.update();
  89. const hdrLoader = new UltraHDRLoader().setPath( 'textures/equirectangular/' );
  90. const hdrTexture = await hdrLoader.loadAsync( 'royal_esplanade_2k.hdr.jpg' );
  91. hdrTexture.mapping = THREE.EquirectangularReflectionMapping;
  92. scene.background = hdrTexture;
  93. scene.backgroundBlurriness = 0.5;
  94. scene.environment = hdrTexture;
  95. setupCloth();
  96. const gui = renderer.inspector.createParameters( 'Settings' );
  97. gui.add( stiffnessUniform, 'value', 0.1, 0.5, 0.01 ).name( 'stiffness' );
  98. gui.add( params, 'wireframe' );
  99. gui.add( params, 'sphere' );
  100. gui.add( params, 'wind', 0, 5, 0.1 );
  101. const materialFolder = gui.addFolder( 'material' );
  102. materialFolder.addColor( API, 'color' ).onChange( function ( color ) {
  103. clothMaterial.color.setHex( color );
  104. } );
  105. materialFolder.add( clothMaterial, 'roughness', 0.0, 1, 0.01 );
  106. materialFolder.add( clothMaterial, 'sheen', 0.0, 1, 0.01 );
  107. materialFolder.add( clothMaterial, 'sheenRoughness', 0.0, 1, 0.01 );
  108. materialFolder.addColor( API, 'sheenColor' ).onChange( function ( color ) {
  109. clothMaterial.sheenColor.setHex( color );
  110. } );
  111. window.addEventListener( 'resize', onWindowResize );
  112. renderer.setAnimationLoop( render );
  113. }
  114. function setupVerletGeometry() {
  115. // this function sets up the geometry of the verlet system, a grid of vertices connected by springs
  116. const addVerletVertex = ( x, y, z, isFixed ) => {
  117. const id = verletVertices.length;
  118. const vertex = {
  119. id,
  120. position: new THREE.Vector3( x, y, z ),
  121. isFixed,
  122. springIds: [],
  123. };
  124. verletVertices.push( vertex );
  125. return vertex;
  126. };
  127. const addVerletSpring = ( vertex0, vertex1 ) => {
  128. const id = verletSprings.length;
  129. const spring = {
  130. id,
  131. vertex0,
  132. vertex1
  133. };
  134. vertex0.springIds.push( id );
  135. vertex1.springIds.push( id );
  136. verletSprings.push( spring );
  137. return spring;
  138. };
  139. // create the cloth's verlet vertices
  140. for ( let x = 0; x <= clothNumSegmentsX; x ++ ) {
  141. const column = [];
  142. for ( let y = 0; y <= clothNumSegmentsY; y ++ ) {
  143. const posX = x * ( clothWidth / clothNumSegmentsX ) - clothWidth * 0.5;
  144. const posZ = y * ( clothHeight / clothNumSegmentsY );
  145. const isFixed = ( y === 0 ) && ( ( x % 5 ) === 0 ); // make some of the top vertices' positions fixed
  146. const vertex = addVerletVertex( posX, clothHeight * 0.5, posZ, isFixed );
  147. column.push( vertex );
  148. }
  149. verletVertexColumns.push( column );
  150. }
  151. // create the cloth's verlet springs
  152. for ( let x = 0; x <= clothNumSegmentsX; x ++ ) {
  153. for ( let y = 0; y <= clothNumSegmentsY; y ++ ) {
  154. const vertex0 = verletVertexColumns[ x ][ y ];
  155. if ( x > 0 ) addVerletSpring( vertex0, verletVertexColumns[ x - 1 ][ y ] );
  156. if ( y > 0 ) addVerletSpring( vertex0, verletVertexColumns[ x ][ y - 1 ] );
  157. if ( x > 0 && y > 0 ) addVerletSpring( vertex0, verletVertexColumns[ x - 1 ][ y - 1 ] );
  158. if ( x > 0 && y < clothNumSegmentsY ) addVerletSpring( vertex0, verletVertexColumns[ x - 1 ][ y + 1 ] );
  159. // You can make the cloth more rigid by adding more springs between further apart vertices
  160. //if (x > 1) addVerletSpring(vertex0, verletVertexColumns[x - 2][y]);
  161. //if (y > 1) addVerletSpring(vertex0, verletVertexColumns[x][y - 2]);
  162. }
  163. }
  164. }
  165. function setupVerletVertexBuffers() {
  166. // setup the buffers holding the vertex data for the compute shaders
  167. const vertexCount = verletVertices.length;
  168. const springListArray = [];
  169. // this springListArray will hold a list of spring ids, ordered by the id of the vertex affected by that spring.
  170. // this is so the compute shader that accumulates the spring forces for each vertex can efficiently iterate over all springs affecting that vertex
  171. const vertexPositionArray = new Float32Array( vertexCount * 3 );
  172. const vertexParamsArray = new Uint32Array( vertexCount * 3 );
  173. // the params Array holds three values for each verlet vertex:
  174. // x: isFixed, y: springCount, z: springPointer
  175. // isFixed is 1 if the verlet is marked as immovable, 0 if not
  176. // springCount is the number of springs connected to that vertex
  177. // springPointer is the index of the first spring in the springListArray that is connected to that vertex
  178. for ( let i = 0; i < vertexCount; i ++ ) {
  179. const vertex = verletVertices[ i ];
  180. vertexPositionArray[ i * 3 ] = vertex.position.x;
  181. vertexPositionArray[ i * 3 + 1 ] = vertex.position.y;
  182. vertexPositionArray[ i * 3 + 2 ] = vertex.position.z;
  183. vertexParamsArray[ i * 3 ] = vertex.isFixed ? 1 : 0;
  184. if ( ! vertex.isFixed ) {
  185. vertexParamsArray[ i * 3 + 1 ] = vertex.springIds.length;
  186. vertexParamsArray[ i * 3 + 2 ] = springListArray.length;
  187. springListArray.push( ...vertex.springIds );
  188. }
  189. }
  190. vertexPositionBuffer = instancedArray( vertexPositionArray, 'vec3' ).setPBO( true ); // setPBO(true) is only important for the WebGL Fallback
  191. vertexForceBuffer = instancedArray( vertexCount, 'vec3' );
  192. vertexParamsBuffer = instancedArray( vertexParamsArray, 'uvec3' );
  193. springListBuffer = instancedArray( new Uint32Array( springListArray ), 'uint' ).setPBO( true );
  194. }
  195. function setupVerletSpringBuffers() {
  196. // setup the buffers holding the spring data for the compute shaders
  197. const springCount = verletSprings.length;
  198. const springVertexIdArray = new Uint32Array( springCount * 2 );
  199. const springRestLengthArray = new Float32Array( springCount );
  200. for ( let i = 0; i < springCount; i ++ ) {
  201. const spring = verletSprings[ i ];
  202. springVertexIdArray[ i * 2 ] = spring.vertex0.id;
  203. springVertexIdArray[ i * 2 + 1 ] = spring.vertex1.id;
  204. springRestLengthArray[ i ] = spring.vertex0.position.distanceTo( spring.vertex1.position );
  205. }
  206. springVertexIdBuffer = instancedArray( springVertexIdArray, 'uvec2' ).setPBO( true );
  207. springRestLengthBuffer = instancedArray( springRestLengthArray, 'float' );
  208. springForceBuffer = instancedArray( springCount * 3, 'vec3' ).setPBO( true );
  209. }
  210. function setupUniforms() {
  211. dampeningUniform = uniform( 0.99 );
  212. spherePositionUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  213. sphereUniform = uniform( 1.0 );
  214. windUniform = uniform( 1.0 );
  215. stiffnessUniform = uniform( 0.2 );
  216. }
  217. function setupComputeShaders() {
  218. // This function sets up the compute shaders for the verlet simulation
  219. // There are two shaders that are executed for each simulation step
  220. const vertexCount = verletVertices.length;
  221. const springCount = verletSprings.length;
  222. // 1. computeSpringForces:
  223. // This shader computes a force for each spring, depending on the distance between the two vertices connected by that spring and the targeted rest length
  224. computeSpringForces = Fn( () => {
  225. const vertexIds = springVertexIdBuffer.element( instanceIndex );
  226. const restLength = springRestLengthBuffer.element( instanceIndex );
  227. const vertex0Position = vertexPositionBuffer.element( vertexIds.x );
  228. const vertex1Position = vertexPositionBuffer.element( vertexIds.y );
  229. const delta = vertex1Position.sub( vertex0Position ).toVar();
  230. const dist = delta.length().max( 0.000001 ).toVar();
  231. const force = dist.sub( restLength ).mul( stiffnessUniform ).mul( delta ).mul( 0.5 ).div( dist );
  232. springForceBuffer.element( instanceIndex ).assign( force );
  233. } )().compute( springCount ).setName( 'Spring Forces' );
  234. // 2. computeVertexForces:
  235. // This shader accumulates the force for each vertex.
  236. // First it iterates over all springs connected to this vertex and accumulates their forces.
  237. // Then it adds a gravital force, wind force, and the collision with the sphere.
  238. // In the end it adds the force to the vertex' position.
  239. computeVertexForces = Fn( () => {
  240. const params = vertexParamsBuffer.element( instanceIndex ).toVar();
  241. const isFixed = params.x;
  242. const springCount = params.y;
  243. const springPointer = params.z;
  244. If( isFixed, () => {
  245. // don't need to calculate vertex forces if the vertex is set as immovable
  246. Return();
  247. } );
  248. const position = vertexPositionBuffer.element( instanceIndex ).toVar( 'vertexPosition' );
  249. const force = vertexForceBuffer.element( instanceIndex ).toVar( 'vertexForce' );
  250. force.mulAssign( dampeningUniform );
  251. const ptrStart = springPointer.toVar( 'ptrStart' );
  252. const ptrEnd = ptrStart.add( springCount ).toVar( 'ptrEnd' );
  253. Loop( { start: ptrStart, end: ptrEnd, type: 'uint', condition: '<' }, ( { i } ) => {
  254. const springId = springListBuffer.element( i ).toVar( 'springId' );
  255. const springForce = springForceBuffer.element( springId );
  256. const springVertexIds = springVertexIdBuffer.element( springId );
  257. const factor = select( springVertexIds.x.equal( instanceIndex ), 1.0, - 1.0 );
  258. force.addAssign( springForce.mul( factor ) );
  259. } );
  260. // gravity
  261. force.y.subAssign( 0.00005 );
  262. // wind
  263. const noise = triNoise3D( position, 1, time ).sub( 0.2 ).mul( 0.0001 );
  264. const windForce = noise.mul( windUniform );
  265. force.z.subAssign( windForce );
  266. // collision with sphere
  267. const deltaSphere = position.add( force ).sub( spherePositionUniform );
  268. const dist = deltaSphere.length();
  269. const sphereForce = float( sphereRadius ).sub( dist ).max( 0 ).mul( deltaSphere ).div( dist ).mul( sphereUniform );
  270. force.addAssign( sphereForce );
  271. vertexForceBuffer.element( instanceIndex ).assign( force );
  272. vertexPositionBuffer.element( instanceIndex ).addAssign( force );
  273. } )().compute( vertexCount ).setName( 'Vertex Forces' );
  274. }
  275. function setupWireframe() {
  276. // adds helpers to visualize the verlet system
  277. // verlet vertex visualizer
  278. const vertexWireframeMaterial = new THREE.SpriteNodeMaterial();
  279. vertexWireframeMaterial.positionNode = vertexPositionBuffer.element( instanceIndex );
  280. vertexWireframeObject = new THREE.Mesh( new THREE.PlaneGeometry( 0.01, 0.01 ), vertexWireframeMaterial );
  281. vertexWireframeObject.frustumCulled = false;
  282. vertexWireframeObject.count = verletVertices.length;
  283. scene.add( vertexWireframeObject );
  284. // verlet spring visualizer
  285. const springWireframePositionBuffer = new THREE.BufferAttribute( new Float32Array( 6 ), 3, false );
  286. const springWireframeIndexBuffer = new THREE.BufferAttribute( new Uint32Array( [ 0, 1 ] ), 1, false );
  287. const springWireframeMaterial = new THREE.LineBasicNodeMaterial();
  288. springWireframeMaterial.positionNode = Fn( () => {
  289. const vertexIds = springVertexIdBuffer.element( instanceIndex );
  290. const vertexId = select( attribute( 'vertexIndex' ).equal( 0 ), vertexIds.x, vertexIds.y );
  291. return vertexPositionBuffer.element( vertexId );
  292. } )();
  293. const springWireframeGeometry = new THREE.InstancedBufferGeometry();
  294. springWireframeGeometry.setAttribute( 'position', springWireframePositionBuffer );
  295. springWireframeGeometry.setAttribute( 'vertexIndex', springWireframeIndexBuffer );
  296. springWireframeGeometry.instanceCount = verletSprings.length;
  297. springWireframeObject = new THREE.Line( springWireframeGeometry, springWireframeMaterial );
  298. springWireframeObject.frustumCulled = false;
  299. springWireframeObject.count = verletSprings.length;
  300. scene.add( springWireframeObject );
  301. }
  302. function setupSphere() {
  303. const geometry = new THREE.IcosahedronGeometry( sphereRadius * 0.95, 4 );
  304. const material = new THREE.MeshStandardNodeMaterial();
  305. sphere = new THREE.Mesh( geometry, material );
  306. scene.add( sphere );
  307. }
  308. function setupClothMesh() {
  309. // This function generates a three Geometry and Mesh to render the cloth based on the verlet systems position data.
  310. // Therefore it creates a plane mesh, in which each vertex will be centered in the center of 4 verlet vertices.
  311. const vertexCount = clothNumSegmentsX * clothNumSegmentsY;
  312. const geometry = new THREE.BufferGeometry();
  313. // verletVertexIdArray will hold the 4 verlet vertex ids that contribute to each geometry vertex's position
  314. const verletVertexIdArray = new Uint32Array( vertexCount * 4 );
  315. const indices = [];
  316. const getIndex = ( x, y ) => {
  317. return y * clothNumSegmentsX + x;
  318. };
  319. for ( let x = 0; x < clothNumSegmentsX; x ++ ) {
  320. for ( let y = 0; y < clothNumSegmentsX; y ++ ) {
  321. const index = getIndex( x, y );
  322. verletVertexIdArray[ index * 4 ] = verletVertexColumns[ x ][ y ].id;
  323. verletVertexIdArray[ index * 4 + 1 ] = verletVertexColumns[ x + 1 ][ y ].id;
  324. verletVertexIdArray[ index * 4 + 2 ] = verletVertexColumns[ x ][ y + 1 ].id;
  325. verletVertexIdArray[ index * 4 + 3 ] = verletVertexColumns[ x + 1 ][ y + 1 ].id;
  326. if ( x > 0 && y > 0 ) {
  327. indices.push( getIndex( x, y ), getIndex( x - 1, y ), getIndex( x - 1, y - 1 ) );
  328. indices.push( getIndex( x, y ), getIndex( x - 1, y - 1 ), getIndex( x, y - 1 ) );
  329. }
  330. }
  331. }
  332. const verletVertexIdBuffer = new THREE.BufferAttribute( verletVertexIdArray, 4, false );
  333. const positionBuffer = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3, false );
  334. geometry.setAttribute( 'position', positionBuffer );
  335. geometry.setAttribute( 'vertexIds', verletVertexIdBuffer );
  336. geometry.setIndex( indices );
  337. clothMaterial = new THREE.MeshPhysicalNodeMaterial( {
  338. color: new THREE.Color().setHex( API.color ),
  339. side: THREE.DoubleSide,
  340. transparent: true,
  341. opacity: 0.85,
  342. sheen: 1.0,
  343. sheenRoughness: 0.5,
  344. sheenColor: new THREE.Color().setHex( API.sheenColor ),
  345. } );
  346. clothMaterial.positionNode = Fn( ( { material } ) => {
  347. // gather the position of the 4 verlet vertices and calculate the center position and normal from that
  348. const vertexIds = attribute( 'vertexIds' );
  349. const v0 = vertexPositionBuffer.element( vertexIds.x ).toVar();
  350. const v1 = vertexPositionBuffer.element( vertexIds.y ).toVar();
  351. const v2 = vertexPositionBuffer.element( vertexIds.z ).toVar();
  352. const v3 = vertexPositionBuffer.element( vertexIds.w ).toVar();
  353. const top = v0.add( v1 );
  354. const right = v1.add( v3 );
  355. const bottom = v2.add( v3 );
  356. const left = v0.add( v2 );
  357. const tangent = right.sub( left ).normalize();
  358. const bitangent = bottom.sub( top ).normalize();
  359. const normal = cross( tangent, bitangent );
  360. // send the normalView from the vertex shader to the fragment shader
  361. material.normalNode = transformNormalToView( normal ).toVarying();
  362. return v0.add( v1 ).add( v2 ).add( v3 ).mul( 0.25 );
  363. } )();
  364. clothMesh = new THREE.Mesh( geometry, clothMaterial );
  365. clothMesh.frustumCulled = false;
  366. scene.add( clothMesh );
  367. }
  368. function setupCloth() {
  369. setupVerletGeometry();
  370. setupVerletVertexBuffers();
  371. setupVerletSpringBuffers();
  372. setupUniforms();
  373. setupComputeShaders();
  374. setupWireframe();
  375. setupSphere();
  376. setupClothMesh();
  377. }
  378. function onWindowResize() {
  379. camera.aspect = window.innerWidth / window.innerHeight;
  380. camera.updateProjectionMatrix();
  381. renderer.setSize( window.innerWidth, window.innerHeight );
  382. }
  383. function updateSphere() {
  384. sphere.position.set( Math.sin( timestamp * 2.1 ) * 0.1, 0, Math.sin( timestamp * 0.8 ) );
  385. spherePositionUniform.value.copy( sphere.position );
  386. }
  387. async function render() {
  388. timer.update();
  389. sphere.visible = params.sphere;
  390. sphereUniform.value = params.sphere ? 1 : 0;
  391. windUniform.value = params.wind;
  392. clothMesh.visible = ! params.wireframe;
  393. vertexWireframeObject.visible = params.wireframe;
  394. springWireframeObject.visible = params.wireframe;
  395. const deltaTime = Math.min( timer.getDelta(), 1 / 60 ); // don't advance the time too far, for example when the window is out of focus
  396. const stepsPerSecond = 360; // ensure the same amount of simulation steps per second on all systems, independent of refresh rate
  397. const timePerStep = 1 / stepsPerSecond;
  398. timeSinceLastStep += deltaTime;
  399. while ( timeSinceLastStep >= timePerStep ) {
  400. // run a verlet system simulation step
  401. timestamp += timePerStep;
  402. timeSinceLastStep -= timePerStep;
  403. updateSphere();
  404. renderer.compute( computeSpringForces );
  405. renderer.compute( computeVertexForces );
  406. }
  407. renderer.render( scene, camera );
  408. }
  409. </script>
  410. </body>
  411. </html>
粤ICP备19079148号