UnrealBloomPass.js 14 KB

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