webgl_postprocessing_godrays.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - postprocessing - godrays</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> - webgl god-rays example - tree by <a href="http://www.turbosquid.com/3d-models/free-tree-3d-model/592617" target="_blank" rel="noopener">stanloshka</a>
  12. </div>
  13. <script type="module">
  14. import * as THREE from '../build/three.module.js';
  15. import Stats from './jsm/libs/stats.module.js';
  16. import { OBJLoader } from './jsm/loaders/OBJLoader.js';
  17. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  18. import { GodRaysFakeSunShader, GodRaysDepthMaskShader, GodRaysCombineShader, GodRaysGenerateShader } from './jsm/shaders/GodRaysShader.js';
  19. let container, stats;
  20. let camera, scene, renderer, materialDepth;
  21. let sphereMesh;
  22. const sunPosition = new THREE.Vector3( 0, 1000, - 1000 );
  23. const clipPosition = new THREE.Vector4();
  24. const screenSpacePosition = new THREE.Vector3();
  25. const postprocessing = { enabled: true };
  26. const orbitRadius = 200;
  27. const bgColor = 0x000511;
  28. const sunColor = 0xffee00;
  29. // Use a smaller size for some of the god-ray render targets for better performance.
  30. const godrayRenderTargetResolutionMultiplier = 1.0 / 4.0;
  31. init();
  32. animate();
  33. function init() {
  34. container = document.createElement( 'div' );
  35. document.body.appendChild( container );
  36. //
  37. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 3000 );
  38. camera.position.z = 200;
  39. scene = new THREE.Scene();
  40. //
  41. materialDepth = new THREE.MeshDepthMaterial();
  42. const materialScene = new THREE.MeshBasicMaterial( { color: 0x000000 } );
  43. // tree
  44. const loader = new OBJLoader();
  45. loader.load( 'models/obj/tree.obj', function ( object ) {
  46. object.material = materialScene;
  47. object.position.set( 0, - 150, - 150 );
  48. object.scale.multiplyScalar( 400 );
  49. scene.add( object );
  50. } );
  51. // sphere
  52. const geo = new THREE.SphereGeometry( 1, 20, 10 );
  53. sphereMesh = new THREE.Mesh( geo, materialScene );
  54. sphereMesh.scale.multiplyScalar( 20 );
  55. scene.add( sphereMesh );
  56. //
  57. renderer = new THREE.WebGLRenderer();
  58. renderer.setClearColor( 0xffffff );
  59. renderer.setPixelRatio( window.devicePixelRatio );
  60. renderer.setSize( window.innerWidth, window.innerHeight );
  61. container.appendChild( renderer.domElement );
  62. renderer.autoClear = false;
  63. const controls = new OrbitControls( camera, renderer.domElement );
  64. controls.minDistance = 50;
  65. controls.maxDistance = 500;
  66. //
  67. stats = new Stats();
  68. container.appendChild( stats.dom );
  69. //
  70. window.addEventListener( 'resize', onWindowResize );
  71. //
  72. initPostprocessing( window.innerWidth, window.innerHeight );
  73. }
  74. //
  75. function onWindowResize() {
  76. const renderTargetWidth = window.innerWidth;
  77. const renderTargetHeight = window.innerHeight;
  78. camera.aspect = renderTargetWidth / renderTargetHeight;
  79. camera.updateProjectionMatrix();
  80. renderer.setSize( renderTargetWidth, renderTargetHeight );
  81. postprocessing.rtTextureColors.setSize( renderTargetWidth, renderTargetHeight );
  82. postprocessing.rtTextureDepth.setSize( renderTargetWidth, renderTargetHeight );
  83. postprocessing.rtTextureDepthMask.setSize( renderTargetWidth, renderTargetHeight );
  84. const adjustedWidth = renderTargetWidth * godrayRenderTargetResolutionMultiplier;
  85. const adjustedHeight = renderTargetHeight * godrayRenderTargetResolutionMultiplier;
  86. postprocessing.rtTextureGodRays1.setSize( adjustedWidth, adjustedHeight );
  87. postprocessing.rtTextureGodRays2.setSize( adjustedWidth, adjustedHeight );
  88. }
  89. function initPostprocessing( renderTargetWidth, renderTargetHeight ) {
  90. postprocessing.scene = new THREE.Scene();
  91. postprocessing.camera = new THREE.OrthographicCamera( - 0.5, 0.5, 0.5, - 0.5, - 10000, 10000 );
  92. postprocessing.camera.position.z = 100;
  93. postprocessing.scene.add( postprocessing.camera );
  94. const pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };
  95. postprocessing.rtTextureColors = new THREE.WebGLRenderTarget( renderTargetWidth, renderTargetHeight, pars );
  96. // Switching the depth formats to luminance from rgb doesn't seem to work. I didn't
  97. // investigate further for now.
  98. // pars.format = LuminanceFormat;
  99. // I would have this quarter size and use it as one of the ping-pong render
  100. // targets but the aliasing causes some temporal flickering
  101. postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( renderTargetWidth, renderTargetHeight, pars );
  102. postprocessing.rtTextureDepthMask = new THREE.WebGLRenderTarget( renderTargetWidth, renderTargetHeight, pars );
  103. // The ping-pong render targets can use an adjusted resolution to minimize cost
  104. const adjustedWidth = renderTargetWidth * godrayRenderTargetResolutionMultiplier;
  105. const adjustedHeight = renderTargetHeight * godrayRenderTargetResolutionMultiplier;
  106. postprocessing.rtTextureGodRays1 = new THREE.WebGLRenderTarget( adjustedWidth, adjustedHeight, pars );
  107. postprocessing.rtTextureGodRays2 = new THREE.WebGLRenderTarget( adjustedWidth, adjustedHeight, pars );
  108. // god-ray shaders
  109. const godraysMaskShader = GodRaysDepthMaskShader;
  110. postprocessing.godrayMaskUniforms = THREE.UniformsUtils.clone( godraysMaskShader.uniforms );
  111. postprocessing.materialGodraysDepthMask = new THREE.ShaderMaterial( {
  112. uniforms: postprocessing.godrayMaskUniforms,
  113. vertexShader: godraysMaskShader.vertexShader,
  114. fragmentShader: godraysMaskShader.fragmentShader
  115. } );
  116. const godraysGenShader = GodRaysGenerateShader;
  117. postprocessing.godrayGenUniforms = THREE.UniformsUtils.clone( godraysGenShader.uniforms );
  118. postprocessing.materialGodraysGenerate = new THREE.ShaderMaterial( {
  119. uniforms: postprocessing.godrayGenUniforms,
  120. vertexShader: godraysGenShader.vertexShader,
  121. fragmentShader: godraysGenShader.fragmentShader
  122. } );
  123. const godraysCombineShader = GodRaysCombineShader;
  124. postprocessing.godrayCombineUniforms = THREE.UniformsUtils.clone( godraysCombineShader.uniforms );
  125. postprocessing.materialGodraysCombine = new THREE.ShaderMaterial( {
  126. uniforms: postprocessing.godrayCombineUniforms,
  127. vertexShader: godraysCombineShader.vertexShader,
  128. fragmentShader: godraysCombineShader.fragmentShader
  129. } );
  130. const godraysFakeSunShader = GodRaysFakeSunShader;
  131. postprocessing.godraysFakeSunUniforms = THREE.UniformsUtils.clone( godraysFakeSunShader.uniforms );
  132. postprocessing.materialGodraysFakeSun = new THREE.ShaderMaterial( {
  133. uniforms: postprocessing.godraysFakeSunUniforms,
  134. vertexShader: godraysFakeSunShader.vertexShader,
  135. fragmentShader: godraysFakeSunShader.fragmentShader
  136. } );
  137. postprocessing.godraysFakeSunUniforms.bgColor.value.setHex( bgColor );
  138. postprocessing.godraysFakeSunUniforms.sunColor.value.setHex( sunColor );
  139. postprocessing.godrayCombineUniforms.fGodRayIntensity.value = 0.75;
  140. postprocessing.quad = new THREE.Mesh(
  141. new THREE.PlaneGeometry( 1.0, 1.0 ),
  142. postprocessing.materialGodraysGenerate
  143. );
  144. postprocessing.quad.position.z = - 9900;
  145. postprocessing.scene.add( postprocessing.quad );
  146. }
  147. function animate() {
  148. requestAnimationFrame( animate, renderer.domElement );
  149. stats.begin();
  150. render();
  151. stats.end();
  152. }
  153. function getStepSize( filterLen, tapsPerPass, pass ) {
  154. return filterLen * Math.pow( tapsPerPass, - pass );
  155. }
  156. function filterGodRays( inputTex, renderTarget, stepSize ) {
  157. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysGenerate;
  158. postprocessing.godrayGenUniforms[ "fStepSize" ].value = stepSize;
  159. postprocessing.godrayGenUniforms[ "tInput" ].value = inputTex;
  160. renderer.setRenderTarget( renderTarget );
  161. renderer.render( postprocessing.scene, postprocessing.camera );
  162. postprocessing.scene.overrideMaterial = null;
  163. }
  164. function render() {
  165. const time = Date.now() / 4000;
  166. sphereMesh.position.x = orbitRadius * Math.cos( time );
  167. sphereMesh.position.z = orbitRadius * Math.sin( time ) - 100;
  168. if ( postprocessing.enabled ) {
  169. clipPosition.x = sunPosition.x;
  170. clipPosition.y = sunPosition.y;
  171. clipPosition.z = sunPosition.z;
  172. clipPosition.w = 1;
  173. clipPosition.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  174. // perspective divide (produce NDC space)
  175. clipPosition.x /= clipPosition.w;
  176. clipPosition.y /= clipPosition.w;
  177. screenSpacePosition.x = ( clipPosition.x + 1 ) / 2; // transform from [-1,1] to [0,1]
  178. screenSpacePosition.y = ( clipPosition.y + 1 ) / 2; // transform from [-1,1] to [0,1]
  179. screenSpacePosition.z = clipPosition.z; // needs to stay in clip space for visibilty checks
  180. // Give it to the god-ray and sun shaders
  181. postprocessing.godrayGenUniforms[ "vSunPositionScreenSpace" ].value.copy( screenSpacePosition );
  182. postprocessing.godraysFakeSunUniforms[ "vSunPositionScreenSpace" ].value.copy( screenSpacePosition );
  183. // -- Draw sky and sun --
  184. // Clear colors and depths, will clear to sky color
  185. renderer.setRenderTarget( postprocessing.rtTextureColors );
  186. renderer.clear( true, true, false );
  187. // Sun render. Runs a shader that gives a brightness based on the screen
  188. // space distance to the sun. Not very efficient, so i make a scissor
  189. // rectangle around the suns position to avoid rendering surrounding pixels.
  190. const sunsqH = 0.74 * window.innerHeight; // 0.74 depends on extent of sun from shader
  191. const sunsqW = 0.74 * window.innerHeight; // both depend on height because sun is aspect-corrected
  192. screenSpacePosition.x *= window.innerWidth;
  193. screenSpacePosition.y *= window.innerHeight;
  194. renderer.setScissor( screenSpacePosition.x - sunsqW / 2, screenSpacePosition.y - sunsqH / 2, sunsqW, sunsqH );
  195. renderer.setScissorTest( true );
  196. postprocessing.godraysFakeSunUniforms[ "fAspect" ].value = window.innerWidth / window.innerHeight;
  197. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysFakeSun;
  198. renderer.setRenderTarget( postprocessing.rtTextureColors );
  199. renderer.render( postprocessing.scene, postprocessing.camera );
  200. renderer.setScissorTest( false );
  201. // -- Draw scene objects --
  202. // Colors
  203. scene.overrideMaterial = null;
  204. renderer.setRenderTarget( postprocessing.rtTextureColors );
  205. renderer.render( scene, camera );
  206. // Depth
  207. scene.overrideMaterial = materialDepth;
  208. renderer.setRenderTarget( postprocessing.rtTextureDepth );
  209. renderer.clear();
  210. renderer.render( scene, camera );
  211. //
  212. postprocessing.godrayMaskUniforms[ "tInput" ].value = postprocessing.rtTextureDepth.texture;
  213. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysDepthMask;
  214. renderer.setRenderTarget( postprocessing.rtTextureDepthMask );
  215. renderer.render( postprocessing.scene, postprocessing.camera );
  216. // -- Render god-rays --
  217. // Maximum length of god-rays (in texture space [0,1]X[0,1])
  218. const filterLen = 1.0;
  219. // Samples taken by filter
  220. const TAPS_PER_PASS = 6.0;
  221. // Pass order could equivalently be 3,2,1 (instead of 1,2,3), which
  222. // would start with a small filter support and grow to large. however
  223. // the large-to-small order produces less objectionable aliasing artifacts that
  224. // appear as a glimmer along the length of the beams
  225. // pass 1 - render into first ping-pong target
  226. filterGodRays( postprocessing.rtTextureDepthMask.texture, postprocessing.rtTextureGodRays2, getStepSize( filterLen, TAPS_PER_PASS, 1.0 ) );
  227. // pass 2 - render into second ping-pong target
  228. filterGodRays( postprocessing.rtTextureGodRays2.texture, postprocessing.rtTextureGodRays1, getStepSize( filterLen, TAPS_PER_PASS, 2.0 ) );
  229. // pass 3 - 1st RT
  230. filterGodRays( postprocessing.rtTextureGodRays1.texture, postprocessing.rtTextureGodRays2, getStepSize( filterLen, TAPS_PER_PASS, 3.0 ) );
  231. // final pass - composite god-rays onto colors
  232. postprocessing.godrayCombineUniforms[ "tColors" ].value = postprocessing.rtTextureColors.texture;
  233. postprocessing.godrayCombineUniforms[ "tGodRays" ].value = postprocessing.rtTextureGodRays2.texture;
  234. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysCombine;
  235. renderer.setRenderTarget( null );
  236. renderer.render( postprocessing.scene, postprocessing.camera );
  237. postprocessing.scene.overrideMaterial = null;
  238. } else {
  239. renderer.setRenderTarget( null );
  240. renderer.clear();
  241. renderer.render( scene, camera );
  242. }
  243. }
  244. </script>
  245. </body>
  246. </html>