CSM.js 8.2 KB

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