UnrealBloomPass.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. import {
  2. AdditiveBlending,
  3. Color,
  4. HalfFloatType,
  5. MeshBasicMaterial,
  6. ShaderMaterial,
  7. UniformsUtils,
  8. Vector2,
  9. Vector3,
  10. WebGLRenderTarget
  11. } from 'three';
  12. import { Pass, FullScreenQuad } from './Pass.js';
  13. import { CopyShader } from '../shaders/CopyShader.js';
  14. import { LuminosityHighPassShader } from '../shaders/LuminosityHighPassShader.js';
  15. /**
  16. * This pass is inspired by the bloom pass of Unreal Engine. It creates a
  17. * mip map chain of bloom textures and blurs them with different radii. Because
  18. * of the weighted combination of mips, and because larger blurs are done on
  19. * higher mips, this effect provides good quality and performance.
  20. *
  21. * When using this pass, tone mapping must be enabled in the renderer settings.
  22. *
  23. * Reference:
  24. * - [Bloom in Unreal Engine]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/}
  25. *
  26. * ```js
  27. * const resolution = new THREE.Vector2( window.innerWidth, window.innerHeight );
  28. * const bloomPass = new UnrealBloomPass( resolution, 1.5, 0.4, 0.85 );
  29. * composer.addPass( bloomPass );
  30. * ```
  31. *
  32. * @augments Pass
  33. * @three_import import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
  34. */
  35. class UnrealBloomPass extends Pass {
  36. /**
  37. * Constructs a new Unreal Bloom pass.
  38. *
  39. * @param {Vector2} [resolution] - The effect's resolution.
  40. * @param {number} [strength=1] - The Bloom strength.
  41. * @param {number} radius - The Bloom radius.
  42. * @param {number} threshold - The luminance threshold limits which bright areas contribute to the Bloom effect.
  43. */
  44. constructor( resolution, strength = 1, radius, threshold ) {
  45. super();
  46. /**
  47. * The Bloom strength.
  48. *
  49. * @type {number}
  50. * @default 1
  51. */
  52. this.strength = strength;
  53. /**
  54. * The Bloom radius.
  55. *
  56. * @type {number}
  57. */
  58. this.radius = radius;
  59. /**
  60. * The luminance threshold limits which bright areas contribute to the Bloom effect.
  61. *
  62. * @type {number}
  63. */
  64. this.threshold = threshold;
  65. /**
  66. * The effect's resolution.
  67. *
  68. * @type {Vector2}
  69. * @default (256,256)
  70. */
  71. this.resolution = ( resolution !== undefined ) ? new Vector2( resolution.x, resolution.y ) : new Vector2( 256, 256 );
  72. /**
  73. * The effect's clear color
  74. *
  75. * @type {Color}
  76. * @default (0,0,0)
  77. */
  78. this.clearColor = new Color( 0, 0, 0 );
  79. /**
  80. * Overwritten to disable the swap.
  81. *
  82. * @type {boolean}
  83. * @default false
  84. */
  85. this.needsSwap = false;
  86. // internals
  87. // render targets
  88. this.renderTargetsHorizontal = [];
  89. this.renderTargetsVertical = [];
  90. this.nMips = 5;
  91. let resx = Math.round( this.resolution.x / 2 );
  92. let resy = Math.round( this.resolution.y / 2 );
  93. this.renderTargetBright = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
  94. this.renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  95. this.renderTargetBright.texture.generateMipmaps = false;
  96. for ( let i = 0; i < this.nMips; i ++ ) {
  97. const renderTargetHorizontal = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
  98. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  99. renderTargetHorizontal.texture.generateMipmaps = false;
  100. this.renderTargetsHorizontal.push( renderTargetHorizontal );
  101. const renderTargetVertical = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
  102. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  103. renderTargetVertical.texture.generateMipmaps = false;
  104. this.renderTargetsVertical.push( renderTargetVertical );
  105. resx = Math.round( resx / 2 );
  106. resy = Math.round( resy / 2 );
  107. }
  108. // luminosity high pass material
  109. const highPassShader = LuminosityHighPassShader;
  110. this.highPassUniforms = UniformsUtils.clone( highPassShader.uniforms );
  111. this.highPassUniforms[ 'luminosityThreshold' ].value = threshold;
  112. this.highPassUniforms[ 'smoothWidth' ].value = 0.01;
  113. this.materialHighPassFilter = new ShaderMaterial( {
  114. uniforms: this.highPassUniforms,
  115. vertexShader: highPassShader.vertexShader,
  116. fragmentShader: highPassShader.fragmentShader
  117. } );
  118. // gaussian blur materials
  119. this.separableBlurMaterials = [];
  120. const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
  121. resx = Math.round( this.resolution.x / 2 );
  122. resy = Math.round( this.resolution.y / 2 );
  123. for ( let i = 0; i < this.nMips; i ++ ) {
  124. this.separableBlurMaterials.push( this._getSeparableBlurMaterial( kernelSizeArray[ i ] ) );
  125. this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
  126. resx = Math.round( resx / 2 );
  127. resy = Math.round( resy / 2 );
  128. }
  129. // composite material
  130. this.compositeMaterial = this._getCompositeMaterial( this.nMips );
  131. this.compositeMaterial.uniforms[ 'blurTexture1' ].value = this.renderTargetsVertical[ 0 ].texture;
  132. this.compositeMaterial.uniforms[ 'blurTexture2' ].value = this.renderTargetsVertical[ 1 ].texture;
  133. this.compositeMaterial.uniforms[ 'blurTexture3' ].value = this.renderTargetsVertical[ 2 ].texture;
  134. this.compositeMaterial.uniforms[ 'blurTexture4' ].value = this.renderTargetsVertical[ 3 ].texture;
  135. this.compositeMaterial.uniforms[ 'blurTexture5' ].value = this.renderTargetsVertical[ 4 ].texture;
  136. this.compositeMaterial.uniforms[ 'bloomStrength' ].value = strength;
  137. this.compositeMaterial.uniforms[ 'bloomRadius' ].value = 0.1;
  138. const bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ];
  139. this.compositeMaterial.uniforms[ 'bloomFactors' ].value = bloomFactors;
  140. this.bloomTintColors = [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ];
  141. this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
  142. // blend material
  143. this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
  144. this.blendMaterial = new ShaderMaterial( {
  145. uniforms: this.copyUniforms,
  146. vertexShader: CopyShader.vertexShader,
  147. fragmentShader: CopyShader.fragmentShader,
  148. blending: AdditiveBlending,
  149. depthTest: false,
  150. depthWrite: false,
  151. transparent: true
  152. } );
  153. this._oldClearColor = new Color();
  154. this._oldClearAlpha = 1;
  155. this._basic = new MeshBasicMaterial();
  156. this._fsQuad = new FullScreenQuad( null );
  157. }
  158. /**
  159. * Frees the GPU-related resources allocated by this instance. Call this
  160. * method whenever the pass is no longer used in your app.
  161. */
  162. dispose() {
  163. for ( let i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
  164. this.renderTargetsHorizontal[ i ].dispose();
  165. }
  166. for ( let i = 0; i < this.renderTargetsVertical.length; i ++ ) {
  167. this.renderTargetsVertical[ i ].dispose();
  168. }
  169. this.renderTargetBright.dispose();
  170. //
  171. for ( let i = 0; i < this.separableBlurMaterials.length; i ++ ) {
  172. this.separableBlurMaterials[ i ].dispose();
  173. }
  174. this.compositeMaterial.dispose();
  175. this.blendMaterial.dispose();
  176. this._basic.dispose();
  177. //
  178. this._fsQuad.dispose();
  179. }
  180. /**
  181. * Sets the size of the pass.
  182. *
  183. * @param {number} width - The width to set.
  184. * @param {number} height - The width to set.
  185. */
  186. setSize( width, height ) {
  187. let resx = Math.round( width / 2 );
  188. let resy = Math.round( height / 2 );
  189. this.renderTargetBright.setSize( resx, resy );
  190. for ( let i = 0; i < this.nMips; i ++ ) {
  191. this.renderTargetsHorizontal[ i ].setSize( resx, resy );
  192. this.renderTargetsVertical[ i ].setSize( resx, resy );
  193. this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
  194. resx = Math.round( resx / 2 );
  195. resy = Math.round( resy / 2 );
  196. }
  197. }
  198. /**
  199. * Performs the Bloom pass.
  200. *
  201. * @param {WebGLRenderer} renderer - The renderer.
  202. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
  203. * destination for the pass.
  204. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
  205. * previous pass from this buffer.
  206. * @param {number} deltaTime - The delta time in seconds.
  207. * @param {boolean} maskActive - Whether masking is active or not.
  208. */
  209. render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
  210. renderer.getClearColor( this._oldClearColor );
  211. this._oldClearAlpha = renderer.getClearAlpha();
  212. const oldAutoClear = renderer.autoClear;
  213. renderer.autoClear = false;
  214. renderer.setClearColor( this.clearColor, 0 );
  215. if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
  216. // Render input to screen
  217. if ( this.renderToScreen ) {
  218. this._fsQuad.material = this._basic;
  219. this._basic.map = readBuffer.texture;
  220. renderer.setRenderTarget( null );
  221. renderer.clear();
  222. this._fsQuad.render( renderer );
  223. }
  224. // 1. Extract Bright Areas
  225. this.highPassUniforms[ 'tDiffuse' ].value = readBuffer.texture;
  226. this.highPassUniforms[ 'luminosityThreshold' ].value = this.threshold;
  227. this._fsQuad.material = this.materialHighPassFilter;
  228. renderer.setRenderTarget( this.renderTargetBright );
  229. renderer.clear();
  230. this._fsQuad.render( renderer );
  231. // 2. Blur All the mips progressively
  232. let inputRenderTarget = this.renderTargetBright;
  233. for ( let i = 0; i < this.nMips; i ++ ) {
  234. this._fsQuad.material = this.separableBlurMaterials[ i ];
  235. this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = inputRenderTarget.texture;
  236. this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionX;
  237. renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] );
  238. renderer.clear();
  239. this._fsQuad.render( renderer );
  240. this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = this.renderTargetsHorizontal[ i ].texture;
  241. this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionY;
  242. renderer.setRenderTarget( this.renderTargetsVertical[ i ] );
  243. renderer.clear();
  244. this._fsQuad.render( renderer );
  245. inputRenderTarget = this.renderTargetsVertical[ i ];
  246. }
  247. // Composite All the mips
  248. this._fsQuad.material = this.compositeMaterial;
  249. this.compositeMaterial.uniforms[ 'bloomStrength' ].value = this.strength;
  250. this.compositeMaterial.uniforms[ 'bloomRadius' ].value = this.radius;
  251. this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
  252. renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] );
  253. renderer.clear();
  254. this._fsQuad.render( renderer );
  255. // Blend it additively over the input texture
  256. this._fsQuad.material = this.blendMaterial;
  257. this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetsHorizontal[ 0 ].texture;
  258. if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
  259. if ( this.renderToScreen ) {
  260. renderer.setRenderTarget( null );
  261. this._fsQuad.render( renderer );
  262. } else {
  263. renderer.setRenderTarget( readBuffer );
  264. this._fsQuad.render( renderer );
  265. }
  266. // Restore renderer settings
  267. renderer.setClearColor( this._oldClearColor, this._oldClearAlpha );
  268. renderer.autoClear = oldAutoClear;
  269. }
  270. // internals
  271. _getSeparableBlurMaterial( kernelRadius ) {
  272. const coefficients = [];
  273. for ( let i = 0; i < kernelRadius; i ++ ) {
  274. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  275. }
  276. return new ShaderMaterial( {
  277. defines: {
  278. 'KERNEL_RADIUS': kernelRadius
  279. },
  280. uniforms: {
  281. 'colorTexture': { value: null },
  282. 'invSize': { value: new Vector2( 0.5, 0.5 ) }, // inverse texture size
  283. 'direction': { value: new Vector2( 0.5, 0.5 ) },
  284. 'gaussianCoefficients': { value: coefficients } // precomputed Gaussian coefficients
  285. },
  286. vertexShader:
  287. `varying vec2 vUv;
  288. void main() {
  289. vUv = uv;
  290. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  291. }`,
  292. fragmentShader:
  293. `#include <common>
  294. varying vec2 vUv;
  295. uniform sampler2D colorTexture;
  296. uniform vec2 invSize;
  297. uniform vec2 direction;
  298. uniform float gaussianCoefficients[KERNEL_RADIUS];
  299. void main() {
  300. float weightSum = gaussianCoefficients[0];
  301. vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum;
  302. for( int i = 1; i < KERNEL_RADIUS; i ++ ) {
  303. float x = float(i);
  304. float w = gaussianCoefficients[i];
  305. vec2 uvOffset = direction * invSize * x;
  306. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb;
  307. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb;
  308. diffuseSum += (sample1 + sample2) * w;
  309. weightSum += 2.0 * w;
  310. }
  311. gl_FragColor = vec4(diffuseSum/weightSum, 1.0);
  312. }`
  313. } );
  314. }
  315. _getCompositeMaterial( nMips ) {
  316. return new ShaderMaterial( {
  317. defines: {
  318. 'NUM_MIPS': nMips
  319. },
  320. uniforms: {
  321. 'blurTexture1': { value: null },
  322. 'blurTexture2': { value: null },
  323. 'blurTexture3': { value: null },
  324. 'blurTexture4': { value: null },
  325. 'blurTexture5': { value: null },
  326. 'bloomStrength': { value: 1.0 },
  327. 'bloomFactors': { value: null },
  328. 'bloomTintColors': { value: null },
  329. 'bloomRadius': { value: 0.0 }
  330. },
  331. vertexShader:
  332. `varying vec2 vUv;
  333. void main() {
  334. vUv = uv;
  335. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  336. }`,
  337. fragmentShader:
  338. `varying vec2 vUv;
  339. uniform sampler2D blurTexture1;
  340. uniform sampler2D blurTexture2;
  341. uniform sampler2D blurTexture3;
  342. uniform sampler2D blurTexture4;
  343. uniform sampler2D blurTexture5;
  344. uniform float bloomStrength;
  345. uniform float bloomRadius;
  346. uniform float bloomFactors[NUM_MIPS];
  347. uniform vec3 bloomTintColors[NUM_MIPS];
  348. float lerpBloomFactor(const in float factor) {
  349. float mirrorFactor = 1.2 - factor;
  350. return mix(factor, mirrorFactor, bloomRadius);
  351. }
  352. void main() {
  353. gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) +
  354. lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) +
  355. lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) +
  356. lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) +
  357. lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );
  358. }`
  359. } );
  360. }
  361. }
  362. UnrealBloomPass.BlurDirectionX = new Vector2( 1.0, 0.0 );
  363. UnrealBloomPass.BlurDirectionY = new Vector2( 0.0, 1.0 );
  364. export { UnrealBloomPass };