webgpu_compute_particles_snow.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute Particles Snow</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 - Compute Snow - 100K Particles
  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, vec3, pass, color, uint, viewportTopLeft, positionWorld, positionLocal, timerLocal, vec2, MeshStandardNodeMaterial, instanceIndex, storage, MeshBasicNodeMaterial, If } from 'three/nodes';
  24. import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js';
  25. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  26. import WebGL from 'three/addons/capabilities/WebGL.js';
  27. import WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';
  28. import StorageInstancedBufferAttribute from 'three/addons/renderers/common/StorageInstancedBufferAttribute.js';
  29. import PostProcessing from 'three/addons/renderers/common/PostProcessing.js';
  30. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  31. import Stats from 'three/addons/libs/stats.module.js';
  32. const maxParticleCount = 100000;
  33. let camera, scene, renderer;
  34. let controls, stats;
  35. let computeParticles;
  36. let postProcessing;
  37. let collisionCamera, collisionPosRT, collisionPosMaterial;
  38. init();
  39. function init() {
  40. if ( WebGPU.isAvailable() === false && WebGL.isWebGL2Available() === false ) {
  41. document.body.appendChild( WebGPU.getErrorMessage() );
  42. throw new Error( 'No WebGPU or WebGL2 support' );
  43. }
  44. const { innerWidth, innerHeight } = window;
  45. camera = new THREE.PerspectiveCamera( 60, innerWidth / innerHeight, .1, 100 );
  46. camera.position.set( 20, 2, 20 );
  47. camera.layers.enable( 2 );
  48. camera.lookAt( 0, 40, 0 );
  49. scene = new THREE.Scene();
  50. scene.fog = new THREE.Fog( 0x0f3c37, 5, 40 );
  51. const dirLight = new THREE.DirectionalLight( 0xf9ff9b, 9 );
  52. dirLight.castShadow = true;
  53. dirLight.position.set( 10, 10, 0 );
  54. dirLight.castShadow = true;
  55. dirLight.shadow.camera.near = 1;
  56. dirLight.shadow.camera.far = 30;
  57. dirLight.shadow.camera.right = 30;
  58. dirLight.shadow.camera.left = - 30;
  59. dirLight.shadow.camera.top = 30;
  60. dirLight.shadow.camera.bottom = - 30;
  61. dirLight.shadow.mapSize.width = 2048;
  62. dirLight.shadow.mapSize.height = 2048;
  63. dirLight.shadow.bias = - 0.009;
  64. scene.add( dirLight );
  65. scene.add( new THREE.HemisphereLight( 0x0f3c37, 0x080d10, 100 ) );
  66. //
  67. collisionCamera = new THREE.OrthographicCamera( - 50, 50, 50, - 50, .1, 50 );
  68. collisionCamera.position.y = 50;
  69. collisionCamera.lookAt( 0, 0, 0 );
  70. collisionCamera.layers.enable( 1 );
  71. collisionPosRT = new THREE.RenderTarget( 1024, 1024 );
  72. collisionPosRT.texture.type = THREE.HalfFloatType;
  73. collisionPosMaterial = new MeshBasicNodeMaterial();
  74. collisionPosMaterial.fog = false;
  75. collisionPosMaterial.toneMapped = false;
  76. collisionPosMaterial.colorNode = positionWorld.y;
  77. //
  78. const createBuffer = ( type = 'vec3' ) => storage( new StorageInstancedBufferAttribute( maxParticleCount, type === 'vec4' ? 4 : 3 ), type, maxParticleCount );
  79. const positionBuffer = createBuffer();
  80. const scaleBuffer = createBuffer();
  81. const staticPositionBuffer = createBuffer();
  82. const dataBuffer = createBuffer( 'vec4' );
  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 scale = scaleBuffer.element( instanceIndex );
  89. const particleData = dataBuffer.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( 500 ).add( 3 );
  95. position.z = randZ.mul( 100 ).add( - 50 );
  96. scale.xyz = instanceIndex.add( Math.random() ).hash().mul( .8 ).add( .2 );
  97. staticPositionBuffer.element( instanceIndex ).assign( vec3( 1000, 10000, 1000 ) );
  98. particleData.y = randY.mul( - .1 ).add( - .02 );
  99. particleData.x = position.x;
  100. particleData.z = position.z;
  101. particleData.w = randX;
  102. } )().compute( maxParticleCount );
  103. //
  104. const surfaceOffset = .2;
  105. const speed = .4;
  106. const computeUpdate = tslFn( () => {
  107. const getCoord = ( pos ) => pos.add( 50 ).div( 100 );
  108. const position = positionBuffer.element( instanceIndex );
  109. const scale = scaleBuffer.element( instanceIndex );
  110. const particleData = dataBuffer.element( instanceIndex );
  111. const velocity = particleData.y;
  112. const random = particleData.w;
  113. const rippleOnSurface = texture( collisionPosRT.texture, getCoord( position.xz ) );
  114. const rippleFloorArea = rippleOnSurface.y.add( scale.x.mul( surfaceOffset ) );
  115. If( position.y.greaterThan( rippleFloorArea ), () => {
  116. position.x = particleData.x.add( timer.mul( random.mul( random ) ).mul( speed ).sin().mul( 3 ) );
  117. position.z = particleData.z.add( timer.mul( random ).mul( speed ).cos().mul( random.mul( 10 ) ) );
  118. position.y = position.y.add( velocity );
  119. } ).else( () => {
  120. staticPositionBuffer.element( instanceIndex ).assign( position );
  121. } );
  122. } );
  123. computeParticles = computeUpdate().compute( maxParticleCount );
  124. // rain
  125. const geometry = new THREE.SphereGeometry( surfaceOffset, 5, 5 );
  126. function particle( staticParticles ) {
  127. const posBuffer = staticParticles ? staticPositionBuffer : positionBuffer;
  128. const layer = staticParticles ? 1 : 2;
  129. const staticMaterial = new MeshStandardNodeMaterial( {
  130. color: 0xeeeeee,
  131. roughness: .9,
  132. metalness: 0
  133. } );
  134. staticMaterial.positionNode = positionLocal.mul( scaleBuffer.toAttribute() ).add( posBuffer.toAttribute() );
  135. const rainParticles = new THREE.Mesh( geometry, staticMaterial );
  136. rainParticles.isInstancedMesh = true;
  137. rainParticles.count = maxParticleCount;
  138. rainParticles.castShadow = true;
  139. rainParticles.layers.disableAll();
  140. rainParticles.layers.enable( layer );
  141. return rainParticles;
  142. }
  143. const dynamicParticles = particle();
  144. const staticParticles = particle( true );
  145. scene.add( dynamicParticles );
  146. scene.add( staticParticles );
  147. // floor geometry
  148. const floorGeometry = new THREE.PlaneGeometry( 100, 100 );
  149. floorGeometry.rotateX( - Math.PI / 2 );
  150. const plane = new THREE.Mesh( floorGeometry, new THREE.MeshStandardMaterial( {
  151. color: 0x0c1e1e,
  152. roughness: .5,
  153. metalness: 0,
  154. transparent: true
  155. } ) );
  156. plane.material.opacityNode = positionLocal.xz.mul( .05 ).distance( 0 ).saturate().oneMinus();
  157. scene.add( plane );
  158. // tree
  159. function tree( count = 8 ) {
  160. const coneMaterial = new MeshStandardNodeMaterial( {
  161. color: 0x0d492c,
  162. roughness: .6,
  163. metalness: 0
  164. } );
  165. const object = new THREE.Group();
  166. for ( let i = 0; i < count; i ++ ) {
  167. const radius = 1 + i;
  168. const coneGeometry = new THREE.ConeGeometry( radius * 0.95, radius * 1.25, 32 );
  169. const cone = new THREE.Mesh( coneGeometry, coneMaterial );
  170. cone.castShadow = true;
  171. cone.position.y = ( ( count - i ) * 1.5 ) + ( count * .6 );
  172. object.add( cone );
  173. }
  174. const geometry = new THREE.CylinderGeometry( 1, 1, count, 32 );
  175. const cone = new THREE.Mesh( geometry, coneMaterial );
  176. cone.position.y = count / 2;
  177. object.add( cone );
  178. return object;
  179. }
  180. const teapotTree = new THREE.Mesh( new TeapotGeometry( .5, 18 ), new MeshBasicNodeMaterial( {
  181. color: 0xfcfb9e
  182. } ) );
  183. teapotTree.position.y = 18;
  184. scene.add( tree() );
  185. scene.add( teapotTree );
  186. //
  187. scene.backgroundNode = viewportTopLeft.distance( .5 ).mul( 2 ).mix( color( 0x0f4140 ), color( 0x060a0d ) );
  188. //
  189. renderer = new WebGPURenderer( { antialias: true } );
  190. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  191. renderer.setPixelRatio( window.devicePixelRatio );
  192. renderer.setSize( window.innerWidth, window.innerHeight );
  193. renderer.setAnimationLoop( animate );
  194. document.body.appendChild( renderer.domElement );
  195. stats = new Stats();
  196. document.body.appendChild( stats.dom );
  197. // post processing
  198. const scenePass = pass( scene, camera );
  199. const scenePassColor = scenePass.getTextureNode();
  200. const vignet = viewportTopLeft.distance( .5 ).mul( 1.35 ).clamp().oneMinus();
  201. const teapotTreePass = pass( teapotTree, camera ).getTextureNode();
  202. const teapotTreePassBlurred = teapotTreePass.gaussianBlur( 3 );
  203. teapotTreePassBlurred.resolution = new THREE.Vector2( .2, .2 );
  204. const scenePassColorBlurred = scenePassColor.gaussianBlur();
  205. scenePassColorBlurred.resolution = new THREE.Vector2( .5, .5 );
  206. scenePassColorBlurred.directionNode = vec2( 1 );
  207. // compose
  208. let totalPass = scenePass;
  209. totalPass = totalPass.add( scenePassColorBlurred.mul( .1 ) );
  210. totalPass = totalPass.mul( vignet );
  211. totalPass = totalPass.add( teapotTreePass.mul( 10 ).add( teapotTreePassBlurred ) );
  212. postProcessing = new PostProcessing( renderer );
  213. postProcessing.outputNode = totalPass;
  214. //
  215. renderer.compute( computeInit );
  216. //
  217. controls = new OrbitControls( camera, renderer.domElement );
  218. controls.target.set( 0, 10, 0 );
  219. controls.minDistance = 25;
  220. controls.maxDistance = 35;
  221. controls.maxPolarAngle = Math.PI / 1.7;
  222. controls.autoRotate = true;
  223. controls.autoRotateSpeed = - 0.7;
  224. controls.update();
  225. //
  226. window.addEventListener( 'resize', onWindowResize );
  227. }
  228. function onWindowResize() {
  229. const { innerWidth, innerHeight } = window;
  230. camera.aspect = innerWidth / innerHeight;
  231. camera.updateProjectionMatrix();
  232. renderer.setSize( innerWidth, innerHeight );
  233. }
  234. function animate() {
  235. stats.update();
  236. controls.update();
  237. // position
  238. scene.overrideMaterial = collisionPosMaterial;
  239. renderer.setRenderTarget( collisionPosRT );
  240. renderer.render( scene, collisionCamera );
  241. // compute
  242. renderer.compute( computeParticles );
  243. // result
  244. scene.overrideMaterial = null;
  245. renderer.setRenderTarget( null );
  246. postProcessing.render();
  247. }
  248. </script>
  249. </body>
  250. </html>