# graphics3d/shadowmap (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/graphics3d/shadowmap/

Shadow map. (directional light real-time shadows, depth texture + orthographic light matrix)

## ShadowMap extends Object

Shadow map. (Real-time directional light shadow, depth texture + orthographic light matrix)
- beginRender() starts the depth pass, and the resulting texture is sampled in the main pass.
- The light matrix is snapped to texels to reduce shadow edge shimmering when moving.
- Restores the previous texture and framebuffer bindings when built. (So that building it after models does not leave the depth texture on a texture unit and turn drawing into INVALID_OPERATION)

Example: Bake shadows in a depth pass and receive them in the main pass

```js
import { ShadowMap, SkinnedModel, SkinnedModelRenderer, Camera3D, Matrix4, Vector3 } from "./build/vanilla.js";

const width = 640;
const height = 360;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
const webGL2RenderingContext = canvas.getContext("webgl2");
const shadowMap = new ShadowMap(webGL2RenderingContext, 1024);
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const skinnedModel = await SkinnedModel.loadFromUrl(webGL2RenderingContext, "examples/ancientmountain/assets/fox.glb", skinnedModelRenderer);
skinnedModel.update(0);
const modelMatrix = Matrix4.createIdentity();
const modelMatrixElements = modelMatrix.getElements();

const focusPosition = Vector3.create(0, 40, 0);
const lightDirection = Vector3.create(-0.45, -0.76, -0.47);
shadowMap.updateLightMatrix(focusPosition, lightDirection, 150, 1, 600);
const lightViewProjectionMatrix = shadowMap.getLightViewProjectionMatrix();
const lightViewProjectionElements = lightViewProjectionMatrix.getElements();
shadowMap.beginRender();
skinnedModelRenderer.drawDepth(skinnedModel, lightViewProjectionElements, modelMatrixElements);

const depthTexture = shadowMap.getDepthTexture();
const resolution = shadowMap.getResolution();
skinnedModelRenderer.setShadowMap(depthTexture, lightViewProjectionElements, 1 / resolution);
skinnedModelRenderer.setShadowStrength(0.8);
skinnedModelRenderer.setSunDirection(0.45, 0.76, 0.47);
const cameraX = 0;
const cameraY = 80;
const cameraZ = 220;
const camera = new Camera3D();
camera.setPerspective(Math.PI / 3, 1, 2000);
camera.setAspectRatio(width / height);
const eyePosition = Vector3.create(cameraX, cameraY, cameraZ);
const targetPosition = Vector3.create(0, 45, 0);
camera.lookAt(eyePosition, targetPosition);
const viewProjectionMatrix = camera.getViewProjectionMatrix();
const viewProjectionElements = viewProjectionMatrix.getElements();
webGL2RenderingContext.bindFramebuffer(webGL2RenderingContext.FRAMEBUFFER, null);
webGL2RenderingContext.viewport(0, 0, width, height);
webGL2RenderingContext.clearColor(0.16, 0.2, 0.26, 1);
webGL2RenderingContext.clear(webGL2RenderingContext.COLOR_BUFFER_BIT | webGL2RenderingContext.DEPTH_BUFFER_BIT);
skinnedModelRenderer.draw(skinnedModel, viewProjectionElements, modelMatrixElements, cameraX, cameraY, cameraZ);
```

- `constructor(webGL2RenderingContext, resolution = 2048)` (constructor, since 0.3.0): Constructor.
  - `webGL2RenderingContext` WebGL2RenderingContext: WebGL2 rendering context.
  - `resolution` number: Side length of the depth texture. (pixels, default 2048)
- `updateLightMatrix(focusPosition, lightDirection, extent, nearDistance, farDistance)` (method, since 0.3.0): Update the light matrix. (Orthographic projection covering the area around the focus, texel snap, the up direction becomes the z axis when the light travels almost straight up or down so the matrix does not break)
  - `focusPosition` Vector3: World position at the center of the shadow coverage.
  - `lightDirection` Vector3: Direction the light travels.
  - `extent` number: Half coverage extent around the focus.
  - `nearDistance` number: Near distance of the light's orthographic projection. (world units)
  - `farDistance` number: Far distance of the light's orthographic projection. (world units, the light eye sits (near distance + far distance) / 2 away from the focus, against the light direction)

  Example: Light matrix that follows a moving focus

  ```js
  import { ShadowMap, Vector3 } from "./build/vanilla.js";
  
  const canvas = document.createElement("canvas");
  const webGL2RenderingContext = canvas.getContext("webgl2");
  const shadowMap = new ShadowMap(webGL2RenderingContext, 2048);
  const playerPosition = Vector3.create(12, 0, -4);
  const sunTravelDirection = Vector3.create(-0.4, -1.0, -0.3);
  shadowMap.updateLightMatrix(playerPosition, sunTravelDirection, 30, 0.5, 200);
  const lightViewProjectionMatrix = shadowMap.getLightViewProjectionMatrix();
  const clipPoint = lightViewProjectionMatrix.transformPoint(12, 0, -4);
  console.log(clipPoint.x, clipPoint.y, clipPoint.z);
  shadowMap.destroy();
  ```

- `beginRender()` (method, since 0.3.0): Start the depth pass. (Binds the framebuffer, sets the viewport and clears depth, when ToonDrawQueue uses the cache it draws into the baked target or copies the baked target and draws on top)
- `setUpdateMode(updateMode, updateInterval = 1)` (method, since 0.4.0): Set how the shadow is redrawn. (ToonDrawQueue follows it, default ShadowUpdateMode.onChange, setting it redraws everything on the next draw)
  - `updateMode` string: ShadowUpdateMode.
  - `updateInterval` number: With interval, every how many frames to draw. (Default 1, 1 if less than 1)

  Example: Draw the sun shadow every three frames

  ```js
  import { ShadowMap, ShadowUpdateMode } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const shadowTarget = new ShadowMap(webGL2RenderingContext, 1024);
  shadowTarget.setUpdateMode(ShadowUpdateMode.interval, 3);
  console.log(shadowTarget.getUpdateMode(), shadowTarget.getUpdateInterval());
  shadowTarget.setUpdateMode(ShadowUpdateMode.everyFrame);
  shadowTarget.destroy();
  ```

- `getUpdateMode()` (method, since 0.4.0): Return how the shadow is redrawn.
  - returns string: ShadowUpdateMode.
- `getUpdateInterval()` (method, since 0.4.0): Return the frame count of interval.
  - returns number: Every how many frames it draws. (1 or more)
- `requestUpdate()` (method, since 0.4.0): Make the next draw redraw everything. (For changes the caster record cannot see, for example when the vertices of a mesh were changed)
- `getWebGL2RenderingContext()` (method, since 0.3.0): Returns the rendering context.
  - returns WebGL2RenderingContext: Rendering context.
- `getFramebuffer()` (method, since 0.3.0): Returns the framebuffer.
  - returns WebGLFramebuffer: Depth-only framebuffer.
- `getDepthTexture()` (method, since 0.3.0): Returns the depth texture.
  - returns WebGLTexture: Depth texture for comparison sampling (sampler2DShadow). (DEPTH_COMPONENT24)
- `getResolution()` (method, since 0.3.0): Returns the resolution.
  - returns number: Side length of the depth texture. (pixels)
- `setFocusStep(worldStep)` (method, since 0.4.0): Set the world step the focus moves in. (for the sun shadow cache, the default 0 does not snap and only snaps to texels)
  - When the focus follows a camera, passing a single texel changes the light matrix, so the ShadowUpdateMode.onChange cache redraws every frame.
  - With a step, the focus is moved to multiples of the world step on each of x, y and z, so the matrix stays the same inside one cell and the baked map is reused. The covered width and depth get the step as margin so the area around the focus never leaves the map.
  - This is the same idea as pinning the focus to a fixed cell in the cached shadows of Unity and Unreal and in virtual shadow maps. (the originals were not read, so this is a guess)
  - Texel snapping still applies on top. With the extra margin, one texel covers slightly more world space.
  - `worldStep` number: World step. (in world units, 0 or less turns it off)

  Example: Moving the focus in one meter steps

  ```js
  import { ShadowMap, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const shadowMap = new ShadowMap(webGL2RenderingContext, 1024);
  shadowMap.setFocusStep(1);
  shadowMap.updateLightMatrix(Vector3.create(0.2, 0, 0), Vector3.create(-0.4, -1, -0.3), 20, 0.5, 100);
  console.log(shadowMap.getFocusStep());
  shadowMap.destroy();
  ```

- `getFocusStep()` (method, since 0.4.0): Return the world step the focus moves in.
  - returns number: World step. (0 means off)
- `getLightViewProjectionMatrix()` (method, since 0.3.0): Returns the light view-projection matrix.
  - returns Matrix4: Light view-projection matrix. (identity before updateLightMatrix)
- `setBias(depthBias, normalBias)` (method, since 0.4.0): Sets the shadow bias. (in shadow texels, default depth 1, normal 1, applied by the receiver when it reads the shadow)
  - It is multiplied by the world size of one texel (light matrix width / resolution), so the same amount applies when the extent or resolution changes. (the same units as Depth Bias and Normal Bias in Unity URP)
  - Depth bias pulls the compared depth toward the light. Normal bias pushes the receiving point along the surface normal before reading. Both are multiplied by the 1.5 texel radius of the 3x3 PCF.
  - ToonRenderer adds a slope-scaled bias on top (grows as the light grazes the surface, 2.5 texels x slope, slope clamped at 10).
  - Lower values keep shadows attached but invite self-shadow acne. Higher values remove acne but make shadows look detached (peter panning).
  - `depthBias` number: Depth bias. (in shadow texels, 0 or more)
  - `normalBias` number: Normal bias. (in shadow texels, 0 or more)

  Example: Setting the shadow bias in texels

  ```js
  import { ShadowMap, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const shadowMap = new ShadowMap(webGL2RenderingContext, 1024);
  shadowMap.updateLightMatrix(Vector3.create(0, 0, 0), Vector3.create(-0.3, -1, -0.2), 20, 1, 100);
  shadowMap.setBias(0.5, 1.5);
  console.log(shadowMap.getDepthBias(), shadowMap.getNormalBias());
  shadowMap.destroy();
  ```

- `getDepthBias()` (method, since 0.4.0): Returns the depth bias.
  - returns number: Depth bias. (in shadow texels, default 1)
- `getNormalBias()` (method, since 0.4.0): Returns the normal bias.
  - returns number: Normal bias. (in shadow texels, default 1)
- `destroy()` (method, since 0.4.0): Destroy. (Deletes the framebuffer, the depth texture and the baked target)

## ShadowAtlas extends Object

Shadow atlas. (Stores real-time shadows of point lights and spotlights as tiles in one depth texture)
- Same form as the additional light shadow atlas of Unity URP. A spotlight is drawn into one perspective shadow map tile, a point light draws the six cube faces into six tiles (90 degree perspective per face).
- updateLights(light list) picks lights with castsShadow true up to SHADOW_ATLAS_MAXIMUM_LIGHTS, divides the tiles and computes view and projection per tile.
  Lights have the form of ToonLightSet.setPointLights. { position, direction (spotlight if present), outerConeAngle, range (far distance, 30 if 0), shadowNear (near distance, default 0.05), castsShadow }
  The order in the list (lightIndex) is noted so ToonRenderer attaches this shadow to that point light. (The atlas is built from the point light list of the default light set)
- Tile size is decided the same as the Unity URP defaults. Each tile asks for tileResolution (default 1024, the default of the URP additional light shadow resolution tier High, and High is the default tier of a light),
  and if they do not all fit in the atlas (default 2048, the URP default), the tile side is halved until they all fit. (Doubling shadowSlicesScaleFactor of URP)
  Tiles are placed in order on a grid of gridSize per side. (gridSize = floor(resolution / tile side)) One point light (six tiles) gives 512, one spotlight gives 1024.
- Drawing: beginRender() clears the target, then per tile beginTile(tile number) sets the viewport to that tile and depth is drawn with getTile(tile number).viewProjectionMatrix. (ToonRenderer.beginShadowAtlasPass and setShadowAtlasTile do this sequence)
- Receiving: the shader picks the point light face from the direction from the light position to the surface (largest axis), computes the position and depth inside the tile from the forward, up and right basis and the near and far distances, and compares with 3x3 PCF.
  The receiving position is pushed toward the normal by (1 + 3 x (1 - dot(N, L))) tile texels at that distance before comparing. (Larger the more the surface is slanted to the light, prevents saw-toothed shadow acne at the light and shade boundary)

Example: Build shadow tiles for one point light and one spotlight

```js
import { ShadowAtlas } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const shadowAtlas = new ShadowAtlas(webGL2RenderingContext, 2048);
shadowAtlas.updateLights([
	{ position: [0, 3, 0], range: 8, castsShadow: true },
	{ position: [2, 4, 1], direction: [0, -1, 0], outerConeAngle: 0.5, range: 10, castsShadow: true },
]);
const tileCount = shadowAtlas.getTileCount();
const firstTile = shadowAtlas.getTile(0);
console.log(tileCount, shadowAtlas.getGridSize(), firstTile.size);
shadowAtlas.destroy();
```

- `constructor(webGL2RenderingContext, resolution = 2048, tileResolution = 1024)` (constructor, since 0.4.0): Constructor. (Depth texture and a framebuffer without color, previous bindings are restored)
  - `webGL2RenderingContext` WebGL2RenderingContext: Rendering context.
  - `resolution` number: Size of one side of the atlas. (Pixels, default 2048)
  - `tileResolution` number: Side each tile asks for. (Pixels, default 1024, halved if they do not all fit)
- `updateLights(pointLights)` (method, since 0.4.0): Divide tiles from the light list. (Ones with castsShadow true up to SHADOW_ATLAS_MAXIMUM_LIGHTS, one tile per spotlight, six per point light)
  - `pointLights` Array<object>: Array in the form of ToonLightSet.setPointLights. (getPointLights can be passed as is)
- `createTile(position, forward, up, tangent, near, far)` (method, since 0.4.0): Build one tile. (Decides the grid position from the number of tiles built so far, and multiplies the basis view matrix with the perspective projection)
  - `position` Array<number>: Light position.
  - `forward` Array<number>: Looking direction.
  - `up` Array<number>: Up direction.
  - `tangent` number: Tangent of the half angle. (1 for a point light face, 90 degrees)
  - `near` number: Near distance.
  - `far` number: Far distance.
  - returns object: { viewProjectionMatrix, x, y, size }
- `beginRender()` (method, since 0.4.0): Start the depth pass. (Binds the framebuffer and clears the whole target, beginTile per tile, when ToonDrawQueue uses the cache it draws into the baked target or copies the baked target and draws on top)
- `setUpdateMode(updateMode, updateInterval = 1)` (method, since 0.4.0): Set how the shadow is redrawn. (ToonDrawQueue follows it, default ShadowUpdateMode.onChange, setting it redraws everything on the next draw)
  - `updateMode` string: ShadowUpdateMode.
  - `updateInterval` number: With interval, every how many frames to draw. (Default 1, 1 if less than 1)

  Example: Draw the point light shadow every three frames

  ```js
  import { ShadowAtlas, ShadowUpdateMode } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const shadowTarget = new ShadowAtlas(webGL2RenderingContext, 1024);
  shadowTarget.setUpdateMode(ShadowUpdateMode.interval, 3);
  console.log(shadowTarget.getUpdateMode(), shadowTarget.getUpdateInterval());
  shadowTarget.setUpdateMode(ShadowUpdateMode.everyFrame);
  shadowTarget.destroy();
  ```

- `getUpdateMode()` (method, since 0.4.0): Return how the shadow is redrawn.
  - returns string: ShadowUpdateMode.
- `getUpdateInterval()` (method, since 0.4.0): Return the frame count of interval.
  - returns number: Every how many frames it draws. (1 or more)
- `requestUpdate()` (method, since 0.4.0): Make the next draw redraw everything. (For changes the caster record cannot see, for example when the vertices of a mesh were changed)
- `beginTile(tileIndex)` (method, since 0.4.0): Set the viewport to one tile.
  - `tileIndex` number: Tile number. (0 ~ getTileCount() - 1)
- `getLightCount()` (method, since 0.4.0): Return the number of lights receiving shadows.
  - returns number: Number of lights that got tiles. (0 ~ SHADOW_ATLAS_MAXIMUM_LIGHTS)
- `getLights()` (method, since 0.4.0): Return the lights receiving shadows. (Values to upload to the shader)
  - returns Array<object>: Array of { lightIndex (order in the light list), position, forward, up, tangent (0 for a point light), near, far, firstTile }.
- `getTileCount()` (method, since 0.4.0): Return the tile count.
  - returns number: Number of tiles built. (One per spotlight, six per point light)
- `getTile(tileIndex)` (method, since 0.4.0): Return a tile.
  - `tileIndex` number: Tile number.
  - returns object: { viewProjectionMatrix (Matrix4), x, y, size (pixels) }
- `getGridSize()` (method, since 0.4.0): Return the number of tiles per side of the grid.
  - returns number: Number of tiles per side of the grid.
- `getTileResolution()` (method, since 0.4.0): Return the side each tile asks for. (Pixels, the value given at construction)
  - returns number: Side each tile asks for. (Pixels)
- `getTileSize()` (method, since 0.4.0): Return the side of a tile. (Pixels)
  - returns number: Side of a tile. (Pixels)
- `getResolution()` (method, since 0.4.0): Returns the resolution.
  - returns number: One side of the atlas. (Pixels)
- `getDepthTexture()` (method, since 0.4.0): Return the depth texture. (Comparison sampling with sampler2DShadow)
  - returns WebGLTexture: Depth texture of the atlas.
- `getFramebuffer()` (method, since 0.4.0): Returns the framebuffer.
  - returns WebGLFramebuffer: Depth framebuffer of the atlas.
- `destroy()` (method, since 0.4.0): Destroy. (Deletes the framebuffer, the depth texture and the baked target)

## Functions and constants

- `SHADOW_ATLAS_MAXIMUM_LIGHTS = 4` (field, since 0.4.0): Upper limit of point lights and spotlights the shadow atlas receives. (Size of the uniform arrays in the shader)
  - returns number

## ShadowUpdateMode (enum)

How the shadow depth is redrawn. (setUpdateMode of ShadowMap and ShadowAtlas, followed by ToonDrawQueue.drawShadows and drawLocalShadows)
- everyFrame: redraws all casters every frame.
- onChange: does not redraw when the lights and casters are unchanged. Casters that stay still are baked separately and only the moving ones are drawn on top every frame. (Default, the screen is the same as drawing every frame)
- interval: redraws everything once every N frames. (The frames in between keep the previous shadow, so the shadows of moving things follow late)

Example: Sun shadow only on change, point light shadow every four frames

```js
import { ShadowMap, ShadowAtlas, ShadowUpdateMode } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const shadowMap = new ShadowMap(webGL2RenderingContext, 1024);
shadowMap.setUpdateMode(ShadowUpdateMode.onChange);
const shadowAtlas = new ShadowAtlas(webGL2RenderingContext, 1024);
shadowAtlas.setUpdateMode(ShadowUpdateMode.interval, 4);
console.log(shadowMap.getUpdateMode(), shadowAtlas.getUpdateMode(), shadowAtlas.getUpdateInterval());
shadowMap.destroy();
shadowAtlas.destroy();
```

- `everyFrame` = `everyFrame`: Everything every frame.
- `onChange` = `onChange`: Only on change. (Default)
- `interval` = `interval`: Every N frames.
