CSM.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. } from '../../../build/three.module.js';
  16. import Frustum from './Frustum.js';
  17. import FrustumBoundingBox from './FrustumBoundingBox.js';
  18. import Shader from './Shader.js';
  19. export default class CSM {
  20. constructor( data ) {
  21. data = data || {};
  22. this.camera = data.camera;
  23. this.parent = data.parent;
  24. this.cascades = data.cascades || 3;
  25. this.maxFar = data.maxFar || 100000;
  26. this.mode = data.mode || 'practical';
  27. this.shadowMapSize = data.shadowMapSize || 2048;
  28. this.shadowBias = data.shadowBias || 0.000001;
  29. this.lightDirection = data.lightDirection || new Vector3( 1, - 1, 1 ).normalize();
  30. this.lightIntensity = data.lightIntensity || 1;
  31. this.lightNear = data.lightNear || 1;
  32. this.lightFar = data.lightFar || 2000;
  33. this.lightMargin = data.lightMargin || 200;
  34. this.customSplitsCallback = data.customSplitsCallback;
  35. this.lights = [];
  36. this.materials = [];
  37. this.createLights();
  38. this.getBreaks();
  39. this.initCascades();
  40. this.injectInclude();
  41. }
  42. createLights() {
  43. for ( let i = 0; i < this.cascades; i ++ ) {
  44. const light = new DirectionalLight( 0xffffff, this.lightIntensity );
  45. light.castShadow = true;
  46. light.shadow.mapSize.width = this.shadowMapSize;
  47. light.shadow.mapSize.height = this.shadowMapSize;
  48. light.shadow.camera.near = this.lightNear;
  49. light.shadow.camera.far = this.lightFar;
  50. light.shadow.bias = this.shadowBias;
  51. this.parent.add( light );
  52. this.parent.add( light.target );
  53. this.lights.push( light );
  54. }
  55. }
  56. initCascades() {
  57. const camera = this.camera;
  58. const far = Math.min(camera.far, this.maxFar);
  59. this.mainFrustum = new Frustum( {
  60. fov: camera.fov,
  61. near: camera.near,
  62. far: far,
  63. aspect: camera.aspect
  64. } );
  65. this.mainFrustum.getViewSpaceVertices();
  66. this.frustums = this.mainFrustum.split( this.breaks );
  67. }
  68. getBreaks() {
  69. const camera = this.camera;
  70. const far = Math.min(camera.far, this.maxFar);
  71. this.breaks = [];
  72. switch ( this.mode ) {
  73. case 'uniform':
  74. this.breaks = uniformSplit( this.cascades, camera.near, far );
  75. break;
  76. case 'logarithmic':
  77. this.breaks = logarithmicSplit( this.cascades, camera.near, far );
  78. break;
  79. case 'practical':
  80. this.breaks = practicalSplit( this.cascades, camera.near, far, 0.5 );
  81. break;
  82. case 'custom':
  83. if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' );
  84. this.breaks = this.customSplitsCallback( this.cascades, camera.near, far );
  85. break;
  86. }
  87. function uniformSplit( amount, near, far ) {
  88. const r = [];
  89. for ( let i = 1; i < amount; i ++ ) {
  90. r.push( ( near + ( far - near ) * i / amount ) / far );
  91. }
  92. r.push( 1 );
  93. return r;
  94. }
  95. function logarithmicSplit( amount, near, far ) {
  96. const r = [];
  97. for ( let i = 1; i < amount; i ++ ) {
  98. r.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
  99. }
  100. r.push( 1 );
  101. return r;
  102. }
  103. function practicalSplit( amount, near, far, lambda ) {
  104. const log = logarithmicSplit( amount, near, far );
  105. const uni = uniformSplit( amount, near, far );
  106. const r = [];
  107. for ( let i = 1; i < amount; i ++ ) {
  108. r.push( MathUtils.lerp( uni[ i - 1 ], log[ i - 1 ], lambda ) );
  109. }
  110. r.push( 1 );
  111. return r;
  112. }
  113. }
  114. update( cameraMatrix ) {
  115. for ( let i = 0; i < this.frustums.length; i ++ ) {
  116. const worldSpaceFrustum = this.frustums[ i ].toSpace( cameraMatrix );
  117. const light = this.lights[ i ];
  118. const lightSpaceFrustum = worldSpaceFrustum.toSpace( light.shadow.camera.matrixWorldInverse );
  119. light.shadow.camera.updateMatrixWorld( true );
  120. const bbox = new FrustumBoundingBox().fromFrustum( lightSpaceFrustum );
  121. bbox.getSize();
  122. bbox.getCenter( this.lightMargin );
  123. const squaredBBWidth = Math.max( bbox.size.x, bbox.size.y );
  124. let center = new Vector3( bbox.center.x, bbox.center.y, bbox.center.z );
  125. center.applyMatrix4( light.shadow.camera.matrixWorld );
  126. light.shadow.camera.left = - squaredBBWidth / 2;
  127. light.shadow.camera.right = squaredBBWidth / 2;
  128. light.shadow.camera.top = squaredBBWidth / 2;
  129. light.shadow.camera.bottom = - squaredBBWidth / 2;
  130. light.position.copy( center );
  131. light.target.position.copy( center );
  132. light.target.position.x += this.lightDirection.x;
  133. light.target.position.y += this.lightDirection.y;
  134. light.target.position.z += this.lightDirection.z;
  135. light.shadow.camera.updateProjectionMatrix();
  136. light.shadow.camera.updateMatrixWorld();
  137. }
  138. }
  139. injectInclude() {
  140. ShaderChunk.lights_fragment_begin = Shader.lights_fragment_begin;
  141. ShaderChunk.lights_pars_begin = Shader.lights_pars_begin;
  142. }
  143. setupMaterial( material ) {
  144. material.defines = material.defines || {};
  145. material.defines.USE_CSM = 1;
  146. material.defines.CSM_CASCADES = this.cascades;
  147. const breaksVec2 = [];
  148. for ( let i = 0; i < this.cascades; i ++ ) {
  149. let amount = this.breaks[ i ];
  150. let prev = this.breaks[ i - 1 ] || 0;
  151. breaksVec2.push( new Vector2( prev, amount ) );
  152. }
  153. const self = this;
  154. const far = Math.min(this.camera.far, this.maxFar);
  155. material.onBeforeCompile = function ( shader ) {
  156. shader.uniforms.CSM_cascades = { value: breaksVec2 };
  157. shader.uniforms.cameraNear = { value: self.camera.near };
  158. shader.uniforms.shadowFar = { value: far };
  159. self.materials.push( shader );
  160. };
  161. }
  162. updateUniforms() {
  163. const far = Math.min(this.camera.far, this.maxFar);
  164. console.log('HERE', far);
  165. for ( let i = 0; i < this.materials.length; i ++ ) {
  166. this.materials[ i ].uniforms.CSM_cascades.value = this.getExtendedBreaks();
  167. this.materials[ i ].uniforms.cameraNear.value = this.camera.near;
  168. this.materials[ i ].uniforms.shadowFar.value = far;
  169. }
  170. }
  171. getExtendedBreaks() {
  172. let breaksVec2 = [];
  173. for ( let i = 0; i < this.cascades; i ++ ) {
  174. let amount = this.breaks[ i ];
  175. let prev = this.breaks[ i - 1 ] || 0;
  176. breaksVec2.push( new Vector2( prev, amount ) );
  177. }
  178. return breaksVec2;
  179. }
  180. updateFrustums() {
  181. this.getBreaks();
  182. this.initCascades();
  183. this.updateUniforms();
  184. }
  185. helper( cameraMatrix ) {
  186. let frustum;
  187. let geometry, vertices;
  188. const material = new LineBasicMaterial( { color: 0xffffff } );
  189. const object = new Object3D();
  190. for ( let i = 0; i < this.frustums.length; i ++ ) {
  191. frustum = this.frustums[ i ].toSpace( cameraMatrix );
  192. geometry = new BufferGeometry();
  193. vertices = [];
  194. for ( let i = 0; i < 5; i ++ ) {
  195. const point = frustum.vertices.near[ i === 4 ? 0 : i ];
  196. vertices.push( point.x, point.y, point.z );
  197. }
  198. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  199. object.add( new Line( geometry, material ) );
  200. geometry = new BufferGeometry();
  201. vertices = [];
  202. for ( let i = 0; i < 5; i ++ ) {
  203. const point = frustum.vertices.far[ i === 4 ? 0 : i ];
  204. vertices.push( point.x, point.y, point.z );
  205. }
  206. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  207. object.add( new Line( geometry, material ) );
  208. for ( let i = 0; i < 4; i ++ ) {
  209. geometry = new BufferGeometry();
  210. vertices = [];
  211. const near = frustum.vertices.near[ i ];
  212. const far = frustum.vertices.far[ i ];
  213. vertices.push( near.x, near.y, near.z );
  214. vertices.push( far.x, far.y, far.z );
  215. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  216. object.add( new Line( geometry, material ) );
  217. }
  218. }
  219. return object;
  220. }
  221. remove() {
  222. for ( let i = 0; i < this.lights.length; i ++ ) {
  223. this.parent.remove( this.lights[ i ] );
  224. }
  225. }
  226. }