webgpu_compute_particles_snow.html 10 KB

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