webgpu_compute_particles_snow.html 11 KB

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