webgpu_compute_particles_rain.html 10 KB

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