webgpu_lights_clustered.html 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - clustered lighting</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. <meta property="og:title" content="three.js webgpu - clustered lighting">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_lights_clustered.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_lights_clustered.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  16. <div class="title-wrapper">
  17. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Clustered Lighting</span>
  18. </div>
  19. <small>
  20. Forward+ clustered lighting.
  21. </small>
  22. </div>
  23. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../build/three.webgpu.js",
  27. "three/webgpu": "../build/three.webgpu.js",
  28. "three/tsl": "../build/three.tsl.js",
  29. "three/addons/": "./jsm/"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three/webgpu';
  35. import { instancedBufferAttribute, pass, uniform, vec3, float, mix, step } from 'three/tsl';
  36. import { ClusteredLighting } from 'three/addons/lighting/ClusteredLighting.js';
  37. import { Inspector } from 'three/addons/inspector/Inspector.js';
  38. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  39. import { SkyMesh } from 'three/addons/objects/SkyMesh.js';
  40. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  41. const GRID = 30; // GRID x GRID spheres
  42. const SPACING = 5;
  43. const RADIUS = 0.5;
  44. const WAVE_HEIGHT = 4;
  45. const BIG_RADIUS = 6;
  46. const BASE_POWER = 45;
  47. let camera, scene, renderer, controls, spheresMesh, lighting;
  48. let renderPipeline, scenePass, clusterInfluence, debugZSliceNode;
  49. const balls = [];
  50. const dummy = new THREE.Object3D();
  51. const params = {
  52. intensity: 1,
  53. animate: true
  54. };
  55. init();
  56. async function init() {
  57. if ( WebGPU.isAvailable() === false ) {
  58. document.body.appendChild( WebGPU.getErrorMessage() );
  59. throw new Error( 'No WebGPU support' );
  60. }
  61. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 20000 );
  62. camera.position.set( 36, 18, 36 );
  63. scene = new THREE.Scene();
  64. renderer = new THREE.WebGPURenderer( { antialias: true } );
  65. renderer.setPixelRatio( window.devicePixelRatio );
  66. renderer.setSize( window.innerWidth, window.innerHeight );
  67. renderer.setAnimationLoop( animate );
  68. renderer.toneMapping = THREE.NeutralToneMapping;
  69. renderer.toneMappingExposure = 1;
  70. lighting = new ClusteredLighting();
  71. renderer.lighting = lighting; // set lighting system
  72. renderer.inspector = new Inspector();
  73. document.body.appendChild( renderer.domElement );
  74. await renderer.init();
  75. // a physical sky drives the backdrop and the image-based lighting; the
  76. // sun sits just below the horizon for an almost-night mood
  77. const sky = new SkyMesh();
  78. sky.scale.setScalar( 10000 );
  79. sky.turbidity.value = 10;
  80. sky.rayleigh.value = 3;
  81. sky.mieCoefficient.value = 0.005;
  82. sky.mieDirectionalG.value = 0.7;
  83. const sun = new THREE.Vector3().setFromSphericalCoords(
  84. 1,
  85. THREE.MathUtils.degToRad( 92 ), // elevation: 2° below the horizon (almost night)
  86. THREE.MathUtils.degToRad( 225 ) // azimuth
  87. );
  88. sky.sunPosition.value.copy( sun );
  89. scene.add( sky );
  90. // the sun sits below the horizon, so keep its disc hidden; bake the sky
  91. // into an environment map for the faint ambient colour it still casts
  92. const pmremGenerator = new THREE.PMREMGenerator( renderer );
  93. sky.showSunDisc.value = false;
  94. scene.environment = pmremGenerator.fromScene( scene ).texture;
  95. scene.environmentIntensity = 0.75;
  96. // ground
  97. const ground = new THREE.Mesh(
  98. new THREE.PlaneGeometry( 1000, 1000 ).rotateX( - Math.PI / 2 ),
  99. new THREE.MeshStandardNodeMaterial( { color: 0x2a2a2a, roughness: 0.6, metalness: 0 } )
  100. );
  101. scene.add( ground );
  102. // four big spheres in the middle for the surrounding lights to play across
  103. const bigPositions = [
  104. new THREE.Vector3( - 9, BIG_RADIUS, - 9 ),
  105. new THREE.Vector3( 9, BIG_RADIUS, - 9 ),
  106. new THREE.Vector3( - 9, BIG_RADIUS, 9 ),
  107. new THREE.Vector3( 9, BIG_RADIUS, 9 )
  108. ];
  109. const bigGeometry = new THREE.SphereGeometry( BIG_RADIUS, 64, 32 );
  110. const bigMaterial = new THREE.MeshStandardNodeMaterial( { color: 0xdddddd, roughness: 0.5, metalness: 0 } );
  111. for ( const position of bigPositions ) {
  112. const bigSphere = new THREE.Mesh( bigGeometry, bigMaterial );
  113. bigSphere.position.copy( position );
  114. scene.add( bigSphere );
  115. }
  116. // a grid of coloured spheres drawn as a single InstancedMesh; each is
  117. // unlit in its own colour and holds a matching point light at its centre
  118. const maxCount = GRID * GRID;
  119. const colorAttribute = new THREE.InstancedBufferAttribute( new Float32Array( maxCount * 3 ), 3 );
  120. const material = new THREE.MeshBasicNodeMaterial();
  121. material.colorNode = instancedBufferAttribute( colorAttribute );
  122. spheresMesh = new THREE.InstancedMesh( new THREE.SphereGeometry( RADIUS, 32, 16 ), material, maxCount );
  123. spheresMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  124. scene.add( spheresMesh );
  125. const color = new THREE.Color();
  126. const span = ( GRID - 1 ) * SPACING;
  127. let i = 0;
  128. for ( let ix = 0; ix < GRID; ix ++ ) {
  129. for ( let iz = 0; iz < GRID; iz ++ ) {
  130. const x = ix * SPACING - span / 2;
  131. const z = iz * SPACING - span / 2;
  132. // leave a clearing where a big sphere sits
  133. if ( bigPositions.some( ( position ) => Math.hypot( x - position.x, z - position.z ) < BIG_RADIUS + 1 ) ) continue;
  134. const phase = ( ix + iz ) * 0.5;
  135. dummy.position.set( x, RADIUS, z );
  136. dummy.updateMatrix();
  137. spheresMesh.setMatrixAt( i, dummy.matrix );
  138. color.setHSL( ( ix * GRID + iz ) / ( GRID * GRID ), 1.0, 0.5 );
  139. colorAttribute.setXYZ( i, color.r, color.g, color.b );
  140. const light = new THREE.PointLight( color, 1, 9 );
  141. light.power = BASE_POWER;
  142. light.position.set( x, RADIUS, z );
  143. scene.add( light );
  144. balls.push( { x, z, phase, light } );
  145. i ++;
  146. }
  147. }
  148. spheresMesh.count = i;
  149. // controls
  150. controls = new OrbitControls( camera, renderer.domElement );
  151. controls.enableDamping = true;
  152. controls.target.set( 0, 6, 0 );
  153. controls.maxPolarAngle = Math.PI * 0.49;
  154. controls.minDistance = 4;
  155. controls.maxDistance = 400;
  156. controls.update();
  157. // post-processing: a debug overlay that tints each screen tile by how many
  158. // lights its cluster holds, for the selected depth slice
  159. scenePass = pass( scene, camera );
  160. clusterInfluence = uniform( 0 );
  161. // the large far plane spreads the exponential z-slices out, so the orb
  162. // field falls around slices 7–11; default into that range
  163. debugZSliceNode = uniform( 10, 'int' );
  164. renderPipeline = new THREE.RenderPipeline( renderer );
  165. updatePostProcessing();
  166. // gui
  167. const gui = renderer.inspector.createParameters( 'Settings' );
  168. gui.add( params, 'intensity', 0, 3 ).name( 'light intensity' ).onChange( ( value ) => {
  169. for ( const ball of balls ) ball.light.power = BASE_POWER * value;
  170. } );
  171. gui.add( params, 'animate' );
  172. gui.add( clusterInfluence, 'value', 0, .7 ).name( 'lights per tile' );
  173. gui.add( debugZSliceNode, 'value', 0, lighting.zSlices - 1, 1 ).name( 'z-slice' );
  174. // events
  175. window.addEventListener( 'resize', onWindowResize );
  176. }
  177. function onWindowResize() {
  178. camera.aspect = window.innerWidth / window.innerHeight;
  179. camera.updateProjectionMatrix();
  180. renderer.setSize( window.innerWidth, window.innerHeight );
  181. updatePostProcessing();
  182. }
  183. function updatePostProcessing() {
  184. // the overlay samples the cluster grid at the current resolution, so it
  185. // is rebuilt whenever the renderer size changes
  186. const lightingNode = lighting.getNode( scene ).setSize( window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio );
  187. // map the light count of each cluster ( 0 … maxLightsPerCluster ) to a
  188. // blue → green → red gradient
  189. const lightCount = lightingNode.getClusterLightCount( debugZSliceNode );
  190. const heatmap = float( lightCount ).div( float( lighting.maxLightsPerCluster ) );
  191. let heatColor = mix( vec3( 0.0, 0.0, 1.0 ), vec3( 0.0, 1.0, 0.0 ), heatmap.mul( 2.0 ).saturate() );
  192. heatColor = mix( heatColor, vec3( 1.0, 0.0, 0.0 ), heatmap.sub( 0.5 ).mul( 2.0 ).saturate() );
  193. // blend the heatmap over the scene by the slider amount; step() keeps
  194. // empty clusters transparent
  195. const finalInfluence = clusterInfluence.mul( step( 0.0001, heatmap ) );
  196. renderPipeline.outputNode = mix( scenePass, heatColor, finalInfluence );
  197. renderPipeline.needsUpdate = true;
  198. }
  199. function animate() {
  200. if ( params.animate === true ) {
  201. const time = performance.now() / 1000;
  202. for ( let i = 0; i < balls.length; i ++ ) {
  203. const ball = balls[ i ];
  204. const y = RADIUS + ( 0.5 + 0.5 * Math.sin( time * 1.5 + ball.phase ) ) * WAVE_HEIGHT;
  205. dummy.position.set( ball.x, y, ball.z );
  206. dummy.updateMatrix();
  207. spheresMesh.setMatrixAt( i, dummy.matrix );
  208. ball.light.position.y = y;
  209. }
  210. spheresMesh.instanceMatrix.needsUpdate = true;
  211. }
  212. controls.update();
  213. renderPipeline.render();
  214. }
  215. </script>
  216. </body>
  217. </html>
粤ICP备19079148号