SSAONode.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import { RenderTarget, Vector2, TempNode, QuadMesh, NodeMaterial, RendererUtils, RedFormat } from 'three/webgpu';
  2. import { reference, logarithmicDepthToViewZ, viewZToPerspectiveDepth, getViewPosition, getScreenPositionFromClip, vogelDiskSample, interleavedGradientNoise, nodeObject, Fn, float, NodeUpdateType, uv, uniform, Loop, vec4, int, dot, max, clamp, length, screenCoordinate, PI2, texture, passTexture } from 'three/tsl';
  3. import { depthAwareBlur } from './depthAwareBlur.js';
  4. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  5. const _size = /*@__PURE__*/ new Vector2();
  6. let _rendererState;
  7. /**
  8. * Post processing node for a fast, screen-space ambient occlusion (SSAO).
  9. *
  10. * It point-samples a per-pixel rotated Vogel disk and estimates obscurance with a single depth tap
  11. * per sample, trading the ground-truth accuracy of {@link GTAONode}'s horizon ray-marching for
  12. * lower cost. A built-in separable, depth-aware blur denoises the result so it can be used without
  13. * temporal accumulation.
  14. * ```js
  15. * const scenePass = pass( scene, camera );
  16. * scenePass.setMRT( mrt( { output, normal: normalView } ) );
  17. * const scenePassColor = scenePass.getTextureNode( 'output' );
  18. * const scenePassDepth = scenePass.getTextureNode( 'depth' );
  19. * const scenePassNormal = scenePass.getTextureNode( 'normal' );
  20. *
  21. * const aoPass = ssao( scenePassDepth, scenePassNormal, camera );
  22. *
  23. * renderPipeline.outputNode = scenePassColor.mul( aoPass.r );
  24. * ```
  25. *
  26. * @augments TempNode
  27. * @three_import import { ssao } from 'three/addons/tsl/display/SSAONode.js';
  28. */
  29. class SSAONode extends TempNode {
  30. static get type() {
  31. return 'SSAONode';
  32. }
  33. /**
  34. * Constructs a new SSAO node.
  35. *
  36. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  37. * @param {Node<vec3>} normalNode - A node that represents the scene's normals.
  38. * @param {Camera} camera - The camera the scene is rendered with.
  39. */
  40. constructor( depthNode, normalNode, camera ) {
  41. super( 'float' );
  42. /**
  43. * A node that represents the scene's depth.
  44. *
  45. * @type {Node<float>}
  46. */
  47. this.depthNode = depthNode;
  48. /**
  49. * A node that represents the scene's normals.
  50. *
  51. * @type {Node<vec3>}
  52. */
  53. this.normalNode = normalNode;
  54. /**
  55. * The resolution scale. The effect renders at a fraction of the drawing buffer
  56. * for extra speed; `0.5` is a good default for a low-frequency signal like AO.
  57. *
  58. * @type {number}
  59. * @default 0.5
  60. */
  61. this.resolutionScale = 0.5;
  62. /**
  63. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  64. * its effect once per frame in `updateBefore()`.
  65. *
  66. * @type {string}
  67. * @default 'frame'
  68. */
  69. this.updateBeforeType = NodeUpdateType.FRAME;
  70. /**
  71. * The world-space radius the occlusion is gathered within.
  72. *
  73. * @type {UniformNode<float>}
  74. */
  75. this.radius = uniform( 0.5 );
  76. /**
  77. * The strength of the occlusion.
  78. *
  79. * @type {UniformNode<float>}
  80. */
  81. this.intensity = uniform( 1 );
  82. /**
  83. * An angle bias that suppresses self-occlusion on near-flat surfaces.
  84. *
  85. * @type {UniformNode<float>}
  86. */
  87. this.bias = uniform( 0.025 );
  88. /**
  89. * How many samples are used to estimate the occlusion. A higher value
  90. * results in a smoother result at a higher runtime cost.
  91. *
  92. * @type {UniformNode<float>}
  93. */
  94. this.samples = uniform( 16 );
  95. /**
  96. * Whether the depth-aware blur that denoises the raw AO is applied or not.
  97. *
  98. * @type {boolean}
  99. * @default true
  100. */
  101. this.blurEnabled = true;
  102. /**
  103. * How strongly the blur rejects samples across depth discontinuities,
  104. * relative to the AO radius. A higher value keeps edges crisper.
  105. *
  106. * @type {UniformNode<float>}
  107. */
  108. this.blurSharpness = uniform( 2 );
  109. /**
  110. * The resolution of the effect. Set from the drawing buffer size and `resolutionScale`.
  111. *
  112. * @type {Vector2}
  113. */
  114. this.resolution = new Vector2();
  115. /**
  116. * The render target the raw ambient occlusion is rendered into. Also holds the
  117. * final result after the separable blur has ping-ponged back into it.
  118. *
  119. * @private
  120. * @type {RenderTarget}
  121. */
  122. this._aoRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, format: RedFormat } );
  123. this._aoRenderTarget.texture.name = 'SSAONode.AO';
  124. /**
  125. * The render target the intermediate (horizontally blurred) result is rendered into.
  126. *
  127. * @private
  128. * @type {RenderTarget}
  129. */
  130. this._blurRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, format: RedFormat } );
  131. this._blurRenderTarget.texture.name = 'SSAONode.Blur';
  132. /**
  133. * Represents the projection matrix of the scene's camera.
  134. *
  135. * @private
  136. * @type {UniformNode<mat4>}
  137. */
  138. this._cameraProjectionMatrix = uniform( camera.projectionMatrix );
  139. /**
  140. * Represents the inverse projection matrix of the scene's camera.
  141. *
  142. * @private
  143. * @type {UniformNode<mat4>}
  144. */
  145. this._cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  146. /**
  147. * Represents the near value of the scene's camera.
  148. *
  149. * @private
  150. * @type {ReferenceNode<float>}
  151. */
  152. this._cameraNear = reference( 'near', 'float', camera );
  153. /**
  154. * Represents the far value of the scene's camera.
  155. *
  156. * @private
  157. * @type {ReferenceNode<float>}
  158. */
  159. this._cameraFar = reference( 'far', 'float', camera );
  160. /**
  161. * The camera the scene is rendered with.
  162. *
  163. * @private
  164. * @type {Camera}
  165. */
  166. this._camera = camera;
  167. /**
  168. * The input texture the blur material reads from. Swapped between the two render
  169. * targets to run the horizontal and vertical passes with a single material.
  170. *
  171. * @private
  172. * @type {TextureNode}
  173. */
  174. this._blurInput = texture( this._aoRenderTarget.texture );
  175. /**
  176. * The blur direction (one texel along x or y).
  177. *
  178. * @private
  179. * @type {UniformNode<vec2>}
  180. */
  181. this._blurDirection = uniform( new Vector2() );
  182. /**
  183. * The material that computes the raw ambient occlusion.
  184. *
  185. * @private
  186. * @type {NodeMaterial}
  187. */
  188. this._aoMaterial = new NodeMaterial();
  189. this._aoMaterial.name = 'SSAO.AO';
  190. /**
  191. * The material that applies the separable, depth-aware blur.
  192. *
  193. * @private
  194. * @type {NodeMaterial}
  195. */
  196. this._blurMaterial = new NodeMaterial();
  197. this._blurMaterial.name = 'SSAO.Blur';
  198. /**
  199. * The result of the effect is represented as a separate texture node.
  200. *
  201. * @private
  202. * @type {PassTextureNode}
  203. */
  204. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  205. }
  206. /**
  207. * Returns the result of the effect as a texture node.
  208. *
  209. * @return {PassTextureNode} A texture node that represents the result of the effect.
  210. */
  211. getTextureNode() {
  212. return this._textureNode;
  213. }
  214. /**
  215. * Sets the size of the effect.
  216. *
  217. * @param {number} width - The width of the effect.
  218. * @param {number} height - The height of the effect.
  219. */
  220. setSize( width, height ) {
  221. width = Math.max( 1, Math.round( this.resolutionScale * width ) );
  222. height = Math.max( 1, Math.round( this.resolutionScale * height ) );
  223. this.resolution.set( width, height );
  224. this._aoRenderTarget.setSize( width, height );
  225. this._blurRenderTarget.setSize( width, height );
  226. }
  227. /**
  228. * This method is used to render the effect once per frame.
  229. *
  230. * @param {NodeFrame} frame - The current node frame.
  231. */
  232. updateBefore( frame ) {
  233. const { renderer } = frame;
  234. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  235. const size = renderer.getDrawingBufferSize( _size );
  236. this.setSize( size.width, size.height );
  237. renderer.setClearColor( 0xffffff, 1 );
  238. // ambient occlusion
  239. _quadMesh.material = this._aoMaterial;
  240. _quadMesh.name = 'SSAO.AO';
  241. renderer.setRenderTarget( this._aoRenderTarget );
  242. _quadMesh.render( renderer );
  243. // separable, depth-aware blur: horizontal ( AO -> blur ) then vertical ( blur -> AO )
  244. if ( this.blurEnabled === true ) {
  245. _quadMesh.material = this._blurMaterial;
  246. _quadMesh.name = 'SSAO.Blur';
  247. this._blurInput.value = this._aoRenderTarget.texture;
  248. this._blurDirection.value.set( 1 / this.resolution.x, 0 );
  249. renderer.setRenderTarget( this._blurRenderTarget );
  250. _quadMesh.render( renderer );
  251. this._blurInput.value = this._blurRenderTarget.texture;
  252. this._blurDirection.value.set( 0, 1 / this.resolution.y );
  253. renderer.setRenderTarget( this._aoRenderTarget );
  254. _quadMesh.render( renderer );
  255. }
  256. RendererUtils.restoreRendererState( renderer, _rendererState );
  257. }
  258. /**
  259. * This method is used to setup the effect's TSL code.
  260. *
  261. * @param {NodeBuilder} builder - The current node builder.
  262. * @return {PassTextureNode}
  263. */
  264. setup( builder ) {
  265. const uvNode = uv();
  266. const sampleDepth = ( uv ) => {
  267. const depth = this.depthNode.sample( uv ).r;
  268. if ( builder.renderer.logarithmicDepthBuffer === true ) {
  269. const viewZ = logarithmicDepthToViewZ( depth, this._cameraNear, this._cameraFar );
  270. return viewZToPerspectiveDepth( viewZ, this._cameraNear, this._cameraFar );
  271. }
  272. return depth;
  273. };
  274. // ambient occlusion
  275. const ao = Fn( () => {
  276. const depth = sampleDepth( uvNode ).toVar();
  277. depth.greaterThanEqual( 1.0 ).discard();
  278. const viewPosition = getViewPosition( uvNode, depth, this._cameraProjectionMatrixInverse ).toVar();
  279. const viewNormal = this.normalNode.sample( uvNode ).rgb.normalize().toVar();
  280. // a low-discrepancy Vogel disk rotated per-pixel decorrelates the samples spatially,
  281. // so a small blur is enough to hide the sampling pattern
  282. const phi = interleavedGradientNoise( screenCoordinate ).mul( PI2 ).toVar();
  283. const samples = this.samples;
  284. // the fragment's clip position is loop-invariant; projection is linear, so each
  285. // sample only has to project its (view-plane) offset and add it
  286. const clipPosition = this._cameraProjectionMatrix.mul( vec4( viewPosition, 1.0 ) ).toVar();
  287. const occlusion = float( 0 ).toVar();
  288. Loop( { start: int( 0 ), end: samples, type: 'int', condition: '<' }, ( { i } ) => {
  289. // disk offset in the view-aligned plane at the fragment's depth, then reprojected
  290. const offset = vogelDiskSample( i, samples, phi ).mul( this.radius );
  291. const clipOffset = this._cameraProjectionMatrix.mul( vec4( offset, 0.0, 0.0 ) );
  292. const sampleUv = getScreenPositionFromClip( clipPosition.add( clipOffset ) );
  293. const sampleViewPosition = getViewPosition( sampleUv, sampleDepth( sampleUv ), this._cameraProjectionMatrixInverse );
  294. // normalized obscurance: only occluders above the tangent plane count, faded by distance
  295. const v = sampleViewPosition.sub( viewPosition ).toVar();
  296. const dist = length( v ).toVar();
  297. const cosAngle = dot( v, viewNormal ).div( max( dist, float( 0.0001 ) ) );
  298. const falloff = this.radius.div( this.radius.add( dist ) );
  299. occlusion.addAssign( max( cosAngle.sub( this.bias ), 0.0 ).mul( falloff ) );
  300. } );
  301. return clamp( occlusion.div( samples ).mul( this.intensity ).oneMinus(), 0.0, 1.0 );
  302. } );
  303. this._aoMaterial.fragmentNode = ao().context( builder.getSharedContext() );
  304. this._aoMaterial.needsUpdate = true;
  305. // separable, depth-aware blur ( run horizontally then vertically via `_blurDirection` )
  306. this._blurMaterial.fragmentNode = depthAwareBlur( this._blurInput, this.depthNode, this._blurDirection, this._camera, this.blurSharpness, this.radius ).context( builder.getSharedContext() );
  307. this._blurMaterial.needsUpdate = true;
  308. return this._textureNode;
  309. }
  310. /**
  311. * Frees internal resources. This method should be called
  312. * when the effect is no longer required.
  313. */
  314. dispose() {
  315. this._aoRenderTarget.dispose();
  316. this._blurRenderTarget.dispose();
  317. this._aoMaterial.dispose();
  318. this._blurMaterial.dispose();
  319. }
  320. }
  321. export default SSAONode;
  322. /**
  323. * TSL function for creating a fast screen-space ambient occlusion (SSAO) effect.
  324. *
  325. * @tsl
  326. * @function
  327. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  328. * @param {Node<vec3>} normalNode - A node that represents the scene's normals.
  329. * @param {Camera} camera - The camera the scene is rendered with.
  330. * @returns {SSAONode}
  331. */
  332. export const ssao = ( depthNode, normalNode, camera ) => new SSAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera );
粤ICP备19079148号