WebGLShadowMap.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { FrontSide, BackSide, DoubleSide, NearestFilter, PCFShadowMap, VSMShadowMap, RGBADepthPacking, NoBlending } from '../../constants.js';
  2. import { WebGLRenderTarget } from '../WebGLRenderTarget.js';
  3. import { MeshDepthMaterial } from '../../materials/MeshDepthMaterial.js';
  4. import { MeshDistanceMaterial } from '../../materials/MeshDistanceMaterial.js';
  5. import { ShaderMaterial } from '../../materials/ShaderMaterial.js';
  6. import { BufferAttribute } from '../../core/BufferAttribute.js';
  7. import { BufferGeometry } from '../../core/BufferGeometry.js';
  8. import { Mesh } from '../../objects/Mesh.js';
  9. import { Vector4 } from '../../math/Vector4.js';
  10. import { Vector2 } from '../../math/Vector2.js';
  11. import { Frustum } from '../../math/Frustum.js';
  12. import * as vsm from '../shaders/ShaderLib/vsm.glsl.js';
  13. function WebGLShadowMap( renderer, objects, capabilities ) {
  14. let _frustum = new Frustum();
  15. const _shadowMapSize = new Vector2(),
  16. _viewportSize = new Vector2(),
  17. _viewport = new Vector4(),
  18. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  19. _distanceMaterial = new MeshDistanceMaterial(),
  20. _materialCache = {},
  21. _maxTextureSize = capabilities.maxTextureSize;
  22. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  23. const shadowMaterialVertical = new ShaderMaterial( {
  24. defines: {
  25. VSM_SAMPLES: 8
  26. },
  27. uniforms: {
  28. shadow_pass: { value: null },
  29. resolution: { value: new Vector2() },
  30. radius: { value: 4.0 }
  31. },
  32. vertexShader: vsm.vertex,
  33. fragmentShader: vsm.fragment
  34. } );
  35. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  36. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  37. const fullScreenTri = new BufferGeometry();
  38. fullScreenTri.setAttribute(
  39. 'position',
  40. new BufferAttribute(
  41. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  42. 3
  43. )
  44. );
  45. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  46. const scope = this;
  47. this.enabled = false;
  48. this.autoUpdate = true;
  49. this.needsUpdate = false;
  50. this.type = PCFShadowMap;
  51. let _previousType = this.type;
  52. this.render = function ( lights, scene, camera ) {
  53. if ( scope.enabled === false ) return;
  54. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  55. if ( lights.length === 0 ) return;
  56. const currentRenderTarget = renderer.getRenderTarget();
  57. const activeCubeFace = renderer.getActiveCubeFace();
  58. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  59. const _state = renderer.state;
  60. // Set GL state for depth map.
  61. _state.setBlending( NoBlending );
  62. _state.buffers.color.setClear( 1, 1, 1, 1 );
  63. _state.buffers.depth.setTest( true );
  64. _state.setScissorTest( false );
  65. // check for shadow map type changes
  66. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  67. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  68. // render depth map
  69. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  70. const light = lights[ i ];
  71. const shadow = light.shadow;
  72. if ( shadow === undefined ) {
  73. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  74. continue;
  75. }
  76. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  77. _shadowMapSize.copy( shadow.mapSize );
  78. const shadowFrameExtents = shadow.getFrameExtents();
  79. _shadowMapSize.multiply( shadowFrameExtents );
  80. _viewportSize.copy( shadow.mapSize );
  81. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  82. if ( _shadowMapSize.x > _maxTextureSize ) {
  83. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  84. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  85. shadow.mapSize.x = _viewportSize.x;
  86. }
  87. if ( _shadowMapSize.y > _maxTextureSize ) {
  88. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  89. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  90. shadow.mapSize.y = _viewportSize.y;
  91. }
  92. }
  93. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  94. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  95. if ( shadow.map !== null ) {
  96. shadow.map.dispose();
  97. }
  98. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  99. shadow.map.texture.name = light.name + '.shadowMap';
  100. shadow.camera.updateProjectionMatrix();
  101. }
  102. renderer.setRenderTarget( shadow.map );
  103. renderer.clear();
  104. const viewportCount = shadow.getViewportCount();
  105. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  106. const viewport = shadow.getViewport( vp );
  107. _viewport.set(
  108. _viewportSize.x * viewport.x,
  109. _viewportSize.y * viewport.y,
  110. _viewportSize.x * viewport.z,
  111. _viewportSize.y * viewport.w
  112. );
  113. _state.viewport( _viewport );
  114. shadow.updateMatrices( light, vp );
  115. _frustum = shadow.getFrustum();
  116. renderObject( scene, camera, shadow.camera, light, this.type );
  117. }
  118. // do blur pass for VSM
  119. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  120. VSMPass( shadow, camera );
  121. }
  122. shadow.needsUpdate = false;
  123. }
  124. _previousType = this.type;
  125. scope.needsUpdate = false;
  126. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  127. };
  128. function VSMPass( shadow, camera ) {
  129. const geometry = objects.update( fullScreenMesh );
  130. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  131. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  132. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  133. shadowMaterialVertical.needsUpdate = true;
  134. shadowMaterialHorizontal.needsUpdate = true;
  135. }
  136. if ( shadow.mapPass === null ) {
  137. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  138. }
  139. // vertical pass
  140. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  141. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  142. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  143. renderer.setRenderTarget( shadow.mapPass );
  144. renderer.clear();
  145. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  146. // horizontal pass
  147. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  148. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  149. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  150. renderer.setRenderTarget( shadow.map );
  151. renderer.clear();
  152. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  153. }
  154. function getDepthMaterial( object, material, light, type ) {
  155. let result = null;
  156. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  157. if ( customMaterial !== undefined ) {
  158. result = customMaterial;
  159. } else {
  160. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  161. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  162. ( material.displacementMap && material.displacementScale !== 0 ) ||
  163. ( material.alphaMap && material.alphaTest > 0 ) ||
  164. ( material.map && material.alphaTest > 0 ) ) {
  165. // in this case we need a unique material instance reflecting the
  166. // appropriate state
  167. const keyA = result.uuid, keyB = material.uuid;
  168. let materialsForVariant = _materialCache[ keyA ];
  169. if ( materialsForVariant === undefined ) {
  170. materialsForVariant = {};
  171. _materialCache[ keyA ] = materialsForVariant;
  172. }
  173. let cachedMaterial = materialsForVariant[ keyB ];
  174. if ( cachedMaterial === undefined ) {
  175. cachedMaterial = result.clone();
  176. materialsForVariant[ keyB ] = cachedMaterial;
  177. material.addEventListener( 'dispose', onMaterialDispose );
  178. }
  179. result = cachedMaterial;
  180. }
  181. }
  182. result.visible = material.visible;
  183. result.wireframe = material.wireframe;
  184. if ( type === VSMShadowMap ) {
  185. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  186. } else {
  187. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  188. }
  189. result.alphaMap = material.alphaMap;
  190. result.alphaTest = material.alphaTest;
  191. result.map = material.map;
  192. result.clipShadows = material.clipShadows;
  193. result.clippingPlanes = material.clippingPlanes;
  194. result.clipIntersection = material.clipIntersection;
  195. result.displacementMap = material.displacementMap;
  196. result.displacementScale = material.displacementScale;
  197. result.displacementBias = material.displacementBias;
  198. result.wireframeLinewidth = material.wireframeLinewidth;
  199. result.linewidth = material.linewidth;
  200. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  201. const materialProperties = renderer.properties.get( result );
  202. materialProperties.light = light;
  203. }
  204. return result;
  205. }
  206. function renderObject( object, camera, shadowCamera, light, type ) {
  207. if ( object.visible === false ) return;
  208. const visible = object.layers.test( camera.layers );
  209. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  210. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  211. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  212. const geometry = objects.update( object );
  213. const material = object.material;
  214. if ( Array.isArray( material ) ) {
  215. const groups = geometry.groups;
  216. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  217. const group = groups[ k ];
  218. const groupMaterial = material[ group.materialIndex ];
  219. if ( groupMaterial && groupMaterial.visible ) {
  220. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  221. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  222. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  223. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  224. }
  225. }
  226. } else if ( material.visible ) {
  227. const depthMaterial = getDepthMaterial( object, material, light, type );
  228. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  229. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  230. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  231. }
  232. }
  233. }
  234. const children = object.children;
  235. for ( let i = 0, l = children.length; i < l; i ++ ) {
  236. renderObject( children[ i ], camera, shadowCamera, light, type );
  237. }
  238. }
  239. function onMaterialDispose( event ) {
  240. const material = event.target;
  241. material.removeEventListener( 'dispose', onMaterialDispose );
  242. // make sure to remove the unique distance/depth materials used for shadow map rendering
  243. for ( const id in _materialCache ) {
  244. const cache = _materialCache[ id ];
  245. const uuid = event.target.uuid;
  246. if ( uuid in cache ) {
  247. const shadowMaterial = cache[ uuid ];
  248. shadowMaterial.dispose();
  249. delete cache[ uuid ];
  250. }
  251. }
  252. }
  253. }
  254. export { WebGLShadowMap };