webgpu_compute_particles_rain.html 12 KB

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