CSM.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 = [];
  50. this.materials = [];
  51. this.createLights();
  52. this.getBreaks();
  53. this.initCascades();
  54. this.injectInclude();
  55. }
  56. createLights() {
  57. for ( let i = 0; i < this.cascades; i ++ ) {
  58. const light = new DirectionalLight( 0xffffff, this.lightIntensity );
  59. light.castShadow = true;
  60. light.shadow.mapSize.width = this.shadowMapSize;
  61. light.shadow.mapSize.height = this.shadowMapSize;
  62. light.shadow.camera.near = this.lightNear;
  63. light.shadow.camera.far = this.lightFar;
  64. light.shadow.bias = this.shadowBias;
  65. this.parent.add( light );
  66. this.parent.add( light.target );
  67. this.lights.push( light );
  68. }
  69. }
  70. initCascades() {
  71. const camera = this.camera;
  72. camera.updateProjectionMatrix();
  73. this.mainFrustum.setFromProjectionMatrix( camera.projectionMatrix, this.maxFar );
  74. this.mainFrustum.split( this.breaks, this.frustums );
  75. }
  76. getBreaks() {
  77. const camera = this.camera;
  78. const far = Math.min(camera.far, this.maxFar);
  79. this.breaks.length = 0;
  80. switch ( this.mode ) {
  81. case 'uniform':
  82. uniformSplit( this.cascades, camera.near, far, this.breaks );
  83. break;
  84. case 'logarithmic':
  85. logarithmicSplit( this.cascades, camera.near, far, this.breaks );
  86. break;
  87. case 'practical':
  88. practicalSplit( this.cascades, camera.near, far, 0.5, this.breaks );
  89. break;
  90. case 'custom':
  91. if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' );
  92. this.customSplitsCallback( this.cascades, camera.near, far, this.breaks );
  93. break;
  94. }
  95. function uniformSplit( amount, near, far, target ) {
  96. for ( let i = 1; i < amount; i ++ ) {
  97. target.push( ( near + ( far - near ) * i / amount ) / far );
  98. }
  99. target.push( 1 );
  100. }
  101. function logarithmicSplit( amount, near, far, target ) {
  102. for ( let i = 1; i < amount; i ++ ) {
  103. target.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
  104. }
  105. target.push( 1 );
  106. }
  107. function practicalSplit( amount, near, far, lambda, target ) {
  108. _uniformArray.length = 0;
  109. _logArray.length = 0;
  110. const log = logarithmicSplit( amount, near, far, _logArray );
  111. const uni = uniformSplit( amount, near, far, _uniformArray );
  112. for ( let i = 1; i < amount; i ++ ) {
  113. target.push( MathUtils.lerp( _uniformArray[ i - 1 ], _logArray[ i - 1 ], lambda ) );
  114. }
  115. target.push( 1 );
  116. }
  117. }
  118. update( cameraMatrix ) {
  119. for ( let i = 0; i < this.frustums.length; i ++ ) {
  120. const light = this.lights[ i ];
  121. light.shadow.camera.updateMatrixWorld( true );
  122. _cameraToLightMatrix.multiplyMatrices( light.shadow.camera.matrixWorldInverse, cameraMatrix );
  123. this.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. const squaredBBWidth = Math.max( _size.x, _size.y );
  134. light.shadow.camera.left = - squaredBBWidth / 2;
  135. light.shadow.camera.right = squaredBBWidth / 2;
  136. light.shadow.camera.top = squaredBBWidth / 2;
  137. light.shadow.camera.bottom = - squaredBBWidth / 2;
  138. light.position.copy( _center );
  139. light.target.position.copy( _center );
  140. light.target.position.x += this.lightDirection.x;
  141. light.target.position.y += this.lightDirection.y;
  142. light.target.position.z += this.lightDirection.z;
  143. light.shadow.camera.updateProjectionMatrix();
  144. light.shadow.camera.updateMatrixWorld();
  145. }
  146. }
  147. injectInclude() {
  148. ShaderChunk.lights_fragment_begin = Shader.lights_fragment_begin;
  149. ShaderChunk.lights_pars_begin = Shader.lights_pars_begin;
  150. }
  151. setupMaterial( material ) {
  152. material.defines = material.defines || {};
  153. material.defines.USE_CSM = 1;
  154. material.defines.CSM_CASCADES = this.cascades;
  155. if ( this.fade ) {
  156. material.defines.CSM_FADE = '';
  157. }
  158. const breaksVec2 = [];
  159. this.getExtendedBreaks( breaksVec2 );
  160. const self = this;
  161. const far = Math.min(this.camera.far, this.maxFar);
  162. material.onBeforeCompile = function ( shader ) {
  163. shader.uniforms.CSM_cascades = { value: breaksVec2 };
  164. shader.uniforms.cameraNear = { value: self.camera.near };
  165. shader.uniforms.shadowFar = { value: far };
  166. self.shaders.push( shader );
  167. };
  168. this.materials.push( material );
  169. }
  170. updateUniforms() {
  171. const far = Math.min(this.camera.far, this.maxFar);
  172. for ( let i = 0; i < this.shaders.length; i ++ ) {
  173. const shader = this.shaders[ i ];
  174. const uniforms = shader.uniforms;
  175. this.getExtendedBreaks( uniforms.CSM_cascades.value );
  176. uniforms.cameraNear.value = this.camera.near;
  177. uniforms.shadowFar.value = far;
  178. }
  179. for ( let i = 0; i < this.materials.length; i ++ ) {
  180. const material = this.materials[ i ];
  181. if ( ! this.fade && 'CSM_FADE' in material.defines ) {
  182. delete material.defines.CSM_FADE;
  183. material.needsUpdate = true;
  184. } else {
  185. material.defines.CSM_FADE = '';
  186. material.needsUpdate = true;
  187. }
  188. }
  189. }
  190. getExtendedBreaks( target ) {
  191. while ( target.length < this.breaks.length ) {
  192. target.push( new Vector2() );
  193. }
  194. target.length = this.breaks.length;
  195. for ( let i = 0; i < this.cascades; i ++ ) {
  196. let amount = this.breaks[ i ];
  197. let prev = this.breaks[ i - 1 ] || 0;
  198. target[ i ].x = prev;
  199. target[ i ].y = amount;
  200. }
  201. }
  202. updateFrustums() {
  203. this.getBreaks();
  204. this.initCascades();
  205. this.updateUniforms();
  206. }
  207. helper( cameraMatrix ) {
  208. let geometry, vertices;
  209. const material = new LineBasicMaterial( { color: 0xffffff } );
  210. const object = new Object3D();
  211. for ( let i = 0; i < this.frustums.length; i ++ ) {
  212. this.frustums[ i ].toSpace( cameraMatrix, _frustum );
  213. geometry = new BufferGeometry();
  214. vertices = [];
  215. for ( let i = 0; i < 5; i ++ ) {
  216. const point = _frustum.vertices.near[ i === 4 ? 0 : i ];
  217. vertices.push( point.x, point.y, point.z );
  218. }
  219. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  220. object.add( new Line( geometry, material ) );
  221. geometry = new BufferGeometry();
  222. vertices = [];
  223. for ( let i = 0; i < 5; i ++ ) {
  224. const point = _frustum.vertices.far[ 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. for ( let i = 0; i < 4; i ++ ) {
  230. geometry = new BufferGeometry();
  231. vertices = [];
  232. const near = _frustum.vertices.near[ i ];
  233. const far = _frustum.vertices.far[ i ];
  234. vertices.push( near.x, near.y, near.z );
  235. vertices.push( far.x, far.y, far.z );
  236. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  237. object.add( new Line( geometry, material ) );
  238. }
  239. }
  240. return object;
  241. }
  242. remove() {
  243. for ( let i = 0; i < this.lights.length; i ++ ) {
  244. this.parent.remove( this.lights[ i ] );
  245. }
  246. }
  247. }