CSM.js 8.7 KB

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