main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

597
node_modules/three/examples/jsm/csm/CSM.js generated vendored Normal file
View File

@@ -0,0 +1,597 @@
import {
Vector2,
Vector3,
DirectionalLight,
MathUtils,
ShaderChunk,
Matrix4,
Box3
} from 'three';
import { CSMFrustum } from './CSMFrustum.js';
import { CSMShader } from './CSMShader.js';
const _cameraToLightMatrix = new Matrix4();
const _lightSpaceFrustum = new CSMFrustum( { webGL: true } );
const _center = new Vector3();
const _bbox = new Box3();
const _uniformArray = [];
const _logArray = [];
const _lightOrientationMatrix = new Matrix4();
const _lightOrientationMatrixInverse = new Matrix4();
const _up = new Vector3( 0, 1, 0 );
/**
* An implementation of Cascade Shadow Maps (CSM).
*
* This module can only be used with {@link WebGLRenderer}. When using {@link WebGPURenderer},
* use {@link CSMShadowNode} instead.
*
* @three_import import { CSM } from 'three/addons/csm/CSM.js';
*/
export class CSM {
/**
* Constructs a new CSM instance.
*
* @param {CSM~Data} data - The CSM data.
*/
constructor( data ) {
/**
* The scene's camera.
*
* @type {Camera}
*/
this.camera = data.camera;
/**
* The parent object, usually the scene.
*
* @type {Object3D}
*/
this.parent = data.parent;
/**
* The number of cascades.
*
* @type {number}
* @default 3
*/
this.cascades = data.cascades || 3;
/**
* The maximum far value.
*
* @type {number}
* @default 100000
*/
this.maxFar = data.maxFar || 100000;
/**
* The frustum split mode.
*
* @type {('practical'|'uniform'|'logarithmic'|'custom')}
* @default 'practical'
*/
this.mode = data.mode || 'practical';
/**
* The shadow map size.
*
* @type {number}
* @default 2048
*/
this.shadowMapSize = data.shadowMapSize || 2048;
/**
* The shadow bias.
*
* @type {number}
* @default 0.000001
*/
this.shadowBias = data.shadowBias || 0.000001;
/**
* The light direction.
*
* @type {Vector3}
*/
this.lightDirection = data.lightDirection || new Vector3( 1, - 1, 1 ).normalize();
/**
* The light intensity.
*
* @type {number}
* @default 3
*/
this.lightIntensity = data.lightIntensity || 3;
/**
* The light near value.
*
* @type {number}
* @default 1
*/
this.lightNear = data.lightNear || 1;
/**
* The light far value.
*
* @type {number}
* @default 2000
*/
this.lightFar = data.lightFar || 2000;
/**
* The light margin.
*
* @type {number}
* @default 200
*/
this.lightMargin = data.lightMargin || 200;
/**
* Custom split callback when using `mode='custom'`.
*
* @type {Function}
*/
this.customSplitsCallback = data.customSplitsCallback;
/**
* Whether to fade between cascades or not.
*
* @type {boolean}
* @default false
*/
this.fade = false;
/**
* The main frustum.
*
* @type {CSMFrustum}
*/
this.mainFrustum = new CSMFrustum( { webGL: true } );
/**
* An array of frustums representing the cascades.
*
* @type {Array<CSMFrustum>}
*/
this.frustums = [];
/**
* An array of numbers in the range `[0,1]` the defines how the
* mainCSM frustum should be split up.
*
* @type {Array<number>}
*/
this.breaks = [];
/**
* An array of directional lights which cast the shadows for
* the different cascades. There is one directional light for each
* cascade.
*
* @type {Array<DirectionalLight>}
*/
this.lights = [];
/**
* A Map holding enhanced material shaders.
*
* @type {Map<Material,Object>}
*/
this.shaders = new Map();
this._createLights();
this.updateFrustums();
this._injectInclude();
}
/**
* Creates the directional lights of this CSM instance.
*
* @private
*/
_createLights() {
for ( let i = 0; i < this.cascades; i ++ ) {
const light = new DirectionalLight( 0xffffff, this.lightIntensity );
light.castShadow = true;
light.shadow.mapSize.width = this.shadowMapSize;
light.shadow.mapSize.height = this.shadowMapSize;
light.shadow.camera.near = this.lightNear;
light.shadow.camera.far = this.lightFar;
light.shadow.bias = this.shadowBias;
this.parent.add( light );
this.parent.add( light.target );
this.lights.push( light );
}
}
/**
* Inits the cascades according to the scene's camera and breaks configuration.
*
* @private
*/
_initCascades() {
const camera = this.camera;
camera.updateProjectionMatrix();
this.mainFrustum.setFromProjectionMatrix( camera.projectionMatrix, this.maxFar );
this.mainFrustum.split( this.breaks, this.frustums );
}
/**
* Updates the shadow bounds of this CSM instance.
*
* @private
*/
_updateShadowBounds() {
const frustums = this.frustums;
for ( let i = 0; i < frustums.length; i ++ ) {
const light = this.lights[ i ];
const shadowCam = light.shadow.camera;
const frustum = this.frustums[ i ];
// Get the two points that represent that furthest points on the frustum assuming
// that's either the diagonal across the far plane or the diagonal across the whole
// frustum itself.
const nearVerts = frustum.vertices.near;
const farVerts = frustum.vertices.far;
const point1 = farVerts[ 0 ];
let point2;
if ( point1.distanceTo( farVerts[ 2 ] ) > point1.distanceTo( nearVerts[ 2 ] ) ) {
point2 = farVerts[ 2 ];
} else {
point2 = nearVerts[ 2 ];
}
let squaredBBWidth = point1.distanceTo( point2 );
if ( this.fade ) {
// expand the shadow extents by the fade margin if fade is enabled.
const camera = this.camera;
const far = Math.max( camera.far, this.maxFar );
const linearDepth = frustum.vertices.far[ 0 ].z / ( far - camera.near );
const margin = 0.25 * Math.pow( linearDepth, 2.0 ) * ( far - camera.near );
squaredBBWidth += margin;
}
shadowCam.left = - squaredBBWidth / 2;
shadowCam.right = squaredBBWidth / 2;
shadowCam.top = squaredBBWidth / 2;
shadowCam.bottom = - squaredBBWidth / 2;
shadowCam.updateProjectionMatrix();
}
}
/**
* Computes the breaks of this CSM instance based on the scene's camera, number of cascades
* and the selected split mode.
*
* @private
*/
_getBreaks() {
const camera = this.camera;
const far = Math.min( camera.far, this.maxFar );
this.breaks.length = 0;
switch ( this.mode ) {
case 'uniform':
uniformSplit( this.cascades, camera.near, far, this.breaks );
break;
case 'logarithmic':
logarithmicSplit( this.cascades, camera.near, far, this.breaks );
break;
case 'practical':
practicalSplit( this.cascades, camera.near, far, 0.5, this.breaks );
break;
case 'custom':
if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' );
this.customSplitsCallback( this.cascades, camera.near, far, this.breaks );
break;
}
function uniformSplit( amount, near, far, target ) {
for ( let i = 1; i < amount; i ++ ) {
target.push( ( near + ( far - near ) * i / amount ) / far );
}
target.push( 1 );
}
function logarithmicSplit( amount, near, far, target ) {
for ( let i = 1; i < amount; i ++ ) {
target.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
}
target.push( 1 );
}
function practicalSplit( amount, near, far, lambda, target ) {
_uniformArray.length = 0;
_logArray.length = 0;
logarithmicSplit( amount, near, far, _logArray );
uniformSplit( amount, near, far, _uniformArray );
for ( let i = 1; i < amount; i ++ ) {
target.push( MathUtils.lerp( _uniformArray[ i - 1 ], _logArray[ i - 1 ], lambda ) );
}
target.push( 1 );
}
}
/**
* Updates the CSM. This method must be called in your animation loop before
* calling `renderer.render()`.
*/
update() {
const camera = this.camera;
const frustums = this.frustums;
// for each frustum we need to find its min-max box aligned with the light orientation
// the position in _lightOrientationMatrix does not matter, as we transform there and back
_lightOrientationMatrix.lookAt( new Vector3(), this.lightDirection, _up );
_lightOrientationMatrixInverse.copy( _lightOrientationMatrix ).invert();
for ( let i = 0; i < frustums.length; i ++ ) {
const light = this.lights[ i ];
const shadowCam = light.shadow.camera;
const texelWidth = ( shadowCam.right - shadowCam.left ) / this.shadowMapSize;
const texelHeight = ( shadowCam.top - shadowCam.bottom ) / this.shadowMapSize;
_cameraToLightMatrix.multiplyMatrices( _lightOrientationMatrixInverse, camera.matrixWorld );
frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum );
const nearVerts = _lightSpaceFrustum.vertices.near;
const farVerts = _lightSpaceFrustum.vertices.far;
_bbox.makeEmpty();
for ( let j = 0; j < 4; j ++ ) {
_bbox.expandByPoint( nearVerts[ j ] );
_bbox.expandByPoint( farVerts[ j ] );
}
_bbox.getCenter( _center );
_center.z = _bbox.max.z + this.lightMargin;
_center.x = Math.floor( _center.x / texelWidth ) * texelWidth;
_center.y = Math.floor( _center.y / texelHeight ) * texelHeight;
_center.applyMatrix4( _lightOrientationMatrix );
light.position.copy( _center );
light.target.position.copy( _center );
light.target.position.x += this.lightDirection.x;
light.target.position.y += this.lightDirection.y;
light.target.position.z += this.lightDirection.z;
}
}
/**
* Injects the CSM shader enhancements into the built-in materials.
*
* @private
*/
_injectInclude() {
ShaderChunk.lights_fragment_begin = CSMShader.lights_fragment_begin;
ShaderChunk.lights_pars_begin = CSMShader.lights_pars_begin;
}
/**
* Applications must call this method for all materials that should be affected by CSM.
*
* @param {Material} material - The material to setup for CSM support.
*/
setupMaterial( material ) {
material.defines = material.defines || {};
material.defines.USE_CSM = 1;
material.defines.CSM_CASCADES = this.cascades;
if ( this.fade ) {
material.defines.CSM_FADE = '';
}
const breaksVec2 = [];
const scope = this;
const shaders = this.shaders;
material.onBeforeCompile = function ( shader ) {
const far = Math.min( scope.camera.far, scope.maxFar );
scope._getExtendedBreaks( breaksVec2 );
shader.uniforms.CSM_cascades = { value: breaksVec2 };
shader.uniforms.cameraNear = { value: scope.camera.near };
shader.uniforms.shadowFar = { value: far };
shaders.set( material, shader );
};
shaders.set( material, null );
}
/**
* Updates the CSM uniforms.
*
* @private
*/
_updateUniforms() {
const far = Math.min( this.camera.far, this.maxFar );
const shaders = this.shaders;
shaders.forEach( function ( shader, material ) {
if ( shader !== null ) {
const uniforms = shader.uniforms;
this._getExtendedBreaks( uniforms.CSM_cascades.value );
uniforms.cameraNear.value = this.camera.near;
uniforms.shadowFar.value = far;
}
if ( ! this.fade && 'CSM_FADE' in material.defines ) {
delete material.defines.CSM_FADE;
material.needsUpdate = true;
} else if ( this.fade && ! ( 'CSM_FADE' in material.defines ) ) {
material.defines.CSM_FADE = '';
material.needsUpdate = true;
}
}, this );
}
/**
* Computes the extended breaks for the CSM uniforms.
*
* @private
* @param {Array<Vector2>} target - The target array that holds the extended breaks.
*/
_getExtendedBreaks( target ) {
while ( target.length < this.breaks.length ) {
target.push( new Vector2() );
}
target.length = this.breaks.length;
for ( let i = 0; i < this.cascades; i ++ ) {
const amount = this.breaks[ i ];
const prev = this.breaks[ i - 1 ] || 0;
target[ i ].x = prev;
target[ i ].y = amount;
}
}
/**
* Applications must call this method every time they change camera or CSM settings.
*/
updateFrustums() {
this._getBreaks();
this._initCascades();
this._updateShadowBounds();
this._updateUniforms();
}
/**
* Applications must call this method when they remove the CSM usage from their scene.
*/
remove() {
for ( let i = 0; i < this.lights.length; i ++ ) {
this.parent.remove( this.lights[ i ].target );
this.parent.remove( this.lights[ i ] );
}
}
/**
* Frees the GPU-related resources allocated by this instance. Call this
* method whenever this instance is no longer used in your app.
*/
dispose() {
const shaders = this.shaders;
shaders.forEach( function ( shader, material ) {
delete material.onBeforeCompile;
delete material.defines.USE_CSM;
delete material.defines.CSM_CASCADES;
delete material.defines.CSM_FADE;
if ( shader !== null ) {
delete shader.uniforms.CSM_cascades;
delete shader.uniforms.cameraNear;
delete shader.uniforms.shadowFar;
}
material.needsUpdate = true;
} );
shaders.clear();
}
}
/**
* Constructor data of `CSM`.
*
* @typedef {Object} CSM~Data
* @property {Camera} camera - The scene's camera.
* @property {Object3D} parent - The parent object, usually the scene.
* @property {number} [cascades=3] - The number of cascades.
* @property {number} [maxFar=100000] - The maximum far value.
* @property {('practical'|'uniform'|'logarithmic'|'custom')} [mode='practical'] - The frustum split mode.
* @property {Function} [customSplitsCallback] - Custom split callback when using `mode='custom'`.
* @property {number} [shadowMapSize=2048] - The shadow map size.
* @property {number} [shadowBias=0.000001] - The shadow bias.
* @property {Vector3} [lightDirection] - The light direction.
* @property {number} [lightIntensity=3] - The light intensity.
* @property {number} [lightNear=1] - The light near value.
* @property {number} [lightNear=2000] - The light far value.
* @property {number} [lightMargin=200] - The light margin.
**/

209
node_modules/three/examples/jsm/csm/CSMFrustum.js generated vendored Normal file
View File

@@ -0,0 +1,209 @@
import { Vector3, Matrix4 } from 'three';
const inverseProjectionMatrix = new Matrix4();
/**
* Represents the frustum of a CSM instance.
*
* @three_import import { CSMFrustum } from 'three/addons/csm/CSMFrustum.js';
*/
class CSMFrustum {
/**
* Constructs a new CSM frustum.
*
* @param {CSMFrustum~Data} [data] - The CSM data.
*/
constructor( data ) {
data = data || {};
/**
* The zNear value. This value depends on whether the CSM
* is used with WebGL or WebGPU. Both API use different
* conventions for their projection matrices.
*
* @type {number}
*/
this.zNear = data.webGL === true ? - 1 : 0;
/**
* An object representing the vertices of the near and
* far plane in view space.
*
* @type {Object}
*/
this.vertices = {
near: [
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3()
],
far: [
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3()
]
};
if ( data.projectionMatrix !== undefined ) {
this.setFromProjectionMatrix( data.projectionMatrix, data.maxFar || 10000 );
}
}
/**
* Setups this CSM frustum from the given projection matrix and max far value.
*
* @param {Matrix4} projectionMatrix - The projection matrix, usually of the scene's camera.
* @param {number} maxFar - The maximum far value.
* @returns {Object} An object representing the vertices of the near and far plane in view space.
*/
setFromProjectionMatrix( projectionMatrix, maxFar ) {
const zNear = this.zNear;
const isOrthographic = projectionMatrix.elements[ 2 * 4 + 3 ] === 0;
inverseProjectionMatrix.copy( projectionMatrix ).invert();
// 3 --- 0 vertices.near/far order
// | |
// 2 --- 1
// clip space spans from [-1, 1]
this.vertices.near[ 0 ].set( 1, 1, zNear );
this.vertices.near[ 1 ].set( 1, - 1, zNear );
this.vertices.near[ 2 ].set( - 1, - 1, zNear );
this.vertices.near[ 3 ].set( - 1, 1, zNear );
this.vertices.near.forEach( function ( v ) {
v.applyMatrix4( inverseProjectionMatrix );
} );
this.vertices.far[ 0 ].set( 1, 1, 1 );
this.vertices.far[ 1 ].set( 1, - 1, 1 );
this.vertices.far[ 2 ].set( - 1, - 1, 1 );
this.vertices.far[ 3 ].set( - 1, 1, 1 );
this.vertices.far.forEach( function ( v ) {
v.applyMatrix4( inverseProjectionMatrix );
const absZ = Math.abs( v.z );
if ( isOrthographic ) {
v.z *= Math.min( maxFar / absZ, 1.0 );
} else {
v.multiplyScalar( Math.min( maxFar / absZ, 1.0 ) );
}
} );
return this.vertices;
}
/**
* Splits the CSM frustum by the given array. The new CSM frustum are pushed into the given
* target array.
*
* @param {Array<number>} breaks - An array of numbers in the range `[0,1]` the defines how the
* CSM frustum should be split up.
* @param {Array<CSMFrustum>} target - The target array that holds the new CSM frustums.
*/
split( breaks, target ) {
while ( breaks.length > target.length ) {
target.push( new CSMFrustum() );
}
target.length = breaks.length;
for ( let i = 0; i < breaks.length; i ++ ) {
const cascade = target[ i ];
if ( i === 0 ) {
for ( let j = 0; j < 4; j ++ ) {
cascade.vertices.near[ j ].copy( this.vertices.near[ j ] );
}
} else {
for ( let j = 0; j < 4; j ++ ) {
cascade.vertices.near[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] );
}
}
if ( i === breaks.length - 1 ) {
for ( let j = 0; j < 4; j ++ ) {
cascade.vertices.far[ j ].copy( this.vertices.far[ j ] );
}
} else {
for ( let j = 0; j < 4; j ++ ) {
cascade.vertices.far[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] );
}
}
}
}
/**
* Transforms the given target CSM frustum into the different coordinate system defined by the
* given camera matrix.
*
* @param {Matrix4} cameraMatrix - The matrix that defines the new coordinate system.
* @param {CSMFrustum} target - The CSM to convert.
*/
toSpace( cameraMatrix, target ) {
for ( let i = 0; i < 4; i ++ ) {
target.vertices.near[ i ]
.copy( this.vertices.near[ i ] )
.applyMatrix4( cameraMatrix );
target.vertices.far[ i ]
.copy( this.vertices.far[ i ] )
.applyMatrix4( cameraMatrix );
}
}
}
/**
* Constructor data of `CSMFrustum`.
*
* @typedef {Object} CSMFrustum~Data
* @property {boolean} [webGL] - Whether this CSM frustum is used with WebGL or WebGPU.
* @property {Matrix4} [projectionMatrix] - A projection matrix usually of the scene's camera.
* @property {number} [maxFar] - The maximum far value.
**/
export { CSMFrustum };

243
node_modules/three/examples/jsm/csm/CSMHelper.js generated vendored Normal file
View File

@@ -0,0 +1,243 @@
import {
Group,
Mesh,
LineSegments,
BufferGeometry,
LineBasicMaterial,
Box3Helper,
Box3,
PlaneGeometry,
MeshBasicMaterial,
BufferAttribute,
DoubleSide
} from 'three';
/**
* A helper for visualizing the cascades of a CSM instance.
*
* @augments Group
* @three_import import { CSMHelper } from 'three/addons/csm/CSMHelper.js';
*/
class CSMHelper extends Group {
/**
* Constructs a new CSM helper.
*
* @param {CSM|CSMShadowNode} csm - The CSM instance to visualize.
*/
constructor( csm ) {
super();
/**
* The CSM instance to visualize.
*
* @type {CSM|CSMShadowNode}
*/
this.csm = csm;
/**
* Whether to display the CSM frustum or not.
*
* @type {boolean}
* @default true
*/
this.displayFrustum = true;
/**
* Whether to display the cascade planes or not.
*
* @type {boolean}
* @default true
*/
this.displayPlanes = true;
/**
* Whether to display the shadow bounds or not.
*
* @type {boolean}
* @default true
*/
this.displayShadowBounds = true;
const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
const positions = new Float32Array( 24 );
const frustumGeometry = new BufferGeometry();
frustumGeometry.setIndex( new BufferAttribute( indices, 1 ) );
frustumGeometry.setAttribute( 'position', new BufferAttribute( positions, 3, false ) );
const frustumLines = new LineSegments( frustumGeometry, new LineBasicMaterial() );
this.add( frustumLines );
this.frustumLines = frustumLines;
this.cascadeLines = [];
this.cascadePlanes = [];
this.shadowLines = [];
}
/**
* This method must be called if one of the `display*` properties is changed at runtime.
*/
updateVisibility() {
const displayFrustum = this.displayFrustum;
const displayPlanes = this.displayPlanes;
const displayShadowBounds = this.displayShadowBounds;
const frustumLines = this.frustumLines;
const cascadeLines = this.cascadeLines;
const cascadePlanes = this.cascadePlanes;
const shadowLines = this.shadowLines;
for ( let i = 0, l = cascadeLines.length; i < l; i ++ ) {
const cascadeLine = cascadeLines[ i ];
const cascadePlane = cascadePlanes[ i ];
const shadowLineGroup = shadowLines[ i ];
cascadeLine.visible = displayFrustum;
cascadePlane.visible = displayFrustum && displayPlanes;
shadowLineGroup.visible = displayShadowBounds;
}
frustumLines.visible = displayFrustum;
}
/**
* Updates the helper. This method should be called in the app's animation loop.
*/
update() {
const csm = this.csm;
const camera = csm.camera;
const cascades = csm.cascades;
const mainFrustum = csm.mainFrustum;
const frustums = csm.frustums;
const lights = csm.lights;
const frustumLines = this.frustumLines;
const frustumLinePositions = frustumLines.geometry.getAttribute( 'position' );
const cascadeLines = this.cascadeLines;
const cascadePlanes = this.cascadePlanes;
const shadowLines = this.shadowLines;
if ( camera === null ) return;
this.position.copy( camera.position );
this.quaternion.copy( camera.quaternion );
this.scale.copy( camera.scale );
this.updateMatrixWorld( true );
while ( cascadeLines.length > cascades ) {
this.remove( cascadeLines.pop() );
this.remove( cascadePlanes.pop() );
this.remove( shadowLines.pop() );
}
while ( cascadeLines.length < cascades ) {
const cascadeLine = new Box3Helper( new Box3(), 0xffffff );
const planeMat = new MeshBasicMaterial( { transparent: true, opacity: 0.1, depthWrite: false, side: DoubleSide } );
const cascadePlane = new Mesh( new PlaneGeometry(), planeMat );
const shadowLineGroup = new Group();
const shadowLine = new Box3Helper( new Box3(), 0xffff00 );
shadowLineGroup.add( shadowLine );
this.add( cascadeLine );
this.add( cascadePlane );
this.add( shadowLineGroup );
cascadeLines.push( cascadeLine );
cascadePlanes.push( cascadePlane );
shadowLines.push( shadowLineGroup );
}
for ( let i = 0; i < cascades; i ++ ) {
const frustum = frustums[ i ];
const light = lights[ i ];
const shadowCam = light.shadow.camera;
const farVerts = frustum.vertices.far;
const cascadeLine = cascadeLines[ i ];
const cascadePlane = cascadePlanes[ i ];
const shadowLineGroup = shadowLines[ i ];
const shadowLine = shadowLineGroup.children[ 0 ];
cascadeLine.box.min.copy( farVerts[ 2 ] );
cascadeLine.box.max.copy( farVerts[ 0 ] );
cascadeLine.box.max.z += 1e-4;
cascadePlane.position.addVectors( farVerts[ 0 ], farVerts[ 2 ] );
cascadePlane.position.multiplyScalar( 0.5 );
cascadePlane.scale.subVectors( farVerts[ 0 ], farVerts[ 2 ] );
cascadePlane.scale.z = 1e-4;
this.remove( shadowLineGroup );
shadowLineGroup.position.copy( shadowCam.position );
shadowLineGroup.quaternion.copy( shadowCam.quaternion );
shadowLineGroup.scale.copy( shadowCam.scale );
shadowLineGroup.updateMatrixWorld( true );
this.attach( shadowLineGroup );
shadowLine.box.min.set( shadowCam.bottom, shadowCam.left, - shadowCam.far );
shadowLine.box.max.set( shadowCam.top, shadowCam.right, - shadowCam.near );
}
const nearVerts = mainFrustum.vertices.near;
const farVerts = mainFrustum.vertices.far;
frustumLinePositions.setXYZ( 0, farVerts[ 0 ].x, farVerts[ 0 ].y, farVerts[ 0 ].z );
frustumLinePositions.setXYZ( 1, farVerts[ 3 ].x, farVerts[ 3 ].y, farVerts[ 3 ].z );
frustumLinePositions.setXYZ( 2, farVerts[ 2 ].x, farVerts[ 2 ].y, farVerts[ 2 ].z );
frustumLinePositions.setXYZ( 3, farVerts[ 1 ].x, farVerts[ 1 ].y, farVerts[ 1 ].z );
frustumLinePositions.setXYZ( 4, nearVerts[ 0 ].x, nearVerts[ 0 ].y, nearVerts[ 0 ].z );
frustumLinePositions.setXYZ( 5, nearVerts[ 3 ].x, nearVerts[ 3 ].y, nearVerts[ 3 ].z );
frustumLinePositions.setXYZ( 6, nearVerts[ 2 ].x, nearVerts[ 2 ].y, nearVerts[ 2 ].z );
frustumLinePositions.setXYZ( 7, nearVerts[ 1 ].x, nearVerts[ 1 ].y, nearVerts[ 1 ].z );
frustumLinePositions.needsUpdate = true;
}
/**
* Frees the GPU-related resources allocated by this instance. Call this
* method whenever this instance is no longer used in your app.
*/
dispose() {
const frustumLines = this.frustumLines;
const cascadeLines = this.cascadeLines;
const cascadePlanes = this.cascadePlanes;
const shadowLines = this.shadowLines;
frustumLines.geometry.dispose();
frustumLines.material.dispose();
const cascades = this.csm.cascades;
for ( let i = 0; i < cascades; i ++ ) {
const cascadeLine = cascadeLines[ i ];
const cascadePlane = cascadePlanes[ i ];
const shadowLineGroup = shadowLines[ i ];
const shadowLine = shadowLineGroup.children[ 0 ];
cascadeLine.dispose(); // Box3Helper
cascadePlane.geometry.dispose();
cascadePlane.material.dispose();
shadowLine.dispose(); // Box3Helper
}
}
}
export { CSMHelper };

307
node_modules/three/examples/jsm/csm/CSMShader.js generated vendored Normal file
View File

@@ -0,0 +1,307 @@
import { ShaderChunk } from 'three';
/**
* @module CSMShader
* @three_import import { CSMShader } from 'three/addons/csm/CSMShader.js';
*/
/**
* The object that holds the GLSL enhancements to enable CSM. This
* code is injected into the built-in material shaders by {@link CSM}.
*
* @type {Object}
*/
const CSMShader = {
lights_fragment_begin: /* glsl */`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
float dotNVi = saturate( dot( normal, geometryViewDir ) );
if ( material.iridescenceThickness == 0.0 ) {
material.iridescence = 0.0;
} else {
material.iridescence = saturate( material.iridescence );
}
if ( material.iridescence > 0.0 ) {
material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
// Iridescence F0 approximation
material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
PointLight pointLight;
#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
PointLightShadow pointLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
pointLight = pointLights[ i ];
getPointLightInfo( pointLight, geometryPosition, directLight );
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
pointLightShadow = pointLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
SpotLight spotLight;
vec4 spotColor;
vec3 spotLightCoord;
bool inSpotLightMap;
#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
SpotLightShadow spotLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
spotLight = spotLights[ i ];
getSpotLightInfo( spotLight, geometryPosition, directLight );
// spot lights are ordered [shadows with maps, shadows without maps, maps without shadows, none]
#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
#else
#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
#endif
#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
#endif
#undef SPOT_LIGHT_MAP_INDEX
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
spotLightShadow = spotLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES )
DirectionalLight directionalLight;
float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear);
#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
DirectionalLightShadow directionalLightShadow;
#endif
#if defined( USE_SHADOWMAP ) && defined( CSM_FADE )
vec2 cascade;
float cascadeCenter;
float closestEdge;
float margin;
float csmx;
float csmy;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
directionalLight = directionalLights[ i ];
getDirectionalLightInfo( directionalLight, directLight );
#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
// NOTE: Depth gets larger away from the camera.
// cascade.x is closer, cascade.y is further
cascade = CSM_cascades[ i ];
cascadeCenter = ( cascade.x + cascade.y ) / 2.0;
closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y;
margin = 0.25 * pow( closestEdge, 2.0 );
csmx = cascade.x - margin / 2.0;
csmy = cascade.y + margin / 2.0;
if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) {
float dist = min( linearDepth - csmx, csmy - linearDepth );
float ratio = clamp( dist / margin, 0.0, 1.0 );
vec3 prevColor = directLight.color;
directionalLightShadow = directionalLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter;
directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 );
ReflectedLight prevLight = reflectedLight;
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter;
float blendRatio = shouldBlend ? ratio : 1.0;
reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio );
reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio );
reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio );
reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio );
}
#endif
}
#pragma unroll_loop_end
#elif defined (USE_SHADOWMAP)
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
directionalLight = directionalLights[ i ];
getDirectionalLightInfo( directionalLight, directLight );
#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
directionalLightShadow = directionalLightShadows[ i ];
if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
}
#pragma unroll_loop_end
#elif ( NUM_DIR_LIGHT_SHADOWS > 0 )
// note: no loop here - all CSM lights are in fact one light only
getDirectionalLightInfo( directionalLights[0], directLight );
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS)
// compute the lights not casting shadows (if any)
#pragma unroll_loop_start
for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) {
directionalLight = directionalLights[ i ];
getDirectionalLightInfo( directionalLight, directLight );
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES )
DirectionalLight directionalLight;
#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
DirectionalLightShadow directionalLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
directionalLight = directionalLights[ i ];
getDirectionalLightInfo( directionalLight, directLight );
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
directionalLightShadow = directionalLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
RectAreaLight rectAreaLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
rectAreaLight = rectAreaLights[ i ];
RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
vec3 iblIrradiance = vec3( 0.0 );
vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
#if defined( USE_LIGHT_PROBES )
irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
#endif
#if ( NUM_HEMI_LIGHTS > 0 )
#pragma unroll_loop_start
for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
}
#pragma unroll_loop_end
#endif
#endif
#if defined( RE_IndirectSpecular )
vec3 radiance = vec3( 0.0 );
vec3 clearcoatRadiance = vec3( 0.0 );
#endif
`,
lights_pars_begin: /* glsl */`
#if defined( USE_CSM ) && defined( CSM_CASCADES )
uniform vec2 CSM_cascades[CSM_CASCADES];
uniform float cameraNear;
uniform float shadowFar;
#endif
` + ShaderChunk.lights_pars_begin
};
export { CSMShader };

599
node_modules/three/examples/jsm/csm/CSMShadowNode.js generated vendored Normal file
View File

@@ -0,0 +1,599 @@
import {
Vector2,
Vector3,
MathUtils,
Matrix4,
Box3,
Object3D,
WebGLCoordinateSystem,
ShadowBaseNode
} from 'three/webgpu';
import { CSMFrustum } from './CSMFrustum.js';
import { viewZToOrthographicDepth, reference, uniform, float, vec4, vec2, If, Fn, min, renderGroup, positionView, shadow } from 'three/tsl';
const _cameraToLightMatrix = new Matrix4();
const _lightSpaceFrustum = new CSMFrustum();
const _center = new Vector3();
const _bbox = new Box3();
const _uniformArray = [];
const _logArray = [];
const _lightDirection = new Vector3();
const _lightOrientationMatrix = new Matrix4();
const _lightOrientationMatrixInverse = new Matrix4();
const _up = new Vector3( 0, 1, 0 );
class LwLight extends Object3D {
constructor() {
super();
this.target = new Object3D();
}
}
/**
* An implementation of Cascade Shadow Maps (CSM).
*
* This module can only be used with {@link WebGPURenderer}. When using {@link WebGLRenderer},
* use {@link CSM} instead.
*
* @augments ShadowBaseNode
* @three_import import { CSMShadowNode } from 'three/addons/csm/CSMShadowNode.js';
*/
class CSMShadowNode extends ShadowBaseNode {
/**
* Constructs a new CSM shadow node.
*
* @param {DirectionalLight} light - The CSM light.
* @param {CSMShadowNode~Data} [data={}] - The CSM data.
*/
constructor( light, data = {} ) {
super( light );
/**
* The scene's camera.
*
* @type {?Camera}
* @default null
*/
this.camera = null;
/**
* The number of cascades.
*
* @type {number}
* @default 3
*/
this.cascades = data.cascades || 3;
/**
* The maximum far value.
*
* @type {number}
* @default 100000
*/
this.maxFar = data.maxFar || 100000;
/**
* The frustum split mode.
*
* @type {('practical'|'uniform'|'logarithmic'|'custom')}
* @default 'practical'
*/
this.mode = data.mode || 'practical';
/**
* The light margin.
*
* @type {number}
* @default 200
*/
this.lightMargin = data.lightMargin || 200;
/**
* Custom split callback when using `mode='custom'`.
*
* @type {Function}
*/
this.customSplitsCallback = data.customSplitsCallback;
/**
* Whether to fade between cascades or not.
*
* @type {boolean}
* @default false
*/
this.fade = false;
/**
* An array of numbers in the range `[0,1]` the defines how the
* mainCSM frustum should be split up.
*
* @type {Array<number>}
*/
this.breaks = [];
this._cascades = [];
/**
* The main frustum.
*
* @type {?CSMFrustum}
* @default null
*/
this.mainFrustum = null;
/**
* An array of frustums representing the cascades.
*
* @type {Array<CSMFrustum>}
*/
this.frustums = [];
/**
* An array of directional lights which cast the shadows for
* the different cascades. There is one directional light for each
* cascade.
*
* @type {Array<DirectionalLight>}
*/
this.lights = [];
this._shadowNodes = [];
}
/**
* Inits the CSM shadow node.
*
* @private
* @param {NodeBuilder} builder - The node builder.
*/
_init( { camera, renderer } ) {
this.camera = camera;
const data = { webGL: renderer.coordinateSystem === WebGLCoordinateSystem };
this.mainFrustum = new CSMFrustum( data );
const light = this.light;
for ( let i = 0; i < this.cascades; i ++ ) {
const lwLight = new LwLight();
lwLight.castShadow = true;
const lShadow = light.shadow.clone();
lShadow.bias = lShadow.bias * ( i + 1 );
this.lights.push( lwLight );
lwLight.shadow = lShadow;
this._shadowNodes.push( shadow( lwLight, lShadow ) );
this._cascades.push( new Vector2() );
}
this.updateFrustums();
}
/**
* Inits the cascades according to the scene's camera and breaks configuration.
*
* @private
*/
_initCascades() {
const camera = this.camera;
camera.updateProjectionMatrix();
this.mainFrustum.setFromProjectionMatrix( camera.projectionMatrix, this.maxFar );
this.mainFrustum.split( this.breaks, this.frustums );
}
/**
* Computes the breaks of this CSM instance based on the scene's camera, number of cascades
* and the selected split mode.
*
* @private
*/
_getBreaks() {
const camera = this.camera;
const far = Math.min( camera.far, this.maxFar );
this.breaks.length = 0;
switch ( this.mode ) {
case 'uniform':
uniformSplit( this.cascades, camera.near, far, this.breaks );
break;
case 'logarithmic':
logarithmicSplit( this.cascades, camera.near, far, this.breaks );
break;
case 'practical':
practicalSplit( this.cascades, camera.near, far, 0.5, this.breaks );
break;
case 'custom':
if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' );
this.customSplitsCallback( this.cascades, camera.near, far, this.breaks );
break;
}
function uniformSplit( amount, near, far, target ) {
for ( let i = 1; i < amount; i ++ ) {
target.push( ( near + ( far - near ) * i / amount ) / far );
}
target.push( 1 );
}
function logarithmicSplit( amount, near, far, target ) {
for ( let i = 1; i < amount; i ++ ) {
target.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
}
target.push( 1 );
}
function practicalSplit( amount, near, far, lambda, target ) {
_uniformArray.length = 0;
_logArray.length = 0;
logarithmicSplit( amount, near, far, _logArray );
uniformSplit( amount, near, far, _uniformArray );
for ( let i = 1; i < amount; i ++ ) {
target.push( MathUtils.lerp( _uniformArray[ i - 1 ], _logArray[ i - 1 ], lambda ) );
}
target.push( 1 );
}
}
/**
* Sets the light breaks.
*
* @private
*/
_setLightBreaks() {
for ( let i = 0, l = this.cascades; i < l; i ++ ) {
const amount = this.breaks[ i ];
const prev = this.breaks[ i - 1 ] || 0;
this._cascades[ i ].set( prev, amount );
}
}
/**
* Updates the shadow bounds of this CSM instance.
*
* @private
*/
_updateShadowBounds() {
const frustums = this.frustums;
for ( let i = 0; i < frustums.length; i ++ ) {
const shadowCam = this.lights[ i ].shadow.camera;
const frustum = this.frustums[ i ];
// Get the two points that represent that furthest points on the frustum assuming
// that's either the diagonal across the far plane or the diagonal across the whole
// frustum itself.
const nearVerts = frustum.vertices.near;
const farVerts = frustum.vertices.far;
const point1 = farVerts[ 0 ];
let point2;
if ( point1.distanceTo( farVerts[ 2 ] ) > point1.distanceTo( nearVerts[ 2 ] ) ) {
point2 = farVerts[ 2 ];
} else {
point2 = nearVerts[ 2 ];
}
let squaredBBWidth = point1.distanceTo( point2 );
if ( this.fade ) {
// expand the shadow extents by the fade margin if fade is enabled.
const camera = this.camera;
const far = Math.max( camera.far, this.maxFar );
const linearDepth = frustum.vertices.far[ 0 ].z / ( far - camera.near );
const margin = 0.25 * Math.pow( linearDepth, 2.0 ) * ( far - camera.near );
squaredBBWidth += margin;
}
shadowCam.left = - squaredBBWidth / 2;
shadowCam.right = squaredBBWidth / 2;
shadowCam.top = squaredBBWidth / 2;
shadowCam.bottom = - squaredBBWidth / 2;
shadowCam.updateProjectionMatrix();
}
}
/**
* Applications must call this method every time they change camera or CSM settings.
*/
updateFrustums() {
this._getBreaks();
this._initCascades();
this._updateShadowBounds();
this._setLightBreaks();
}
/**
* Setups the TSL when using fading.
*
* @private
* @return {ShaderCallNodeInternal}
*/
_setupFade() {
const cameraNear = reference( 'camera.near', 'float', this ).setGroup( renderGroup );
const cascades = reference( '_cascades', 'vec2', this ).setGroup( renderGroup ).setName( 'cascades' );
const shadowFar = uniform( 'float' ).setGroup( renderGroup ).setName( 'shadowFar' )
.onRenderUpdate( () => Math.min( this.maxFar, this.camera.far ) );
const linearDepth = viewZToOrthographicDepth( positionView.z, cameraNear, shadowFar ).toVar( 'linearDepth' );
const lastCascade = this.cascades - 1;
return Fn( ( builder ) => {
this.setupShadowPosition( builder );
const ret = vec4( 1, 1, 1, 1 ).toVar( 'shadowValue' );
const cascade = vec2().toVar( 'cascade' );
const cascadeCenter = float().toVar( 'cascadeCenter' );
const margin = float().toVar( 'margin' );
const csmX = float().toVar( 'csmX' );
const csmY = float().toVar( 'csmY' );
for ( let i = 0; i < this.cascades; i ++ ) {
const isLastCascade = i === lastCascade;
cascade.assign( cascades.element( i ) );
cascadeCenter.assign( cascade.x.add( cascade.y ).div( 2.0 ) );
const closestEdge = linearDepth.lessThan( cascadeCenter ).select( cascade.x, cascade.y );
margin.assign( float( 0.25 ).mul( closestEdge.pow( 2.0 ) ) );
csmX.assign( cascade.x.sub( margin.div( 2.0 ) ) );
if ( isLastCascade ) {
csmY.assign( cascade.y );
} else {
csmY.assign( cascade.y.add( margin.div( 2.0 ) ) );
}
const inRange = linearDepth.greaterThanEqual( csmX ).and( linearDepth.lessThanEqual( csmY ) );
If( inRange, () => {
const dist = min( linearDepth.sub( csmX ), csmY.sub( linearDepth ) ).toVar();
let ratio = dist.div( margin ).clamp( 0.0, 1.0 );
if ( i === 0 ) {
// don't fade at nearest edge
ratio = linearDepth.greaterThan( cascadeCenter ).select( ratio, 1 );
}
ret.subAssign( this._shadowNodes[ i ].oneMinus().mul( ratio ) );
} );
}
return ret;
} )();
}
/**
* Setups the TSL when no fading (default).
*
* @private
* @return {ShaderCallNodeInternal}
*/
_setupStandard() {
const cameraNear = reference( 'camera.near', 'float', this ).setGroup( renderGroup );
const cascades = reference( '_cascades', 'vec2', this ).setGroup( renderGroup ).setName( 'cascades' );
const shadowFar = uniform( 'float' ).setGroup( renderGroup ).setName( 'shadowFar' )
.onRenderUpdate( () => Math.min( this.maxFar, this.camera.far ) );
const linearDepth = viewZToOrthographicDepth( positionView.z, cameraNear, shadowFar ).toVar( 'linearDepth' );
return Fn( ( builder ) => {
this.setupShadowPosition( builder );
const ret = vec4( 1, 1, 1, 1 ).toVar( 'shadowValue' );
const cascade = vec2().toVar( 'cascade' );
for ( let i = 0; i < this.cascades; i ++ ) {
cascade.assign( cascades.element( i ) );
If( linearDepth.greaterThanEqual( cascade.x ).and( linearDepth.lessThanEqual( cascade.y ) ), () => {
ret.assign( this._shadowNodes[ i ] );
} );
}
return ret;
} )();
}
setup( builder ) {
if ( this.camera === null ) this._init( builder );
return this.fade === true ? this._setupFade() : this._setupStandard();
}
updateBefore( /*builder*/ ) {
const light = this.light;
const parent = light.parent;
const camera = this.camera;
const frustums = this.frustums;
// make sure the placeholder light objects which represent the
// multiple cascade shadow casters are part of the scene graph
for ( let i = 0; i < this.lights.length; i ++ ) {
const lwLight = this.lights[ i ];
if ( lwLight.parent === null ) {
parent.add( lwLight.target );
parent.add( lwLight );
}
}
_lightDirection.subVectors( light.target.position, light.position ).normalize();
// for each frustum we need to find its min-max box aligned with the light orientation
// the position in _lightOrientationMatrix does not matter, as we transform there and back
_lightOrientationMatrix.lookAt( light.position, light.target.position, _up );
_lightOrientationMatrixInverse.copy( _lightOrientationMatrix ).invert();
for ( let i = 0; i < frustums.length; i ++ ) {
const lwLight = this.lights[ i ];
const shadow = lwLight.shadow;
const shadowCam = shadow.camera;
const texelWidth = ( shadowCam.right - shadowCam.left ) / shadow.mapSize.width;
const texelHeight = ( shadowCam.top - shadowCam.bottom ) / shadow.mapSize.height;
_cameraToLightMatrix.multiplyMatrices( _lightOrientationMatrixInverse, camera.matrixWorld );
frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum );
const nearVerts = _lightSpaceFrustum.vertices.near;
const farVerts = _lightSpaceFrustum.vertices.far;
_bbox.makeEmpty();
for ( let j = 0; j < 4; j ++ ) {
_bbox.expandByPoint( nearVerts[ j ] );
_bbox.expandByPoint( farVerts[ j ] );
}
_bbox.getCenter( _center );
_center.z = _bbox.max.z + this.lightMargin;
_center.x = Math.floor( _center.x / texelWidth ) * texelWidth;
_center.y = Math.floor( _center.y / texelHeight ) * texelHeight;
_center.applyMatrix4( _lightOrientationMatrix );
lwLight.position.copy( _center );
lwLight.target.position.copy( _center );
lwLight.target.position.add( _lightDirection );
}
}
/**
* Frees the GPU-related resources allocated by this instance. Call this
* method whenever this instance is no longer used in your app.
*/
dispose() {
for ( let i = 0; i < this.lights.length; i ++ ) {
const light = this.lights[ i ];
const parent = light.parent;
parent.remove( light.target );
parent.remove( light );
}
super.dispose();
}
}
/**
* Constructor data of `CSMShadowNode`.
*
* @typedef {Object} CSMShadowNode~Data
* @property {number} [cascades=3] - The number of cascades.
* @property {number} [maxFar=100000] - The maximum far value.
* @property {('practical'|'uniform'|'logarithmic'|'custom')} [mode='practical'] - The frustum split mode.
* @property {Function} [customSplitsCallback] - Custom split callback when using `mode='custom'`.
* @property {number} [lightMargin=200] - The light margin.
**/
export { CSMShadowNode };