webgpu_compute_particles_rain.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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.layers.enable( 2 ); // @TODO: Fix .castShadow and remove it
  47. camera.position.set( 40, 8, 0 );
  48. camera.lookAt( 0, 0, 0 );
  49. scene = new THREE.Scene();
  50. const dirLight = new THREE.DirectionalLight( 0xffffff, .5 );
  51. dirLight.castShadow = true;
  52. dirLight.position.set( 3, 12, 17 );
  53. dirLight.castShadow = true;
  54. dirLight.shadow.camera.near = 5;
  55. dirLight.shadow.camera.far = 50;
  56. dirLight.shadow.camera.right = 10;
  57. dirLight.shadow.camera.left = - 10;
  58. dirLight.shadow.camera.top = 10;
  59. dirLight.shadow.camera.bottom = - 10;
  60. dirLight.shadow.mapSize.width = 2048;
  61. dirLight.shadow.mapSize.height = 2048;
  62. dirLight.shadow.bias = - 0.01;
  63. scene.add( dirLight );
  64. scene.add( new THREE.AmbientLight( 0x111111 ) );
  65. //
  66. collisionCamera = new THREE.OrthographicCamera( - 50, 50, 50, - 50, .1, 50 );
  67. collisionCamera.position.y = 50;
  68. collisionCamera.lookAt( 0, 0, 0 );
  69. collisionCamera.layers.disableAll();
  70. collisionCamera.layers.enable( 1 );
  71. collisionPosRT = new THREE.RenderTarget( 1024, 1024 );
  72. collisionPosRT.texture.type = THREE.HalfFloatType;
  73. collisionPosMaterial = new MeshBasicNodeMaterial();
  74. collisionPosMaterial.colorNode = positionWorld;
  75. //
  76. const createBuffer = ( type = 'vec3' ) => storage( new THREE.InstancedBufferAttribute( new Float32Array( maxParticleCount * 4 ), 4 ), type, maxParticleCount );
  77. const positionBuffer = createBuffer();
  78. const velocityBuffer = createBuffer();
  79. const ripplePositionBuffer = createBuffer();
  80. const rippleTimeBuffer = createBuffer();
  81. // compute
  82. const timer = timerLocal();
  83. const randUint = () => uint( Math.random() * 0xFFFFFF );
  84. const computeInit = tslFn( () => {
  85. const position = positionBuffer.element( instanceIndex );
  86. const velocity = velocityBuffer.element( instanceIndex );
  87. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  88. const randX = instanceIndex.hash();
  89. const randY = instanceIndex.add( randUint() ).hash();
  90. const randZ = instanceIndex.add( randUint() ).hash();
  91. position.x = randX.mul( 100 ).add( - 50 );
  92. position.y = randY.mul( 25 );
  93. position.z = randZ.mul( 100 ).add( - 50 );
  94. velocity.y = randX.mul( - .04 ).add( - .2 );
  95. rippleTime.x = 1000;
  96. } )().compute( maxParticleCount );
  97. //
  98. const computeUpdate = tslFn( () => {
  99. const getCoord = ( pos ) => pos.add( 50 ).div( 100 );
  100. const position = positionBuffer.element( instanceIndex );
  101. const velocity = velocityBuffer.element( instanceIndex );
  102. const ripplePosition = ripplePositionBuffer.element( instanceIndex );
  103. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  104. position.addAssign( velocity );
  105. rippleTime.x = rippleTime.x.add( timerDelta().mul( 4 ) );
  106. //
  107. const collisionArea = texture( collisionPosRT.texture, getCoord( position.xz ) );
  108. const surfaceOffset = .05;
  109. const floorPosition = collisionArea.y.add( surfaceOffset );
  110. // floor
  111. const ripplePivotOffsetY = - .9;
  112. If( position.y.add( ripplePivotOffsetY ).lessThan( floorPosition ), () => {
  113. position.y = 25;
  114. ripplePosition.x = position.x;
  115. ripplePosition.y = floorPosition;
  116. ripplePosition.z = position.z;
  117. // reset hit time: x = time
  118. rippleTime.x = 1;
  119. // next drops will not fall in the same place
  120. position.x = instanceIndex.add( timer ).hash().mul( 100 ).add( - 50 );
  121. position.z = instanceIndex.add( timer.add( randUint() ) ).hash().mul( 100 ).add( - 50 );
  122. } );
  123. const rippleOnSurface = texture( collisionPosRT.texture, getCoord( ripplePosition.xz ) );
  124. const rippleFloorArea = rippleOnSurface.y.add( surfaceOffset );
  125. If( ripplePosition.y.greaterThan( rippleFloorArea ), () => {
  126. rippleTime.x = 1000;
  127. } );
  128. } );
  129. computeParticles = computeUpdate().compute( maxParticleCount );
  130. // rain
  131. const billboarding = tslFn( () => {
  132. const particlePosition = positionBuffer.toAttribute();
  133. const worldMatrix = modelWorldMatrix.toVar();
  134. worldMatrix[ 3 ][ 0 ] = particlePosition.x;
  135. worldMatrix[ 3 ][ 1 ] = particlePosition.y;
  136. worldMatrix[ 3 ][ 2 ] = particlePosition.z;
  137. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  138. modelViewMatrix[ 0 ][ 0 ] = 1;
  139. modelViewMatrix[ 0 ][ 1 ] = 0;
  140. modelViewMatrix[ 0 ][ 2 ] = 0;
  141. //modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  142. //modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  143. modelViewMatrix[ 2 ][ 0 ] = 0;
  144. modelViewMatrix[ 2 ][ 1 ] = 0;
  145. modelViewMatrix[ 2 ][ 2 ] = 1;
  146. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionGeometry );
  147. } );
  148. const rainMaterial = new MeshBasicNodeMaterial();
  149. rainMaterial.colorNode = uv().distance( vec2( .5, 0 ) ).oneMinus().mul( 3 ).exp().mul( .1 );
  150. rainMaterial.vertexNode = billboarding();
  151. rainMaterial.opacity = .2;
  152. rainMaterial.side = THREE.DoubleSide;
  153. rainMaterial.forceSinglePass = true;
  154. rainMaterial.depthWrite = false;
  155. rainMaterial.depthTest = true;
  156. rainMaterial.transparent = true;
  157. const rainParticles = new THREE.Mesh( new THREE.PlaneGeometry( .1, 2 ), rainMaterial );
  158. rainParticles.isInstancedMesh = true;
  159. rainParticles.count = instanceCount;
  160. rainParticles.layers.disableAll();
  161. rainParticles.layers.enable( 2 );
  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. rippleParticles.layers.disableAll();
  190. rippleParticles.layers.enable( 2 );
  191. scene.add( rippleParticles );
  192. // floor geometry
  193. const floorGeometry = new THREE.PlaneGeometry( 1000, 1000 );
  194. floorGeometry.rotateX( - Math.PI / 2 );
  195. const plane = new THREE.Mesh( floorGeometry, new THREE.MeshBasicMaterial( { color: 0x050505 } ) );
  196. scene.add( plane );
  197. //
  198. collisionBox = new THREE.Mesh( new THREE.BoxGeometry( 30, 1, 15 ), new THREE.MeshStandardMaterial() );
  199. collisionBox.material.color.set( 0x333333 );
  200. collisionBox.position.y = 12;
  201. collisionBox.scale.x = 3.5;
  202. collisionBox.layers.enable( 1 );
  203. collisionBox.castShadow = true;
  204. scene.add( collisionBox );
  205. //
  206. const loader = new THREE.BufferGeometryLoader();
  207. loader.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  208. geometry.computeVertexNormals();
  209. monkey = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial( { roughness: 1, metalness: 0 } ) );
  210. monkey.receiveShadow = true;
  211. monkey.scale.setScalar( 5 );
  212. monkey.rotation.y = Math.PI / 2;
  213. monkey.position.y = 4.5;
  214. monkey.layers.enable( 1 ); // add to collision layer
  215. scene.add( monkey );
  216. } );
  217. //
  218. clock = new THREE.Clock();
  219. //
  220. renderer = new WebGPURenderer( { antialias: true } );
  221. renderer.setPixelRatio( window.devicePixelRatio );
  222. renderer.setSize( window.innerWidth, window.innerHeight );
  223. renderer.setAnimationLoop( animate );
  224. document.body.appendChild( renderer.domElement );
  225. stats = new Stats();
  226. document.body.appendChild( stats.dom );
  227. //
  228. renderer.compute( computeInit );
  229. //
  230. controls = new OrbitControls( camera, renderer.domElement );
  231. controls.minDistance = 5;
  232. controls.maxDistance = 50;
  233. controls.update();
  234. //
  235. window.addEventListener( 'resize', onWindowResize );
  236. // gui
  237. const gui = new GUI();
  238. gui.add( collisionBox.position, 'z', - 50, 50, .001 ).name( 'position' );
  239. gui.add( collisionBox.scale, 'x', .1, 3.5, 0.01 ).name( 'scale' );
  240. gui.add( rainParticles, 'count', 200, maxParticleCount, 1 ).name( 'drop count' ).onChange( ( v ) => rippleParticles.count = v );
  241. }
  242. function onWindowResize() {
  243. const { innerWidth, innerHeight } = window;
  244. camera.aspect = innerWidth / innerHeight;
  245. camera.updateProjectionMatrix();
  246. renderer.setSize( innerWidth, innerHeight );
  247. }
  248. function animate() {
  249. stats.update();
  250. if ( monkey ) {
  251. monkey.rotation.y += clock.getDelta();
  252. }
  253. // position
  254. scene.overrideMaterial = collisionPosMaterial;
  255. renderer.setRenderTarget( collisionPosRT );
  256. renderer.render( scene, collisionCamera );
  257. // compute
  258. renderer.compute( computeParticles );
  259. // result
  260. scene.overrideMaterial = null;
  261. renderer.setRenderTarget( null );
  262. renderer.render( scene, camera );
  263. }
  264. </script>
  265. </body>
  266. </html>