@expofp/renderer 3.45.16 → 3.46.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,324 @@
1
+ import { degToRad } from '@expofp/geometry';
2
+ import { Box3, PCFShadowMap, Vector3, } from 'three';
3
+ import { clamp } from '../../utils/math';
4
+ /**
5
+ * The fixed sun's shadow map: where the sun stands, which area the map covers, and when the map is
6
+ * drawn again.
7
+ *
8
+ * The map is baked. It is fitted to what the camera sees and redrawn when the sun, the visible
9
+ * casters or the fitted area change, so camera motion inside the fitted area reuses it. `Lighting`
10
+ * mounts the sun and calls {@link fitShadowCamera} from the scene's `onBeforeRender`; the lookup
11
+ * lives with the materials, in `effects/sun-shadow`.
12
+ */
13
+ /**
14
+ * Aims the shadow-only sun from a heading and an elevation. The heading turns counterclockwise on
15
+ * screen from the plan's `+x`; the plan's `+y` points down the screen, hence `-sin`.
16
+ * @param settings - The rig.
17
+ * @param target - The sun's position, a direction in plan space.
18
+ */
19
+ export function aimSun(settings, target) {
20
+ const heading = degToRad(settings.sunShadow.headingDegrees);
21
+ const elevation = degToRad(settings.sunShadow.elevationDegrees);
22
+ target.set(Math.cos(elevation) * Math.cos(heading), -Math.cos(elevation) * Math.sin(heading), Math.sin(elevation));
23
+ }
24
+ /**
25
+ * Turns shadow maps on, PCF with a blur radius.
26
+ * @param state - The root state, for the renderer.
27
+ * @param state.gl - The renderer.
28
+ */
29
+ export function enableShadowMaps(state) {
30
+ const renderer = state.gl;
31
+ renderer.shadowMap.enabled = true;
32
+ renderer.shadowMap.type = PCFShadowMap;
33
+ const shadowMap = renderer.shadowMap;
34
+ if (shadowMap.__efpDepthRange)
35
+ return;
36
+ shadowMap.__efpDepthRange = true;
37
+ // MapLibre leaves `depthRange` at `[0, 0.9865]` for its 3D layers, and three leaves it as it finds
38
+ // it. The shadow pass would then write depths compressed by that range while the lookup assumes
39
+ // `[0, 1]`, and every receiver would read as behind the map. The pass draws at the full range and
40
+ // hands the host its own range back.
41
+ const gl = renderer.getContext();
42
+ const render = shadowMap.render.bind(shadowMap);
43
+ shadowMap.render = (lights, scene, camera) => {
44
+ const pending = lights.some((light) => light.castShadow && light.shadow?.needsUpdate);
45
+ if (!pending) {
46
+ render(lights, scene, camera);
47
+ return;
48
+ }
49
+ const range = gl.getParameter(gl.DEPTH_RANGE);
50
+ gl.depthRange(0, 1);
51
+ render(lights, scene, camera);
52
+ gl.depthRange(range[0], range[1]);
53
+ };
54
+ }
55
+ /**
56
+ * Fits the sun's shadow camera to what the camera sees, a quarter wider, and asks for a redraw of
57
+ * the map when the fit changed. Four steps:
58
+ *
59
+ * 1. {@link readCasters}: what the sun and the visible casters look like this frame.
60
+ * 2. {@link measureCasters}, when that changed: their extent in the sun's view, which sets the
61
+ * depth range, and the floor catcher's size.
62
+ * 3. {@link fitView}: the area the camera sees, kept while the view stays inside it.
63
+ * 4. {@link applyFit}: the shadow camera's frustum and biases, and the redraw.
64
+ * @param light - The shadow-only sun.
65
+ * @param scene - The scene, walked for casters.
66
+ * @param space - The scene's space.
67
+ * @param catcher - The floor's shadow catcher, sized to the casters.
68
+ * @param viewCamera - The camera the frame draws with.
69
+ */
70
+ export function fitShadowCamera(light, scene, space, catcher, viewCamera) {
71
+ light.shadow.autoUpdate = false;
72
+ const signature = readCasters(light, scene);
73
+ const castersChanged = signature !== _lastSignature;
74
+ if (castersChanged) {
75
+ _lastSignature = signature;
76
+ if (!measureCasters(light, space, catcher)) {
77
+ // An empty map: a hidden layer's old shadows leave with it.
78
+ light.shadow.needsUpdate = true;
79
+ return;
80
+ }
81
+ }
82
+ else if (_bounds.isEmpty()) {
83
+ return;
84
+ }
85
+ const texel = fitView(light, space, viewCamera, castersChanged);
86
+ if (texel !== undefined)
87
+ applyFit(light, texel);
88
+ }
89
+ /**
90
+ * Whether any visible mesh casts the sun's shadow.
91
+ * @param scene - The scene.
92
+ * @returns Whether one does.
93
+ */
94
+ export function hasVisibleCaster(scene) {
95
+ let found = false;
96
+ scene.traverseVisible((object) => {
97
+ if (!found && object.isMesh && object.castShadow)
98
+ found = true;
99
+ });
100
+ return found;
101
+ }
102
+ /**
103
+ * Collects the visible casters into `_casters`, and describes the sun and what each caster shows.
104
+ * Cheap to build every frame, so the heavier steps run only when it changes.
105
+ * @param light - The sun.
106
+ * @param scene - The scene.
107
+ * @returns The signature.
108
+ */
109
+ function readCasters(light, scene) {
110
+ let signature = `${light.position.x},${light.position.y},${light.position.z}`;
111
+ _casters.length = 0;
112
+ scene.traverseVisible((object) => {
113
+ const mesh = object;
114
+ if (!mesh.isMesh || !mesh.castShadow)
115
+ return;
116
+ _casters.push(mesh);
117
+ signature += `|${mesh.id}:${mesh.matrixWorld.elements.join(',')}:${instanceSignature(mesh)}`;
118
+ });
119
+ return signature;
120
+ }
121
+ /**
122
+ * Measures the casters: their bounds in the world and in the plan, the floor catcher's size, and
123
+ * their extent in the sun's own view, with the shadow camera aimed the way
124
+ * `DirectionalLightShadow.updateMatrices` aims it.
125
+ * @param light - The sun.
126
+ * @param space - The scene's space.
127
+ * @param catcher - The floor's shadow catcher.
128
+ * @returns Whether any caster has bounds.
129
+ */
130
+ function measureCasters(light, space, catcher) {
131
+ _bounds.makeEmpty();
132
+ for (const mesh of _casters) {
133
+ const instanced = mesh;
134
+ instanced.computeBoundingBox?.();
135
+ const box = instanced.boundingBox ?? mesh.geometry.boundingBox;
136
+ if (!box)
137
+ continue;
138
+ _bounds.union(_box.copy(box).applyMatrix4(mesh.matrixWorld));
139
+ }
140
+ if (_bounds.isEmpty())
141
+ return false;
142
+ // The catcher covers the casters' extent: a small quad keeps its interpolated shadow coordinates
143
+ // precise once the map's texels get small.
144
+ _boundsPlan.copy(_bounds).applyMatrix4(space.matrixInverse);
145
+ _boundsPlan.getCenter(_corner);
146
+ _boundsPlan.getSize(_footprint);
147
+ catcher.position.set(_corner.x, _corner.y, CATCHER_ELEVATION);
148
+ catcher.scale.set(_footprint.x * 1.2, _footprint.y * 1.2, 1);
149
+ const camera = light.shadow.camera;
150
+ light.updateWorldMatrix(true, false);
151
+ light.target.updateWorldMatrix(true, false);
152
+ camera.position.setFromMatrixPosition(light.matrixWorld);
153
+ camera.lookAt(_to.setFromMatrixPosition(light.target.matrixWorld));
154
+ camera.updateMatrixWorld();
155
+ _depth[0] = Infinity;
156
+ _depth[1] = -Infinity;
157
+ for (let corner = 0; corner < 8; corner++) {
158
+ cornerOf(_bounds, corner, _corner).applyMatrix4(camera.matrixWorldInverse);
159
+ _depth[0] = Math.min(_depth[0], _corner.z);
160
+ _depth[1] = Math.max(_depth[1], _corner.z);
161
+ }
162
+ return true;
163
+ }
164
+ /**
165
+ * Fits the map's area to the view's ground footprint, in the sun's view.
166
+ *
167
+ * The footprint is measured from the ground point under the screen center, which is what the camera
168
+ * turns about, so turning keeps it. Receivers decide the area: the map is a view along the sun, so
169
+ * a caster outside the area still lands in it. The floor covers ground receivers, and a copy raised
170
+ * to the casters' height covers roofs in view; the raise stops at the footprint's own size, which
171
+ * keeps a close-up tight beside a tall tower.
172
+ * @param light - The sun.
173
+ * @param space - The scene's space.
174
+ * @param viewCamera - The camera the frame draws with.
175
+ * @param force - Whether to refit even when the view stays inside the fitted area.
176
+ * @returns The map's texel size in world units after a refit, or `undefined` to keep the map.
177
+ */
178
+ function fitView(light, space, viewCamera, force) {
179
+ const view = light.shadow.camera.matrixWorldInverse;
180
+ const pivot = groundCorner(viewCamera, space, CENTER, _boundsPlan, _corner);
181
+ const pivotX = pivot.x;
182
+ const pivotY = pivot.y;
183
+ let groundRadius = 0;
184
+ for (let corner = 0; corner < 4; corner++) {
185
+ const hit = groundCorner(viewCamera, space, corner, _boundsPlan, _corner);
186
+ groundRadius = Math.max(groundRadius, Math.hypot(hit.x - pivotX, hit.y - pivotY));
187
+ }
188
+ const height = clamp(_boundsPlan.max.z, 0, groundRadius);
189
+ _footprint.set(pivotX, pivotY, 0).applyMatrix4(space.matrix).applyMatrix4(view);
190
+ const centerX = _footprint.x;
191
+ const centerY = _footprint.y;
192
+ let radius = 0;
193
+ for (let corner = 0; corner < 4; corner++) {
194
+ const hit = groundCorner(viewCamera, space, corner, _boundsPlan, _corner);
195
+ for (const z of [0, height]) {
196
+ _footprint.set(hit.x, hit.y, z).applyMatrix4(space.matrix).applyMatrix4(view);
197
+ radius = Math.max(radius, Math.hypot(_footprint.x - centerX, _footprint.y - centerY));
198
+ }
199
+ }
200
+ // Quarter octaves, so a zoom resizes the fit in steps.
201
+ const stepped = 2 ** (Math.ceil(Math.log2(Math.max(radius, 1e-30)) * 4) / 4);
202
+ const offset = Math.hypot(centerX - _viewFit[0], centerY - _viewFit[1]);
203
+ const covered = offset + stepped <= _viewFit[2] && stepped * REFIT_ZOOM_IN >= _viewFit[2] / FIT_MARGIN;
204
+ if (covered && !force)
205
+ return undefined;
206
+ // Wider than the view by `FIT_MARGIN`, which is the room the coverage test spends.
207
+ const fitRadius = stepped * FIT_MARGIN;
208
+ const texel = (2 * fitRadius) / SHADOW_MAP_SIZE;
209
+ // Snapped to whole texels, so the grid stays put under a still shadow.
210
+ _viewFit[0] = Math.round(centerX / texel) * texel;
211
+ _viewFit[1] = Math.round(centerY / texel) * texel;
212
+ _viewFit[2] = fitRadius;
213
+ return texel;
214
+ }
215
+ /**
216
+ * Sets the shadow camera's frustum from the view fit and the casters' depth, and the biases from
217
+ * the texel size, then asks for a redraw.
218
+ * @param light - The sun.
219
+ * @param texel - The map's texel size, in world units.
220
+ */
221
+ function applyFit(light, texel) {
222
+ const camera = light.shadow.camera;
223
+ const [centerX, centerY, radius] = _viewFit;
224
+ const [minZ, maxZ] = _depth;
225
+ const margin = (maxZ - minZ) * 0.01 + texel;
226
+ camera.left = centerX - radius;
227
+ camera.right = centerX + radius;
228
+ camera.bottom = centerY - radius;
229
+ camera.top = centerY + radius;
230
+ // Depth from every caster, so a tower outside the view still shades what is in it.
231
+ camera.near = -maxZ - margin;
232
+ camera.far = -minZ + margin;
233
+ camera.updateProjectionMatrix();
234
+ // In world units through the normal, and a texel's depth offset in the map's own `0`–`1` depth.
235
+ light.shadow.normalBias = texel * 1.5;
236
+ light.shadow.bias = -texel / (camera.far - camera.near);
237
+ light.shadow.needsUpdate = true;
238
+ }
239
+ /**
240
+ * Where a corner of the view meets the plan floor, in plan units, clamped to the casters' extent so
241
+ * a corner above the horizon stays on the plan.
242
+ * @param camera - The view camera.
243
+ * @param space - The scene's space.
244
+ * @param corner - `0`–`3`, one bit per screen axis, or {@link CENTER}.
245
+ * @param limit - The casters' bounds, in plan units.
246
+ * @param target - Receives the point.
247
+ * @returns `target`.
248
+ */
249
+ function groundCorner(camera, space, corner, limit, target) {
250
+ const x = corner === CENTER ? 0 : corner & 1 ? 1 : -1;
251
+ const y = corner === CENTER ? 0 : corner & 2 ? 1 : -1;
252
+ _near.set(x, y, -1).unproject(camera).applyMatrix4(space.matrixInverse);
253
+ _far.set(x, y, 1).unproject(camera).applyMatrix4(space.matrixInverse);
254
+ const dz = _far.z - _near.z;
255
+ const t = Math.abs(dz) > 1e-12 ? -_near.z / dz : -1;
256
+ if (t >= 0 && t <= 1)
257
+ target.lerpVectors(_near, _far, t);
258
+ else
259
+ target.copy(_far);
260
+ target.x = clamp(target.x, limit.min.x, limit.max.x);
261
+ target.y = clamp(target.y, limit.min.y, limit.max.y);
262
+ return target;
263
+ }
264
+ /**
265
+ * What a caster shows: its live instances, which of them are visible, and where they are.
266
+ * @param mesh - A shadow caster.
267
+ * @returns A string that changes when any of those does.
268
+ */
269
+ function instanceSignature(mesh) {
270
+ const instanced = mesh;
271
+ if (instanced.instancesCount === undefined || !instanced.getVisibleAt)
272
+ return '';
273
+ let visible = 0;
274
+ for (let id = 0; id < instanced.instancesCount; id++) {
275
+ if (instanced.getVisibleAt(id))
276
+ visible = (visible * 31 + id + 1) | 0;
277
+ }
278
+ return `${instanced.instancesCount}/${visible}/${instanced.matricesTexture?.version ?? 0}`;
279
+ }
280
+ /**
281
+ * One corner of a box.
282
+ * @param box - The box.
283
+ * @param corner - `0`–`7`, one bit per axis.
284
+ * @param target - Receives the corner.
285
+ * @returns `target`.
286
+ */
287
+ function cornerOf(box, corner, target) {
288
+ return target.set(corner & 1 ? box.max.x : box.min.x, corner & 2 ? box.max.y : box.min.y, corner & 4 ? box.max.z : box.min.z);
289
+ }
290
+ /** The shadow map's width and height, in texels: about 64 MB of depth. */
291
+ export const SHADOW_MAP_SIZE = 4096;
292
+ /** The shadow lookup's spread, in texels. */
293
+ export const SHADOW_RADIUS = 2;
294
+ /**
295
+ * Just below the floor. 2D content writes no depth, so the catcher draws over the floor, and a
296
+ * model's own ground, which writes depth, hides it cleanly.
297
+ */
298
+ export const CATCHER_ELEVATION = -0.5;
299
+ /** The catcher draws after every other transparent object, so it shades whatever floor they drew. */
300
+ export const CATCHER_RENDER_ORDER = 1e6;
301
+ /**
302
+ * How far the view may zoom in before the map refits to it. `2` refits at half the fitted size;
303
+ * `√2` refits twice as often during a zoom and keeps edges up to `√2` times sharper meanwhile.
304
+ */
305
+ const REFIT_ZOOM_IN = Math.SQRT2;
306
+ /** How much wider than the view the fitted area is. */
307
+ const FIT_MARGIN = 1.25;
308
+ /** `groundCorner`'s index for the screen center. */
309
+ const CENTER = -1;
310
+ let _lastSignature = '';
311
+ /** The casters found by {@link readCasters}. */
312
+ const _casters = [];
313
+ /** The casters' nearest and farthest depth in the sun's view. */
314
+ const _depth = [0, 0];
315
+ /** The view fit: center x, center y, radius, in the sun's view. */
316
+ const _viewFit = [NaN, NaN, NaN];
317
+ const _bounds = new Box3();
318
+ const _box = new Box3();
319
+ const _boundsPlan = new Box3();
320
+ const _to = new Vector3();
321
+ const _corner = new Vector3();
322
+ const _footprint = new Vector3();
323
+ const _near = new Vector3();
324
+ const _far = new Vector3();
@@ -6,6 +6,7 @@ import { applyAmbientOcclusion } from './effects/ao';
6
6
  import { useDimPatch } from './effects/color-dim';
7
7
  import { applyContactShadow } from './effects/contact-shadow';
8
8
  import { useSceneEffects } from './effects/effects-context';
9
+ import { applySunShadow } from './effects/sun-shadow';
9
10
  import { overlayParams, sharedParams } from './shared';
10
11
  const logger = createLogger('color-material');
11
12
  /**
@@ -112,6 +113,7 @@ export function ColorMaterial(props) {
112
113
  if (solid) {
113
114
  applyContactShadow(parameters, effects);
114
115
  applyAmbientOcclusion(parameters, effects);
116
+ applySunShadow(parameters, effects);
115
117
  }
116
118
  dimPatch(parameters);
117
119
  };
@@ -1,10 +1,13 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useEffect, useState } from 'react';
3
3
  import { LessEqualDepth, } from 'three';
4
+ import { declareBeforeMain } from '../../core/shader-source';
5
+ import { DEFAULT_MODEL_OPACITY } from '../models/model-opacity';
4
6
  import { applyAmbientOcclusion } from './effects/ao';
5
7
  import { useDimPatch } from './effects/color-dim';
6
8
  import { applyContactShadow } from './effects/contact-shadow';
7
9
  import { useSceneEffects } from './effects/effects-context';
10
+ import { applySunShadow } from './effects/sun-shadow';
8
11
  /**
9
12
  * The material a model draws with: the GLB's own, cloned and adjusted for the plan's depth rules, for
10
13
  * the plan's shading, and for per-instance opacity.
@@ -91,16 +94,19 @@ function adjust(material, opacityUniform, dimPatch, effects, translucent) {
91
94
  // Applied at the end of the fragment chain, after `<dithering_fragment>`, so it multiplies the
92
95
  // final composed alpha rather than an intermediate one. The instanced mesh injects the uniform
93
96
  // fetch at the top of `main()`, so the name is in scope by the time this runs.
94
- parameters.fragmentShader = parameters.fragmentShader.replace('#include <dithering_fragment>',
97
+ // A slot holding a negative opacity defers to the shared default; see `model-opacity`.
98
+ parameters.uniforms[DEFAULT_OPACITY_UNIFORM] = DEFAULT_MODEL_OPACITY;
99
+ parameters.fragmentShader = declareBeforeMain(parameters.fragmentShader, `uniform float ${DEFAULT_OPACITY_UNIFORM};`).replace('#include <dithering_fragment>',
95
100
  /*glsl*/ `
96
101
  #include <dithering_fragment>
97
- gl_FragColor.a *= ${opacityUniform};
102
+ gl_FragColor.a *= ${opacityUniform} < 0. ? ${DEFAULT_OPACITY_UNIFORM} : ${opacityUniform};
98
103
  `.trim());
99
104
  // The plan's shading, ahead of the dim patch. All three insert above the same anchor, so the later
100
105
  // install runs last, and the order they run in is the order they describe: the shadow and the
101
106
  // occlusion shade the surface, and dimming desaturates the result.
102
107
  applyContactShadow(parameters, effects);
103
108
  applyAmbientOcclusion(parameters, effects);
109
+ applySunShadow(parameters, effects);
104
110
  // Dim touches rgb and opacity touches alpha, so the two patches stay independent in any order. Dim
105
111
  // lands ahead of the colorspace conversion either way, which is where a gamma-corrected darken has
106
112
  // to be.
@@ -109,3 +115,5 @@ function adjust(material, opacityUniform, dimPatch, effects, translucent) {
109
115
  material.needsUpdate = true;
110
116
  return material;
111
117
  }
118
+ /** The shared default opacity's uniform name. */
119
+ const DEFAULT_OPACITY_UNIFORM = 'uDefaultModelOpacity';
@@ -42,7 +42,9 @@ export function createAmbientOcclusion() {
42
42
  */
43
43
  export const OCCLUSION_DEFAULTS = {
44
44
  /** Whether the term runs at all. */
45
- enabled: true,
45
+ // Off by default: the sun shadow is the plan's main depth cue, and ambient occlusion costs
46
+ // three passes a frame.
47
+ enabled: false,
46
48
  /**
47
49
  * How far the term looks for an occluder, in plan units.
48
50
  *
@@ -15,8 +15,15 @@ import { Color, type IUniform, Matrix4, type WebGLProgramParametersWithUniforms
15
15
  export interface ContactShadow {
16
16
  /** The shadow's reach above a volume's base, in plan units. */
17
17
  shadowDistance: IUniform<number>;
18
- /** The shadow's depth, from `0` to `1`. */
18
+ /**
19
+ * The depth the shader blends to, from `0` to `1`: {@link ContactShadow.contactStrength} while the
20
+ * term is on, `0` while it is off. Written through {@link writeContactStrength}.
21
+ */
19
22
  shadowStrength: IUniform<number>;
23
+ /** Whether the contact shadow draws. The shader has no switch, so off parks its depth at `0`. */
24
+ contactEnabled: boolean;
25
+ /** The depth the term draws at while on, from `0` to `1`, kept while it is off. */
26
+ contactStrength: number;
20
27
  /**
21
28
  * The shade both darkening terms blend toward.
22
29
  *
@@ -71,6 +78,11 @@ export interface ContactShadow {
71
78
  * after, either of which would leave the shadow silently absent from a material that asked for it.
72
79
  */
73
80
  export declare function applyContactShadow(parameters: WebGLProgramParametersWithUniforms, shadow: ContactShadow): void;
81
+ /**
82
+ * Writes the depth the shader blends to from the switch and the wanted depth.
83
+ * @param shadow - The scene's contact shadow state, written in place.
84
+ */
85
+ export declare function writeContactStrength(shadow: ContactShadow): void;
74
86
  /**
75
87
  * Builds this term's scene-wide state, at the agreed defaults.
76
88
  *
@@ -47,6 +47,13 @@ export function applyContactShadow(parameters, shadow) {
47
47
  parameters.vertexShader = vertexShader;
48
48
  parameters.fragmentShader = fragmentShader;
49
49
  }
50
+ /**
51
+ * Writes the depth the shader blends to from the switch and the wanted depth.
52
+ * @param shadow - The scene's contact shadow state, written in place.
53
+ */
54
+ export function writeContactStrength(shadow) {
55
+ shadow.shadowStrength.value = shadow.contactEnabled ? shadow.contactStrength : 0;
56
+ }
50
57
  /**
51
58
  * Builds this term's scene-wide state, at the agreed defaults.
52
59
  *
@@ -60,6 +67,8 @@ export function createContactShadow() {
60
67
  return {
61
68
  shadowDistance: { value: CONTACT_SHADOW_DEFAULTS.distance },
62
69
  shadowStrength: { value: CONTACT_SHADOW_DEFAULTS.strength },
70
+ contactEnabled: true,
71
+ contactStrength: CONTACT_SHADOW_DEFAULTS.strength,
63
72
  shadowColor: { value: new Color(CONTACT_SHADOW_DEFAULTS.color) },
64
73
  shadowHex: CONTACT_SHADOW_DEFAULTS.color,
65
74
  planFromWorld: { value: new Matrix4() },
@@ -0,0 +1,32 @@
1
+ import { type Color, type IUniform, Matrix4, type WebGLProgramParametersWithUniforms } from 'three';
2
+ /** The darkening in full shadow, from `0` to `1`. `Lighting` writes it every frame. */
3
+ export declare const SUN_SHADOW_STRENGTH: IUniform<number>;
4
+ /**
5
+ * View space → the sun's shadow-map coordinates, `shadow.matrix · camera.matrixWorld`, composed on
6
+ * the CPU in float64. In MapLibre mode the world unit is the whole Earth, so three's own lookup
7
+ * (`shadowMatrix · worldPosition` in float32) loses more depth than a building is tall. View-space
8
+ * positions are camera-relative and stay precise. `Lighting` writes it as the scene starts to draw,
9
+ * once the camera has moved for the frame.
10
+ */
11
+ export declare const SHADOW_FROM_VIEW: IUniform<Matrix4>;
12
+ /**
13
+ * Replaces the sun's shadow coordinate with the camera-relative one, and declares the lookup.
14
+ * @param parameters - The compiling program.
15
+ * @returns Whether the shader has a shadow coordinate to replace.
16
+ */
17
+ export declare function applySunShadowVertex(parameters: WebGLProgramParametersWithUniforms): boolean;
18
+ /**
19
+ * Installs the sun-shadow darkening ahead of the output chain, on a lit material.
20
+ * @param parameters - The compiling program.
21
+ * @param effects - The scene's effect state, for the shade every darkening term blends toward.
22
+ * @param effects.shadowColor - The shade.
23
+ */
24
+ export declare function applySunShadow(parameters: WebGLProgramParametersWithUniforms, effects: {
25
+ shadowColor: IUniform<Color>;
26
+ }): void;
27
+ /**
28
+ * Points the floor's shadow catcher at the same lookup.
29
+ * @param parameters - The compiling program.
30
+ */
31
+ export declare function applySunShadowCatcher(parameters: WebGLProgramParametersWithUniforms): void;
32
+ //# sourceMappingURL=sun-shadow.d.ts.map
@@ -0,0 +1,108 @@
1
+ import { Matrix4, ShaderChunk, } from 'three';
2
+ import { declareBeforeMain, replaceAnchor, sceneColorAnchor } from '../../../core/shader-source';
3
+ // Darkens a lit surface where the fixed, shadow-only sun cannot reach it.
4
+ //
5
+ // The sun casts the scene's only shadow map, so three sorts it to directional shadow index `0`. It
6
+ // has intensity `0` and only casts; the shadow it measures stands in for the share of light the
7
+ // camera-relative directional light gives, which is what `SUN_SHADOW_STRENGTH` holds.
8
+ //
9
+ // One lookup per pixel, ours, replaces three's two: three's light loop samples the map for the sun
10
+ // although its light is zero, and three's PCF rotates five taps by screen-space noise, which crawls
11
+ // across a still surface whenever the camera moves. Ours takes four fixed hardware-compare taps.
12
+ /** The darkening in full shadow, from `0` to `1`. `Lighting` writes it every frame. */
13
+ export const SUN_SHADOW_STRENGTH = { value: 0 };
14
+ /**
15
+ * View space → the sun's shadow-map coordinates, `shadow.matrix · camera.matrixWorld`, composed on
16
+ * the CPU in float64. In MapLibre mode the world unit is the whole Earth, so three's own lookup
17
+ * (`shadowMatrix · worldPosition` in float32) loses more depth than a building is tall. View-space
18
+ * positions are camera-relative and stay precise. `Lighting` writes it as the scene starts to draw,
19
+ * once the camera has moved for the frame.
20
+ */
21
+ export const SHADOW_FROM_VIEW = { value: new Matrix4() };
22
+ /**
23
+ * Replaces the sun's shadow coordinate with the camera-relative one, and declares the lookup.
24
+ * @param parameters - The compiling program.
25
+ * @returns Whether the shader has a shadow coordinate to replace.
26
+ */
27
+ export function applySunShadowVertex(parameters) {
28
+ if (parameters.vertexShader.includes(VIEW_UNIFORM))
29
+ return true;
30
+ // The patch needs three's shadow chunk, the place the shadow coordinate is written.
31
+ if (!parameters.vertexShader.includes(VERTEX_ANCHOR))
32
+ return false;
33
+ parameters.uniforms[VIEW_UNIFORM] = SHADOW_FROM_VIEW;
34
+ parameters.vertexShader = replaceAnchor(declareBeforeMain(parameters.vertexShader, `uniform mat4 ${VIEW_UNIFORM};`), VERTEX_ANCHOR, `${VERTEX_ANCHOR}\n${VERTEX_APPLY}`);
35
+ parameters.fragmentShader = declareBeforeMain(parameters.fragmentShader, LOOKUP);
36
+ return true;
37
+ }
38
+ /**
39
+ * Installs the sun-shadow darkening ahead of the output chain, on a lit material.
40
+ * @param parameters - The compiling program.
41
+ * @param effects - The scene's effect state, for the shade every darkening term blends toward.
42
+ * @param effects.shadowColor - The shade.
43
+ */
44
+ export function applySunShadow(parameters, effects) {
45
+ if (parameters.fragmentShader.includes(UNIFORM))
46
+ return;
47
+ const anchor = sceneColorAnchor(parameters.fragmentShader);
48
+ if (!anchor)
49
+ return;
50
+ if (!applySunShadowVertex(parameters))
51
+ return;
52
+ parameters.uniforms[UNIFORM] = SUN_SHADOW_STRENGTH;
53
+ parameters.uniforms[COLOR_UNIFORM] = effects.shadowColor;
54
+ parameters.fragmentShader = declareBeforeMain(parameters.fragmentShader, `uniform float ${UNIFORM};\nuniform vec3 ${COLOR_UNIFORM};`)
55
+ // three's own sample for the sun, whose light is zero anyway.
56
+ .replace('#include <lights_fragment_begin>', LIGHTS_WITHOUT_DIRECTIONAL_SHADOWS)
57
+ .replace(anchor, `${APPLY}\n${anchor}`);
58
+ }
59
+ /**
60
+ * Points the floor's shadow catcher at the same lookup.
61
+ * @param parameters - The compiling program.
62
+ */
63
+ export function applySunShadowCatcher(parameters) {
64
+ if (!applySunShadowVertex(parameters))
65
+ return;
66
+ parameters.fragmentShader = parameters.fragmentShader.replace('getShadowMask()', 'sunShadowLit()');
67
+ }
68
+ const UNIFORM = 'uSunShadowStrength';
69
+ /** The shade the contact shadow and ambient occlusion blend toward too. */
70
+ const COLOR_UNIFORM = 'uSunShadowColor';
71
+ const VIEW_UNIFORM = 'uShadowFromView';
72
+ const VERTEX_ANCHOR = /* glsl */ `#include <shadowmap_vertex>`;
73
+ const VERTEX_APPLY = /* glsl */ `
74
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
75
+ vDirectionalShadowCoord[ 0 ] = ${VIEW_UNIFORM} * vec4( mvPosition.xyz + normalize( transformedNormal ) * directionalLightShadows[ 0 ].shadowNormalBias, 1.0 );
76
+ #endif
77
+ `;
78
+ const LOOKUP = /* glsl */ `
79
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 && defined( SHADOWMAP_TYPE_PCF )
80
+ float sunShadowLit() {
81
+ vec4 coord = vDirectionalShadowCoord[ 0 ];
82
+ coord.z += directionalLightShadows[ 0 ].shadowBias;
83
+ if ( coord.x < 0.0 || coord.x > 1.0 || coord.y < 0.0 || coord.y > 1.0 || coord.z > 1.0 ) return 1.0;
84
+ // Four taps half a radius apart, each a hardware 2x2 compare: a fixed 4x4 footprint.
85
+ vec2 offset = directionalLightShadows[ 0 ].shadowRadius * 0.5 / directionalLightShadows[ 0 ].shadowMapSize;
86
+ return 0.25 * (
87
+ texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( -offset.x, -offset.y ), coord.z ) ) +
88
+ texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( offset.x, -offset.y ), coord.z ) ) +
89
+ texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( -offset.x, offset.y ), coord.z ) ) +
90
+ texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( offset.x, offset.y ), coord.z ) )
91
+ );
92
+ }
93
+ #else
94
+ float sunShadowLit() { return 1.0; }
95
+ #endif
96
+ `;
97
+ const APPLY = /* glsl */ `
98
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
99
+ if ( receiveShadow ) {
100
+ // Shadow-casting lights sort first, so the sun is directional light 0 as well.
101
+ float sunFacing = max( dot( normalize( normal ), directionalLights[ 0 ].direction ), 0.0 );
102
+ // A face turned from the sun keeps its color, so it skips the lookup.
103
+ float sunLit = sunFacing > 0.0 ? sunShadowLit() : 1.0;
104
+ gl_FragColor.rgb = mix( gl_FragColor.rgb, ${COLOR_UNIFORM}, min( ${UNIFORM} * sunFacing, 1.0 ) * ( 1.0 - sunLit ) );
105
+ }
106
+ #endif
107
+ `;
108
+ const LIGHTS_WITHOUT_DIRECTIONAL_SHADOWS = ShaderChunk.lights_fragment_begin.replace('( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )', '( UNROLLED_LOOP_INDEX < 0 )');