CSM.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import {
  2. Vector2,
  3. Vector3,
  4. DirectionalLight,
  5. MathUtils,
  6. ShaderChunk,
  7. Matrix4,
  8. Box3
  9. } from 'three';
  10. import { CSMFrustum } from './CSMFrustum.js';
  11. import { CSMShader } from './CSMShader.js';
  12. const _cameraToLightMatrix = new Matrix4();
  13. const _lightSpaceFrustum = new CSMFrustum();
  14. const _center = new Vector3();
  15. const _bbox = new Box3();
  16. const _uniformArray = [];
  17. const _logArray = [];
  18. export class CSM {
  19. constructor( data ) {
  20. data = data || {};
  21. this.camera = data.camera;
  22. this.parent = data.parent;
  23. this.cascades = data.cascades || 3;
  24. this.maxFar = data.maxFar || 100000;
  25. this.mode = data.mode || 'practical';
  26. this.shadowMapSize = data.shadowMapSize || 2048;
  27. this.shadowBias = data.shadowBias || 0.000001;
  28. this.lightDirection = data.lightDirection || new Vector3( 1, - 1, 1 ).normalize();
  29. this.lightIntensity = data.lightIntensity || 1;
  30. this.lightNear = data.lightNear || 1;
  31. this.lightFar = data.lightFar || 2000;
  32. this.lightMargin = data.lightMargin || 200;
  33. this.customSplitsCallback = data.customSplitsCallback;
  34. this.fade = false;
  35. this.mainFrustum = new CSMFrustum();
  36. this.frustums = [];
  37. this.breaks = [];
  38. this.lights = [];
  39. this.shaders = new Map();
  40. this.createLights();
  41. this.updateFrustums();
  42. this.injectInclude();
  43. }
  44. createLights() {
  45. for ( let i = 0; i < this.cascades; i ++ ) {
  46. const light = new DirectionalLight( 0xffffff, this.lightIntensity );
  47. light.castShadow = true;
  48. light.shadow.mapSize.width = this.shadowMapSize;
  49. light.shadow.mapSize.height = this.shadowMapSize;
  50. light.shadow.camera.near = this.lightNear;
  51. light.shadow.camera.far = this.lightFar;
  52. light.shadow.bias = this.shadowBias;
  53. this.parent.add( light );
  54. this.parent.add( light.target );
  55. this.lights.push( light );
  56. }
  57. }
  58. initCascades() {
  59. const camera = this.camera;
  60. camera.updateProjectionMatrix();
  61. this.mainFrustum.setFromProjectionMatrix( camera.projectionMatrix, this.maxFar );
  62. this.mainFrustum.split( this.breaks, this.frustums );
  63. }
  64. updateShadowBounds() {
  65. const frustums = this.frustums;
  66. for ( let i = 0; i < frustums.length; i ++ ) {
  67. const light = this.lights[ i ];
  68. const shadowCam = light.shadow.camera;
  69. const frustum = this.frustums[ i ];
  70. // Get the two points that represent that furthest points on the frustum assuming
  71. // that's either the diagonal across the far plane or the diagonal across the whole
  72. // frustum itself.
  73. const nearVerts = frustum.vertices.near;
  74. const farVerts = frustum.vertices.far;
  75. const point1 = farVerts[ 0 ];
  76. let point2;
  77. if ( point1.distanceTo( farVerts[ 2 ] ) > point1.distanceTo( nearVerts[ 2 ] ) ) {
  78. point2 = farVerts[ 2 ];
  79. } else {
  80. point2 = nearVerts[ 2 ];
  81. }
  82. let squaredBBWidth = point1.distanceTo( point2 );
  83. if ( this.fade ) {
  84. // expand the shadow extents by the fade margin if fade is enabled.
  85. const camera = this.camera;
  86. const far = Math.max( camera.far, this.maxFar );
  87. const linearDepth = frustum.vertices.far[ 0 ].z / ( far - camera.near );
  88. const margin = 0.25 * Math.pow( linearDepth, 2.0 ) * ( far - camera.near );
  89. squaredBBWidth += margin;
  90. }
  91. shadowCam.left = - squaredBBWidth / 2;
  92. shadowCam.right = squaredBBWidth / 2;
  93. shadowCam.top = squaredBBWidth / 2;
  94. shadowCam.bottom = - squaredBBWidth / 2;
  95. shadowCam.updateProjectionMatrix();
  96. }
  97. }
  98. getBreaks() {
  99. const camera = this.camera;
  100. const far = Math.min( camera.far, this.maxFar );
  101. this.breaks.length = 0;
  102. switch ( this.mode ) {
  103. case 'uniform':
  104. uniformSplit( this.cascades, camera.near, far, this.breaks );
  105. break;
  106. case 'logarithmic':
  107. logarithmicSplit( this.cascades, camera.near, far, this.breaks );
  108. break;
  109. case 'practical':
  110. practicalSplit( this.cascades, camera.near, far, 0.5, this.breaks );
  111. break;
  112. case 'custom':
  113. if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' );
  114. this.customSplitsCallback( this.cascades, camera.near, far, this.breaks );
  115. break;
  116. }
  117. function uniformSplit( amount, near, far, target ) {
  118. for ( let i = 1; i < amount; i ++ ) {
  119. target.push( ( near + ( far - near ) * i / amount ) / far );
  120. }
  121. target.push( 1 );
  122. }
  123. function logarithmicSplit( amount, near, far, target ) {
  124. for ( let i = 1; i < amount; i ++ ) {
  125. target.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
  126. }
  127. target.push( 1 );
  128. }
  129. function practicalSplit( amount, near, far, lambda, target ) {
  130. _uniformArray.length = 0;
  131. _logArray.length = 0;
  132. logarithmicSplit( amount, near, far, _logArray );
  133. uniformSplit( amount, near, far, _uniformArray );
  134. for ( let i = 1; i < amount; i ++ ) {
  135. target.push( MathUtils.lerp( _uniformArray[ i - 1 ], _logArray[ i - 1 ], lambda ) );
  136. }
  137. target.push( 1 );
  138. }
  139. }
  140. update() {
  141. const camera = this.camera;
  142. const frustums = this.frustums;
  143. for ( let i = 0; i < frustums.length; i ++ ) {
  144. const light = this.lights[ i ];
  145. const shadowCam = light.shadow.camera;
  146. const texelWidth = ( shadowCam.right - shadowCam.left ) / this.shadowMapSize;
  147. const texelHeight = ( shadowCam.top - shadowCam.bottom ) / this.shadowMapSize;
  148. light.shadow.camera.updateMatrixWorld( true );
  149. _cameraToLightMatrix.multiplyMatrices( light.shadow.camera.matrixWorldInverse, camera.matrixWorld );
  150. frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum );
  151. const nearVerts = _lightSpaceFrustum.vertices.near;
  152. const farVerts = _lightSpaceFrustum.vertices.far;
  153. _bbox.makeEmpty();
  154. for ( let j = 0; j < 4; j ++ ) {
  155. _bbox.expandByPoint( nearVerts[ j ] );
  156. _bbox.expandByPoint( farVerts[ j ] );
  157. }
  158. _bbox.getCenter( _center );
  159. _center.z = _bbox.max.z + this.lightMargin;
  160. _center.x = Math.floor( _center.x / texelWidth ) * texelWidth;
  161. _center.y = Math.floor( _center.y / texelHeight ) * texelHeight;
  162. _center.applyMatrix4( light.shadow.camera.matrixWorld );
  163. light.position.copy( _center );
  164. light.target.position.copy( _center );
  165. light.target.position.x += this.lightDirection.x;
  166. light.target.position.y += this.lightDirection.y;
  167. light.target.position.z += this.lightDirection.z;
  168. }
  169. }
  170. injectInclude() {
  171. ShaderChunk.lights_fragment_begin = CSMShader.lights_fragment_begin;
  172. ShaderChunk.lights_pars_begin = CSMShader.lights_pars_begin;
  173. }
  174. setupMaterial( material ) {
  175. material.defines = material.defines || {};
  176. material.defines.USE_CSM = 1;
  177. material.defines.CSM_CASCADES = this.cascades;
  178. if ( this.fade ) {
  179. material.defines.CSM_FADE = '';
  180. }
  181. const breaksVec2 = [];
  182. const scope = this;
  183. const shaders = this.shaders;
  184. material.onBeforeCompile = function ( shader ) {
  185. const far = Math.min( scope.camera.far, scope.maxFar );
  186. scope.getExtendedBreaks( breaksVec2 );
  187. shader.uniforms.CSM_cascades = { value: breaksVec2 };
  188. shader.uniforms.cameraNear = { value: scope.camera.near };
  189. shader.uniforms.shadowFar = { value: far };
  190. shaders.set( material, shader );
  191. };
  192. shaders.set( material, null );
  193. }
  194. updateUniforms() {
  195. const far = Math.min( this.camera.far, this.maxFar );
  196. const shaders = this.shaders;
  197. shaders.forEach( function ( shader, material ) {
  198. if ( shader !== null ) {
  199. const uniforms = shader.uniforms;
  200. this.getExtendedBreaks( uniforms.CSM_cascades.value );
  201. uniforms.cameraNear.value = this.camera.near;
  202. uniforms.shadowFar.value = far;
  203. }
  204. if ( ! this.fade && 'CSM_FADE' in material.defines ) {
  205. delete material.defines.CSM_FADE;
  206. material.needsUpdate = true;
  207. } else if ( this.fade && ! ( 'CSM_FADE' in material.defines ) ) {
  208. material.defines.CSM_FADE = '';
  209. material.needsUpdate = true;
  210. }
  211. }, this );
  212. }
  213. getExtendedBreaks( target ) {
  214. while ( target.length < this.breaks.length ) {
  215. target.push( new Vector2() );
  216. }
  217. target.length = this.breaks.length;
  218. for ( let i = 0; i < this.cascades; i ++ ) {
  219. const amount = this.breaks[ i ];
  220. const prev = this.breaks[ i - 1 ] || 0;
  221. target[ i ].x = prev;
  222. target[ i ].y = amount;
  223. }
  224. }
  225. updateFrustums() {
  226. this.getBreaks();
  227. this.initCascades();
  228. this.updateShadowBounds();
  229. this.updateUniforms();
  230. }
  231. remove() {
  232. for ( let i = 0; i < this.lights.length; i ++ ) {
  233. this.parent.remove( this.lights[ i ] );
  234. }
  235. }
  236. dispose() {
  237. const shaders = this.shaders;
  238. shaders.forEach( function ( shader, material ) {
  239. delete material.onBeforeCompile;
  240. delete material.defines.USE_CSM;
  241. delete material.defines.CSM_CASCADES;
  242. delete material.defines.CSM_FADE;
  243. if ( shader !== null ) {
  244. delete shader.uniforms.CSM_cascades;
  245. delete shader.uniforms.cameraNear;
  246. delete shader.uniforms.shadowFar;
  247. }
  248. material.needsUpdate = true;
  249. } );
  250. shaders.clear();
  251. }
  252. }