webgpu_lights_clustered.html 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. <link type="text/css" rel="stylesheet" href="example.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  12. <div class="title-wrapper">
  13. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Clustered Lighting</span>
  14. </div>
  15. <small>
  16. Forward+ clustered lighting.
  17. </small>
  18. </div>
  19. <script type="importmap">
  20. {
  21. "imports": {
  22. "three": "../build/three.webgpu.js",
  23. "three/webgpu": "../build/three.webgpu.js",
  24. "three/tsl": "../build/three.tsl.js",
  25. "three/addons/": "./jsm/"
  26. }
  27. }
  28. </script>
  29. <script type="module">
  30. import * as THREE from 'three/webgpu';
  31. import { pass, uniform, vec3, float, mix, step } from 'three/tsl';
  32. import { ClusteredLighting } from 'three/addons/lighting/ClusteredLighting.js';
  33. import { Inspector } from 'three/addons/inspector/Inspector.js';
  34. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  35. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  36. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  37. const MODEL_INDEX_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/model-index.json';
  38. const SAMPLE_ASSETS_BASE_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/';
  39. let camera, scene, renderer,
  40. lights, lightDummy,
  41. controls,
  42. scenePass, clusterInfluence, debugZSliceNode,
  43. lighting,
  44. maxCount,
  45. count,
  46. renderPipeline;
  47. init();
  48. async function init() {
  49. if ( WebGPU.isAvailable() === false ) {
  50. document.body.appendChild( WebGPU.getErrorMessage() );
  51. throw new Error( 'No WebGPU support' );
  52. }
  53. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 70 );
  54. camera.position.set( - 10, 5, 0 );
  55. scene = new THREE.Scene();
  56. scene.fog = new THREE.Fog( 0x111111, 30, 80 );
  57. scene.background = new THREE.Color( 0x111111 );
  58. maxCount = 1000;
  59. count = 700;
  60. // sponza
  61. const loader = new GLTFLoader();
  62. const modelURL = await getSponzaModelURL();
  63. const gltf = await loader.loadAsync( modelURL );
  64. const model = gltf.scene;
  65. model.traverse( ( child ) => {
  66. if ( child.isLight && child.parent ) child.parent.remove( child );
  67. } );
  68. scene.add( model );
  69. const box = new THREE.Box3().setFromObject( model );
  70. const modelSize = box.getSize( new THREE.Vector3() );
  71. const modelCenter = box.getCenter( new THREE.Vector3() );
  72. const material = new THREE.MeshBasicMaterial();
  73. lightDummy = new THREE.InstancedMesh( new THREE.SphereGeometry( 0.05, 16, 8 ), material, maxCount );
  74. lightDummy.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  75. lightDummy.frustumCulled = false;
  76. lightDummy.count = count;
  77. scene.add( lightDummy );
  78. // lights
  79. lights = new THREE.Group();
  80. scene.add( lights );
  81. const addLight = ( hexColor, power = 30, distance = 1 ) => {
  82. const light = new THREE.PointLight( hexColor, 1, distance );
  83. light.position.set(
  84. modelCenter.x + ( Math.random() - 0.5 ) * modelSize.x * 0.7,
  85. ( box.min.y + Math.random() * modelSize.y * 0.7 ) + 0.4,
  86. modelCenter.z + ( Math.random() - 0.5 ) * modelSize.z * 0.5
  87. );
  88. light.power = power;
  89. light.userData.fixedPosition = light.position.clone();
  90. light.visible = ( lights.children.length < count );
  91. light.updateMatrixWorld();
  92. lightDummy.setMatrixAt( lights.children.length, light.matrixWorld );
  93. lights.add( light );
  94. return light;
  95. };
  96. const color = new THREE.Color();
  97. for ( let i = 0; i < maxCount; i ++ ) {
  98. const hex = ( Math.random() * 0x888888 ) + 0x888888;
  99. lightDummy.setColorAt( i, color.setHex( hex ) );
  100. addLight( hex );
  101. }
  102. //
  103. const lightAmbient = new THREE.AmbientLight( 0xffffff, .1 );
  104. scene.add( lightAmbient );
  105. // renderer
  106. lighting = new ClusteredLighting(); // ( maxLights = 1024, tileSize = 32, zSlices = 24, maxLightsPerCluster = 64 )
  107. renderer = new THREE.WebGPURenderer( { antialias: true } );
  108. renderer.setPixelRatio( window.devicePixelRatio );
  109. renderer.setSize( window.innerWidth, window.innerHeight );
  110. renderer.setAnimationLoop( animate );
  111. renderer.lighting = lighting; // set lighting system
  112. renderer.toneMapping = THREE.NeutralToneMapping;
  113. renderer.toneMappingExposure = 1.5;
  114. renderer.inspector = new Inspector();
  115. document.body.appendChild( renderer.domElement );
  116. // controls
  117. controls = new OrbitControls( camera, renderer.domElement );
  118. controls.target.set( 0, 5, 0 );
  119. controls.maxDistance = 60;
  120. controls.update();
  121. // events
  122. window.addEventListener( 'resize', onWindowResize );
  123. // post processing
  124. scenePass = pass( scene, camera );
  125. clusterInfluence = uniform( 0 );
  126. renderPipeline = new THREE.RenderPipeline( renderer );
  127. debugZSliceNode = uniform( 15, 'int' );
  128. updatePostProcessing();
  129. // gui
  130. const gui = renderer.inspector.createParameters( 'Settings' );
  131. const params = {
  132. count
  133. };
  134. gui.add( params, 'count', 0, maxCount, 1 ).name( 'light count' ).onChange( ( value ) => {
  135. lightDummy.count = value;
  136. for ( let i = 0; i < lights.children.length; i ++ ) {
  137. lights.children[ i ].visible = ( i < value );
  138. }
  139. } );
  140. gui.add( clusterInfluence, 'value', 0, .7 ).name( 'lights per tile' );
  141. gui.add( debugZSliceNode, 'value', 0, lighting.zSlices - 1, 1 ).name( 'z-slice' );
  142. }
  143. function updatePostProcessing() {
  144. // cluster light count debug overlay; needs to be updated every time the renderer size changes
  145. const lightingNode = lighting.getNode( scene ).setSize( window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio );
  146. // Calculate a color mapping based on the actual number of lights directly affecting the cluster.
  147. // We map between 0 and maxLightsPerCluster to a gradient
  148. const lightCount = lightingNode.getClusterLightCount( debugZSliceNode );
  149. const heatmap = float( lightCount ).div( float( lighting.maxLightsPerCluster ) );
  150. // Gradient mapping: Blue (0.0) -> Green (0.5) -> Red (1.0)
  151. let heatColor = mix( vec3( 0.0, 0.0, 1.0 ), vec3( 0.0, 1.0, 0.0 ), heatmap.mul( 2.0 ).saturate() );
  152. heatColor = mix( heatColor, vec3( 1.0, 0.0, 0.0 ), heatmap.sub( 0.5 ).mul( 2.0 ).saturate() );
  153. // Blend the heatmap over the original scene based on the slider value
  154. // The `step` drops opacity to 0.0 if there are strictly no lights in the cluster
  155. const finalInfluence = clusterInfluence.mul( step( 0.0001, heatmap ) );
  156. renderPipeline.outputNode = mix( scenePass, heatColor, finalInfluence );
  157. renderPipeline.needsUpdate = true;
  158. }
  159. async function getSponzaModelURL() {
  160. const response = await fetch( MODEL_INDEX_URL );
  161. const models = await response.json();
  162. const sponzaInfo = models.find( ( model ) => model.name === 'Sponza' );
  163. if ( ! sponzaInfo ) {
  164. throw new Error( 'Sponza entry was not found in the glTF sample model index.' );
  165. }
  166. const variants = sponzaInfo.variants || {};
  167. const variantName = variants[ 'glTF-Binary' ] || variants[ 'glTF' ] || variants[ 'glTF-Embedded' ] || Object.values( variants )[ 0 ];
  168. if ( ! variantName ) {
  169. throw new Error( 'Sponza has no supported glTF variant in the model index.' );
  170. }
  171. const variantFolder = variantName.endsWith( '.glb' ) ? 'glTF-Binary' : 'glTF';
  172. return `${ SAMPLE_ASSETS_BASE_URL }${ sponzaInfo.name }/${ variantFolder }/${ variantName }`;
  173. }
  174. function onWindowResize() {
  175. camera.aspect = window.innerWidth / window.innerHeight;
  176. camera.updateProjectionMatrix();
  177. renderer.setSize( window.innerWidth, window.innerHeight );
  178. updatePostProcessing();
  179. }
  180. function animate() {
  181. const time = performance.now() / 1000;
  182. for ( let i = 0; i < lights.children.length; i ++ ) {
  183. const light = lights.children[ i ];
  184. const lightTime = ( time * 0.5 ) + light.id;
  185. light.position.copy( light.userData.fixedPosition );
  186. light.position.x += Math.sin( lightTime * 0.7 ) * 1.5;
  187. light.position.y += Math.cos( lightTime * 0.5 ) * .3;
  188. light.position.z += Math.cos( lightTime * 0.3 ) * 1.5;
  189. lightDummy.setMatrixAt( i, light.matrixWorld );
  190. }
  191. renderPipeline.render();
  192. }
  193. </script>
  194. </body>
  195. </html>
粤ICP备19079148号