webgpu_compute_particles_rain.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute Particles Rain</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <link type="text/css" rel="stylesheet" href="main.css">
  7. </head>
  8. <body>
  9. <div id="info">
  10. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - GPU Compute Rain
  11. </div>
  12. <script type="importmap">
  13. {
  14. "imports": {
  15. "three": "../build/three.module.js",
  16. "three/addons/": "./jsm/",
  17. "three/nodes": "./jsm/nodes/Nodes.js"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { tslFn, texture, uv, uint, positionWorld, modelWorldMatrix, cameraViewMatrix, timerLocal, timerDelta, cameraProjectionMatrix, vec2, instanceIndex, positionGeometry, storage, MeshBasicNodeMaterial, If } from 'three/nodes';
  24. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  25. import WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';
  26. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  27. import Stats from 'three/addons/libs/stats.module.js';
  28. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  29. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  30. const maxParticleCount = 50000;
  31. const instanceCount = maxParticleCount / 2;
  32. let camera, scene, renderer;
  33. let controls, stats;
  34. let computeParticles;
  35. let monkey;
  36. let clock;
  37. let collisionBox, collisionCamera, collisionPosRT, collisionPosMaterial;
  38. init();
  39. function init() {
  40. if ( WebGPU.isAvailable() === false ) {
  41. document.body.appendChild( WebGPU.getErrorMessage() );
  42. throw new Error( 'No WebGPU support' );
  43. }
  44. const { innerWidth, innerHeight } = window;
  45. camera = new THREE.PerspectiveCamera( 60, innerWidth / innerHeight, .1, 110 );
  46. camera.position.set( 40, 8, 0 );
  47. camera.lookAt( 0, 0, 0 );
  48. scene = new THREE.Scene();
  49. const dirLight = new THREE.DirectionalLight( 0xffffff, .5 );
  50. dirLight.castShadow = true;
  51. dirLight.position.set( 3, 12, 17 );
  52. dirLight.castShadow = true;
  53. dirLight.shadow.camera.near = 5;
  54. dirLight.shadow.camera.far = 50;
  55. dirLight.shadow.camera.right = 10;
  56. dirLight.shadow.camera.left = - 10;
  57. dirLight.shadow.camera.top = 10;
  58. dirLight.shadow.camera.bottom = - 10;
  59. dirLight.shadow.mapSize.width = 2048;
  60. dirLight.shadow.mapSize.height = 2048;
  61. dirLight.shadow.bias = - 0.01;
  62. scene.add( dirLight );
  63. scene.add( new THREE.AmbientLight( 0x111111 ) );
  64. //
  65. collisionCamera = new THREE.OrthographicCamera( - 50, 50, 50, - 50, .1, 50 );
  66. collisionCamera.position.y = 50;
  67. collisionCamera.lookAt( 0, 0, 0 );
  68. collisionCamera.layers.disableAll();
  69. collisionCamera.layers.enable( 1 );
  70. collisionPosRT = new THREE.RenderTarget( 1024, 1024 );
  71. collisionPosRT.texture.type = THREE.HalfFloatType;
  72. collisionPosMaterial = new MeshBasicNodeMaterial();
  73. collisionPosMaterial.colorNode = positionWorld;
  74. //
  75. const createBuffer = ( type = 'vec3' ) => storage( new THREE.InstancedBufferAttribute( new Float32Array( maxParticleCount * 4 ), 4 ), type, maxParticleCount );
  76. const positionBuffer = createBuffer();
  77. const velocityBuffer = createBuffer();
  78. const ripplePositionBuffer = createBuffer();
  79. const rippleTimeBuffer = createBuffer();
  80. // compute
  81. const timer = timerLocal();
  82. const randUint = () => uint( Math.random() * 0xFFFFFF );
  83. const computeInit = tslFn( () => {
  84. const position = positionBuffer.element( instanceIndex );
  85. const velocity = velocityBuffer.element( instanceIndex );
  86. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  87. const randX = instanceIndex.hash();
  88. const randY = instanceIndex.add( randUint() ).hash();
  89. const randZ = instanceIndex.add( randUint() ).hash();
  90. position.x = randX.mul( 100 ).add( - 50 );
  91. position.y = randY.mul( 25 );
  92. position.z = randZ.mul( 100 ).add( - 50 );
  93. velocity.y = randX.mul( - .04 ).add( - .2 );
  94. rippleTime.x = 1000;
  95. } )().compute( maxParticleCount );
  96. //
  97. const computeUpdate = tslFn( () => {
  98. const getCoord = ( pos ) => pos.add( 50 ).div( 100 );
  99. const position = positionBuffer.element( instanceIndex );
  100. const velocity = velocityBuffer.element( instanceIndex );
  101. const ripplePosition = ripplePositionBuffer.element( instanceIndex );
  102. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  103. position.addAssign( velocity );
  104. rippleTime.x = rippleTime.x.add( timerDelta().mul( 4 ) );
  105. //
  106. const collisionArea = texture( collisionPosRT.texture, getCoord( position.xz ) );
  107. const surfaceOffset = .05;
  108. const floorPosition = collisionArea.y.add( surfaceOffset );
  109. // floor
  110. const ripplePivotOffsetY = - .9;
  111. If( position.y.add( ripplePivotOffsetY ).lessThan( floorPosition ), () => {
  112. position.y = 25;
  113. ripplePosition.x = position.x;
  114. ripplePosition.y = floorPosition;
  115. ripplePosition.z = position.z;
  116. // reset hit time: x = time
  117. rippleTime.x = 1;
  118. // next drops will not fall in the same place
  119. position.x = instanceIndex.add( timer ).hash().mul( 100 ).add( - 50 );
  120. position.z = instanceIndex.add( timer.add( randUint() ) ).hash().mul( 100 ).add( - 50 );
  121. } );
  122. const rippleOnSurface = texture( collisionPosRT.texture, getCoord( ripplePosition.xz ) );
  123. const rippleFloorArea = rippleOnSurface.y.add( surfaceOffset );
  124. If( ripplePosition.y.greaterThan( rippleFloorArea ), () => {
  125. rippleTime.x = 1000;
  126. } );
  127. } );
  128. computeParticles = computeUpdate().compute( maxParticleCount );
  129. // rain
  130. const billboarding = tslFn( () => {
  131. const particlePosition = positionBuffer.toAttribute();
  132. const worldMatrix = modelWorldMatrix.toVar();
  133. worldMatrix[ 3 ][ 0 ] = particlePosition.x;
  134. worldMatrix[ 3 ][ 1 ] = particlePosition.y;
  135. worldMatrix[ 3 ][ 2 ] = particlePosition.z;
  136. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  137. modelViewMatrix[ 0 ][ 0 ] = 1;
  138. modelViewMatrix[ 0 ][ 1 ] = 0;
  139. modelViewMatrix[ 0 ][ 2 ] = 0;
  140. //modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  141. //modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  142. modelViewMatrix[ 2 ][ 0 ] = 0;
  143. modelViewMatrix[ 2 ][ 1 ] = 0;
  144. modelViewMatrix[ 2 ][ 2 ] = 1;
  145. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionGeometry );
  146. } );
  147. const rainMaterial = new MeshBasicNodeMaterial();
  148. rainMaterial.colorNode = uv().distance( vec2( .5, 0 ) ).oneMinus().mul( 3 ).exp().mul( .1 );
  149. rainMaterial.vertexNode = billboarding();
  150. rainMaterial.opacity = .2;
  151. rainMaterial.side = THREE.DoubleSide;
  152. rainMaterial.forceSinglePass = true;
  153. rainMaterial.depthWrite = false;
  154. rainMaterial.depthTest = true;
  155. rainMaterial.transparent = true;
  156. const rainParticles = new THREE.Mesh( new THREE.PlaneGeometry( .1, 2 ), rainMaterial );
  157. rainParticles.isInstancedMesh = true;
  158. rainParticles.count = instanceCount;
  159. scene.add( rainParticles );
  160. // ripple
  161. const rippleTime = rippleTimeBuffer.element( instanceIndex ).x;
  162. const rippleEffect = tslFn( () => {
  163. const center = uv().add( vec2( - .5 ) ).length().mul( 7 );
  164. const distance = rippleTime.sub( center );
  165. return distance.min( 1 ).sub( distance.max( 1 ).sub( 1 ) );
  166. } );
  167. const rippleMaterial = new MeshBasicNodeMaterial();
  168. rippleMaterial.colorNode = rippleEffect();
  169. rippleMaterial.positionNode = positionGeometry.add( ripplePositionBuffer.toAttribute() );
  170. rippleMaterial.opacityNode = rippleTime.mul( .3 ).oneMinus().max( 0 ).mul( .5 );
  171. rippleMaterial.side = THREE.DoubleSide;
  172. rippleMaterial.forceSinglePass = true;
  173. rippleMaterial.depthWrite = false;
  174. rippleMaterial.depthTest = true;
  175. rippleMaterial.transparent = true;
  176. // ripple geometry
  177. const surfaceRippleGeometry = new THREE.PlaneGeometry( 2.5, 2.5 );
  178. surfaceRippleGeometry.rotateX( - Math.PI / 2 );
  179. const xRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  180. xRippleGeometry.rotateY( - Math.PI / 2 );
  181. const zRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  182. const rippleGeometry = BufferGeometryUtils.mergeGeometries( [ surfaceRippleGeometry, xRippleGeometry, zRippleGeometry ] );
  183. const rippleParticles = new THREE.Mesh( rippleGeometry, rippleMaterial );
  184. rippleParticles.isInstancedMesh = true;
  185. rippleParticles.count = instanceCount;
  186. scene.add( rippleParticles );
  187. // floor geometry
  188. const floorGeometry = new THREE.PlaneGeometry( 1000, 1000 );
  189. floorGeometry.rotateX( - Math.PI / 2 );
  190. const plane = new THREE.Mesh( floorGeometry, new THREE.MeshBasicMaterial( { color: 0x050505 } ) );
  191. scene.add( plane );
  192. //
  193. collisionBox = new THREE.Mesh( new THREE.BoxGeometry( 30, 1, 15 ), new THREE.MeshStandardMaterial() );
  194. collisionBox.material.color.set( 0x333333 );
  195. collisionBox.position.y = 12;
  196. collisionBox.scale.x = 3.5;
  197. collisionBox.layers.enable( 1 );
  198. collisionBox.castShadow = true;
  199. scene.add( collisionBox );
  200. //
  201. const loader = new THREE.BufferGeometryLoader();
  202. loader.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  203. geometry.computeVertexNormals();
  204. monkey = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial( { roughness: 1, metalness: 0 } ) );
  205. monkey.receiveShadow = true;
  206. monkey.scale.setScalar( 5 );
  207. monkey.rotation.y = Math.PI / 2;
  208. monkey.position.y = 4.5;
  209. monkey.layers.enable( 1 ); // add to collision layer
  210. scene.add( monkey );
  211. } );
  212. //
  213. clock = new THREE.Clock();
  214. //
  215. renderer = new WebGPURenderer( { antialias: true } );
  216. renderer.setPixelRatio( window.devicePixelRatio );
  217. renderer.setSize( window.innerWidth, window.innerHeight );
  218. renderer.setAnimationLoop( animate );
  219. document.body.appendChild( renderer.domElement );
  220. stats = new Stats();
  221. document.body.appendChild( stats.dom );
  222. //
  223. renderer.compute( computeInit );
  224. //
  225. controls = new OrbitControls( camera, renderer.domElement );
  226. controls.minDistance = 5;
  227. controls.maxDistance = 50;
  228. controls.update();
  229. //
  230. window.addEventListener( 'resize', onWindowResize );
  231. // gui
  232. const gui = new GUI();
  233. gui.add( collisionBox.position, 'z', - 50, 50, .001 ).name( 'position' );
  234. gui.add( collisionBox.scale, 'x', .1, 3.5, 0.01 ).name( 'scale' );
  235. gui.add( rainParticles, 'count', 200, maxParticleCount, 1 ).name( 'drop count' ).onChange( ( v ) => rippleParticles.count = v );
  236. }
  237. function onWindowResize() {
  238. const { innerWidth, innerHeight } = window;
  239. camera.aspect = innerWidth / innerHeight;
  240. camera.updateProjectionMatrix();
  241. renderer.setSize( innerWidth, innerHeight );
  242. }
  243. function animate() {
  244. stats.update();
  245. if ( monkey ) {
  246. monkey.rotation.y += clock.getDelta();
  247. }
  248. // position
  249. scene.overrideMaterial = collisionPosMaterial;
  250. renderer.setRenderTarget( collisionPosRT );
  251. renderer.render( scene, collisionCamera );
  252. // compute
  253. renderer.compute( computeParticles );
  254. // result
  255. scene.overrideMaterial = null;
  256. renderer.setRenderTarget( null );
  257. renderer.render( scene, camera );
  258. }
  259. </script>
  260. </body>
  261. </html>