GTAONode.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import { DataTexture, RenderTarget, RepeatWrapping, Vector2, Vector3, TempNode, QuadMesh, NodeMaterial, RendererUtils } 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. let _rendererState;
  6. /**
  7. * Post processing node for applying Ground Truth Ambient Occlusion (GTAO) to a scene.
  8. * ```js
  9. * const postProcessing = new THREE.PostProcessing( renderer );
  10. *
  11. * const scenePass = pass( scene, camera );
  12. * scenePass.setMRT( mrt( {
  13. * output: output,
  14. * normal: normalView
  15. * } ) );
  16. *
  17. * const scenePassColor = scenePass.getTextureNode( 'output' );
  18. * const scenePassNormal = scenePass.getTextureNode( 'normal' );
  19. * const scenePassDepth = scenePass.getTextureNode( 'depth' );
  20. *
  21. * const aoPass = ao( scenePassDepth, scenePassNormal, camera );
  22. *
  23. * postProcessing.outputNod = aoPass.getTextureNode().mul( scenePassColor );
  24. * ```
  25. *
  26. * Reference: {@link https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf}.
  27. *
  28. * @augments TempNode
  29. */
  30. class GTAONode extends TempNode {
  31. static get type() {
  32. return 'GTAONode';
  33. }
  34. /**
  35. * Constructs a new GTAO node.
  36. *
  37. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  38. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  39. * @param {Camera} camera - The camera the scene is rendered with.
  40. */
  41. constructor( depthNode, normalNode, camera ) {
  42. super( 'vec4' );
  43. /**
  44. * A node that represents the scene's depth.
  45. *
  46. * @type {Node<float>}
  47. */
  48. this.depthNode = depthNode;
  49. /**
  50. * A node that represents the scene's normals. If no normals are passed to the
  51. * constructor (because MRT is not available), normals can be automatically
  52. * reconstructed from depth values in the shader.
  53. *
  54. * @type {?Node<vec3>}
  55. */
  56. this.normalNode = normalNode;
  57. /**
  58. * The resolution scale. By default the effect is rendered in full resolution
  59. * for best quality but a value of `0.5` should be sufficient for most scenes.
  60. *
  61. * @type {number}
  62. * @default 1
  63. */
  64. this.resolutionScale = 1;
  65. /**
  66. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  67. * its effect once per frame in `updateBefore()`.
  68. *
  69. * @type {string}
  70. * @default 'frame'
  71. */
  72. this.updateBeforeType = NodeUpdateType.FRAME;
  73. /**
  74. * The render target the ambient occlusion is rendered into.
  75. *
  76. * @private
  77. * @type {RenderTarget}
  78. */
  79. this._aoRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false } );
  80. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  81. // uniforms
  82. /**
  83. * The radius of the ambient occlusion.
  84. *
  85. * @type {UniformNode<float>}
  86. */
  87. this.radius = uniform( 0.25 );
  88. /**
  89. * The resolution of the effect. Can be scaled via
  90. * `resolutionScale`.
  91. *
  92. * @type {UniformNode<vec2>}
  93. */
  94. this.resolution = uniform( new Vector2() );
  95. /**
  96. * The thickness of the ambient occlusion.
  97. *
  98. * @type {UniformNode<float>}
  99. */
  100. this.thickness = uniform( 1 );
  101. /**
  102. * Another option to tweak the occlusion. The recommended range is
  103. * `[1,2]` for attenuating the AO.
  104. *
  105. * @type {UniformNode<float>}
  106. */
  107. this.distanceExponent = uniform( 1 );
  108. /**
  109. * The distance fall off value of the ambient occlusion.
  110. * A lower value leads to a larger AO effect. The value
  111. * should lie in the range `[0,1]`.
  112. *
  113. * @type {UniformNode<float>}
  114. */
  115. this.distanceFallOff = uniform( 1 );
  116. /**
  117. * The scale of the ambient occlusion.
  118. *
  119. * @type {UniformNode<float>}
  120. */
  121. this.scale = uniform( 1 );
  122. /**
  123. * How many samples are used to compute the AO.
  124. * A higher value results in better quality but also
  125. * in a more expensive runtime behavior.
  126. *
  127. * @type {UniformNode<float>}
  128. */
  129. this.samples = uniform( 16 );
  130. /**
  131. * The node represents the internal noise texture used by the AO.
  132. *
  133. * @private
  134. * @type {TextureNode}
  135. */
  136. this._noiseNode = texture( generateMagicSquareNoise() );
  137. /**
  138. * Represents the projection matrix of the scene's camera.
  139. *
  140. * @private
  141. * @type {UniformNode<mat4>}
  142. */
  143. this._cameraProjectionMatrix = uniform( camera.projectionMatrix );
  144. /**
  145. * Represents the inverse projection matrix of the scene's camera.
  146. *
  147. * @private
  148. * @type {UniformNode<mat4>}
  149. */
  150. this._cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  151. /**
  152. * Represents the near value of the scene's camera.
  153. *
  154. * @private
  155. * @type {ReferenceNode<float>}
  156. */
  157. this._cameraNear = reference( 'near', 'float', camera );
  158. /**
  159. * Represents the far value of the scene's camera.
  160. *
  161. * @private
  162. * @type {ReferenceNode<float>}
  163. */
  164. this._cameraFar = reference( 'far', 'float', camera );
  165. /**
  166. * The material that is used to render the effect.
  167. *
  168. * @private
  169. * @type {NodeMaterial}
  170. */
  171. this._material = new NodeMaterial();
  172. this._material.name = 'GTAO';
  173. /**
  174. * The result of the effect is represented as a separate texture node.
  175. *
  176. * @private
  177. * @type {PassTextureNode}
  178. */
  179. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  180. }
  181. /**
  182. * Returns the result of the effect as a texture node.
  183. *
  184. * @return {PassTextureNode} A texture node that represents the result of the effect.
  185. */
  186. getTextureNode() {
  187. return this._textureNode;
  188. }
  189. /**
  190. * Sets the size of the effect.
  191. *
  192. * @param {number} width - The width of the effect.
  193. * @param {number} height - The height of the effect.
  194. */
  195. setSize( width, height ) {
  196. width = Math.round( this.resolutionScale * width );
  197. height = Math.round( this.resolutionScale * height );
  198. this.resolution.value.set( width, height );
  199. this._aoRenderTarget.setSize( width, height );
  200. }
  201. /**
  202. * This method is used to render the effect once per frame.
  203. *
  204. * @param {NodeFrame} frame - The current node frame.
  205. */
  206. updateBefore( frame ) {
  207. const { renderer } = frame;
  208. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  209. //
  210. const size = renderer.getDrawingBufferSize( _size );
  211. this.setSize( size.width, size.height );
  212. _quadMesh.material = this._material;
  213. // clear
  214. renderer.setClearColor( 0xffffff, 1 );
  215. // ao
  216. renderer.setRenderTarget( this._aoRenderTarget );
  217. _quadMesh.render( renderer );
  218. // restore
  219. RendererUtils.restoreRendererState( renderer, _rendererState );
  220. }
  221. /**
  222. * This method is used to setup the effect's TSL code.
  223. *
  224. * @param {NodeBuilder} builder - The current node builder.
  225. * @return {PassTextureNode}
  226. */
  227. setup( builder ) {
  228. const uvNode = uv();
  229. const sampleDepth = ( uv ) => {
  230. const depth = this.depthNode.sample( uv ).r;
  231. if ( builder.renderer.logarithmicDepthBuffer === true ) {
  232. const viewZ = logarithmicDepthToViewZ( depth, this._cameraNear, this._cameraFar );
  233. return viewZToPerspectiveDepth( viewZ, this._cameraNear, this._cameraFar );
  234. }
  235. return depth;
  236. };
  237. const sampleNoise = ( uv ) => this._noiseNode.sample( uv );
  238. const sampleNormal = ( uv ) => ( this.normalNode !== null ) ? this.normalNode.sample( uv ).rgb.normalize() : getNormalFromDepth( uv, this.depthNode.value, this._cameraProjectionMatrixInverse );
  239. const ao = Fn( () => {
  240. const depth = sampleDepth( uvNode ).toVar();
  241. depth.greaterThanEqual( 1.0 ).discard();
  242. const viewPosition = getViewPosition( uvNode, depth, this._cameraProjectionMatrixInverse ).toVar();
  243. const viewNormal = sampleNormal( uvNode ).toVar();
  244. const radiusToUse = this.radius;
  245. const noiseResolution = textureSize( this._noiseNode, 0 );
  246. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  247. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  248. const noiseTexel = sampleNoise( noiseUv );
  249. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  250. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  251. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  252. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  253. const DIRECTIONS = this.samples.lessThan( 30 ).select( 3, 5 ).toVar();
  254. const STEPS = add( this.samples, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS ).toVar();
  255. const ao = float( 0 ).toVar();
  256. Loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  257. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI ).toVar();
  258. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  259. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  260. const viewDir = normalize( viewPosition.xyz.negate() ).toVar();
  261. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) ).toVar();
  262. const sliceTangent = cross( sliceBitangent, viewDir );
  263. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  264. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent ).toVar();
  265. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  266. Loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  267. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  268. // x
  269. const sampleScreenPositionX = getScreenPosition( viewPosition.add( sampleViewOffset ), this._cameraProjectionMatrix ).toVar();
  270. const sampleDepthX = sampleDepth( sampleScreenPositionX ).toVar();
  271. const sampleSceneViewPositionX = getViewPosition( sampleScreenPositionX, sampleDepthX, this._cameraProjectionMatrixInverse ).toVar();
  272. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition ).toVar();
  273. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  274. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  275. cosHorizons.x.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  276. } );
  277. // y
  278. const sampleScreenPositionY = getScreenPosition( viewPosition.sub( sampleViewOffset ), this._cameraProjectionMatrix ).toVar();
  279. const sampleDepthY = sampleDepth( sampleScreenPositionY ).toVar();
  280. const sampleSceneViewPositionY = getViewPosition( sampleScreenPositionY, sampleDepthY, this._cameraProjectionMatrixInverse ).toVar();
  281. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition ).toVar();
  282. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  283. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  284. cosHorizons.y.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  285. } );
  286. } );
  287. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) ).toVar();
  288. const nx = dot( normalInSlice, sliceTangent );
  289. const ny = dot( normalInSlice, viewDir );
  290. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  291. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  292. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  293. ao.addAssign( occlusion );
  294. } );
  295. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  296. ao.assign( pow( ao, this.scale ) );
  297. return vec4( vec3( ao ), 1.0 );
  298. } );
  299. this._material.fragmentNode = ao().context( builder.getSharedContext() );
  300. this._material.needsUpdate = true;
  301. //
  302. return this._textureNode;
  303. }
  304. /**
  305. * Frees internal resources. This method should be called
  306. * when the effect is no longer required.
  307. */
  308. dispose() {
  309. this._aoRenderTarget.dispose();
  310. this._material.dispose();
  311. }
  312. }
  313. export default GTAONode;
  314. /**
  315. * Generates the AO's noise texture for the given size.
  316. *
  317. * @param {number} [size=5] - The noise size.
  318. * @return {DataTexture} The generated noise texture.
  319. */
  320. function generateMagicSquareNoise( size = 5 ) {
  321. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  322. const magicSquare = generateMagicSquare( noiseSize );
  323. const noiseSquareSize = magicSquare.length;
  324. const data = new Uint8Array( noiseSquareSize * 4 );
  325. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  326. const iAng = magicSquare[ inx ];
  327. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  328. const randomVec = new Vector3(
  329. Math.cos( angle ),
  330. Math.sin( angle ),
  331. 0
  332. ).normalize();
  333. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  334. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  335. data[ inx * 4 + 2 ] = 127;
  336. data[ inx * 4 + 3 ] = 255;
  337. }
  338. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  339. noiseTexture.wrapS = RepeatWrapping;
  340. noiseTexture.wrapT = RepeatWrapping;
  341. noiseTexture.needsUpdate = true;
  342. return noiseTexture;
  343. }
  344. /**
  345. * Computes an array of magic square values required to generate the noise texture.
  346. *
  347. * @param {number} size - The noise size.
  348. * @return {Array<number>} The magic square values.
  349. */
  350. function generateMagicSquare( size ) {
  351. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  352. const noiseSquareSize = noiseSize * noiseSize;
  353. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  354. let i = Math.floor( noiseSize / 2 );
  355. let j = noiseSize - 1;
  356. for ( let num = 1; num <= noiseSquareSize; ) {
  357. if ( i === - 1 && j === noiseSize ) {
  358. j = noiseSize - 2;
  359. i = 0;
  360. } else {
  361. if ( j === noiseSize ) {
  362. j = 0;
  363. }
  364. if ( i < 0 ) {
  365. i = noiseSize - 1;
  366. }
  367. }
  368. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  369. j -= 2;
  370. i ++;
  371. continue;
  372. } else {
  373. magicSquare[ i * noiseSize + j ] = num ++;
  374. }
  375. j ++;
  376. i --;
  377. }
  378. return magicSquare;
  379. }
  380. /**
  381. * TSL function for creating a Ground Truth Ambient Occlusion (GTAO) effect.
  382. *
  383. * @tsl
  384. * @function
  385. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  386. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  387. * @param {Camera} camera - The camera the scene is rendered with.
  388. * @returns {GTAONode}
  389. */
  390. export const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
粤ICP备19079148号