WebGLShadowMap.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. import { FrontSide, BackSide, DoubleSide, RGBAFormat, NearestFilter, PCFShadowMap, RGBADepthPacking, NoBlending } from '../../constants.js';
  6. import { WebGLRenderTarget } from '../WebGLRenderTarget.js';
  7. import { MeshDepthMaterial } from '../../materials/MeshDepthMaterial.js';
  8. import { MeshDistanceMaterial } from '../../materials/MeshDistanceMaterial.js';
  9. import { Vector4 } from '../../math/Vector4.js';
  10. import { Vector3 } from '../../math/Vector3.js';
  11. import { Vector2 } from '../../math/Vector2.js';
  12. import { Matrix4 } from '../../math/Matrix4.js';
  13. import { Frustum } from '../../math/Frustum.js';
  14. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  15. var _frustum = new Frustum(),
  16. _projScreenMatrix = new Matrix4(),
  17. _shadowMapSize = new Vector2(),
  18. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  19. _lookTarget = new Vector3(),
  20. _lightPositionWorld = new Vector3(),
  21. _MorphingFlag = 1,
  22. _SkinningFlag = 2,
  23. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  24. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  25. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  26. _materialCache = {};
  27. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  28. var cubeDirections = [
  29. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  30. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  31. ];
  32. var cubeUps = [
  33. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  34. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  35. ];
  36. var cube2DViewPorts = [
  37. new Vector4(), new Vector4(), new Vector4(),
  38. new Vector4(), new Vector4(), new Vector4()
  39. ];
  40. // init
  41. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  42. var useMorphing = ( i & _MorphingFlag ) !== 0;
  43. var useSkinning = ( i & _SkinningFlag ) !== 0;
  44. var depthMaterial = new MeshDepthMaterial( {
  45. supportsMultiview: false,
  46. depthPacking: RGBADepthPacking,
  47. morphTargets: useMorphing,
  48. skinning: useSkinning
  49. } );
  50. _depthMaterials[ i ] = depthMaterial;
  51. //
  52. var distanceMaterial = new MeshDistanceMaterial( {
  53. morphTargets: useMorphing,
  54. skinning: useSkinning
  55. } );
  56. _distanceMaterials[ i ] = distanceMaterial;
  57. }
  58. //
  59. var scope = this;
  60. this.enabled = false;
  61. this.autoUpdate = true;
  62. this.needsUpdate = false;
  63. this.type = PCFShadowMap;
  64. this.render = function ( lights, scene, camera ) {
  65. if ( scope.enabled === false ) return;
  66. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  67. if ( lights.length === 0 ) return;
  68. var currentRenderTarget = _renderer.getRenderTarget();
  69. var activeCubeFace = _renderer.getActiveCubeFace();
  70. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  71. var _state = _renderer.state;
  72. // Set GL state for depth map.
  73. _state.setBlending( NoBlending );
  74. _state.buffers.color.setClear( 1, 1, 1, 1 );
  75. _state.buffers.depth.setTest( true );
  76. _state.setScissorTest( false );
  77. // render depth map
  78. var faceCount;
  79. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  80. var light = lights[ i ];
  81. var shadow = light.shadow;
  82. var isPointLight = light && light.isPointLight;
  83. if ( shadow === undefined ) {
  84. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  85. continue;
  86. }
  87. var shadowCamera = shadow.camera;
  88. _shadowMapSize.copy( shadow.mapSize );
  89. _shadowMapSize.min( _maxShadowMapSize );
  90. if ( isPointLight ) {
  91. var vpWidth = _shadowMapSize.x;
  92. var vpHeight = _shadowMapSize.y;
  93. // These viewports map a cube-map onto a 2D texture with the
  94. // following orientation:
  95. //
  96. // xzXZ
  97. // y Y
  98. //
  99. // X - Positive x direction
  100. // x - Negative x direction
  101. // Y - Positive y direction
  102. // y - Negative y direction
  103. // Z - Positive z direction
  104. // z - Negative z direction
  105. // positive X
  106. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  107. // negative X
  108. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  109. // positive Z
  110. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  111. // negative Z
  112. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  113. // positive Y
  114. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  115. // negative Y
  116. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  117. _shadowMapSize.x *= 4.0;
  118. _shadowMapSize.y *= 2.0;
  119. }
  120. if ( shadow.map === null ) {
  121. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  122. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  123. shadow.map.texture.name = light.name + ".shadowMap";
  124. shadowCamera.updateProjectionMatrix();
  125. }
  126. if ( shadow.isSpotLightShadow ) {
  127. shadow.update( light );
  128. }
  129. var shadowMap = shadow.map;
  130. var shadowMatrix = shadow.matrix;
  131. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  132. shadowCamera.position.copy( _lightPositionWorld );
  133. if ( isPointLight ) {
  134. faceCount = 6;
  135. // for point lights we set the shadow matrix to be a translation-only matrix
  136. // equal to inverse of the light's position
  137. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  138. } else {
  139. faceCount = 1;
  140. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  141. shadowCamera.lookAt( _lookTarget );
  142. shadowCamera.updateMatrixWorld();
  143. // compute shadow matrix
  144. shadowMatrix.set(
  145. 0.5, 0.0, 0.0, 0.5,
  146. 0.0, 0.5, 0.0, 0.5,
  147. 0.0, 0.0, 0.5, 0.5,
  148. 0.0, 0.0, 0.0, 1.0
  149. );
  150. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  151. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  152. }
  153. _renderer.setRenderTarget( shadowMap );
  154. _renderer.clear();
  155. // render shadow map for each cube face (if omni-directional) or
  156. // run a single pass if not
  157. for ( var face = 0; face < faceCount; face ++ ) {
  158. if ( isPointLight ) {
  159. _lookTarget.copy( shadowCamera.position );
  160. _lookTarget.add( cubeDirections[ face ] );
  161. shadowCamera.up.copy( cubeUps[ face ] );
  162. shadowCamera.lookAt( _lookTarget );
  163. shadowCamera.updateMatrixWorld();
  164. var vpDimensions = cube2DViewPorts[ face ];
  165. _state.viewport( vpDimensions );
  166. }
  167. // update camera matrices and frustum
  168. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  169. _frustum.setFromMatrix( _projScreenMatrix );
  170. // set object matrices & frustum culling
  171. renderObject( scene, camera, shadowCamera, isPointLight );
  172. }
  173. }
  174. scope.needsUpdate = false;
  175. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  176. };
  177. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  178. var geometry = object.geometry;
  179. var result = null;
  180. var materialVariants = _depthMaterials;
  181. var customMaterial = object.customDepthMaterial;
  182. if ( isPointLight ) {
  183. materialVariants = _distanceMaterials;
  184. customMaterial = object.customDistanceMaterial;
  185. }
  186. if ( ! customMaterial ) {
  187. var useMorphing = false;
  188. if ( material.morphTargets ) {
  189. if ( geometry && geometry.isBufferGeometry ) {
  190. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  191. } else if ( geometry && geometry.isGeometry ) {
  192. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  193. }
  194. }
  195. if ( object.isSkinnedMesh && material.skinning === false ) {
  196. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  197. }
  198. var useSkinning = object.isSkinnedMesh && material.skinning;
  199. var variantIndex = 0;
  200. if ( useMorphing ) variantIndex |= _MorphingFlag;
  201. if ( useSkinning ) variantIndex |= _SkinningFlag;
  202. result = materialVariants[ variantIndex ];
  203. } else {
  204. result = customMaterial;
  205. }
  206. if ( _renderer.localClippingEnabled &&
  207. material.clipShadows === true &&
  208. material.clippingPlanes.length !== 0 ) {
  209. // in this case we need a unique material instance reflecting the
  210. // appropriate state
  211. var keyA = result.uuid, keyB = material.uuid;
  212. var materialsForVariant = _materialCache[ keyA ];
  213. if ( materialsForVariant === undefined ) {
  214. materialsForVariant = {};
  215. _materialCache[ keyA ] = materialsForVariant;
  216. }
  217. var cachedMaterial = materialsForVariant[ keyB ];
  218. if ( cachedMaterial === undefined ) {
  219. cachedMaterial = result.clone();
  220. materialsForVariant[ keyB ] = cachedMaterial;
  221. }
  222. result = cachedMaterial;
  223. }
  224. result.visible = material.visible;
  225. result.wireframe = material.wireframe;
  226. result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ];
  227. result.clipShadows = material.clipShadows;
  228. result.clippingPlanes = material.clippingPlanes;
  229. result.clipIntersection = material.clipIntersection;
  230. result.wireframeLinewidth = material.wireframeLinewidth;
  231. result.linewidth = material.linewidth;
  232. if ( isPointLight && result.isMeshDistanceMaterial ) {
  233. result.referencePosition.copy( lightPositionWorld );
  234. result.nearDistance = shadowCameraNear;
  235. result.farDistance = shadowCameraFar;
  236. }
  237. return result;
  238. }
  239. function renderObject( object, camera, shadowCamera, isPointLight ) {
  240. if ( object.visible === false ) return;
  241. var visible = object.layers.test( camera.layers );
  242. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  243. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  244. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  245. var geometry = _objects.update( object );
  246. var material = object.material;
  247. if ( Array.isArray( material ) ) {
  248. var groups = geometry.groups;
  249. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  250. var group = groups[ k ];
  251. var groupMaterial = material[ group.materialIndex ];
  252. if ( groupMaterial && groupMaterial.visible ) {
  253. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  254. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  255. }
  256. }
  257. } else if ( material.visible ) {
  258. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  259. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  260. }
  261. }
  262. }
  263. var children = object.children;
  264. for ( var i = 0, l = children.length; i < l; i ++ ) {
  265. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  266. }
  267. }
  268. }
  269. export { WebGLShadowMap };