DepthOfFieldNode.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import { TempNode, NodeMaterial, NodeUpdateType, RenderTarget, Vector2, HalfFloatType, RedFormat, QuadMesh, RendererUtils } from 'three/webgpu';
  2. import { convertToTexture, nodeObject, Fn, uniform, smoothstep, step, texture, max, uniformArray, outputStruct, property, vec4, vec3, uv, Loop, min, mix } from 'three/tsl';
  3. import { gaussianBlur } from './GaussianBlurNode.js';
  4. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  5. let _rendererState;
  6. /**
  7. * Post processing node for creating depth of field (DOF) effect.
  8. *
  9. * References:
  10. * - {@link https://pixelmischiefblog.wordpress.com/2016/11/25/bokeh-depth-of-field/}
  11. * - {@link https://www.adriancourreges.com/blog/2016/09/09/doom-2016-graphics-study/}
  12. *
  13. * @augments TempNode
  14. * @three_import import { dof } from 'three/addons/tsl/display/DepthOfFieldNode.js';
  15. */
  16. class DepthOfFieldNode extends TempNode {
  17. static get type() {
  18. return 'DepthOfFieldNode';
  19. }
  20. /**
  21. * Constructs a new DOF node.
  22. *
  23. * @param {TextureNode} textureNode - The texture node that represents the input of the effect.
  24. * @param {Node<float>} viewZNode - Represents the viewZ depth values of the scene.
  25. * @param {Node<float>} focusDistanceNode - Defines the effect's focus which is the distance along the camera's look direction in world units.
  26. * @param {Node<float>} focalLengthNode - How far an object can be from the focal plane before it goes completely out-of-focus in world units.
  27. * @param {Node<float>} bokehScaleNode - A unitless value for artistic purposes to adjust the size of the bokeh.
  28. */
  29. constructor( textureNode, viewZNode, focusDistanceNode, focalLengthNode, bokehScaleNode ) {
  30. super( 'vec4' );
  31. /**
  32. * The texture node that represents the input of the effect.
  33. *
  34. * @type {TextureNode}
  35. */
  36. this.textureNode = textureNode;
  37. /**
  38. * Represents the viewZ depth values of the scene.
  39. *
  40. * @type {Node<float>}
  41. */
  42. this.viewZNode = viewZNode;
  43. /**
  44. * Defines the effect's focus which is the distance along the camera's look direction in world units.
  45. *
  46. * @type {Node<float>}
  47. */
  48. this.focusDistanceNode = focusDistanceNode;
  49. /**
  50. * How far an object can be from the focal plane before it goes completely out-of-focus in world units.
  51. *
  52. * @type {Node<float>}
  53. */
  54. this.focalLengthNode = focalLengthNode;
  55. /**
  56. * A unitless value for artistic purposes to adjust the size of the bokeh.
  57. *
  58. * @type {Node<float>}
  59. */
  60. this.bokehScaleNode = bokehScaleNode;
  61. /**
  62. * The inverse size of the resolution.
  63. *
  64. * @private
  65. * @type {UniformNode<vec2>}
  66. */
  67. this._invSize = uniform( new Vector2() );
  68. /**
  69. * The render target used for the near and far field.
  70. *
  71. * @private
  72. * @type {RenderTarget}
  73. */
  74. this._CoCRT = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType, format: RedFormat, count: 2 } );
  75. this._CoCRT.textures[ 0 ].name = 'DepthOfField.NearField';
  76. this._CoCRT.textures[ 1 ].name = 'DepthOfField.FarField';
  77. /**
  78. * The render target used for blurring the near field.
  79. *
  80. * @private
  81. * @type {RenderTarget}
  82. */
  83. this._CoCBlurredRT = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType, format: RedFormat } );
  84. this._CoCBlurredRT.texture.name = 'DepthOfField.NearFieldBlurred';
  85. /**
  86. * The render target used for the first blur pass.
  87. *
  88. * @private
  89. * @type {RenderTarget}
  90. */
  91. this._blur64RT = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  92. this._blur64RT.texture.name = 'DepthOfField.Blur64';
  93. /**
  94. * The render target used for the near field's second blur pass.
  95. *
  96. * @private
  97. * @type {RenderTarget}
  98. */
  99. this._blur16NearRT = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  100. this._blur16NearRT.texture.name = 'DepthOfField.Blur16Near';
  101. /**
  102. * The render target used for the far field's second blur pass.
  103. *
  104. * @private
  105. * @type {RenderTarget}
  106. */
  107. this._blur16FarRT = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  108. this._blur16FarRT.texture.name = 'DepthOfField.Blur16Far';
  109. /**
  110. * The render target used for the composite
  111. *
  112. * @private
  113. * @type {RenderTarget}
  114. */
  115. this._compositeRT = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  116. this._compositeRT.texture.name = 'DepthOfField.Composite';
  117. /**
  118. * The material used for the CoC/near and far fields.
  119. *
  120. * @private
  121. * @type {NodeMaterial}
  122. */
  123. this._CoCMaterial = new NodeMaterial();
  124. /**
  125. * The material used for blurring the near field.
  126. *
  127. * @private
  128. * @type {NodeMaterial}
  129. */
  130. this._CoCBlurredMaterial = new NodeMaterial();
  131. /**
  132. * The material used for the 64 tap blur.
  133. *
  134. * @private
  135. * @type {NodeMaterial}
  136. */
  137. this._blur64Material = new NodeMaterial();
  138. /**
  139. * The material used for the 16 tap blur.
  140. *
  141. * @private
  142. * @type {NodeMaterial}
  143. */
  144. this._blur16Material = new NodeMaterial();
  145. /**
  146. * The material used for the final composite.
  147. *
  148. * @private
  149. * @type {NodeMaterial}
  150. */
  151. this._compositeMaterial = new NodeMaterial();
  152. /**
  153. * The result of the effect is represented as a separate texture node.
  154. *
  155. * @private
  156. * @type {TextureNode}
  157. */
  158. this._textureNode = texture( this._compositeRT.texture );
  159. /**
  160. * The result of the CoC pass as a texture node.
  161. *
  162. * @private
  163. * @type {TextureNode}
  164. */
  165. this._CoCTextureNode = texture( this._CoCRT.texture );
  166. /**
  167. * The result of the blur64 pass as a texture node.
  168. *
  169. * @private
  170. * @type {TextureNode}
  171. */
  172. this._blur64TextureNode = texture( this._blur64RT.texture );
  173. /**
  174. * The result of the near field's blur16 pass as a texture node.
  175. *
  176. * @private
  177. * @type {TextureNode}
  178. */
  179. this._blur16NearTextureNode = texture( this._blur16NearRT.texture );
  180. /**
  181. * The result of the far field's blur16 pass as a texture node.
  182. *
  183. * @private
  184. * @type {TextureNode}
  185. */
  186. this._blur16FarTextureNode = texture( this._blur16FarRT.texture );
  187. /**
  188. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node updates
  189. * its internal uniforms once per frame in `updateBefore()`.
  190. *
  191. * @type {string}
  192. * @default 'frame'
  193. */
  194. this.updateBeforeType = NodeUpdateType.FRAME;
  195. }
  196. /**
  197. * Sets the size of the effect.
  198. *
  199. * @param {number} width - The width of the effect.
  200. * @param {number} height - The height of the effect.
  201. */
  202. setSize( width, height ) {
  203. this._invSize.value.set( 1 / width, 1 / height );
  204. this._CoCRT.setSize( width, height );
  205. this._compositeRT.setSize( width, height );
  206. // blur runs in half resolution
  207. const halfResX = Math.round( width / 2 );
  208. const halfResY = Math.round( height / 2 );
  209. this._CoCBlurredRT.setSize( halfResX, halfResY );
  210. this._blur64RT.setSize( halfResX, halfResY );
  211. this._blur16NearRT.setSize( halfResX, halfResY );
  212. this._blur16FarRT.setSize( halfResX, halfResY );
  213. }
  214. /**
  215. * Returns the result of the effect as a texture node.
  216. *
  217. * @return {PassTextureNode} A texture node that represents the result of the effect.
  218. */
  219. getTextureNode() {
  220. return this._textureNode;
  221. }
  222. /**
  223. * This method is used to update the effect's uniforms once per frame.
  224. *
  225. * @param {NodeFrame} frame - The current node frame.
  226. */
  227. updateBefore( frame ) {
  228. const { renderer } = frame;
  229. // resize
  230. const map = this.textureNode.value;
  231. this.setSize( map.image.width, map.image.height );
  232. // save state
  233. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  234. renderer.setClearColor( 0x000000, 0 );
  235. // coc
  236. _quadMesh.material = this._CoCMaterial;
  237. renderer.setRenderTarget( this._CoCRT );
  238. _quadMesh.name = 'DoF [ CoC ]';
  239. _quadMesh.render( renderer );
  240. // blur near field to avoid visible aliased edges when the near field
  241. // is blended with the background
  242. this._CoCTextureNode.value = this._CoCRT.textures[ 0 ];
  243. _quadMesh.material = this._CoCBlurredMaterial;
  244. renderer.setRenderTarget( this._CoCBlurredRT );
  245. _quadMesh.name = 'DoF [ CoC Blur ]';
  246. _quadMesh.render( renderer );
  247. // blur64 near
  248. this._CoCTextureNode.value = this._CoCBlurredRT.texture;
  249. _quadMesh.material = this._blur64Material;
  250. renderer.setRenderTarget( this._blur64RT );
  251. _quadMesh.name = 'DoF [ Blur64 Near ]';
  252. _quadMesh.render( renderer );
  253. // blur16 near
  254. _quadMesh.material = this._blur16Material;
  255. renderer.setRenderTarget( this._blur16NearRT );
  256. _quadMesh.name = 'DoF [ Blur16 Near ]';
  257. _quadMesh.render( renderer );
  258. // blur64 far
  259. this._CoCTextureNode.value = this._CoCRT.textures[ 1 ];
  260. _quadMesh.material = this._blur64Material;
  261. renderer.setRenderTarget( this._blur64RT );
  262. _quadMesh.name = 'DoF [ Blur64 Far ]';
  263. _quadMesh.render( renderer );
  264. // blur16 far
  265. _quadMesh.material = this._blur16Material;
  266. renderer.setRenderTarget( this._blur16FarRT );
  267. _quadMesh.name = 'DoF [ Blur16 Far ]';
  268. _quadMesh.render( renderer );
  269. // composite
  270. _quadMesh.material = this._compositeMaterial;
  271. renderer.setRenderTarget( this._compositeRT );
  272. _quadMesh.name = 'DoF [ Composite ]';
  273. _quadMesh.render( renderer );
  274. // restore
  275. RendererUtils.restoreRendererState( renderer, _rendererState );
  276. }
  277. /**
  278. * This method is used to setup the effect's TSL code.
  279. *
  280. * @param {NodeBuilder} builder - The current node builder.
  281. * @return {ShaderCallNodeInternal}
  282. */
  283. setup( builder ) {
  284. const kernels = this._generateKernels();
  285. // CoC, near and far fields
  286. const nearField = property( 'float' );
  287. const farField = property( 'float' );
  288. const outputNode = outputStruct( nearField, farField );
  289. const CoC = Fn( () => {
  290. const signedDist = this.viewZNode.negate().sub( this.focusDistanceNode );
  291. const CoC = smoothstep( 0, this.focalLengthNode, signedDist.abs() );
  292. nearField.assign( step( signedDist, 0 ).mul( CoC ) );
  293. farField.assign( step( 0, signedDist ).mul( CoC ) );
  294. return vec4( 0 );
  295. } );
  296. this._CoCMaterial.colorNode = CoC().context( builder.getSharedContext() );
  297. this._CoCMaterial.outputNode = outputNode;
  298. this._CoCMaterial.needsUpdate = true;
  299. // blurred CoC for near field
  300. this._CoCBlurredMaterial.colorNode = gaussianBlur( this._CoCTextureNode, 1, 2 );
  301. this._CoCBlurredMaterial.needsUpdate = true;
  302. // bokeh 64 blur pass
  303. const bokeh64 = uniformArray( kernels.points64 );
  304. const blur64 = Fn( () => {
  305. const acc = vec3();
  306. const uvNode = uv();
  307. const CoC = this._CoCTextureNode.sample( uvNode ).r;
  308. const sampleStep = this._invSize.mul( this.bokehScaleNode ).mul( CoC );
  309. Loop( 64, ( { i } ) => {
  310. const sUV = uvNode.add( sampleStep.mul( bokeh64.element( i ) ) );
  311. const tap = this.textureNode.sample( sUV );
  312. acc.addAssign( tap.rgb );
  313. } );
  314. acc.divAssign( 64 );
  315. return vec4( acc, CoC );
  316. } );
  317. this._blur64Material.fragmentNode = blur64().context( builder.getSharedContext() );
  318. this._blur64Material.needsUpdate = true;
  319. // bokeh 16 blur pass
  320. const bokeh16 = uniformArray( kernels.points16 );
  321. const blur16 = Fn( () => {
  322. const uvNode = uv();
  323. const col = this._blur64TextureNode.sample( uvNode ).toVar();
  324. const maxVal = col.rgb;
  325. const CoC = col.a;
  326. const sampleStep = this._invSize.mul( this.bokehScaleNode ).mul( CoC );
  327. Loop( 16, ( { i } ) => {
  328. const sUV = uvNode.add( sampleStep.mul( bokeh16.element( i ) ) );
  329. const tap = this._blur64TextureNode.sample( sUV );
  330. maxVal.assign( max( tap.rgb, maxVal ) );
  331. } );
  332. return vec4( maxVal, CoC );
  333. } );
  334. this._blur16Material.fragmentNode = blur16().context( builder.getSharedContext() );
  335. this._blur16Material.needsUpdate = true;
  336. // composite
  337. const composite = Fn( () => {
  338. const uvNode = uv();
  339. const near = this._blur16NearTextureNode.sample( uvNode );
  340. const far = this._blur16FarTextureNode.sample( uvNode );
  341. const beauty = this.textureNode.sample( uvNode );
  342. // TODO: applying the bokeh scale to the near field CoC value introduces blending
  343. // issues around edges of blurred foreground objects when their are rendered above
  344. // the background. for now, don't apply the bokeh scale to the blend factors. that
  345. // will cause less blur for objects which are partly out-of-focus (CoC between 0 and 1).
  346. const blendNear = min( near.a, 0.5 ).mul( 2 );
  347. const blendFar = min( far.a, 0.5 ).mul( 2 );
  348. const result = vec4( 0, 0, 0, 1 ).toVar();
  349. result.rgb = mix( beauty.rgb, far.rgb, blendFar );
  350. result.rgb = mix( result.rgb, near.rgb, blendNear );
  351. return result;
  352. } );
  353. this._compositeMaterial.fragmentNode = composite().context( builder.getSharedContext() );
  354. this._compositeMaterial.needsUpdate = true;
  355. return this._textureNode;
  356. }
  357. _generateKernels() {
  358. // Vogel's method, see https://www.shadertoy.com/view/4fBXRG
  359. // this approach allows to generate uniformly distributed sample
  360. // points in a disc-shaped pattern. Blurring with these samples
  361. // produces a typical optical lens blur
  362. const GOLDEN_ANGLE = 2.39996323;
  363. const SAMPLES = 80;
  364. const points64 = [];
  365. const points16 = [];
  366. let idx64 = 0;
  367. let idx16 = 0;
  368. for ( let i = 0; i < SAMPLES; i ++ ) {
  369. const theta = i * GOLDEN_ANGLE;
  370. const r = Math.sqrt( i ) / Math.sqrt( SAMPLES );
  371. const p = new Vector2( r * Math.cos( theta ), r * Math.sin( theta ) );
  372. if ( i % 5 === 0 ) {
  373. points16[ idx16 ] = p;
  374. idx16 ++;
  375. } else {
  376. points64[ idx64 ] = p;
  377. idx64 ++;
  378. }
  379. }
  380. return { points16, points64 };
  381. }
  382. /**
  383. * Frees internal resources. This method should be called
  384. * when the effect is no longer required.
  385. */
  386. dispose() {
  387. this._CoCRT.dispose();
  388. this._CoCBlurredRT.dispose();
  389. this._blur64RT.dispose();
  390. this._blur16NearRT.dispose();
  391. this._blur16FarRT.dispose();
  392. this._compositeRT.dispose();
  393. this._CoCMaterial.dispose();
  394. this._CoCBlurredMaterial.dispose();
  395. this._blur64Material.dispose();
  396. this._blur16Material.dispose();
  397. this._compositeMaterial.dispose();
  398. }
  399. }
  400. export default DepthOfFieldNode;
  401. /**
  402. * TSL function for creating a depth-of-field effect (DOF) for post processing.
  403. *
  404. * @tsl
  405. * @function
  406. * @param {Node<vec4>} node - The node that represents the input of the effect.
  407. * @param {Node<float>} viewZNode - Represents the viewZ depth values of the scene.
  408. * @param {Node<float> | number} focusDistance - Defines the effect's focus which is the distance along the camera's look direction in world units.
  409. * @param {Node<float> | number} focalLength - How far an object can be from the focal plane before it goes completely out-of-focus in world units.
  410. * @param {Node<float> | number} bokehScale - A unitless value for artistic purposes to adjust the size of the bokeh.
  411. * @returns {DepthOfFieldNode}
  412. */
  413. export const dof = ( node, viewZNode, focusDistance = 1, focalLength = 1, bokehScale = 1 ) => nodeObject( new DepthOfFieldNode( convertToTexture( node ), nodeObject( viewZNode ), nodeObject( focusDistance ), nodeObject( focalLength ), nodeObject( bokehScale ) ) );
粤ICP备19079148号