webgpu_lights_clustered.html 8.8 KB

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