webgl_postprocessing_godrays.html 13 KB

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