webgpu_compute_particles_rain.html 11 KB

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