webgpu_compute_particles_snow.html 10 KB

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