CSM.js 9.1 KB

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