WebGLShadowMap.js 12 KB

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