SSAOPass.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. import {
  2. AddEquation,
  3. Color,
  4. CustomBlending,
  5. DataTexture,
  6. DepthTexture,
  7. DstAlphaFactor,
  8. DstColorFactor,
  9. FloatType,
  10. HalfFloatType,
  11. MathUtils,
  12. MeshNormalMaterial,
  13. NearestFilter,
  14. NoBlending,
  15. RedFormat,
  16. DepthStencilFormat,
  17. UnsignedInt248Type,
  18. RepeatWrapping,
  19. ShaderMaterial,
  20. UniformsUtils,
  21. Vector3,
  22. WebGLRenderTarget,
  23. ZeroFactor
  24. } from 'three';
  25. import { Pass, FullScreenQuad } from './Pass.js';
  26. import { SimplexNoise } from '../math/SimplexNoise.js';
  27. import { SSAOBlurShader, SSAODepthShader, SSAOShader } from '../shaders/SSAOShader.js';
  28. import { CopyShader } from '../shaders/CopyShader.js';
  29. /**
  30. * A pass for a basic SSAO effect.
  31. *
  32. * {@link SAOPass} and {@link GTAPass} produce a more advanced AO but are also
  33. * more expensive.
  34. *
  35. * ```js
  36. * const ssaoPass = new SSAOPass( scene, camera, width, height );
  37. * composer.addPass( ssaoPass );
  38. * ```
  39. *
  40. * @augments Pass
  41. */
  42. class SSAOPass extends Pass {
  43. /**
  44. * Constructs a new SSAO pass.
  45. *
  46. * @param {Scene} scene - The scene to compute the AO for.
  47. * @param {Camera} camera - The camera.
  48. * @param {number} [width=512] - The width of the effect.
  49. * @param {number} [height=512] - The height of the effect.
  50. * @param {number} [kernelSize=32] - The kernel size.
  51. */
  52. constructor( scene, camera, width = 512, height = 512, kernelSize = 32 ) {
  53. super();
  54. /**
  55. * The width of the effect.
  56. *
  57. * @type {number}
  58. * @default 512
  59. */
  60. this.width = width;
  61. /**
  62. * The height of the effect.
  63. *
  64. * @type {number}
  65. * @default 512
  66. */
  67. this.height = height;
  68. /**
  69. * Overwritten to perform a clear operation by default.
  70. *
  71. * @type {boolean}
  72. * @default true
  73. */
  74. this.clear = true;
  75. /**
  76. * Overwritten to disable the swap.
  77. *
  78. * @type {boolean}
  79. * @default false
  80. */
  81. this.needsSwap = false;
  82. /**
  83. * The camera.
  84. *
  85. * @type {Camera}
  86. */
  87. this.camera = camera;
  88. /**
  89. * The scene to render the AO for.
  90. *
  91. * @type {Scene}
  92. */
  93. this.scene = scene;
  94. /**
  95. * The kernel radius controls how wide the
  96. * AO spreads.
  97. *
  98. * @type {number}
  99. * @default 8
  100. */
  101. this.kernelRadius = 8;
  102. this.kernel = [];
  103. this.noiseTexture = null;
  104. /**
  105. * The output configuration.
  106. *
  107. * @type {number}
  108. * @default 0
  109. */
  110. this.output = 0;
  111. /**
  112. * Defines the minimum distance that should be
  113. * affected by the AO.
  114. *
  115. * @type {number}
  116. * @default 0.005
  117. */
  118. this.minDistance = 0.005;
  119. /**
  120. * Defines the maximum distance that should be
  121. * affected by the AO.
  122. *
  123. * @type {number}
  124. * @default 0.1
  125. */
  126. this.maxDistance = 0.1;
  127. this._visibilityCache = new Map();
  128. //
  129. this._generateSampleKernel( kernelSize );
  130. this._generateRandomKernelRotations();
  131. // depth texture
  132. const depthTexture = new DepthTexture();
  133. depthTexture.format = DepthStencilFormat;
  134. depthTexture.type = UnsignedInt248Type;
  135. // normal render target with depth buffer
  136. this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
  137. minFilter: NearestFilter,
  138. magFilter: NearestFilter,
  139. type: HalfFloatType,
  140. depthTexture: depthTexture
  141. } );
  142. // ssao render target
  143. this.ssaoRenderTarget = new WebGLRenderTarget( this.width, this.height, { type: HalfFloatType } );
  144. this.blurRenderTarget = this.ssaoRenderTarget.clone();
  145. // ssao material
  146. this.ssaoMaterial = new ShaderMaterial( {
  147. defines: Object.assign( {}, SSAOShader.defines ),
  148. uniforms: UniformsUtils.clone( SSAOShader.uniforms ),
  149. vertexShader: SSAOShader.vertexShader,
  150. fragmentShader: SSAOShader.fragmentShader,
  151. blending: NoBlending
  152. } );
  153. this.ssaoMaterial.defines[ 'KERNEL_SIZE' ] = kernelSize;
  154. this.ssaoMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
  155. this.ssaoMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
  156. this.ssaoMaterial.uniforms[ 'tNoise' ].value = this.noiseTexture;
  157. this.ssaoMaterial.uniforms[ 'kernel' ].value = this.kernel;
  158. this.ssaoMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
  159. this.ssaoMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
  160. this.ssaoMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
  161. this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
  162. this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
  163. // normal material
  164. this.normalMaterial = new MeshNormalMaterial();
  165. this.normalMaterial.blending = NoBlending;
  166. // blur material
  167. this.blurMaterial = new ShaderMaterial( {
  168. defines: Object.assign( {}, SSAOBlurShader.defines ),
  169. uniforms: UniformsUtils.clone( SSAOBlurShader.uniforms ),
  170. vertexShader: SSAOBlurShader.vertexShader,
  171. fragmentShader: SSAOBlurShader.fragmentShader
  172. } );
  173. this.blurMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
  174. this.blurMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
  175. // material for rendering the depth
  176. this.depthRenderMaterial = new ShaderMaterial( {
  177. defines: Object.assign( {}, SSAODepthShader.defines ),
  178. uniforms: UniformsUtils.clone( SSAODepthShader.uniforms ),
  179. vertexShader: SSAODepthShader.vertexShader,
  180. fragmentShader: SSAODepthShader.fragmentShader,
  181. blending: NoBlending
  182. } );
  183. this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
  184. this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
  185. this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
  186. // material for rendering the content of a render target
  187. this.copyMaterial = new ShaderMaterial( {
  188. uniforms: UniformsUtils.clone( CopyShader.uniforms ),
  189. vertexShader: CopyShader.vertexShader,
  190. fragmentShader: CopyShader.fragmentShader,
  191. transparent: true,
  192. depthTest: false,
  193. depthWrite: false,
  194. blendSrc: DstColorFactor,
  195. blendDst: ZeroFactor,
  196. blendEquation: AddEquation,
  197. blendSrcAlpha: DstAlphaFactor,
  198. blendDstAlpha: ZeroFactor,
  199. blendEquationAlpha: AddEquation
  200. } );
  201. // internals
  202. this._fsQuad = new FullScreenQuad( null );
  203. this._originalClearColor = new Color();
  204. }
  205. /**
  206. * Frees the GPU-related resources allocated by this instance. Call this
  207. * method whenever the pass is no longer used in your app.
  208. */
  209. dispose() {
  210. // dispose render targets
  211. this.normalRenderTarget.dispose();
  212. this.ssaoRenderTarget.dispose();
  213. this.blurRenderTarget.dispose();
  214. // dispose materials
  215. this.normalMaterial.dispose();
  216. this.blurMaterial.dispose();
  217. this.copyMaterial.dispose();
  218. this.depthRenderMaterial.dispose();
  219. // dispose full screen quad
  220. this._fsQuad.dispose();
  221. }
  222. /**
  223. * Performs the SSAO pass.
  224. *
  225. * @param {WebGLRenderer} renderer - The renderer.
  226. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
  227. * destination for the pass.
  228. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
  229. * previous pass from this buffer.
  230. * @param {number} deltaTime - The delta time in seconds.
  231. * @param {boolean} maskActive - Whether masking is active or not.
  232. */
  233. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  234. // render normals and depth (honor only meshes, points and lines do not contribute to SSAO)
  235. this._overrideVisibility();
  236. this._renderOverride( renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0 );
  237. this._restoreVisibility();
  238. // render SSAO
  239. this.ssaoMaterial.uniforms[ 'kernelRadius' ].value = this.kernelRadius;
  240. this.ssaoMaterial.uniforms[ 'minDistance' ].value = this.minDistance;
  241. this.ssaoMaterial.uniforms[ 'maxDistance' ].value = this.maxDistance;
  242. this._renderPass( renderer, this.ssaoMaterial, this.ssaoRenderTarget );
  243. // render blur
  244. this._renderPass( renderer, this.blurMaterial, this.blurRenderTarget );
  245. // output result to screen
  246. switch ( this.output ) {
  247. case SSAOPass.OUTPUT.SSAO:
  248. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
  249. this.copyMaterial.blending = NoBlending;
  250. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  251. break;
  252. case SSAOPass.OUTPUT.Blur:
  253. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
  254. this.copyMaterial.blending = NoBlending;
  255. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  256. break;
  257. case SSAOPass.OUTPUT.Depth:
  258. this._renderPass( renderer, this.depthRenderMaterial, this.renderToScreen ? null : readBuffer );
  259. break;
  260. case SSAOPass.OUTPUT.Normal:
  261. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.normalRenderTarget.texture;
  262. this.copyMaterial.blending = NoBlending;
  263. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  264. break;
  265. case SSAOPass.OUTPUT.Default:
  266. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
  267. this.copyMaterial.blending = CustomBlending;
  268. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  269. break;
  270. default:
  271. console.warn( 'THREE.SSAOPass: Unknown output type.' );
  272. }
  273. }
  274. /**
  275. * Sets the size of the pass.
  276. *
  277. * @param {number} width - The width to set.
  278. * @param {number} height - The width to set.
  279. */
  280. setSize( width, height ) {
  281. this.width = width;
  282. this.height = height;
  283. this.ssaoRenderTarget.setSize( width, height );
  284. this.normalRenderTarget.setSize( width, height );
  285. this.blurRenderTarget.setSize( width, height );
  286. this.ssaoMaterial.uniforms[ 'resolution' ].value.set( width, height );
  287. this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
  288. this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
  289. this.blurMaterial.uniforms[ 'resolution' ].value.set( width, height );
  290. }
  291. // internals
  292. _renderPass( renderer, passMaterial, renderTarget, clearColor, clearAlpha ) {
  293. // save original state
  294. renderer.getClearColor( this._originalClearColor );
  295. const originalClearAlpha = renderer.getClearAlpha();
  296. const originalAutoClear = renderer.autoClear;
  297. renderer.setRenderTarget( renderTarget );
  298. // setup pass state
  299. renderer.autoClear = false;
  300. if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
  301. renderer.setClearColor( clearColor );
  302. renderer.setClearAlpha( clearAlpha || 0.0 );
  303. renderer.clear();
  304. }
  305. this._fsQuad.material = passMaterial;
  306. this._fsQuad.render( renderer );
  307. // restore original state
  308. renderer.autoClear = originalAutoClear;
  309. renderer.setClearColor( this._originalClearColor );
  310. renderer.setClearAlpha( originalClearAlpha );
  311. }
  312. _renderOverride( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
  313. renderer.getClearColor( this._originalClearColor );
  314. const originalClearAlpha = renderer.getClearAlpha();
  315. const originalAutoClear = renderer.autoClear;
  316. renderer.setRenderTarget( renderTarget );
  317. renderer.autoClear = false;
  318. clearColor = overrideMaterial.clearColor || clearColor;
  319. clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
  320. if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
  321. renderer.setClearColor( clearColor );
  322. renderer.setClearAlpha( clearAlpha || 0.0 );
  323. renderer.clear();
  324. }
  325. this.scene.overrideMaterial = overrideMaterial;
  326. renderer.render( this.scene, this.camera );
  327. this.scene.overrideMaterial = null;
  328. // restore original state
  329. renderer.autoClear = originalAutoClear;
  330. renderer.setClearColor( this._originalClearColor );
  331. renderer.setClearAlpha( originalClearAlpha );
  332. }
  333. _generateSampleKernel( kernelSize ) {
  334. const kernel = this.kernel;
  335. for ( let i = 0; i < kernelSize; i ++ ) {
  336. const sample = new Vector3();
  337. sample.x = ( Math.random() * 2 ) - 1;
  338. sample.y = ( Math.random() * 2 ) - 1;
  339. sample.z = Math.random();
  340. sample.normalize();
  341. let scale = i / kernelSize;
  342. scale = MathUtils.lerp( 0.1, 1, scale * scale );
  343. sample.multiplyScalar( scale );
  344. kernel.push( sample );
  345. }
  346. }
  347. _generateRandomKernelRotations() {
  348. const width = 4, height = 4;
  349. const simplex = new SimplexNoise();
  350. const size = width * height;
  351. const data = new Float32Array( size );
  352. for ( let i = 0; i < size; i ++ ) {
  353. const x = ( Math.random() * 2 ) - 1;
  354. const y = ( Math.random() * 2 ) - 1;
  355. const z = 0;
  356. data[ i ] = simplex.noise3d( x, y, z );
  357. }
  358. this.noiseTexture = new DataTexture( data, width, height, RedFormat, FloatType );
  359. this.noiseTexture.wrapS = RepeatWrapping;
  360. this.noiseTexture.wrapT = RepeatWrapping;
  361. this.noiseTexture.needsUpdate = true;
  362. }
  363. _overrideVisibility() {
  364. const scene = this.scene;
  365. const cache = this._visibilityCache;
  366. scene.traverse( function ( object ) {
  367. cache.set( object, object.visible );
  368. if ( object.isPoints || object.isLine ) object.visible = false;
  369. } );
  370. }
  371. _restoreVisibility() {
  372. const scene = this.scene;
  373. const cache = this._visibilityCache;
  374. scene.traverse( function ( object ) {
  375. const visible = cache.get( object );
  376. object.visible = visible;
  377. } );
  378. cache.clear();
  379. }
  380. }
  381. SSAOPass.OUTPUT = {
  382. 'Default': 0,
  383. 'SSAO': 1,
  384. 'Blur': 2,
  385. 'Depth': 3,
  386. 'Normal': 4
  387. };
  388. export { SSAOPass };
粤ICP备19079148号