1
0

webgpu_compute_particles_rain.html 11 KB

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