webgpu_lights_clustered.html 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 WebGPU from 'three/addons/capabilities/WebGPU.js';
  40. const GRID = 30; // GRID x GRID spheres
  41. const SPACING = 5;
  42. const RADIUS = 0.5;
  43. const WAVE_HEIGHT = 4;
  44. const BIG_RADIUS = 6;
  45. const BASE_POWER = 45;
  46. let camera, scene, renderer, controls, spheresMesh, lighting;
  47. let renderPipeline, scenePass, clusterInfluence, debugZSliceNode;
  48. const balls = [];
  49. const dummy = new THREE.Object3D();
  50. const params = {
  51. intensity: 1,
  52. animate: true
  53. };
  54. init();
  55. async function init() {
  56. if ( WebGPU.isAvailable() === false ) {
  57. document.body.appendChild( WebGPU.getErrorMessage() );
  58. throw new Error( 'No WebGPU support' );
  59. }
  60. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 200 );
  61. camera.position.set( 36, 18, 36 );
  62. scene = new THREE.Scene();
  63. renderer = new THREE.WebGPURenderer( { antialias: true } );
  64. renderer.setPixelRatio( window.devicePixelRatio );
  65. renderer.setSize( window.innerWidth, window.innerHeight );
  66. renderer.setAnimationLoop( animate );
  67. renderer.toneMapping = THREE.NeutralToneMapping;
  68. renderer.toneMappingExposure = 1;
  69. lighting = new ClusteredLighting();
  70. renderer.lighting = lighting; // set lighting system
  71. renderer.inspector = new Inspector();
  72. document.body.appendChild( renderer.domElement );
  73. await renderer.init();
  74. // ground
  75. const ground = new THREE.Mesh(
  76. new THREE.PlaneGeometry( 1000, 1000 ).rotateX( - Math.PI / 2 ),
  77. new THREE.MeshPhongNodeMaterial( { color: 0x2a2a2a, shininess: 80 } )
  78. );
  79. scene.add( ground );
  80. // four big spheres in the middle for the surrounding lights to play across
  81. const bigPositions = [
  82. new THREE.Vector3( - 9, BIG_RADIUS, - 9 ),
  83. new THREE.Vector3( 9, BIG_RADIUS, - 9 ),
  84. new THREE.Vector3( - 9, BIG_RADIUS, 9 ),
  85. new THREE.Vector3( 9, BIG_RADIUS, 9 )
  86. ];
  87. const bigGeometry = new THREE.SphereGeometry( BIG_RADIUS, 64, 32 );
  88. const bigMaterial = new THREE.MeshPhongNodeMaterial( { color: 0xdddddd, shininess: 80 } );
  89. for ( const position of bigPositions ) {
  90. const bigSphere = new THREE.Mesh( bigGeometry, bigMaterial );
  91. bigSphere.position.copy( position );
  92. scene.add( bigSphere );
  93. }
  94. // a grid of coloured spheres drawn as a single InstancedMesh; each is
  95. // unlit in its own colour and holds a matching point light at its centre
  96. const maxCount = GRID * GRID;
  97. const colorAttribute = new THREE.InstancedBufferAttribute( new Float32Array( maxCount * 3 ), 3 );
  98. const material = new THREE.MeshBasicNodeMaterial();
  99. material.colorNode = instancedBufferAttribute( colorAttribute );
  100. spheresMesh = new THREE.InstancedMesh( new THREE.SphereGeometry( RADIUS, 32, 16 ), material, maxCount );
  101. spheresMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  102. scene.add( spheresMesh );
  103. const color = new THREE.Color();
  104. const span = ( GRID - 1 ) * SPACING;
  105. let i = 0;
  106. for ( let ix = 0; ix < GRID; ix ++ ) {
  107. for ( let iz = 0; iz < GRID; iz ++ ) {
  108. const x = ix * SPACING - span / 2;
  109. const z = iz * SPACING - span / 2;
  110. // leave a clearing where a big sphere sits
  111. if ( bigPositions.some( ( position ) => Math.hypot( x - position.x, z - position.z ) < BIG_RADIUS + 1 ) ) continue;
  112. const phase = ( ix + iz ) * 0.5;
  113. dummy.position.set( x, RADIUS, z );
  114. dummy.updateMatrix();
  115. spheresMesh.setMatrixAt( i, dummy.matrix );
  116. color.setHSL( ( ix * GRID + iz ) / ( GRID * GRID ), 1.0, 0.5 );
  117. colorAttribute.setXYZ( i, color.r, color.g, color.b );
  118. const light = new THREE.PointLight( color, 1, 9 );
  119. light.power = BASE_POWER;
  120. light.position.set( x, RADIUS, z );
  121. scene.add( light );
  122. balls.push( { x, z, phase, light } );
  123. i ++;
  124. }
  125. }
  126. spheresMesh.count = i;
  127. // controls
  128. controls = new OrbitControls( camera, renderer.domElement );
  129. controls.enableDamping = true;
  130. controls.target.set( 0, 6, 0 );
  131. controls.maxPolarAngle = Math.PI * 0.49;
  132. controls.minDistance = 4;
  133. controls.maxDistance = 400;
  134. controls.update();
  135. // post-processing: a debug overlay that tints each screen tile by how many
  136. // lights its cluster holds, for the selected depth slice
  137. scenePass = pass( scene, camera );
  138. clusterInfluence = uniform( 0 );
  139. debugZSliceNode = uniform( 20, 'int' );
  140. renderPipeline = new THREE.RenderPipeline( renderer );
  141. updatePostProcessing();
  142. // gui
  143. const gui = renderer.inspector.createParameters( 'Settings' );
  144. gui.add( params, 'intensity', 0, 3 ).name( 'light intensity' ).onChange( ( value ) => {
  145. for ( const ball of balls ) ball.light.power = BASE_POWER * value;
  146. } );
  147. gui.add( params, 'animate' );
  148. gui.add( clusterInfluence, 'value', 0, .7 ).name( 'lights per tile' );
  149. gui.add( debugZSliceNode, 'value', 0, lighting.zSlices - 1, 1 ).name( 'z-slice' );
  150. // events
  151. window.addEventListener( 'resize', onWindowResize );
  152. }
  153. function onWindowResize() {
  154. camera.aspect = window.innerWidth / window.innerHeight;
  155. camera.updateProjectionMatrix();
  156. renderer.setSize( window.innerWidth, window.innerHeight );
  157. updatePostProcessing();
  158. }
  159. function updatePostProcessing() {
  160. // the overlay samples the cluster grid at the current resolution, so it
  161. // is rebuilt whenever the renderer size changes
  162. const lightingNode = lighting.getNode( scene ).setSize( window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio );
  163. // map the light count of each cluster ( 0 … maxLightsPerCluster ) to a
  164. // blue → green → red gradient
  165. const lightCount = lightingNode.getClusterLightCount( debugZSliceNode );
  166. const heatmap = float( lightCount ).div( float( lighting.maxLightsPerCluster ) );
  167. let heatColor = mix( vec3( 0.0, 0.0, 1.0 ), vec3( 0.0, 1.0, 0.0 ), heatmap.mul( 2.0 ).saturate() );
  168. heatColor = mix( heatColor, vec3( 1.0, 0.0, 0.0 ), heatmap.sub( 0.5 ).mul( 2.0 ).saturate() );
  169. // blend the heatmap over the scene by the slider amount; step() keeps
  170. // empty clusters transparent
  171. const finalInfluence = clusterInfluence.mul( step( 0.0001, heatmap ) );
  172. renderPipeline.outputNode = mix( scenePass, heatColor, finalInfluence );
  173. renderPipeline.needsUpdate = true;
  174. }
  175. function animate() {
  176. if ( params.animate === true ) {
  177. const time = performance.now() / 1000;
  178. for ( let i = 0; i < balls.length; i ++ ) {
  179. const ball = balls[ i ];
  180. const y = RADIUS + ( 0.5 + 0.5 * Math.sin( time * 1.5 + ball.phase ) ) * WAVE_HEIGHT;
  181. dummy.position.set( ball.x, y, ball.z );
  182. dummy.updateMatrix();
  183. spheresMesh.setMatrixAt( i, dummy.matrix );
  184. ball.light.position.y = y;
  185. }
  186. spheresMesh.instanceMatrix.needsUpdate = true;
  187. }
  188. controls.update();
  189. renderPipeline.render();
  190. }
  191. </script>
  192. </body>
  193. </html>
粤ICP备19079148号