webgl_lightprobes_sponza.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - light probe volume (Sponza)</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</a> - light probe volume (Sponza)<br/>
  12. WASD to move, mouse to look
  13. </div>
  14. <progress id="progressBar" value="0" max="100" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)"></progress>
  15. <script type="importmap">
  16. {
  17. "imports": {
  18. "three": "../build/three.module.js",
  19. "three/addons/": "./jsm/"
  20. }
  21. }
  22. </script>
  23. <script type="module">
  24. import * as THREE from 'three';
  25. import { FirstPersonControls } from 'three/addons/controls/FirstPersonControls.js';
  26. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  27. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  28. import { Sky } from 'three/addons/objects/Sky.js';
  29. import { LightProbeGrid } from 'three/addons/lighting/LightProbeGrid.js';
  30. import { LightProbeGridHelper } from 'three/addons/helpers/LightProbeGridHelper.js';
  31. const MODEL_INDEX_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/model-index.json';
  32. const SAMPLE_ASSETS_BASE_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/';
  33. let camera, scene, renderer, controls, timer;
  34. let probes = null, probesHelper = null;
  35. let modelSize = null;
  36. let dirLight = null, sky = null, sun = new THREE.Vector3();
  37. const _box = new THREE.Box3();
  38. const _size = new THREE.Vector3();
  39. const _center = new THREE.Vector3();
  40. init();
  41. async function init() {
  42. timer = new THREE.Timer();
  43. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 1000 );
  44. camera.position.set( - 10.25, 4.99, 0.40 );
  45. camera.rotation.set( 1.6505, - 1.5008, 1.6507 );
  46. scene = new THREE.Scene();
  47. sky = new Sky();
  48. sky.scale.setScalar( 450000 );
  49. scene.add( sky );
  50. const skyUniforms = sky.material.uniforms;
  51. skyUniforms[ 'turbidity' ].value = 10;
  52. skyUniforms[ 'rayleigh' ].value = 2;
  53. skyUniforms[ 'mieCoefficient' ].value = 0.005;
  54. skyUniforms[ 'mieDirectionalG' ].value = 0.8;
  55. renderer = new THREE.WebGLRenderer( { antialias: true } );
  56. renderer.setPixelRatio( Math.min( window.devicePixelRatio, 1.5 ) );
  57. renderer.setSize( window.innerWidth, window.innerHeight );
  58. renderer.setAnimationLoop( animate );
  59. renderer.shadowMap.enabled = true;
  60. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  61. renderer.toneMappingExposure = 1.0;
  62. document.body.appendChild( renderer.domElement );
  63. controls = new FirstPersonControls( camera, renderer.domElement );
  64. controls.movementSpeed = 2.0;
  65. controls.lookSpeed = 0.16;
  66. const progressBar = document.getElementById( 'progressBar' );
  67. const manager = new THREE.LoadingManager();
  68. manager.onProgress = function ( url, loaded, total ) {
  69. progressBar.value = loaded / total * 100;
  70. };
  71. manager.onLoad = function () {
  72. progressBar.remove();
  73. };
  74. const loader = new GLTFLoader( manager );
  75. const modelURL = await getSponzaModelURL();
  76. const gltf = await loader.loadAsync( modelURL );
  77. const model = gltf.scene;
  78. const embeddedLights = [];
  79. model.traverse( ( child ) => {
  80. if ( child.isMesh ) {
  81. child.castShadow = true;
  82. child.receiveShadow = true;
  83. } else if ( child.isLight ) {
  84. embeddedLights.push( child );
  85. }
  86. } );
  87. for ( const light of embeddedLights ) {
  88. if ( light.parent ) light.parent.remove( light );
  89. }
  90. scene.add( model );
  91. _box.setFromObject( model );
  92. modelSize = _box.getSize( _size ).clone();
  93. const modelCenter = _box.getCenter( _center ).clone();
  94. const targetY = modelCenter.y + modelSize.y * 0.2;
  95. const lightBaseDistance = Math.max( modelSize.x, modelSize.z );
  96. const probeFar = Math.max( modelSize.x, modelSize.y, modelSize.z ) * 2.0;
  97. let rebakeTimer = null;
  98. let isBaking = false;
  99. let bakeQueued = false;
  100. dirLight = new THREE.DirectionalLight( 0xfff2dc, 50.0 );
  101. dirLight.target.position.set( modelCenter.x, targetY, modelCenter.z );
  102. scene.add( dirLight.target );
  103. dirLight.castShadow = true;
  104. dirLight.shadow.mapSize.setScalar( 2048 );
  105. const shadowExtent = Math.max( modelSize.x, modelSize.z ) * 0.7;
  106. dirLight.shadow.camera.left = - shadowExtent;
  107. dirLight.shadow.camera.right = shadowExtent;
  108. dirLight.shadow.camera.top = shadowExtent;
  109. dirLight.shadow.camera.bottom = - shadowExtent;
  110. dirLight.shadow.camera.near = 0.1;
  111. dirLight.shadow.camera.far = modelSize.y * 4.0;
  112. scene.add( dirLight );
  113. const params = {
  114. enabled: true,
  115. showProbes: false,
  116. probeSize: 0.25,
  117. boundsX: - 0.5,
  118. boundsY: 6,
  119. boundsZ: - 0.3,
  120. sizeX: 19,
  121. sizeY: 11,
  122. sizeZ: 7,
  123. countX: 7,
  124. countY: 7,
  125. countZ: 3,
  126. lightAzimuth: - 45,
  127. lightElevation: 55,
  128. lightIntensity: 50.0,
  129. shadows: true
  130. };
  131. function updateLightPosition() {
  132. const azimuth = THREE.MathUtils.degToRad( params.lightAzimuth );
  133. const elevation = THREE.MathUtils.degToRad( params.lightElevation );
  134. const radius = lightBaseDistance;
  135. const horizontal = Math.cos( elevation ) * radius;
  136. const vertical = Math.sin( elevation ) * radius;
  137. dirLight.position.set(
  138. modelCenter.x + Math.cos( azimuth ) * horizontal,
  139. targetY + vertical,
  140. modelCenter.z + Math.sin( azimuth ) * horizontal
  141. );
  142. dirLight.target.position.set( modelCenter.x, targetY, modelCenter.z );
  143. dirLight.target.updateMatrixWorld();
  144. const phi = THREE.MathUtils.degToRad( 90 - params.lightElevation );
  145. const theta = THREE.MathUtils.degToRad( params.lightAzimuth );
  146. sun.setFromSphericalCoords( 1, phi, theta );
  147. sky.material.uniforms[ 'sunPosition' ].value.copy( sun );
  148. }
  149. function scheduleRebake() {
  150. if ( rebakeTimer !== null ) clearTimeout( rebakeTimer );
  151. rebakeTimer = setTimeout( () => {
  152. rebakeTimer = null;
  153. bakeWithSettings();
  154. }, 250 );
  155. }
  156. async function bakeWithSettings() {
  157. if ( isBaking ) {
  158. bakeQueued = true;
  159. return;
  160. }
  161. isBaking = true;
  162. do {
  163. bakeQueued = false;
  164. if ( probes ) {
  165. scene.remove( probes );
  166. probes.dispose();
  167. }
  168. probes = new LightProbeGrid(
  169. params.sizeX, params.sizeY, params.sizeZ,
  170. params.countX, params.countY, params.countZ
  171. );
  172. probes.position.set( params.boundsX, params.boundsY, params.boundsZ );
  173. probes.bake( renderer, scene, {
  174. cubemapSize: 32,
  175. near: 0.05,
  176. far: probeFar
  177. } );
  178. probes.visible = params.enabled;
  179. scene.add( probes );
  180. if ( ! probesHelper ) {
  181. probesHelper = new LightProbeGridHelper( probes, params.probeSize );
  182. probesHelper.visible = params.showProbes;
  183. scene.add( probesHelper );
  184. } else {
  185. probesHelper.probes = probes;
  186. probesHelper.update();
  187. probesHelper.visible = params.showProbes;
  188. }
  189. } while ( bakeQueued );
  190. isBaking = false;
  191. }
  192. updateLightPosition();
  193. const gui = new GUI();
  194. gui.add( params, 'enabled' ).name( 'GI' ).onChange( ( value ) => {
  195. if ( probes ) probes.visible = value;
  196. } );
  197. gui.add( params, 'lightAzimuth', - 180, 180, 1 ).name( 'Light Azimuth' ).onChange( () => {
  198. updateLightPosition();
  199. scheduleRebake();
  200. } );
  201. gui.add( params, 'lightElevation', 5, 85, 1 ).name( 'Light Elevation' ).onChange( () => {
  202. updateLightPosition();
  203. scheduleRebake();
  204. } );
  205. gui.add( params, 'lightIntensity', 0, 50, 0.1 ).name( 'Light Intensity' ).onChange( ( value ) => {
  206. dirLight.intensity = value;
  207. scheduleRebake();
  208. } );
  209. gui.add( params, 'shadows' ).name( 'Shadows' ).onChange( ( value ) => {
  210. setShadowsEnabled( value );
  211. scheduleRebake();
  212. } );
  213. gui.add( params, 'showProbes' ).name( 'Show Probes' ).onChange( ( value ) => {
  214. if ( probesHelper ) probesHelper.visible = value;
  215. } );
  216. gui.add( params, 'probeSize', 0.05, 2.0, 0.05 ).name( 'Probe Size' ).onChange( ( value ) => {
  217. if ( probesHelper ) {
  218. scene.remove( probesHelper );
  219. probesHelper.dispose();
  220. probesHelper = new LightProbeGridHelper( probes, value );
  221. probesHelper.visible = params.showProbes;
  222. scene.add( probesHelper );
  223. }
  224. } );
  225. gui.add( { log: () => {
  226. console.log( 'position:', camera.position.x.toFixed( 2 ), camera.position.y.toFixed( 2 ), camera.position.z.toFixed( 2 ) );
  227. console.log( 'rotation:', camera.rotation.x.toFixed( 4 ), camera.rotation.y.toFixed( 4 ), camera.rotation.z.toFixed( 4 ) );
  228. } }, 'log' ).name( 'Log Camera' );
  229. setShadowsEnabled( params.shadows );
  230. await bakeWithSettings();
  231. window.addEventListener( 'resize', onWindowResize );
  232. }
  233. async function getSponzaModelURL() {
  234. const response = await fetch( MODEL_INDEX_URL );
  235. const models = await response.json();
  236. const sponzaInfo = models.find( ( model ) => model.name === 'Sponza' );
  237. if ( ! sponzaInfo ) {
  238. throw new Error( 'Sponza entry was not found in the glTF sample model index.' );
  239. }
  240. const variants = sponzaInfo.variants || {};
  241. const variantName = variants[ 'glTF-Binary' ] || variants[ 'glTF' ] || variants[ 'glTF-Embedded' ] || Object.values( variants )[ 0 ];
  242. if ( ! variantName ) {
  243. throw new Error( 'Sponza has no supported glTF variant in the model index.' );
  244. }
  245. const variantFolder = variantName.endsWith( '.glb' ) ? 'glTF-Binary' : 'glTF';
  246. return `${ SAMPLE_ASSETS_BASE_URL }${ sponzaInfo.name }/${ variantFolder }/${ variantName }`;
  247. }
  248. function setShadowsEnabled( enabled ) {
  249. if ( ! renderer || ! dirLight ) return;
  250. renderer.shadowMap.enabled = enabled;
  251. dirLight.castShadow = enabled;
  252. }
  253. function onWindowResize() {
  254. camera.aspect = window.innerWidth / window.innerHeight;
  255. camera.updateProjectionMatrix();
  256. renderer.setSize( window.innerWidth, window.innerHeight );
  257. }
  258. function animate( timestamp ) {
  259. timer.update( timestamp );
  260. controls.update( timer.getDelta() );
  261. renderer.render( scene, camera );
  262. }
  263. </script>
  264. </body>
  265. </html>
粤ICP备19079148号