1
0

webgpu_tsl_vfx_linkedparticles.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - VFX Linked particles</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js webgpu</a> - VFX Linked particles
  12. <br>
  13. Based on <a href="https://github.com/ULuIQ12/webgpu-tsl-linkedparticles" target="_blank" rel="noopener">this experiment</a> by Christophe Choffel
  14. </div>
  15. <script type="importmap">
  16. {
  17. "imports": {
  18. "three": "../build/three.webgpu.js",
  19. "three/webgpu": "../build/three.webgpu.js",
  20. "three/tsl": "../build/three.tsl.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import { atan, cos, float, max, min, mix, PI, PI2, sin, vec2, vec3, color, Fn, hash, hue, If, instanceIndex, Loop, mx_fractal_noise_float, mx_fractal_noise_vec3, pass, pcurve, storage, deltaTime, time, uv, uniform, step } from 'three/tsl';
  28. import { bloom } from 'three/addons/tsl/display/BloomNode.js';
  29. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  30. import { Timer } from 'three/addons/misc/Timer.js';
  31. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  32. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  33. let camera, scene, renderer, postProcessing, controls, timer, light;
  34. let updateParticles, spawnParticles; // TSL compute nodes
  35. let getInstanceColor; // TSL function
  36. const screenPointer = new THREE.Vector2();
  37. const scenePointer = new THREE.Vector3();
  38. const raycastPlane = new THREE.Plane( new THREE.Vector3( 0, 0, 1 ), 0 );
  39. const raycaster = new THREE.Raycaster();
  40. const nbParticles = Math.pow( 2, 13 );
  41. const timeScale = uniform( 1.0 );
  42. const particleLifetime = uniform( 0.5 );
  43. const particleSize = uniform( 1.0 );
  44. const linksWidth = uniform( 0.005 );
  45. const colorOffset = uniform( 0.0 );
  46. const colorVariance = uniform( 2.0 );
  47. const colorRotationSpeed = uniform( 1.0 );
  48. const spawnIndex = uniform( 0 );
  49. const nbToSpawn = uniform( 5 );
  50. const spawnPosition = uniform( vec3( 0.0 ) );
  51. const previousSpawnPosition = uniform( vec3( 0.0 ) );
  52. const turbFrequency = uniform( 0.5 );
  53. const turbAmplitude = uniform( 0.5 );
  54. const turbOctaves = uniform( 2 );
  55. const turbLacunarity = uniform( 2.0 );
  56. const turbGain = uniform( 0.5 );
  57. const turbFriction = uniform( 0.01 );
  58. init();
  59. function init() {
  60. if ( WebGPU.isAvailable() === false ) {
  61. document.body.appendChild( WebGPU.getErrorMessage() );
  62. throw new Error( 'No WebGPU support' );
  63. }
  64. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 200 );
  65. camera.position.set( 0, 0, 10 );
  66. scene = new THREE.Scene();
  67. timer = new Timer();
  68. timer.connect( document );
  69. // renderer
  70. renderer = new THREE.WebGPURenderer( { antialias: true } );
  71. renderer.setClearColor( 0x14171a );
  72. renderer.setPixelRatio( window.devicePixelRatio );
  73. renderer.setSize( window.innerWidth, window.innerHeight );
  74. renderer.setAnimationLoop( animate );
  75. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  76. document.body.appendChild( renderer.domElement );
  77. // TSL function
  78. // current color from index
  79. getInstanceColor = /*#__PURE__*/ Fn( ( [ i ] ) => {
  80. return hue( color( 0x0000ff ), colorOffset.add( mx_fractal_noise_float( i.toFloat().mul( .1 ), 2, 2.0, 0.5, colorVariance ) ) );
  81. } );
  82. // Particles
  83. // storage buffers
  84. const particlePositions = storage( new THREE.StorageInstancedBufferAttribute( nbParticles, 4 ), 'vec4', nbParticles );
  85. const particleVelocities = storage( new THREE.StorageInstancedBufferAttribute( nbParticles, 4 ), 'vec4', nbParticles );
  86. // init particles buffers
  87. renderer.computeAsync( /*#__PURE__*/ Fn( () => {
  88. particlePositions.element( instanceIndex ).xyz.assign( vec3( 10000.0 ) );
  89. particlePositions.element( instanceIndex ).w.assign( vec3( - 1.0 ) ); // life is stored in w component; x<0 means dead
  90. } )().compute( nbParticles ) );
  91. // particles output
  92. const particleQuadSize = 0.05;
  93. const particleGeom = new THREE.PlaneGeometry( particleQuadSize, particleQuadSize );
  94. const particleMaterial = new THREE.SpriteNodeMaterial();
  95. particleMaterial.blending = THREE.AdditiveBlending;
  96. particleMaterial.depthWrite = false;
  97. particleMaterial.positionNode = particlePositions.toAttribute();
  98. particleMaterial.scaleNode = vec2( particleSize );
  99. particleMaterial.rotationNode = atan( particleVelocities.toAttribute().y, particleVelocities.toAttribute().x );
  100. particleMaterial.colorNode = /*#__PURE__*/ Fn( () => {
  101. const life = particlePositions.toAttribute().w;
  102. const modLife = pcurve( life.oneMinus(), 8.0, 1.0 );
  103. const pulse = pcurve(
  104. sin( hash( instanceIndex ).mul( PI2 ).add( time.mul( 0.5 ).mul( PI2 ) ) ).mul( 0.5 ).add( 0.5 ),
  105. 0.25,
  106. 0.25
  107. ).mul( 10.0 ).add( 1.0 );
  108. return getInstanceColor( instanceIndex ).mul( pulse.mul( modLife ) );
  109. } )();
  110. particleMaterial.opacityNode = /*#__PURE__*/ Fn( () => {
  111. const circle = step( uv().xy.sub( 0.5 ).length(), 0.5 );
  112. const life = particlePositions.toAttribute().w;
  113. return circle.mul( life );
  114. } )();
  115. const particleMesh = new THREE.InstancedMesh( particleGeom, particleMaterial, nbParticles );
  116. particleMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  117. particleMesh.frustumCulled = false;
  118. scene.add( particleMesh );
  119. // Links between particles
  120. // first, we define the indices for the links, 2 quads per particle, the indexation is fixed
  121. const linksIndices = [];
  122. for ( let i = 0; i < nbParticles; i ++ ) {
  123. const baseIndex = i * 8;
  124. for ( let j = 0; j < 2; j ++ ) {
  125. const offset = baseIndex + j * 4;
  126. linksIndices.push( offset, offset + 1, offset + 2, offset, offset + 2, offset + 3 );
  127. }
  128. }
  129. // storage buffers attributes for the links
  130. const nbVertices = nbParticles * 8;
  131. const linksVerticesSBA = new THREE.StorageBufferAttribute( nbVertices, 4 );
  132. const linksColorsSBA = new THREE.StorageBufferAttribute( nbVertices, 4 );
  133. // links output
  134. const linksGeom = new THREE.BufferGeometry();
  135. linksGeom.setAttribute( 'position', linksVerticesSBA );
  136. linksGeom.setAttribute( 'color', linksColorsSBA );
  137. linksGeom.setIndex( linksIndices );
  138. const linksMaterial = new THREE.MeshBasicNodeMaterial();
  139. linksMaterial.vertexColors = true;
  140. linksMaterial.side = THREE.DoubleSide;
  141. linksMaterial.transparent = true;
  142. linksMaterial.depthWrite = false;
  143. linksMaterial.depthTest = false;
  144. linksMaterial.blending = THREE.AdditiveBlending;
  145. linksMaterial.opacityNode = storage( linksColorsSBA, 'vec4', linksColorsSBA.count ).toAttribute().w;
  146. const linksMesh = new THREE.Mesh( linksGeom, linksMaterial );
  147. linksMesh.frustumCulled = false;
  148. scene.add( linksMesh );
  149. // compute nodes
  150. updateParticles = /*#__PURE__*/ Fn( () => {
  151. const position = particlePositions.element( instanceIndex ).xyz;
  152. const life = particlePositions.element( instanceIndex ).w;
  153. const velocity = particleVelocities.element( instanceIndex ).xyz;
  154. const dt = deltaTime.mul( 0.1 ).mul( timeScale );
  155. If( life.greaterThan( 0.0 ), () => {
  156. // first we update the particles positions and velocities
  157. // velocity comes from a turbulence field, and is multiplied by the particle lifetime so that it slows down over time
  158. const localVel = mx_fractal_noise_vec3( position.mul( turbFrequency ), turbOctaves, turbLacunarity, turbGain, turbAmplitude ).mul( life.add( .01 ) );
  159. velocity.addAssign( localVel );
  160. velocity.mulAssign( turbFriction.oneMinus() );
  161. position.addAssign( velocity.mul( dt ) );
  162. // then we decrease the lifetime
  163. life.subAssign( dt.mul( particleLifetime.reciprocal() ) );
  164. // then we find the two closest particles and set a quad to each of them
  165. const closestDist1 = float( 10000.0 ).toVar();
  166. const closestPos1 = vec3( 0.0 ).toVar();
  167. const closestLife1 = float( 0.0 ).toVar();
  168. const closestDist2 = float( 10000.0 ).toVar();
  169. const closestPos2 = vec3( 0.0 ).toVar();
  170. const closestLife2 = float( 0.0 ).toVar();
  171. Loop( nbParticles, ( { i } ) => {
  172. const otherPart = particlePositions.element( i );
  173. If( i.notEqual( instanceIndex ).and( otherPart.w.greaterThan( 0.0 ) ), () => { // if not self and other particle is alive
  174. const otherPosition = otherPart.xyz;
  175. const dist = position.sub( otherPosition ).lengthSq();
  176. const moreThanZero = dist.greaterThan( 0.0 );
  177. If( dist.lessThan( closestDist1 ).and( moreThanZero ), () => {
  178. closestDist1.assign( dist );
  179. closestPos1.assign( otherPosition.xyz );
  180. closestLife1.assign( otherPart.w );
  181. } ).ElseIf( dist.lessThan( closestDist2 ).and( moreThanZero ), () => {
  182. closestDist2.assign( dist );
  183. closestPos2.assign( otherPosition.xyz );
  184. closestLife2.assign( otherPart.w );
  185. } );
  186. } );
  187. } );
  188. // then we update the links correspondingly
  189. const linksPositions = storage( linksVerticesSBA, 'vec4', linksVerticesSBA.count );
  190. const linksColors = storage( linksColorsSBA, 'vec4', linksColorsSBA.count );
  191. const firstLinkIndex = instanceIndex.mul( 8 );
  192. const secondLinkIndex = firstLinkIndex.add( 4 );
  193. // positions link 1
  194. linksPositions.element( firstLinkIndex ).xyz.assign( position );
  195. linksPositions.element( firstLinkIndex ).y.addAssign( linksWidth );
  196. linksPositions.element( firstLinkIndex.add( 1 ) ).xyz.assign( position );
  197. linksPositions.element( firstLinkIndex.add( 1 ) ).y.addAssign( linksWidth.negate() );
  198. linksPositions.element( firstLinkIndex.add( 2 ) ).xyz.assign( closestPos1 );
  199. linksPositions.element( firstLinkIndex.add( 2 ) ).y.addAssign( linksWidth.negate() );
  200. linksPositions.element( firstLinkIndex.add( 3 ) ).xyz.assign( closestPos1 );
  201. linksPositions.element( firstLinkIndex.add( 3 ) ).y.addAssign( linksWidth );
  202. // positions link 2
  203. linksPositions.element( secondLinkIndex ).xyz.assign( position );
  204. linksPositions.element( secondLinkIndex ).y.addAssign( linksWidth );
  205. linksPositions.element( secondLinkIndex.add( 1 ) ).xyz.assign( position );
  206. linksPositions.element( secondLinkIndex.add( 1 ) ).y.addAssign( linksWidth.negate() );
  207. linksPositions.element( secondLinkIndex.add( 2 ) ).xyz.assign( closestPos2 );
  208. linksPositions.element( secondLinkIndex.add( 2 ) ).y.addAssign( linksWidth.negate() );
  209. linksPositions.element( secondLinkIndex.add( 3 ) ).xyz.assign( closestPos2 );
  210. linksPositions.element( secondLinkIndex.add( 3 ) ).y.addAssign( linksWidth );
  211. // colors are the same for all vertices of both quads
  212. const linkColor = getInstanceColor( instanceIndex );
  213. // store the minimum lifetime of the closest particles in the w component of colors
  214. const l1 = max( 0.0, min( closestLife1, life ) ).pow( 0.8 ); // pow is here to apply a slight curve to the opacity
  215. const l2 = max( 0.0, min( closestLife2, life ) ).pow( 0.8 );
  216. Loop( 4, ( { i } ) => {
  217. linksColors.element( firstLinkIndex.add( i ) ).xyz.assign( linkColor );
  218. linksColors.element( firstLinkIndex.add( i ) ).w.assign( l1 );
  219. linksColors.element( secondLinkIndex.add( i ) ).xyz.assign( linkColor );
  220. linksColors.element( secondLinkIndex.add( i ) ).w.assign( l2 );
  221. } );
  222. } );
  223. } )().compute( nbParticles );
  224. spawnParticles = /*#__PURE__*/ Fn( () => {
  225. const particleIndex = spawnIndex.add( instanceIndex ).mod( nbParticles ).toInt();
  226. const position = particlePositions.element( particleIndex ).xyz;
  227. const life = particlePositions.element( particleIndex ).w;
  228. const velocity = particleVelocities.element( particleIndex ).xyz;
  229. life.assign( 1.0 ); // sets it alive
  230. // random spherical direction
  231. const rRange = float( 0.01 );
  232. const rTheta = hash( particleIndex ).mul( PI2 );
  233. const rPhi = hash( particleIndex.add( 1 ) ).mul( PI );
  234. const rx = sin( rTheta ).mul( cos( rPhi ) );
  235. const ry = sin( rTheta ).mul( sin( rPhi ) );
  236. const rz = cos( rTheta );
  237. const rDir = vec3( rx, ry, rz );
  238. // position is interpolated between the previous cursor position and the current one over the number of particles spawned
  239. const pos = mix( previousSpawnPosition, spawnPosition, instanceIndex.toFloat().div( nbToSpawn.sub( 1 ).toFloat() ).clamp() );
  240. position.assign( pos.add( rDir.mul( rRange ) ) );
  241. // start in that direction
  242. velocity.assign( rDir.mul( 5.0 ) );
  243. } )().compute( nbToSpawn.value );
  244. // background , an inverted icosahedron
  245. const backgroundGeom = new THREE.IcosahedronGeometry( 100, 5 ).applyMatrix4( new THREE.Matrix4().makeScale( - 1, 1, 1 ) );
  246. const backgroundMaterial = new THREE.MeshStandardNodeMaterial();
  247. backgroundMaterial.roughness = 0.4;
  248. backgroundMaterial.metalness = 0.9;
  249. backgroundMaterial.flatShading = true;
  250. backgroundMaterial.colorNode = color( 0x0 );
  251. const backgroundMesh = new THREE.Mesh( backgroundGeom, backgroundMaterial );
  252. scene.add( backgroundMesh );
  253. // light for the background
  254. light = new THREE.PointLight( 0xffffff, 3000 );
  255. scene.add( light );
  256. // post processing
  257. postProcessing = new THREE.PostProcessing( renderer );
  258. const scenePass = pass( scene, camera );
  259. const scenePassColor = scenePass.getTextureNode( 'output' );
  260. const bloomPass = bloom( scenePassColor, 0.75, 0.1, 0.5 );
  261. postProcessing.outputNode = scenePassColor.add( bloomPass );
  262. // controls
  263. controls = new OrbitControls( camera, renderer.domElement );
  264. controls.enableDamping = true;
  265. controls.autoRotate = true;
  266. controls.maxDistance = 75;
  267. window.addEventListener( 'resize', onWindowResize );
  268. // pointer handling
  269. window.addEventListener( 'pointermove', onPointerMove );
  270. // GUI
  271. const gui = new GUI();
  272. gui.add( controls, 'autoRotate' ).name( 'Auto Rotate' );
  273. gui.add( controls, 'autoRotateSpeed', - 10.0, 10.0, 0.01 ).name( 'Auto Rotate Speed' );
  274. const partFolder = gui.addFolder( 'Particles' );
  275. partFolder.add( timeScale, 'value', 0.0, 4.0, 0.01 ).name( 'timeScale' );
  276. partFolder.add( nbToSpawn, 'value', 1, 100, 1 ).name( 'Spawn rate' );
  277. partFolder.add( particleSize, 'value', 0.01, 3.0, 0.01 ).name( 'Size' );
  278. partFolder.add( particleLifetime, 'value', 0.01, 2.0, 0.01 ).name( 'Lifetime' );
  279. partFolder.add( linksWidth, 'value', 0.001, 0.1, 0.001 ).name( 'Links width' );
  280. partFolder.add( colorVariance, 'value', 0.0, 10.0, 0.01 ).name( 'Color variance' );
  281. partFolder.add( colorRotationSpeed, 'value', 0.0, 5.0, 0.01 ).name( 'Color rotation speed' );
  282. const turbFolder = gui.addFolder( 'Turbulence' );
  283. turbFolder.add( turbFriction, 'value', 0.0, 0.3, 0.01 ).name( 'Friction' );
  284. turbFolder.add( turbFrequency, 'value', 0.0, 1.0, 0.01 ).name( 'Frequency' );
  285. turbFolder.add( turbAmplitude, 'value', 0.0, 10.0, 0.01 ).name( 'Amplitude' );
  286. turbFolder.add( turbOctaves, 'value', 1, 9, 1 ).name( 'Octaves' );
  287. turbFolder.add( turbLacunarity, 'value', 1.0, 5.0, 0.01 ).name( 'Lacunarity' );
  288. turbFolder.add( turbGain, 'value', 0.0, 1.0, 0.01 ).name( 'Gain' );
  289. const bloomFolder = gui.addFolder( 'bloom' );
  290. bloomFolder.add( bloomPass.threshold, 'value', 0, 2.0, 0.01 ).name( 'Threshold' );
  291. bloomFolder.add( bloomPass.strength, 'value', 0, 10, 0.01 ).name( 'Strength' );
  292. bloomFolder.add( bloomPass.radius, 'value', 0, 1, 0.01 ).name( 'Radius' );
  293. }
  294. function onWindowResize() {
  295. camera.aspect = window.innerWidth / window.innerHeight;
  296. camera.updateProjectionMatrix();
  297. renderer.setSize( window.innerWidth, window.innerHeight );
  298. }
  299. function onPointerMove( e ) {
  300. screenPointer.x = ( e.clientX / window.innerWidth ) * 2 - 1;
  301. screenPointer.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
  302. }
  303. function updatePointer() {
  304. raycaster.setFromCamera( screenPointer, camera );
  305. raycaster.ray.intersectPlane( raycastPlane, scenePointer );
  306. }
  307. function animate() {
  308. timer.update();
  309. // compute particles
  310. renderer.compute( updateParticles );
  311. renderer.compute( spawnParticles );
  312. // update particle index for next spawn
  313. spawnIndex.value = ( spawnIndex.value + nbToSpawn.value ) % nbParticles;
  314. // update raycast plane to face camera
  315. raycastPlane.normal.applyEuler( camera.rotation );
  316. updatePointer();
  317. // lerping spawn position
  318. previousSpawnPosition.value.copy( spawnPosition.value );
  319. spawnPosition.value.lerp( scenePointer, 0.1 );
  320. // rotating colors
  321. colorOffset.value += timer.getDelta() * colorRotationSpeed.value * timeScale.value;
  322. const elapsedTime = timer.getElapsed();
  323. light.position.set(
  324. Math.sin( elapsedTime * 0.5 ) * 30,
  325. Math.cos( elapsedTime * 0.3 ) * 30,
  326. Math.sin( elapsedTime * 0.2 ) * 30,
  327. );
  328. controls.update();
  329. postProcessing.render();
  330. }
  331. </script>
  332. </body>
  333. </html>
粤ICP备19079148号