ShadowNode.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. import ShadowBaseNode, { shadowPositionWorld } from './ShadowBaseNode.js';
  2. import { float, vec2, vec3, int, Fn, nodeObject } from '../tsl/TSLBase.js';
  3. import { reference } from '../accessors/ReferenceNode.js';
  4. import { texture, textureLoad } from '../accessors/TextureNode.js';
  5. import { normalWorld } from '../accessors/Normal.js';
  6. import { mix, sqrt } from '../math/MathNode.js';
  7. import { add } from '../math/OperatorNode.js';
  8. import { DepthTexture } from '../../textures/DepthTexture.js';
  9. import NodeMaterial from '../../materials/nodes/NodeMaterial.js';
  10. import QuadMesh from '../../renderers/common/QuadMesh.js';
  11. import { Loop } from '../utils/LoopNode.js';
  12. import { screenCoordinate } from '../display/ScreenNode.js';
  13. import { HalfFloatType, LessCompare, RGFormat, VSMShadowMap, WebGPUCoordinateSystem } from '../../constants.js';
  14. import { renderGroup } from '../core/UniformGroupNode.js';
  15. import { viewZToLogarithmicDepth } from '../display/ViewportDepthNode.js';
  16. import { lightShadowMatrix } from '../accessors/Lights.js';
  17. import { resetRendererAndSceneState, restoreRendererAndSceneState } from '../../renderers/common/RendererUtils.js';
  18. import { getDataFromObject } from '../core/NodeUtils.js';
  19. import { getShadowMaterial, BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter } from './ShadowFilterNode.js';
  20. import ChainMap from '../../renderers/common/ChainMap.js';
  21. import { warn } from '../../utils.js';
  22. import { textureSize } from '../accessors/TextureSizeNode.js';
  23. import { uv } from '../accessors/UV.js';
  24. //
  25. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  26. const _shadowRenderObjectKeys = [];
  27. /**
  28. * Creates a function to render shadow objects in a scene.
  29. *
  30. * @param {Renderer} renderer - The renderer.
  31. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  32. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  33. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  34. * @return {Function} A function that renders shadow objects.
  35. *
  36. * The returned function has the following parameters:
  37. * @param {Object3D} object - The 3D object to render.
  38. * @param {Scene} scene - The scene containing the object.
  39. * @param {Camera} _camera - The camera used for rendering.
  40. * @param {BufferGeometry} geometry - The geometry of the object.
  41. * @param {Material} material - The material of the object.
  42. * @param {Group} group - The group the object belongs to.
  43. * @param {...any} params - Additional parameters for rendering.
  44. */
  45. export const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  46. _shadowRenderObjectKeys[ 0 ] = renderer;
  47. _shadowRenderObjectKeys[ 1 ] = shadow;
  48. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  49. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  50. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  51. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  52. if ( useVelocity ) {
  53. getDataFromObject( object ).useVelocity = true;
  54. }
  55. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  56. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  57. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  58. }
  59. };
  60. renderObjectFunction.shadowType = shadowType;
  61. renderObjectFunction.useVelocity = useVelocity;
  62. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  63. }
  64. _shadowRenderObjectKeys[ 0 ] = null;
  65. _shadowRenderObjectKeys[ 1 ] = null;
  66. return renderObjectFunction;
  67. };
  68. /**
  69. * Represents the shader code for the first VSM render pass.
  70. *
  71. * @method
  72. * @param {Object} inputs - The input parameter object.
  73. * @param {Node<float>} inputs.samples - The number of samples
  74. * @param {Node<float>} inputs.radius - The radius.
  75. * @param {Node<float>} inputs.size - The size.
  76. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  77. * @return {Node<vec2>} The VSM output.
  78. */
  79. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  80. const mean = float( 0 ).toVar( 'meanVertical' );
  81. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  82. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  83. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  84. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  85. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  86. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  87. if ( shadowPass.value.isArrayTexture ) {
  88. depth = depth.depth( depthLayer );
  89. }
  90. depth = depth.x;
  91. mean.addAssign( depth );
  92. squaredMean.addAssign( depth.mul( depth ) );
  93. } );
  94. mean.divAssign( samples );
  95. squaredMean.divAssign( samples );
  96. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  97. return vec2( mean, std_dev );
  98. } );
  99. /**
  100. * Represents the shader code for the second VSM render pass.
  101. *
  102. * @method
  103. * @param {Object} inputs - The input parameter object.
  104. * @param {Node<float>} inputs.samples - The number of samples
  105. * @param {Node<float>} inputs.radius - The radius.
  106. * @param {Node<float>} inputs.size - The size.
  107. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  108. * @return {Node<vec2>} The VSM output.
  109. */
  110. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  111. const mean = float( 0 ).toVar( 'meanHorizontal' );
  112. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  113. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  114. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  115. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  116. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  117. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  118. if ( shadowPass.value.isArrayTexture ) {
  119. distribution = distribution.depth( depthLayer );
  120. }
  121. mean.addAssign( distribution.x );
  122. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  123. } );
  124. mean.divAssign( samples );
  125. squaredMean.divAssign( samples );
  126. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  127. return vec2( mean, std_dev );
  128. } );
  129. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  130. //
  131. let _rendererState;
  132. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  133. /**
  134. * Represents the default shadow implementation for lighting nodes.
  135. *
  136. * @augments ShadowBaseNode
  137. */
  138. class ShadowNode extends ShadowBaseNode {
  139. static get type() {
  140. return 'ShadowNode';
  141. }
  142. /**
  143. * Constructs a new shadow node.
  144. *
  145. * @param {Light} light - The shadow casting light.
  146. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  147. */
  148. constructor( light, shadow = null ) {
  149. super( light );
  150. /**
  151. * The light shadow which defines the properties light's
  152. * shadow.
  153. *
  154. * @type {?LightShadow}
  155. * @default null
  156. */
  157. this.shadow = shadow || light.shadow;
  158. /**
  159. * A reference to the shadow map which is a render target.
  160. *
  161. * @type {?RenderTarget}
  162. * @default null
  163. */
  164. this.shadowMap = null;
  165. /**
  166. * Only relevant for VSM shadows. Render target for the
  167. * first VSM render pass.
  168. *
  169. * @type {?RenderTarget}
  170. * @default null
  171. */
  172. this.vsmShadowMapVertical = null;
  173. /**
  174. * Only relevant for VSM shadows. Render target for the
  175. * second VSM render pass.
  176. *
  177. * @type {?RenderTarget}
  178. * @default null
  179. */
  180. this.vsmShadowMapHorizontal = null;
  181. /**
  182. * Only relevant for VSM shadows. Node material which
  183. * is used to render the first VSM pass.
  184. *
  185. * @type {?NodeMaterial}
  186. * @default null
  187. */
  188. this.vsmMaterialVertical = null;
  189. /**
  190. * Only relevant for VSM shadows. Node material which
  191. * is used to render the second VSM pass.
  192. *
  193. * @type {?NodeMaterial}
  194. * @default null
  195. */
  196. this.vsmMaterialHorizontal = null;
  197. /**
  198. * A reference to the output node which defines the
  199. * final result of this shadow node.
  200. *
  201. * @type {?Node}
  202. * @private
  203. * @default null
  204. */
  205. this._node = null;
  206. this._cameraFrameId = new WeakMap();
  207. /**
  208. * This flag can be used for type testing.
  209. *
  210. * @type {boolean}
  211. * @readonly
  212. * @default true
  213. */
  214. this.isShadowNode = true;
  215. /**
  216. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  217. *
  218. * @type {number}
  219. * @readonly
  220. * @default true
  221. */
  222. this.depthLayer = 0;
  223. }
  224. /**
  225. * Setups the shadow filtering.
  226. *
  227. * @param {NodeBuilder} builder - A reference to the current node builder.
  228. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  229. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  230. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  231. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  232. * @param {LightShadow} inputs.shadow - The light shadow.
  233. * @return {Node<float>} The result node of the shadow filtering.
  234. */
  235. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  236. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  237. .and( shadowCoord.x.lessThanEqual( 1 ) )
  238. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  239. .and( shadowCoord.y.lessThanEqual( 1 ) )
  240. .and( shadowCoord.z.lessThanEqual( 1 ) );
  241. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  242. return frustumTest.select( shadowNode, float( 1 ) );
  243. }
  244. /**
  245. * Setups the shadow coordinates.
  246. *
  247. * @param {NodeBuilder} builder - A reference to the current node builder.
  248. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  249. * @return {Node<vec3>} The shadow coordinates.
  250. */
  251. setupShadowCoord( builder, shadowPosition ) {
  252. const { shadow } = this;
  253. const { renderer } = builder;
  254. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  255. let shadowCoord = shadowPosition;
  256. let coordZ;
  257. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  258. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  259. coordZ = shadowCoord.z;
  260. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  261. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  262. }
  263. } else {
  264. const w = shadowCoord.w;
  265. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  266. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  267. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  268. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  269. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  270. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  271. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  272. }
  273. shadowCoord = vec3(
  274. shadowCoord.x,
  275. shadowCoord.y.oneMinus(), // follow webgpu standards
  276. coordZ.add( bias )
  277. );
  278. return shadowCoord;
  279. }
  280. /**
  281. * Returns the shadow filtering function for the given shadow type.
  282. *
  283. * @param {number} type - The shadow type.
  284. * @return {Function} The filtering function.
  285. */
  286. getShadowFilterFn( type ) {
  287. return _shadowFilterLib[ type ];
  288. }
  289. setupRenderTarget( shadow, builder ) {
  290. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  291. depthTexture.name = 'ShadowDepthTexture';
  292. depthTexture.compareFunction = LessCompare;
  293. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  294. shadowMap.texture.name = 'ShadowMap';
  295. shadowMap.texture.type = shadow.mapType;
  296. shadowMap.depthTexture = depthTexture;
  297. return { shadowMap, depthTexture };
  298. }
  299. /**
  300. * Setups the shadow output node.
  301. *
  302. * @param {NodeBuilder} builder - A reference to the current node builder.
  303. * @return {Node<vec3>} The shadow output node.
  304. */
  305. setupShadow( builder ) {
  306. const { renderer, camera } = builder;
  307. const { light, shadow } = this;
  308. const shadowMapType = renderer.shadowMap.type;
  309. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  310. shadow.camera.coordinateSystem = camera.coordinateSystem;
  311. shadow.camera.updateProjectionMatrix();
  312. // VSM
  313. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  314. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  315. if ( shadowMap.depth > 1 ) {
  316. if ( ! shadowMap._vsmShadowMapVertical ) {
  317. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  318. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  319. }
  320. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  321. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  322. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  323. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  324. }
  325. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  326. } else {
  327. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  328. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  329. }
  330. let shadowPassVertical = texture( depthTexture );
  331. if ( depthTexture.isArrayTexture ) {
  332. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  333. }
  334. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  335. if ( depthTexture.isArrayTexture ) {
  336. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  337. }
  338. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  339. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  340. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  341. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  342. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  343. material.name = 'VSMVertical';
  344. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  345. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  346. material.name = 'VSMHorizontal';
  347. }
  348. //
  349. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  350. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  351. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  352. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  353. //
  354. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  355. if ( filterFn === null ) {
  356. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  357. }
  358. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  359. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  360. let shadowColor = texture( shadowMap.texture, shadowCoord );
  361. if ( depthTexture.isArrayTexture ) {
  362. shadowColor = shadowColor.depth( this.depthLayer );
  363. }
  364. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  365. this.shadowMap = shadowMap;
  366. this.shadow.map = shadowMap;
  367. // Shadow Output + Inspector
  368. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  369. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  370. return texture( this.shadowMap.texture );
  371. } ).toInspector( `${ inspectName } / Depth`, () => {
  372. return textureLoad( this.shadowMap.depthTexture, uv().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  373. } );
  374. }
  375. /**
  376. * The implementation performs the setup of the output node. An output is only
  377. * produces if shadow mapping is globally enabled in the renderer.
  378. *
  379. * @param {NodeBuilder} builder - A reference to the current node builder.
  380. * @return {ShaderCallNodeInternal} The output node.
  381. */
  382. setup( builder ) {
  383. if ( builder.renderer.shadowMap.enabled === false ) return;
  384. return Fn( () => {
  385. let node = this._node;
  386. this.setupShadowPosition( builder );
  387. if ( node === null ) {
  388. this._node = node = this.setupShadow( builder );
  389. }
  390. if ( builder.material.shadowNode ) { // @deprecated, r171
  391. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  392. }
  393. if ( builder.material.receivedShadowNode ) {
  394. node = builder.material.receivedShadowNode( node );
  395. }
  396. return node;
  397. } )();
  398. }
  399. /**
  400. * Renders the shadow. The logic of this function could be included
  401. * into {@link ShadowNode#updateShadow} however more specialized shadow
  402. * nodes might require a custom shadow map rendering. By having a
  403. * dedicated method, it's easier to overwrite the default behavior.
  404. *
  405. * @param {NodeFrame} frame - A reference to the current node frame.
  406. */
  407. renderShadow( frame ) {
  408. const { shadow, shadowMap, light } = this;
  409. const { renderer, scene } = frame;
  410. shadow.updateMatrices( light );
  411. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  412. const currentSceneName = scene.name;
  413. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  414. renderer.render( scene, shadow.camera );
  415. scene.name = currentSceneName;
  416. }
  417. /**
  418. * Updates the shadow.
  419. *
  420. * @param {NodeFrame} frame - A reference to the current node frame.
  421. */
  422. updateShadow( frame ) {
  423. const { shadowMap, light, shadow } = this;
  424. const { renderer, scene, camera } = frame;
  425. const shadowType = renderer.shadowMap.type;
  426. const depthVersion = shadowMap.depthTexture.version;
  427. this._depthVersionCached = depthVersion;
  428. const _shadowCameraLayer = shadow.camera.layers.mask;
  429. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  430. shadow.camera.layers.mask = camera.layers.mask;
  431. }
  432. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  433. const currentMRT = renderer.getMRT();
  434. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  435. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  436. scene.overrideMaterial = getShadowMaterial( light );
  437. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  438. renderer.setClearColor( 0x000000, 0 );
  439. renderer.setRenderTarget( shadowMap );
  440. this.renderShadow( frame );
  441. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  442. // vsm blur pass
  443. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  444. this.vsmPass( renderer );
  445. }
  446. shadow.camera.layers.mask = _shadowCameraLayer;
  447. restoreRendererAndSceneState( renderer, scene, _rendererState );
  448. }
  449. /**
  450. * For VSM additional render passes are required.
  451. *
  452. * @param {Renderer} renderer - A reference to the current renderer.
  453. */
  454. vsmPass( renderer ) {
  455. const { shadow } = this;
  456. const depth = this.shadowMap.depth;
  457. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  458. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  459. renderer.setRenderTarget( this.vsmShadowMapVertical );
  460. _quadMesh.material = this.vsmMaterialVertical;
  461. _quadMesh.render( renderer );
  462. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  463. _quadMesh.material = this.vsmMaterialHorizontal;
  464. _quadMesh.render( renderer );
  465. }
  466. /**
  467. * Frees the internal resources of this shadow node.
  468. */
  469. dispose() {
  470. this.shadowMap.dispose();
  471. this.shadowMap = null;
  472. if ( this.vsmShadowMapVertical !== null ) {
  473. this.vsmShadowMapVertical.dispose();
  474. this.vsmShadowMapVertical = null;
  475. this.vsmMaterialVertical.dispose();
  476. this.vsmMaterialVertical = null;
  477. }
  478. if ( this.vsmShadowMapHorizontal !== null ) {
  479. this.vsmShadowMapHorizontal.dispose();
  480. this.vsmShadowMapHorizontal = null;
  481. this.vsmMaterialHorizontal.dispose();
  482. this.vsmMaterialHorizontal = null;
  483. }
  484. super.dispose();
  485. }
  486. /**
  487. * The implementation performs the update of the shadow map if necessary.
  488. *
  489. * @param {NodeFrame} frame - A reference to the current node frame.
  490. */
  491. updateBefore( frame ) {
  492. const { shadow } = this;
  493. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  494. if ( needsUpdate ) {
  495. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  496. needsUpdate = false;
  497. }
  498. this._cameraFrameId[ frame.camera ] = frame.frameId;
  499. }
  500. if ( needsUpdate ) {
  501. this.updateShadow( frame );
  502. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  503. shadow.needsUpdate = false;
  504. }
  505. }
  506. }
  507. }
  508. export default ShadowNode;
  509. /**
  510. * TSL function for creating an instance of `ShadowNode`.
  511. *
  512. * @tsl
  513. * @function
  514. * @param {Light} light - The shadow casting light.
  515. * @param {?LightShadow} [shadow] - The light shadow.
  516. * @return {ShadowNode} The created shadow node.
  517. */
  518. export const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
粤ICP备19079148号