CSM.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. const farTopRight = _lightSpaceFrustum.vertices.far[ 0 ];
  125. const nearBotLeft = _lightSpaceFrustum.vertices.near[ 2 ];
  126. let squaredBBWidth = farTopRight.distanceTo( nearBotLeft );
  127. _bbox.makeEmpty();
  128. for ( let j = 0; j < 4; j ++ ) {
  129. _bbox.expandByPoint( _lightSpaceFrustum.vertices.near[ j ] );
  130. _bbox.expandByPoint( _lightSpaceFrustum.vertices.far[ j ] );
  131. }
  132. if ( this.fade ) {
  133. // expand the shadow extents by the fade margin if fade is enabled.
  134. const camera = this.camera;
  135. const far = Math.max( camera.far, this.maxFar );
  136. const linearDepth = frustums[ i ].vertices.far[ 0 ].z / ( far - camera.near );
  137. const margin = 0.25 * Math.pow( linearDepth, 2.0 ) * ( far - camera.near );
  138. squaredBBWidth += margin;
  139. }
  140. const texelSize = squaredBBWidth / this.shadowMapSize;
  141. _bbox.getCenter( _center );
  142. _center.z = _bbox.max.z + this.lightMargin;
  143. _center.x = Math.floor( _center.x / texelSize ) * texelSize;
  144. _center.y = Math.floor( _center.y / texelSize ) * texelSize;
  145. _center.applyMatrix4( light.shadow.camera.matrixWorld );
  146. light.shadow.camera.left = - squaredBBWidth / 2;
  147. light.shadow.camera.right = squaredBBWidth / 2;
  148. light.shadow.camera.top = squaredBBWidth / 2;
  149. light.shadow.camera.bottom = - squaredBBWidth / 2;
  150. light.position.copy( _center );
  151. light.target.position.copy( _center );
  152. light.target.position.x += this.lightDirection.x;
  153. light.target.position.y += this.lightDirection.y;
  154. light.target.position.z += this.lightDirection.z;
  155. light.shadow.camera.updateProjectionMatrix();
  156. light.shadow.camera.updateMatrixWorld();
  157. }
  158. }
  159. injectInclude() {
  160. ShaderChunk.lights_fragment_begin = Shader.lights_fragment_begin;
  161. ShaderChunk.lights_pars_begin = Shader.lights_pars_begin;
  162. }
  163. setupMaterial( material ) {
  164. material.defines = material.defines || {};
  165. material.defines.USE_CSM = 1;
  166. material.defines.CSM_CASCADES = this.cascades;
  167. if ( this.fade ) {
  168. material.defines.CSM_FADE = '';
  169. }
  170. const breaksVec2 = [];
  171. const self = this;
  172. const shaders = this.shaders;
  173. material.onBeforeCompile = function ( shader ) {
  174. const far = Math.min( self.camera.far, self.maxFar );
  175. self.getExtendedBreaks( breaksVec2 );
  176. shader.uniforms.CSM_cascades = { value: breaksVec2 };
  177. shader.uniforms.cameraNear = { value: self.camera.near };
  178. shader.uniforms.shadowFar = { value: far };
  179. shaders.set( material, shader );
  180. };
  181. shaders.set( material, null );
  182. }
  183. updateUniforms() {
  184. const far = Math.min( this.camera.far, this.maxFar );
  185. const shaders = this.shaders;
  186. shaders.forEach( function ( shader, material ) {
  187. if ( shader !== null ) {
  188. const uniforms = shader.uniforms;
  189. this.getExtendedBreaks( uniforms.CSM_cascades.value );
  190. uniforms.cameraNear.value = this.camera.near;
  191. uniforms.shadowFar.value = far;
  192. }
  193. if ( ! this.fade && 'CSM_FADE' in material.defines ) {
  194. delete material.defines.CSM_FADE;
  195. material.needsUpdate = true;
  196. } else if ( this.fade && ! ( 'CSM_FADE' in material.defines ) ) {
  197. material.defines.CSM_FADE = '';
  198. material.needsUpdate = true;
  199. }
  200. }, this );
  201. }
  202. getExtendedBreaks( target ) {
  203. while ( target.length < this.breaks.length ) {
  204. target.push( new Vector2() );
  205. }
  206. target.length = this.breaks.length;
  207. for ( let i = 0; i < this.cascades; i ++ ) {
  208. let amount = this.breaks[ i ];
  209. let prev = this.breaks[ i - 1 ] || 0;
  210. target[ i ].x = prev;
  211. target[ i ].y = amount;
  212. }
  213. }
  214. updateFrustums() {
  215. this.getBreaks();
  216. this.initCascades();
  217. this.updateUniforms();
  218. }
  219. helper( cameraMatrix ) {
  220. let geometry, vertices;
  221. const material = new LineBasicMaterial( { color: 0xffffff } );
  222. const object = new Object3D();
  223. for ( let i = 0; i < this.frustums.length; i ++ ) {
  224. this.frustums[ i ].toSpace( cameraMatrix, _frustum );
  225. geometry = new BufferGeometry();
  226. vertices = [];
  227. for ( let i = 0; i < 5; i ++ ) {
  228. const point = _frustum.vertices.near[ i === 4 ? 0 : i ];
  229. vertices.push( point.x, point.y, point.z );
  230. }
  231. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  232. object.add( new Line( geometry, material ) );
  233. geometry = new BufferGeometry();
  234. vertices = [];
  235. for ( let i = 0; i < 5; i ++ ) {
  236. const point = _frustum.vertices.far[ i === 4 ? 0 : i ];
  237. vertices.push( point.x, point.y, point.z );
  238. }
  239. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  240. object.add( new Line( geometry, material ) );
  241. for ( let i = 0; i < 4; i ++ ) {
  242. geometry = new BufferGeometry();
  243. vertices = [];
  244. const near = _frustum.vertices.near[ i ];
  245. const far = _frustum.vertices.far[ i ];
  246. vertices.push( near.x, near.y, near.z );
  247. vertices.push( far.x, far.y, far.z );
  248. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  249. object.add( new Line( geometry, material ) );
  250. }
  251. }
  252. return object;
  253. }
  254. remove() {
  255. for ( let i = 0; i < this.lights.length; i ++ ) {
  256. this.parent.remove( this.lights[ i ] );
  257. }
  258. }
  259. dispose() {
  260. const shaders = this.shaders;
  261. shaders.forEach( function ( shader, material ) {
  262. delete material.onBeforeCompile;
  263. delete material.defines.USE_CSM;
  264. delete material.defines.CSM_CASCADES;
  265. delete material.defines.CSM_FADE;
  266. delete shader.uniforms.CSM_cascades;
  267. delete shader.uniforms.cameraNear;
  268. delete shader.uniforms.shadowFar;
  269. material.needsUpdate = true;
  270. } );
  271. shaders.clear();
  272. }
  273. }