GTAONode.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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, sqrt, sub, 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 );
  296. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  297. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent ).toVar();
  298. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  299. // For each slice, the inner loop performs ray marching to find the horizons.
  300. Loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  301. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  302. // The loop marches in two opposite directions (x and y) along the slice's line to find the horizon on both sides.
  303. // x
  304. const sampleScreenPositionX = getScreenPosition( viewPosition.add( sampleViewOffset ), this._cameraProjectionMatrix ).toVar();
  305. const sampleDepthX = sampleDepth( sampleScreenPositionX ).toVar();
  306. const sampleSceneViewPositionX = getViewPosition( sampleScreenPositionX, sampleDepthX, this._cameraProjectionMatrixInverse ).toVar();
  307. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition ).toVar();
  308. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  309. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  310. cosHorizons.x.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  311. } );
  312. // y
  313. const sampleScreenPositionY = getScreenPosition( viewPosition.sub( sampleViewOffset ), this._cameraProjectionMatrix ).toVar();
  314. const sampleDepthY = sampleDepth( sampleScreenPositionY ).toVar();
  315. const sampleSceneViewPositionY = getViewPosition( sampleScreenPositionY, sampleDepthY, this._cameraProjectionMatrixInverse ).toVar();
  316. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition ).toVar();
  317. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  318. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  319. cosHorizons.y.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  320. } );
  321. } );
  322. // After the horizons are found for a given slice, their contribution to the total occlusion is calculated.
  323. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) ).toVar();
  324. const nx = dot( normalInSlice, sliceTangent );
  325. const ny = dot( normalInSlice, viewDir );
  326. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  327. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  328. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  329. ao.addAssign( occlusion );
  330. } );
  331. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  332. ao.assign( pow( ao, this.scale ) );
  333. return ao;
  334. } );
  335. this._material.fragmentNode = ao().context( builder.getSharedContext() );
  336. this._material.needsUpdate = true;
  337. //
  338. return this._textureNode;
  339. }
  340. /**
  341. * Frees internal resources. This method should be called
  342. * when the effect is no longer required.
  343. */
  344. dispose() {
  345. this._aoRenderTarget.dispose();
  346. this._material.dispose();
  347. }
  348. }
  349. export default GTAONode;
  350. /**
  351. * Generates the AO's noise texture for the given size.
  352. *
  353. * @param {number} [size=5] - The noise size.
  354. * @return {DataTexture} The generated noise texture.
  355. */
  356. function generateMagicSquareNoise( size = 5 ) {
  357. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  358. const magicSquare = generateMagicSquare( noiseSize );
  359. const noiseSquareSize = magicSquare.length;
  360. const data = new Uint8Array( noiseSquareSize * 4 );
  361. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  362. const iAng = magicSquare[ inx ];
  363. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  364. const randomVec = new Vector3(
  365. Math.cos( angle ),
  366. Math.sin( angle ),
  367. 0
  368. ).normalize();
  369. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  370. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  371. data[ inx * 4 + 2 ] = 127;
  372. data[ inx * 4 + 3 ] = 255;
  373. }
  374. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  375. noiseTexture.wrapS = RepeatWrapping;
  376. noiseTexture.wrapT = RepeatWrapping;
  377. noiseTexture.needsUpdate = true;
  378. return noiseTexture;
  379. }
  380. /**
  381. * Computes an array of magic square values required to generate the noise texture.
  382. *
  383. * @param {number} size - The noise size.
  384. * @return {Array<number>} The magic square values.
  385. */
  386. function generateMagicSquare( size ) {
  387. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  388. const noiseSquareSize = noiseSize * noiseSize;
  389. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  390. let i = Math.floor( noiseSize / 2 );
  391. let j = noiseSize - 1;
  392. for ( let num = 1; num <= noiseSquareSize; ) {
  393. if ( i === - 1 && j === noiseSize ) {
  394. j = noiseSize - 2;
  395. i = 0;
  396. } else {
  397. if ( j === noiseSize ) {
  398. j = 0;
  399. }
  400. if ( i < 0 ) {
  401. i = noiseSize - 1;
  402. }
  403. }
  404. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  405. j -= 2;
  406. i ++;
  407. continue;
  408. } else {
  409. magicSquare[ i * noiseSize + j ] = num ++;
  410. }
  411. j ++;
  412. i --;
  413. }
  414. return magicSquare;
  415. }
  416. /**
  417. * TSL function for creating a Ground Truth Ambient Occlusion (GTAO) effect.
  418. *
  419. * @tsl
  420. * @function
  421. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  422. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  423. * @param {Camera} camera - The camera the scene is rendered with.
  424. * @returns {GTAONode}
  425. */
  426. export const ao = ( depthNode, normalNode, camera ) => new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera );
粤ICP备19079148号