GTAONode.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. import { DataTexture, RenderTarget, RepeatWrapping, Vector2, Vector3, TempNode, QuadMesh, NodeMaterial, RendererUtils, RedFormat } from 'three/webgpu';
  2. import { reference, logarithmicDepthToViewZ, viewZToPerspectiveDepth, getNormalFromDepth, getScreenPosition, getViewPosition, nodeObject, Fn, float, NodeUpdateType, uv, uniform, Loop, vec2, vec3, vec4, int, dot, max, pow, abs, If, textureSize, sin, cos, PI, texture, passTexture, mat3, add, normalize, mul, cross, div, mix, acos, clamp } from 'three/tsl';
  3. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  4. const _size = /*@__PURE__*/ new Vector2();
  5. // From Activision GTAO paper: https://www.activision.com/cdn/research/s2016_pbs_activision_occlusion.pptx
  6. const _temporalRotations = [ 60, 300, 180, 240, 120, 0 ];
  7. let _rendererState;
  8. /**
  9. * Post processing node for applying Ground Truth Ambient Occlusion (GTAO) to a scene.
  10. * ```js
  11. * const renderPipeline = new THREE.RenderPipeline( renderer );
  12. *
  13. * const scenePass = pass( scene, camera );
  14. * scenePass.setMRT( mrt( {
  15. * output: output,
  16. * normal: normalView
  17. * } ) );
  18. *
  19. * const scenePassColor = scenePass.getTextureNode( 'output' );
  20. * const scenePassNormal = scenePass.getTextureNode( 'normal' );
  21. * const scenePassDepth = scenePass.getTextureNode( 'depth' );
  22. *
  23. * const aoPass = ao( scenePassDepth, scenePassNormal, camera );
  24. * const aoPassOutput = aoPass.getTextureNode();
  25. *
  26. * renderPipeline.outputNode = scenePassColor.mul( vec4( vec3( aoPassOutput.r ), 1 ) );
  27. * ```
  28. *
  29. * Reference: [Practical Real-Time Strategies for Accurate Indirect Occlusion](https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf).
  30. *
  31. * @augments TempNode
  32. * @three_import import { ao } from 'three/addons/tsl/display/GTAONode.js';
  33. */
  34. class GTAONode extends TempNode {
  35. static get type() {
  36. return 'GTAONode';
  37. }
  38. /**
  39. * Constructs a new GTAO node.
  40. *
  41. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  42. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  43. * @param {Camera} camera - The camera the scene is rendered with.
  44. */
  45. constructor( depthNode, normalNode, camera ) {
  46. super( 'float' );
  47. /**
  48. * A node that represents the scene's depth.
  49. *
  50. * @type {Node<float>}
  51. */
  52. this.depthNode = depthNode;
  53. /**
  54. * A node that represents the scene's normals. If no normals are passed to the
  55. * constructor (because MRT is not available), normals can be automatically
  56. * reconstructed from depth values in the shader.
  57. *
  58. * @type {?Node<vec3>}
  59. */
  60. this.normalNode = normalNode;
  61. /**
  62. * The resolution scale. By default the effect is rendered in full resolution
  63. * for best quality but a value of `0.5` should be sufficient for most scenes.
  64. *
  65. * @type {number}
  66. * @default 1
  67. */
  68. this.resolutionScale = 1;
  69. /**
  70. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  71. * its effect once per frame in `updateBefore()`.
  72. *
  73. * @type {string}
  74. * @default 'frame'
  75. */
  76. this.updateBeforeType = NodeUpdateType.FRAME;
  77. /**
  78. * The render target the ambient occlusion is rendered into.
  79. *
  80. * @private
  81. * @type {RenderTarget}
  82. */
  83. this._aoRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, format: RedFormat } );
  84. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  85. // uniforms
  86. /**
  87. * The radius of the ambient occlusion.
  88. *
  89. * @type {UniformNode<float>}
  90. */
  91. this.radius = uniform( 0.25 );
  92. /**
  93. * The resolution of the effect. Can be scaled via
  94. * `resolutionScale`.
  95. *
  96. * @type {UniformNode<vec2>}
  97. */
  98. this.resolution = uniform( new Vector2() );
  99. /**
  100. * The thickness of the ambient occlusion.
  101. *
  102. * @type {UniformNode<float>}
  103. */
  104. this.thickness = uniform( 1 );
  105. /**
  106. * Another option to tweak the occlusion. The recommended range is
  107. * `[1,2]` for attenuating the AO.
  108. *
  109. * @type {UniformNode<float>}
  110. */
  111. this.distanceExponent = uniform( 1 );
  112. /**
  113. * The distance fall off value of the ambient occlusion.
  114. * A lower value leads to a larger AO effect. The value
  115. * should lie in the range `[0,1]`.
  116. *
  117. * @type {UniformNode<float>}
  118. */
  119. this.distanceFallOff = uniform( 1 );
  120. /**
  121. * The scale of the ambient occlusion.
  122. *
  123. * @type {UniformNode<float>}
  124. */
  125. this.scale = uniform( 1 );
  126. /**
  127. * How many samples are used to compute the AO.
  128. * A higher value results in better quality but also
  129. * in a more expensive runtime behavior.
  130. *
  131. * @type {UniformNode<float>}
  132. */
  133. this.samples = uniform( 16 );
  134. /**
  135. * Whether to use temporal filtering or not. Setting this property to
  136. * `true` requires the usage of `TRAANode`. This will help to reduce noise
  137. * although it introduces typical TAA artifacts like ghosting and temporal
  138. * instabilities.
  139. *
  140. * If setting this property to `false`, a manual denoise via `DenoiseNode`
  141. * might be required.
  142. *
  143. * @type {boolean}
  144. * @default false
  145. */
  146. this.useTemporalFiltering = false;
  147. /**
  148. * The node represents the internal noise texture used by the AO.
  149. *
  150. * @private
  151. * @type {TextureNode}
  152. */
  153. this._noiseNode = texture( generateMagicSquareNoise() );
  154. /**
  155. * Represents the projection matrix of the scene's camera.
  156. *
  157. * @private
  158. * @type {UniformNode<mat4>}
  159. */
  160. this._cameraProjectionMatrix = uniform( camera.projectionMatrix );
  161. /**
  162. * Represents the inverse projection matrix of the scene's camera.
  163. *
  164. * @private
  165. * @type {UniformNode<mat4>}
  166. */
  167. this._cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  168. /**
  169. * Represents the near value of the scene's camera.
  170. *
  171. * @private
  172. * @type {ReferenceNode<float>}
  173. */
  174. this._cameraNear = reference( 'near', 'float', camera );
  175. /**
  176. * Represents the far value of the scene's camera.
  177. *
  178. * @private
  179. * @type {ReferenceNode<float>}
  180. */
  181. this._cameraFar = reference( 'far', 'float', camera );
  182. /**
  183. * Temporal direction that influences the rotation angle for each slice.
  184. *
  185. * @private
  186. * @type {UniformNode<float>}
  187. */
  188. this._temporalDirection = uniform( 0 );
  189. /**
  190. * The material that is used to render the effect.
  191. *
  192. * @private
  193. * @type {NodeMaterial}
  194. */
  195. this._material = new NodeMaterial();
  196. this._material.name = 'GTAO';
  197. /**
  198. * The result of the effect is represented as a separate texture node.
  199. *
  200. * @private
  201. * @type {PassTextureNode}
  202. */
  203. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  204. }
  205. /**
  206. * Returns the result of the effect as a texture node.
  207. *
  208. * @return {PassTextureNode} A texture node that represents the result of the effect.
  209. */
  210. getTextureNode() {
  211. return this._textureNode;
  212. }
  213. /**
  214. * Sets the size of the effect.
  215. *
  216. * @param {number} width - The width of the effect.
  217. * @param {number} height - The height of the effect.
  218. */
  219. setSize( width, height ) {
  220. width = Math.round( this.resolutionScale * width );
  221. height = Math.round( this.resolutionScale * height );
  222. this.resolution.value.set( width, height );
  223. this._aoRenderTarget.setSize( width, height );
  224. }
  225. /**
  226. * This method is used to render the effect once per frame.
  227. *
  228. * @param {NodeFrame} frame - The current node frame.
  229. */
  230. updateBefore( frame ) {
  231. const { renderer } = frame;
  232. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  233. // update temporal uniforms
  234. if ( this.useTemporalFiltering === true ) {
  235. const frameId = frame.frameId;
  236. this._temporalDirection.value = _temporalRotations[ frameId % 6 ] / 360;
  237. } else {
  238. this._temporalDirection.value = 0;
  239. }
  240. //
  241. const size = renderer.getDrawingBufferSize( _size );
  242. this.setSize( size.width, size.height );
  243. _quadMesh.material = this._material;
  244. _quadMesh.name = 'AO';
  245. // clear
  246. renderer.setClearColor( 0xffffff, 1 );
  247. // ao
  248. renderer.setRenderTarget( this._aoRenderTarget );
  249. _quadMesh.render( renderer );
  250. // restore
  251. RendererUtils.restoreRendererState( renderer, _rendererState );
  252. }
  253. /**
  254. * This method is used to setup the effect's TSL code.
  255. *
  256. * @param {NodeBuilder} builder - The current node builder.
  257. * @return {PassTextureNode}
  258. */
  259. setup( builder ) {
  260. const uvNode = uv();
  261. const sampleDepth = ( uv ) => {
  262. const depth = this.depthNode.sample( uv ).r;
  263. if ( builder.renderer.logarithmicDepthBuffer === true ) {
  264. const viewZ = logarithmicDepthToViewZ( depth, this._cameraNear, this._cameraFar );
  265. return viewZToPerspectiveDepth( viewZ, this._cameraNear, this._cameraFar );
  266. }
  267. return depth;
  268. };
  269. const sampleNoise = ( uv ) => this._noiseNode.sample( uv );
  270. const sampleNormal = ( uv ) => ( this.normalNode !== null ) ? this.normalNode.sample( uv ).rgb.normalize() : getNormalFromDepth( uv, this.depthNode.value, this._cameraProjectionMatrixInverse );
  271. const ao = Fn( () => {
  272. const depth = sampleDepth( uvNode ).toVar();
  273. depth.greaterThanEqual( 1.0 ).discard();
  274. const viewPosition = getViewPosition( uvNode, depth, this._cameraProjectionMatrixInverse ).toVar();
  275. const viewNormal = sampleNormal( uvNode ).toVar();
  276. const radiusToUse = this.radius;
  277. const noiseResolution = textureSize( this._noiseNode, 0 );
  278. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  279. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  280. const noiseTexel = sampleNoise( noiseUv );
  281. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  282. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  283. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  284. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  285. const DIRECTIONS = this.samples.lessThan( 30 ).select( 3, 5 ).toVar();
  286. const STEPS = add( this.samples, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS ).toVar();
  287. const ao = float( 0 ).toVar();
  288. // Each iteration analyzes one vertical "slice" of the 3D space around the fragment.
  289. Loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  290. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI ).add( this._temporalDirection ).toVar();
  291. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  292. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  293. const viewDir = normalize( viewPosition.xyz.negate() ).toVar();
  294. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) ).toVar();
  295. const sliceTangent = cross( sliceBitangent, viewDir ).toVar();
  296. // Project the view normal onto the slice plane (remove component along sliceBitangent).
  297. // The unnormalized length is the foreshortening weight applied at slice integration.
  298. // (Activision GTAO paper, Section 3.2 "Per-pixel sampling".)
  299. const projNRaw = viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ).toVar();
  300. const projNLen = projNRaw.length().toVar();
  301. const projN = projNRaw.div( max( projNLen, float( 0.0001 ) ) ).toVar();
  302. // γ — angle of projN within the slice plane, signed by the tangent direction.
  303. const nSin = dot( projN, sliceTangent ).toVar();
  304. const nCos = clamp( dot( projN, viewDir ), 0, 1 ).toVar();
  305. const signNSin = nSin.greaterThanEqual( 0 ).select( float( 1 ), float( - 1 ) );
  306. const angleN = signNSin.mul( acos( nCos ) ).toVar();
  307. const tangentToNormalInSlice = cross( projN, sliceBitangent ).toVar();
  308. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  309. // For each slice, the inner loop performs ray marching to find the horizons.
  310. Loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  311. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  312. // The loop marches in two opposite directions (x and y) along the slice's line to find the horizon on both sides.
  313. // x
  314. const sampleScreenPositionX = getScreenPosition( viewPosition.add( sampleViewOffset ), this._cameraProjectionMatrix ).toVar();
  315. const sampleDepthX = sampleDepth( sampleScreenPositionX ).toVar();
  316. const sampleSceneViewPositionX = getViewPosition( sampleScreenPositionX, sampleDepthX, this._cameraProjectionMatrixInverse ).toVar();
  317. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition ).toVar();
  318. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  319. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  320. cosHorizons.x.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  321. } );
  322. // y
  323. const sampleScreenPositionY = getScreenPosition( viewPosition.sub( sampleViewOffset ), this._cameraProjectionMatrix ).toVar();
  324. const sampleDepthY = sampleDepth( sampleScreenPositionY ).toVar();
  325. const sampleSceneViewPositionY = getViewPosition( sampleScreenPositionY, sampleDepthY, this._cameraProjectionMatrixInverse ).toVar();
  326. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition ).toVar();
  327. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  328. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  329. cosHorizons.y.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  330. } );
  331. } );
  332. // Cosine-weighted inner integral, closed-form (Activision GTAO paper, Eq. 7).
  333. // Per horizon h_i: term_i = −cos( 2 h_i − γ ) + cos( γ ) + 2 h_i sin( γ )
  334. // The 0.25 factor is ½ (integral normalization) × ½ (averaging the two horizons).
  335. //
  336. // In this slice setup `sliceTangent = cross( sliceBitangent, viewDir )` works out
  337. // opposite to `sampleDir`, so the +sampleDir samples (cosHorizons.x) live on the
  338. // −T side of the slice and −sampleDir samples (cosHorizons.y) on the +T side.
  339. // γ is signed by +T (sliceTangent), so hPos must read from cosHorizons.y.
  340. const hPos = acos( cosHorizons.y ).toVar();
  341. const hNeg = acos( cosHorizons.x ).negate().toVar();
  342. const termPos = cos( hPos.mul( 2 ).sub( angleN ) ).negate().add( nCos ).add( hPos.mul( 2 ).mul( nSin ) );
  343. const termNeg = cos( hNeg.mul( 2 ).sub( angleN ) ).negate().add( nCos ).add( hNeg.mul( 2 ).mul( nSin ) );
  344. const a = termPos.add( termNeg ).mul( 0.25 );
  345. // |projN| is the foreshortening weight from the per-slice normal projection.
  346. ao.addAssign( projNLen.mul( a ) );
  347. } );
  348. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  349. ao.assign( pow( ao, this.scale ) );
  350. return ao;
  351. } );
  352. this._material.fragmentNode = ao().context( builder.getSharedContext() );
  353. this._material.needsUpdate = true;
  354. //
  355. return this._textureNode;
  356. }
  357. /**
  358. * Frees internal resources. This method should be called
  359. * when the effect is no longer required.
  360. */
  361. dispose() {
  362. this._aoRenderTarget.dispose();
  363. this._material.dispose();
  364. }
  365. }
  366. export default GTAONode;
  367. /**
  368. * Generates the AO's noise texture for the given size.
  369. *
  370. * @param {number} [size=5] - The noise size.
  371. * @return {DataTexture} The generated noise texture.
  372. */
  373. function generateMagicSquareNoise( size = 5 ) {
  374. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  375. const magicSquare = generateMagicSquare( noiseSize );
  376. const noiseSquareSize = magicSquare.length;
  377. const data = new Uint8Array( noiseSquareSize * 4 );
  378. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  379. const iAng = magicSquare[ inx ];
  380. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  381. const randomVec = new Vector3(
  382. Math.cos( angle ),
  383. Math.sin( angle ),
  384. 0
  385. ).normalize();
  386. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  387. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  388. data[ inx * 4 + 2 ] = 127;
  389. data[ inx * 4 + 3 ] = 255;
  390. }
  391. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  392. noiseTexture.wrapS = RepeatWrapping;
  393. noiseTexture.wrapT = RepeatWrapping;
  394. noiseTexture.needsUpdate = true;
  395. return noiseTexture;
  396. }
  397. /**
  398. * Computes an array of magic square values required to generate the noise texture.
  399. *
  400. * @param {number} size - The noise size.
  401. * @return {Array<number>} The magic square values.
  402. */
  403. function generateMagicSquare( size ) {
  404. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  405. const noiseSquareSize = noiseSize * noiseSize;
  406. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  407. let i = Math.floor( noiseSize / 2 );
  408. let j = noiseSize - 1;
  409. for ( let num = 1; num <= noiseSquareSize; ) {
  410. if ( i === - 1 && j === noiseSize ) {
  411. j = noiseSize - 2;
  412. i = 0;
  413. } else {
  414. if ( j === noiseSize ) {
  415. j = 0;
  416. }
  417. if ( i < 0 ) {
  418. i = noiseSize - 1;
  419. }
  420. }
  421. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  422. j -= 2;
  423. i ++;
  424. continue;
  425. } else {
  426. magicSquare[ i * noiseSize + j ] = num ++;
  427. }
  428. j ++;
  429. i --;
  430. }
  431. return magicSquare;
  432. }
  433. /**
  434. * TSL function for creating a Ground Truth Ambient Occlusion (GTAO) effect.
  435. *
  436. * @tsl
  437. * @function
  438. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  439. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  440. * @param {Camera} camera - The camera the scene is rendered with.
  441. * @returns {GTAONode}
  442. */
  443. export const ao = ( depthNode, normalNode, camera ) => new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera );
粤ICP备19079148号