StrandedKitty / three-csm

☀️ Cascaded shadow maps (CSMs) implementation for Three.js
MIT License
296 stars 21 forks source link
shaders threejs webgl

three-csm

Cascaded shadow maps (CSMs) implementation for Three.js. This approach provides higher resolution of shadows near the camera and lower resolution far away by using several shadow maps. CSMs are usually used for shadows cast by the sun over a large terrain.

Examples

Cascaded Shadow Maps

Installation

<script src="https://github.com/StrandedKitty/three-csm/raw/master/build/three-csm.js"></script>

Using CommonJS:

npm i three-csm
const THREE = require('three');
THREE.CSM = require('three-csm');

Using ES6 modules:

import * as THREE from 'three';
import CSM from 'three-csm';
THREE.CSM = CSM;

Basic usage

let camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
let renderer = new THREE.WebGLRenderer();

renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // or any other type of shadowmap

let csm = new THREE.CSM({
    maxFar: camera.far,
    cascades: 4,
    shadowMapSize: 1024,
    lightDirection: new THREE.Vector3(1, -1, 1).normalize(),
    camera: camera,
    parent: scene
});

let material = new THREE.MeshPhongMaterial(); // works with Phong and Standard materials
csm.setupMaterial(material); // must be called to pass all CSM-related uniforms to the shader

let mesh = new THREE.Mesh(new THREE.BoxBufferGeometry(), material);
mesh.castShadow = true;
mesh.receiveShadow = true;

scene.add(mesh);

Finally, in your update loop, call the update function before rendering:

csm.update(camera.matrix);

API

CSM

constructor(settings: CSMParams)

Parameters

setupMaterial(material: THREE.Material)

Updates defines and uniforms of passed material. Should be called for every material which must use CSMs.

Parameters

update()

Updates positions of frustum splits in world space. Should be called before every frame before rendering.

updateFrustums()

Recalculates frustums for shadow cascades. Must be called after changing the camera projection matrix, split mode, maxFar or shadowBias settings.

updateCascades(cascades: number)

Updates number of shadow cascades, automatically recompiles all materials previously passed to setupMaterial().

Parameters

updateShadowMapSize(size: number)

Updates shadow map size for all directional lights used by CSM instance.

Parameters

dispose()

Removes and disposes all directional lights used by CSM instance.

Contributing

Feel free to contribute. Use npm run dev to run a dev server.

References

  1. Rouslan Dimitrov. Cascaded ShadowMaps
  2. Cascaded Shadow Maps on Windows Dev Center
  3. 3D Game Development with LWJGL 3. Cascaded Shadow Maps
  4. GPU Gems 3. Chapter 10