2
0

webgl_shaders_tonemapping.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - adaptive tone-mapping</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. <style>
  9. .label {
  10. background-color: black;
  11. position: absolute;
  12. z-index: 100;
  13. padding: 5px
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div id="d">
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl demo :
  21. Earth diffuse and city lights by <a href="http://seanward.org" target="_blank" rel="noopener">Sean Ward</a> :
  22. </div>
  23. <div class="label" style="position: absolute;left: 10%;bottom: 10%;">
  24. Low Dynamic Range<br/>
  25. Static Tone Mapping
  26. </div>
  27. <div class="label" style="position: absolute;left: 40%;bottom: 10%;">
  28. High Dynamic Range<br/>
  29. Static Tone Mapping
  30. </div>
  31. <div class="label" style="position: absolute;left: 73%;bottom: 10%;">
  32. High Dynamic Range<br/>
  33. Adaptive Tone Mapping
  34. </div>
  35. </div>
  36. <script type="module">
  37. import * as THREE from '../build/three.module.js';
  38. import { GUI } from './jsm/libs/dat.gui.module.js';
  39. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  40. import { EffectComposer } from './jsm/postprocessing/EffectComposer.js';
  41. import { RenderPass } from './jsm/postprocessing/RenderPass.js';
  42. import { ShaderPass } from './jsm/postprocessing/ShaderPass.js';
  43. import { AdaptiveToneMappingPass } from './jsm/postprocessing/AdaptiveToneMappingPass.js';
  44. import { BloomPass } from './jsm/postprocessing/BloomPass.js';
  45. import { GammaCorrectionShader } from './jsm/shaders/GammaCorrectionShader.js';
  46. let bloomPass, adaptToneMappingPass, ldrToneMappingPass, hdrToneMappingPass;
  47. let params;
  48. let camera, scene, renderer, dynamicHdrEffectComposer, hdrEffectComposer, ldrEffectComposer;
  49. let cameraCube, sceneCube;
  50. let cameraBG, debugScene;
  51. let adaptiveLuminanceMat, currentLuminanceMat;
  52. let directionalLight;
  53. let orbitControls;
  54. let windowHalfX = window.innerWidth / 2;
  55. let windowHalfY = window.innerHeight / 2;
  56. let windowThirdX = window.innerWidth / 3;
  57. init();
  58. animate();
  59. function init() {
  60. params = {
  61. bloomAmount: 1.0,
  62. sunLight: 4.0,
  63. enabled: true,
  64. avgLuminance: 0.7,
  65. middleGrey: 0.04,
  66. maxLuminance: 16,
  67. adaptionRate: 2.0
  68. };
  69. const container = document.createElement( 'div' );
  70. document.body.appendChild( container );
  71. // CAMERAS
  72. camera = new THREE.PerspectiveCamera( 70, windowThirdX / window.innerHeight, 0.1, 100000 );
  73. camera.position.x = 700;
  74. camera.position.y = 400;
  75. camera.position.z = 800;
  76. cameraCube = new THREE.PerspectiveCamera( 70, windowThirdX / window.innerHeight, 1, 100000 );
  77. cameraBG = new THREE.OrthographicCamera( - windowHalfX, windowHalfX, windowHalfY, - windowHalfY, - 10000, 10000 );
  78. cameraBG.position.z = 100;
  79. orbitControls = new OrbitControls( camera, container );
  80. orbitControls.autoRotate = true;
  81. orbitControls.autoRotateSpeed = 1;
  82. // SCENE
  83. scene = new THREE.Scene();
  84. sceneCube = new THREE.Scene();
  85. debugScene = new THREE.Scene();
  86. // LIGHTS
  87. const ambient = new THREE.AmbientLight( 0x050505 );
  88. scene.add( ambient );
  89. directionalLight = new THREE.DirectionalLight( 0xffffff, params.sunLight );
  90. directionalLight.position.set( 2, 0, 10 ).normalize();
  91. scene.add( directionalLight );
  92. const atmoShader = {
  93. side: THREE.BackSide,
  94. // blending: THREE.AdditiveBlending,
  95. transparent: true,
  96. lights: true,
  97. uniforms: THREE.UniformsUtils.merge( [
  98. THREE.UniformsLib[ "common" ],
  99. THREE.UniformsLib[ "lights" ]
  100. ] ),
  101. vertexShader: [
  102. "varying vec3 vViewPosition;",
  103. "varying vec3 vNormal;",
  104. "void main() {",
  105. THREE.ShaderChunk[ "beginnormal_vertex" ],
  106. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  107. " vNormal = normalize( transformedNormal );",
  108. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  109. "vViewPosition = -mvPosition.xyz;",
  110. "gl_Position = projectionMatrix * mvPosition;",
  111. "}"
  112. ].join( "\n" ),
  113. fragmentShader: [
  114. THREE.ShaderChunk[ "common" ],
  115. THREE.ShaderChunk[ "bsdfs" ],
  116. THREE.ShaderChunk[ "lights_pars_begin" ],
  117. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  118. "void main() {",
  119. "vec3 normal = normalize( -vNormal );",
  120. "vec3 viewPosition = normalize( vViewPosition );",
  121. "#if NUM_DIR_LIGHTS > 0",
  122. "vec3 dirDiffuse = vec3( 0.0 );",
  123. "for( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {",
  124. "vec4 lDirection = viewMatrix * vec4( directionalLights[i].direction, 0.0 );",
  125. "vec3 dirVector = normalize( lDirection.xyz );",
  126. "float dotProduct = dot( viewPosition, dirVector );",
  127. "dotProduct = 1.0 * max( dotProduct, 0.0 ) + (1.0 - max( -dot( normal, dirVector ), 0.0 ));",
  128. "dotProduct *= dotProduct;",
  129. "dirDiffuse += max( 0.5 * dotProduct, 0.0 ) * directionalLights[i].color;",
  130. "}",
  131. "#endif",
  132. //Fade out atmosphere at edge
  133. "float viewDot = abs(dot( normal, viewPosition ));",
  134. "viewDot = clamp( pow( viewDot + 0.6, 10.0 ), 0.0, 1.0);",
  135. "vec3 color = vec3( 0.05, 0.09, 0.13 ) * dirDiffuse;",
  136. "gl_FragColor = vec4( color, viewDot );",
  137. "}"
  138. ].join( "\n" )
  139. };
  140. const earthAtmoMat = new THREE.ShaderMaterial( atmoShader );
  141. const earthMat = new THREE.MeshPhongMaterial( {
  142. color: 0xffffff,
  143. shininess: 200
  144. } );
  145. const textureLoader = new THREE.TextureLoader();
  146. textureLoader.load( 'textures/planets/earth_atmos_4096.jpg', function ( tex ) {
  147. earthMat.map = tex;
  148. earthMat.map.encoding = THREE.sRGBEncoding;
  149. earthMat.needsUpdate = true;
  150. } );
  151. textureLoader.load( 'textures/planets/earth_specular_2048.jpg', function ( tex ) {
  152. earthMat.specularMap = tex;
  153. earthMat.specularMap.encoding = THREE.sRGBEncoding;
  154. earthMat.needsUpdate = true;
  155. } );
  156. // let earthNormal = textureLoader.load( 'textures/planets/earth-new-normal-2048.jpg', function( tex ) {
  157. // earthMat.normalMap = tex;
  158. // earthMat.needsUpdate = true;
  159. // } );
  160. const earthLights = textureLoader.load( 'textures/planets/earth_lights_2048.png' );
  161. earthLights.encoding = THREE.sRGBEncoding;
  162. const earthLightsMat = new THREE.MeshBasicMaterial( {
  163. color: 0xffffff,
  164. blending: THREE.AdditiveBlending,
  165. transparent: true,
  166. depthTest: false,
  167. map: earthLights,
  168. } );
  169. const clouds = textureLoader.load( 'textures/planets/earth_clouds_2048.png' );
  170. clouds.encoding = THREE.sRGBEncoding;
  171. const earthCloudsMat = new THREE.MeshLambertMaterial( {
  172. color: 0xffffff,
  173. blending: THREE.NormalBlending,
  174. transparent: true,
  175. depthTest: false,
  176. map: clouds
  177. } );
  178. const earthGeo = new THREE.SphereGeometry( 600, 24, 24 );
  179. const sphereMesh = new THREE.Mesh( earthGeo, earthMat );
  180. scene.add( sphereMesh );
  181. const sphereLightsMesh = new THREE.Mesh( earthGeo, earthLightsMat );
  182. scene.add( sphereLightsMesh );
  183. const sphereCloudsMesh = new THREE.Mesh( earthGeo, earthCloudsMat );
  184. scene.add( sphereCloudsMesh );
  185. const sphereAtmoMesh = new THREE.Mesh( earthGeo, earthAtmoMat );
  186. sphereAtmoMesh.scale.set( 1.05, 1.05, 1.05 );
  187. scene.add( sphereAtmoMesh );
  188. const vBGShader = [
  189. // "attribute vec2 uv;",
  190. "varying vec2 vUv;",
  191. "void main() {",
  192. "vUv = uv;",
  193. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  194. "}"
  195. ].join( "\n" );
  196. const pBGShader = [
  197. "uniform sampler2D map;",
  198. "varying vec2 vUv;",
  199. "void main() {",
  200. "vec2 sampleUV = vUv;",
  201. "vec4 color = texture2D( map, sampleUV, 0.0 );",
  202. "gl_FragColor = vec4( color.xyz, 1.0 );",
  203. "}"
  204. ].join( "\n" );
  205. // Skybox
  206. adaptiveLuminanceMat = new THREE.ShaderMaterial( {
  207. uniforms: {
  208. "map": { value: null }
  209. },
  210. vertexShader: vBGShader,
  211. fragmentShader: pBGShader,
  212. depthTest: false,
  213. // color: 0xffffff
  214. blending: THREE.NoBlending
  215. } );
  216. currentLuminanceMat = new THREE.ShaderMaterial( {
  217. uniforms: {
  218. "map": { value: null }
  219. },
  220. vertexShader: vBGShader,
  221. fragmentShader: pBGShader,
  222. depthTest: false
  223. // color: 0xffffff
  224. // blending: THREE.NoBlending
  225. } );
  226. let quadBG = new THREE.Mesh( new THREE.PlaneGeometry( 0.1, 0.1 ), currentLuminanceMat );
  227. quadBG.position.z = - 500;
  228. quadBG.position.x = - window.innerWidth * 0.5 + window.innerWidth * 0.05;
  229. quadBG.scale.set( window.innerWidth, window.innerHeight, 1 );
  230. debugScene.add( quadBG );
  231. quadBG = new THREE.Mesh( new THREE.PlaneGeometry( 0.1, 0.1 ), adaptiveLuminanceMat );
  232. quadBG.position.z = - 500;
  233. quadBG.position.x = - window.innerWidth * 0.5 + window.innerWidth * 0.15;
  234. quadBG.scale.set( window.innerWidth, window.innerHeight, 1 );
  235. debugScene.add( quadBG );
  236. const r = "textures/cube/MilkyWay/";
  237. const urls = [ r + "dark-s_px.jpg", r + "dark-s_nx.jpg",
  238. r + "dark-s_py.jpg", r + "dark-s_ny.jpg",
  239. r + "dark-s_pz.jpg", r + "dark-s_nz.jpg" ];
  240. const textureCube = new THREE.CubeTextureLoader().load( urls );
  241. textureCube.encoding = THREE.sRGBEncoding;
  242. sceneCube.background = textureCube;
  243. renderer = new THREE.WebGLRenderer();
  244. renderer.setPixelRatio( window.devicePixelRatio );
  245. renderer.setSize( window.innerWidth, window.innerHeight );
  246. renderer.autoClear = false;
  247. container.appendChild( renderer.domElement );
  248. // let width = window.innerWidth || 1;
  249. const height = window.innerHeight || 1;
  250. const parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  251. const regularRenderTarget = new THREE.WebGLRenderTarget( windowThirdX, height, parameters );
  252. ldrEffectComposer = new EffectComposer( renderer, regularRenderTarget );
  253. parameters.type = THREE.FloatType;
  254. if ( renderer.capabilities.isWebGL2 === false && renderer.extensions.has( 'OES_texture_half_float_linear' ) === false ) {
  255. parameters.type = undefined; // avoid usage of floating point textures
  256. }
  257. const hdrRenderTarget = new THREE.WebGLRenderTarget( windowThirdX, height, parameters );
  258. dynamicHdrEffectComposer = new EffectComposer( renderer, hdrRenderTarget );
  259. dynamicHdrEffectComposer.setSize( window.innerWidth, window.innerHeight );
  260. hdrEffectComposer = new EffectComposer( renderer, hdrRenderTarget );
  261. const debugPass = new RenderPass( debugScene, cameraBG );
  262. debugPass.clear = false;
  263. const scenePass = new RenderPass( scene, camera, undefined, undefined, undefined );
  264. const skyboxPass = new RenderPass( sceneCube, cameraCube );
  265. scenePass.clear = false;
  266. adaptToneMappingPass = new AdaptiveToneMappingPass( true, 256 );
  267. adaptToneMappingPass.needsSwap = true;
  268. ldrToneMappingPass = new AdaptiveToneMappingPass( false, 256 );
  269. hdrToneMappingPass = new AdaptiveToneMappingPass( false, 256 );
  270. bloomPass = new BloomPass();
  271. const gammaCorrectionPass = new ShaderPass( GammaCorrectionShader );
  272. dynamicHdrEffectComposer.addPass( skyboxPass );
  273. dynamicHdrEffectComposer.addPass( scenePass );
  274. dynamicHdrEffectComposer.addPass( adaptToneMappingPass );
  275. dynamicHdrEffectComposer.addPass( bloomPass );
  276. dynamicHdrEffectComposer.addPass( gammaCorrectionPass );
  277. hdrEffectComposer.addPass( skyboxPass );
  278. hdrEffectComposer.addPass( scenePass );
  279. hdrEffectComposer.addPass( hdrToneMappingPass );
  280. hdrEffectComposer.addPass( bloomPass );
  281. hdrEffectComposer.addPass( gammaCorrectionPass );
  282. ldrEffectComposer.addPass( skyboxPass );
  283. ldrEffectComposer.addPass( scenePass );
  284. ldrEffectComposer.addPass( ldrToneMappingPass );
  285. ldrEffectComposer.addPass( bloomPass );
  286. ldrEffectComposer.addPass( gammaCorrectionPass );
  287. const gui = new GUI();
  288. const sceneGui = gui.addFolder( 'Scenes' );
  289. const toneMappingGui = gui.addFolder( 'ToneMapping' );
  290. const staticToneMappingGui = gui.addFolder( 'StaticOnly' );
  291. const adaptiveToneMappingGui = gui.addFolder( 'AdaptiveOnly' );
  292. sceneGui.add( params, 'bloomAmount', 0.0, 10.0 );
  293. sceneGui.add( params, 'sunLight', 0.1, 12.0 );
  294. toneMappingGui.add( params, 'enabled' );
  295. toneMappingGui.add( params, 'middleGrey', 0, 12 );
  296. toneMappingGui.add( params, 'maxLuminance', 1, 30 );
  297. staticToneMappingGui.add( params, 'avgLuminance', 0.001, 2.0 );
  298. adaptiveToneMappingGui.add( params, 'adaptionRate', 0.0, 10.0 );
  299. gui.open();
  300. window.addEventListener( 'resize', onWindowResize );
  301. }
  302. function onWindowResize() {
  303. windowHalfX = window.innerWidth / 2;
  304. windowHalfY = window.innerHeight / 2;
  305. windowThirdX = window.innerWidth / 3;
  306. camera.aspect = windowThirdX / window.innerHeight;
  307. camera.updateProjectionMatrix();
  308. cameraCube.aspect = windowThirdX / window.innerHeight;
  309. cameraCube.updateProjectionMatrix();
  310. renderer.setSize( window.innerWidth, window.innerHeight );
  311. }
  312. function animate() {
  313. requestAnimationFrame( animate );
  314. if ( bloomPass ) {
  315. bloomPass.copyUniforms[ "opacity" ].value = params.bloomAmount;
  316. }
  317. if ( adaptToneMappingPass ) {
  318. adaptToneMappingPass.setAdaptionRate( params.adaptionRate );
  319. adaptiveLuminanceMat.uniforms[ "map" ].value = adaptToneMappingPass.luminanceRT;
  320. currentLuminanceMat.uniforms[ "map" ].value = adaptToneMappingPass.currentLuminanceRT;
  321. adaptToneMappingPass.enabled = params.enabled;
  322. adaptToneMappingPass.setMaxLuminance( params.maxLuminance );
  323. adaptToneMappingPass.setMiddleGrey( params.middleGrey );
  324. hdrToneMappingPass.enabled = params.enabled;
  325. hdrToneMappingPass.setMaxLuminance( params.maxLuminance );
  326. hdrToneMappingPass.setMiddleGrey( params.middleGrey );
  327. if ( hdrToneMappingPass.setAverageLuminance ) {
  328. hdrToneMappingPass.setAverageLuminance( params.avgLuminance );
  329. }
  330. ldrToneMappingPass.enabled = params.enabled;
  331. ldrToneMappingPass.setMaxLuminance( params.maxLuminance );
  332. ldrToneMappingPass.setMiddleGrey( params.middleGrey );
  333. if ( ldrToneMappingPass.setAverageLuminance ) {
  334. ldrToneMappingPass.setAverageLuminance( params.avgLuminance );
  335. }
  336. }
  337. directionalLight.intensity = params.sunLight;
  338. orbitControls.update();
  339. render();
  340. }
  341. function render() {
  342. camera.lookAt( scene.position );
  343. cameraCube.rotation.copy( camera.rotation );
  344. renderer.setViewport( 0, 0, windowThirdX, window.innerHeight );
  345. ldrEffectComposer.render( 0.017 );
  346. renderer.setViewport( windowThirdX, 0, windowThirdX, window.innerHeight );
  347. hdrEffectComposer.render( 0.017 );
  348. renderer.setViewport( windowThirdX * 2, 0, windowThirdX, window.innerHeight );
  349. dynamicHdrEffectComposer.render( 0.017 );
  350. }
  351. </script>
  352. </body>
  353. </html>