@expofp/renderer 3.49.2 → 3.51.0

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.
Files changed (66) hide show
  1. package/dist/Renderer.d.ts +2 -2
  2. package/dist/core/SquareDataTexture.d.ts +5 -0
  3. package/dist/core/SquareDataTexture.js +6 -0
  4. package/dist/core/batch/BatchedMesh.d.ts +12 -0
  5. package/dist/core/batch/BatchedMesh.js +29 -0
  6. package/dist/core/instanced/InstancedMesh.d.ts +5 -0
  7. package/dist/core/instanced/InstancedMesh.js +12 -0
  8. package/dist/core/sprites/BatchedSprites.js +2 -2
  9. package/dist/core/sprites/RaycastingSprites.d.ts +9 -1
  10. package/dist/core/sprites/RaycastingSprites.js +23 -3
  11. package/dist/core/sprites/sprite-material.js +5 -6
  12. package/dist/core/text/MemberTexture.js +2 -4
  13. package/dist/events/LayoutDriver.js +17 -1
  14. package/dist/events/layout-targets.js +30 -5
  15. package/dist/events/placement/box.d.ts +14 -0
  16. package/dist/events/placement/box.js +19 -2
  17. package/dist/events/placement/index.d.ts +1 -0
  18. package/dist/events/placement/index.js +1 -0
  19. package/dist/events/placement/pass.js +9 -8
  20. package/dist/events/pointer.d.ts +27 -6
  21. package/dist/events/pointer.js +50 -9
  22. package/dist/index.d.ts +1 -1
  23. package/dist/index.js +2 -2
  24. package/dist/objects/containers/SlotContainer.d.ts +5 -0
  25. package/dist/objects/containers/SlotContainer.js +7 -0
  26. package/dist/objects/images/Images.js +1 -1
  27. package/dist/objects/lighting/Lighting.d.ts +56 -38
  28. package/dist/objects/lighting/Lighting.js +136 -344
  29. package/dist/objects/lighting/lighting-gui.js +32 -18
  30. package/dist/objects/lighting/studio-environment.d.ts +15 -43
  31. package/dist/objects/lighting/studio-environment.js +18 -126
  32. package/dist/objects/lighting/sun-shadow-map.d.ts +39 -15
  33. package/dist/objects/lighting/sun-shadow-map.js +163 -26
  34. package/dist/objects/materials/ColorMaterial.d.ts +11 -8
  35. package/dist/objects/materials/ColorMaterial.js +33 -11
  36. package/dist/objects/materials/ModelMaterial.js +3 -2
  37. package/dist/objects/materials/OutlineMaterial.d.ts +21 -0
  38. package/dist/objects/materials/OutlineMaterial.js +77 -0
  39. package/dist/objects/materials/TextureMaterial.d.ts +10 -0
  40. package/dist/objects/materials/TextureMaterial.js +13 -2
  41. package/dist/objects/materials/effects/ao/index.d.ts +2 -5
  42. package/dist/objects/materials/effects/ao/index.js +4 -7
  43. package/dist/objects/materials/effects/contact-shadow.d.ts +21 -10
  44. package/dist/objects/materials/effects/contact-shadow.js +60 -16
  45. package/dist/objects/materials/effects/effects-context.d.ts +2 -1
  46. package/dist/objects/materials/effects/effects-context.js +2 -1
  47. package/dist/objects/materials/effects/side-shade.d.ts +40 -0
  48. package/dist/objects/materials/effects/side-shade.js +52 -0
  49. package/dist/objects/materials/effects/sun-shadow.d.ts +5 -21
  50. package/dist/objects/materials/effects/sun-shadow.js +56 -89
  51. package/dist/objects/models/Models.d.ts +3 -2
  52. package/dist/objects/models/Models.js +46 -8
  53. package/dist/objects/models/gltf-cache.js +1 -1
  54. package/dist/objects/models/model-asset.d.ts +84 -20
  55. package/dist/objects/models/model-asset.js +171 -40
  56. package/dist/objects/models/model-container.d.ts +46 -10
  57. package/dist/objects/models/model-container.js +92 -19
  58. package/dist/objects/shapes/Shapes.js +11 -6
  59. package/dist/objects/shapes/shape-container.d.ts +3 -2
  60. package/dist/objects/shapes/shape-container.js +6 -4
  61. package/dist/objects/shapes/shape-geometry.d.ts +16 -4
  62. package/dist/objects/shapes/shape-geometry.js +17 -13
  63. package/dist/types/defs.d.ts +30 -1
  64. package/dist/utils/math.d.ts +14 -0
  65. package/dist/utils/math.js +20 -0
  66. package/package.json +2 -2
@@ -2,27 +2,27 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { degToRad } from '@expofp/geometry';
3
3
  import { useFrame, useThree } from '@react-three/fiber';
4
4
  import { useEffect, useLayoutEffect, useRef, useState } from 'react';
5
- import { Color, Matrix4, Vector3, } from 'three';
5
+ import { Matrix4, Vector3, } from 'three';
6
6
  import { useSpace } from '../../space/Space';
7
- import { createLogger } from '../../utils/logging';
8
7
  import { clamp } from '../../utils/math';
9
8
  import { writeContactStrength } from '../materials/effects/contact-shadow';
10
9
  import { useSceneEffects } from '../materials/effects/effects-context';
11
- import { applySunShadowCatcher, SHADOW_FROM_VIEW, SUN_SHADOW_STRENGTH, } from '../materials/effects/sun-shadow';
10
+ import { applySunShadow, SHADOW_FROM_VIEW } from '../materials/effects/sun-shadow';
12
11
  import { setDefaultModelOpacity } from '../models/model-opacity';
13
12
  import { useLightingGui } from './lighting-gui';
14
- import { hasLitMaterial, loadStudioEnvironment, markEnvironmentPending, orientEnvironment, STUDIO_HDRI_URL, } from './studio-environment';
15
- import { aimSun, CATCHER_ELEVATION, CATCHER_RENDER_ORDER, enableShadowMaps, fitShadowCamera, hasVisibleCaster, SHADOW_MAP_SIZE, SHADOW_RADIUS, } from './sun-shadow-map';
16
- const logger = createLogger('lighting');
13
+ import { createStudioEnvironment, hasLitMaterial, orientEnvironment, } from './studio-environment';
14
+ import { aimSun, CATCHER_ELEVATION, CATCHER_RENDER_ORDER, enableShadowMaps, fitShadowCamera, hasVisibleCaster, syncMovingSun, } from './sun-shadow-map';
17
15
  /**
18
- * Scene lighting: a hemisphere fill along the plan's up axis, and a warm directional light at a
19
- * fixed pitch on the camera's heading. The one intensity control is `contrast`, and `Lighting`
20
- * derives both `π`-unit intensities from it every frame — so an up-facing surface (a roof) lands on
21
- * its authored color and no surface the design accounts for clips.
16
+ * Scene lighting: a directional light from the fixed sun, which casts the shadow too, and the studio
17
+ * environment. A GUI toggle puts the light back on the camera's heading at a fixed pitch.
18
+ *
19
+ * **One rule keeps a roof at its color: the sun and the studio sum to `1` on an up-facing surface.**
20
+ * The sun gives a roof `sun · cos θ`, and the studio fills the rest. Walls are darker than roofs
21
+ * because the solid shapes' side shade darkens their albedo, not because the rig is balanced
22
+ * against them, so nothing here searches for a clip.
22
23
  *
23
24
  * That is also why the renderer skips tone mapping (see `Renderer.tsx` and `ExternalCanvas.tsx`): a
24
- * curve brings an unbounded light sum back into range, and `contrast` keeps this rig's sum in range
25
- * to begin with, at every pitch.
25
+ * curve brings an unbounded light sum back into range, and this rig's sum is in range to begin with.
26
26
  *
27
27
  * Only lit materials see the lights — solid shape batches and models. Every 2D primitive draws
28
28
  * through a `MeshBasicMaterial`, so lines, text and images are unaffected.
@@ -33,18 +33,17 @@ const logger = createLogger('lighting');
33
33
  * under any fit. The directional light needs its target under the same matrix for that, since its
34
34
  * direction is the difference of two world positions.
35
35
  * @param props - The values a caller set, any subset; see {@link LightingProps}.
36
- * @returns The two lights, and the directional light's target.
36
+ * @returns The two lights, the directional light's target, and the shadow catcher.
37
37
  */
38
38
  export function Lighting(props) {
39
- const { contrast, skyColor, groundColor, directionalColor, shadowColor, modelOpacity } = props;
39
+ const { sun, shadowColor, modelOpacity } = props;
40
40
  // Down to the primitives here rather than in the effect below, so the effect runs when a value
41
41
  // really moved. A caller writing `lighting={{ sunShadow: {...} }}` inline hands a fresh object
42
42
  // every render, and an object in the dependency list would re-apply and redraw on each of them.
43
- const { share: environmentShare, rotationDegrees: environmentRotation } = props.environment ?? {};
43
+ const { rotationDegrees: environmentRotation } = props.environment ?? {};
44
44
  const { enabled: sunEnabled, headingDegrees: sunHeading, elevationDegrees: sunElevation, strength: sunStrength, } = props.sunShadow ?? {};
45
45
  const { enabled: contactEnabled, distance: contactDistance, strength: contactStrength, } = props.contactShadow ?? {};
46
46
  const { enabled: occlusionEnabled, radius: occlusionRadius, strength: occlusionStrength, } = props.ambientOcclusion ?? {};
47
- const fillRef = useRef(null);
48
47
  const directionalRef = useRef(null);
49
48
  const targetRef = useRef(null);
50
49
  const space = useSpace();
@@ -53,53 +52,33 @@ export function Lighting(props) {
53
52
  // `useState` rather than `useRef` so the render body may read it, the way `useDimPatch` holds its
54
53
  // patch.
55
54
  const [settings] = useState(copyDefaults);
56
- // What each light's color was last set from, so a hex string is parsed on change, not per frame.
57
- const appliedRef = useRef({ sky: '', ground: '', directional: '' });
55
+ // What the derived rig was last computed from; the first frame differs in every field.
56
+ const derivedRef = useRef({
57
+ pitch: NaN,
58
+ studio: undefined,
59
+ sun: NaN,
60
+ strength: NaN,
61
+ });
58
62
  const catcherRef = useRef(null);
59
- const sunRef = useRef(null);
63
+ const movingSunRef = useRef(null);
60
64
  const get = useThree((state) => state.get);
61
- const [studio, setStudio] = useState(null);
65
+ // Made in the first frame that holds a lit material, so a plan of flat 2D content never renders the
66
+ // studio. Made inside a frame because that is where this renderer owns the GL state, which matters
67
+ // in external mode, where the context is the host's.
68
+ const studioRef = useRef(null);
62
69
  useLayoutEffect(() => {
63
70
  directionalRef.current.target = targetRef.current;
64
- sunRef.current.target = targetRef.current;
71
+ movingSunRef.current.target = targetRef.current;
65
72
  }, []);
66
- // The studio HDRI, prefiltered once, plus its irradiance for the roof pin. It loads once the scene
67
- // holds a lit material, so a plan of flat 2D content skips the download.
68
- const [wantsEnvironment, setWantsEnvironment] = useState(false);
69
- useEffect(() => {
70
- if (!wantsEnvironment)
71
- return undefined;
72
- let disposed = false;
73
- let loaded = null;
74
- // Read by the story screenshot helper, which waits for the HDRI as it waits for a frame.
75
- markEnvironmentPending(get().scene, true);
76
- loadStudioEnvironment(get().gl, STUDIO_HDRI_URL).then((environment) => {
77
- if (disposed) {
78
- environment.texture.dispose();
79
- return;
80
- }
81
- loaded = environment;
82
- // Still pending: the frame that applies it clears the flag. A frame asked for here could run
83
- // before React commits the new state, draw without the HDRI, and read as settled.
84
- setStudio(environment);
85
- }, (error) => {
86
- markEnvironmentPending(get().scene, false);
87
- logger.warn('failed to load the studio HDRI: %O', error);
88
- });
89
- return () => {
90
- disposed = true;
91
- const { scene } = get();
92
- markEnvironmentPending(scene, false);
93
- if (scene.environment && scene.environment === loaded?.texture)
94
- scene.environment = null;
95
- loaded?.texture.dispose();
96
- };
97
- }, [get, invalidate, wantsEnvironment]);
98
- // The frame that applies the HDRI, asked for once React has committed it.
99
- useEffect(() => {
100
- if (studio)
101
- invalidate();
102
- }, [studio, invalidate]);
73
+ // The studio goes with the mount: three keeps the texture's GPU copy until it is disposed.
74
+ useEffect(() => () => {
75
+ const { scene } = get();
76
+ const studio = studioRef.current;
77
+ if (scene.environment && scene.environment === studio?.texture)
78
+ scene.environment = null;
79
+ studio?.texture.dispose();
80
+ studioRef.current = null;
81
+ }, [get]);
103
82
  // Turns the renderer's shadow maps on; each light opts in with `castShadow`.
104
83
  useEffect(() => {
105
84
  enableShadowMaps(get());
@@ -114,18 +93,22 @@ export function Lighting(props) {
114
93
  const previous = scene.onBeforeRender;
115
94
  scene.onBeforeRender = (renderer, drawnScene, camera, ...rest) => {
116
95
  previous.call(scene, renderer, drawnScene, camera, ...rest);
117
- const sun = sunRef.current;
96
+ const sun = directionalRef.current;
118
97
  if (!sun)
119
98
  return;
120
- // The sun casts while some model can; the shadow map and the floor catcher exist only then. Decided here, before three counts the lights that cast for this frame.
99
+ // The sun casts while some mesh can; the shadow map and the catcher exist only then. Decided
100
+ // here, before three counts the lights that cast for this frame.
121
101
  const casting = settings.sunShadow.enabled && hasVisibleCaster(scene);
122
102
  sun.castShadow = casting;
123
103
  catcherRef.current.visible = casting;
124
- if (!casting)
104
+ if (!casting) {
105
+ syncMovingSun(movingSunRef.current, sun, false);
125
106
  return;
107
+ }
126
108
  // Fitted here, after camera-controls has moved the camera, so a fast zoom is measured with the
127
109
  // camera this frame draws with.
128
110
  fitShadowCamera(sun, scene, space, catcherRef.current, camera);
111
+ syncMovingSun(movingSunRef.current, sun, hasVisibleCaster(scene, true));
129
112
  sun.shadow.updateMatrices(sun);
130
113
  _cameraWorld.copy(camera.matrixWorldInverse).invert();
131
114
  SHADOW_FROM_VIEW.value.multiplyMatrices(sun.shadow.matrix, _cameraWorld);
@@ -140,11 +123,8 @@ export function Lighting(props) {
140
123
  // `OcclusionPasses` keep for their own writes.
141
124
  useEffect(() => {
142
125
  applyLightValues(settings, {
143
- contrast,
144
- skyColor,
145
- groundColor,
146
- directionalColor,
147
- environment: { share: environmentShare, rotationDegrees: environmentRotation },
126
+ sun,
127
+ environment: { rotationDegrees: environmentRotation },
148
128
  sunShadow: {
149
129
  enabled: sunEnabled,
150
130
  headingDegrees: sunHeading,
@@ -174,11 +154,7 @@ export function Lighting(props) {
174
154
  settings,
175
155
  effects,
176
156
  invalidate,
177
- contrast,
178
- skyColor,
179
- groundColor,
180
- directionalColor,
181
- environmentShare,
157
+ sun,
182
158
  environmentRotation,
183
159
  sunEnabled,
184
160
  sunHeading,
@@ -198,73 +174,75 @@ export function Lighting(props) {
198
174
  useLightingGui(settings);
199
175
  // Runs only on frames something already asked for, and camera movement is what asks for them.
200
176
  useFrame((state) => {
201
- const fill = fillRef.current;
202
177
  const directional = directionalRef.current;
203
178
  const scene = state.scene;
204
- if (!wantsEnvironment && hasLitMaterial(scene)) {
205
- // Marked here, in the frame that decides, so the scene reads as unsettled from this frame on,
206
- // through the effect that starts the load.
207
- markEnvironmentPending(scene, true);
208
- setWantsEnvironment(true);
179
+ if (!studioRef.current && hasLitMaterial(scene)) {
180
+ studioRef.current = createStudioEnvironment(state.gl);
209
181
  }
182
+ const studio = studioRef.current;
210
183
  aimDirectionalLight(state.camera, space, settings, directional.position);
211
- // The plan's up axis, as a point whose world position lands back on it — which is what three
212
- // reads a hemisphere light's sky axis from. Recomputed rather than memoized, because the space
213
- // is refitted in place and never changes identity.
214
- fill.position
215
- .setFromMatrixColumn(space.matrix, 2)
216
- .normalize()
217
- .applyMatrix4(space.matrixInverse);
218
- // Here rather than as JSX props: the GUI mutates `settings` in place and asks for a redraw, not
219
- // for a React render, so a prop would hold whatever the value was at mount. `applyColor` parses
220
- // a hex string only when it changed, so a still rig costs three comparisons a frame.
221
- applyColor(fill.color, settings.skyColor, appliedRef.current, 'sky');
222
- applyColor(fill.groundColor, settings.groundColor, appliedRef.current, 'ground');
223
- applyColor(directional.color, settings.directionalColor, appliedRef.current, 'directional');
224
- // The pitch as aimed, not `settings.pitchDegrees`: `trackPitch` takes it from the camera instead.
184
+ // The rest of the rig is a function of a few inputs that a prop or the GUI moves, so it is
185
+ // derived when one of them moved and left alone otherwise. The pitch is the one as aimed, not
186
+ // `settings.pitchDegrees`: the sun and `trackPitch` set it otherwise.
225
187
  const pitch = Math.acos(clamp(directional.position.z, -1, 1));
226
- // Defensive only: the slider never leaves `0`–`1`, but a value set out of band must not hand an
227
- // over-range contrast to a ceiling that assumes one.
228
- const contrast = clamp(settings.contrast, 0, 1);
229
- // The HDRI's share comes off the roof's budget first; the rig fills what is left.
230
- const share = studio ? clamp(settings.environment.share, 0, 1) : 0;
231
- const environmentIntensity = studio ? share / peakChannel(studio.up) : 0;
232
- const env = {
233
- intensity: environmentIntensity,
234
- up: studio?.up ?? BLACK,
235
- // The HDRI's light on a wall averaged over every heading, so the rig stays the same as the
236
- // camera turns and a low, bright sun in the HDRI leaves room for the directional light.
237
- wall: studio?.wall ?? BLACK,
238
- };
239
- const { hemisphereIntensity, directionalIntensity } = intensitiesFromContrast(contrast, pitch, fill.color, fill.groundColor, directional.color, env);
240
- fill.intensity = hemisphereIntensity * Math.PI;
241
- directional.intensity = directionalIntensity * Math.PI;
242
- const environment = studio && share > 0 ? studio.texture : null;
243
- if (scene.environment !== environment)
244
- scene.environment = environment;
245
- if (studio)
246
- markEnvironmentPending(scene, false);
247
- scene.environmentIntensity = environmentIntensity;
248
- orientEnvironment(space, settings.environment.rotationDegrees, scene.environmentRotation);
249
- // The camera-relative lights light; the sun only casts.
250
- const sun = sunRef.current;
251
- SUN_SHADOW_STRENGTH.value = 0;
252
- if (settings.sunShadow.enabled) {
253
- sun.shadow.radius = SHADOW_RADIUS;
254
- sun.shadow.mapSize.set(SHADOW_MAP_SIZE, SHADOW_MAP_SIZE);
255
- aimSun(settings, sun.position);
256
- catcherRef.current.material.color.copy(effects.shadowColor.value);
257
- // How far a roof and the floor in full shadow blend toward the shadow color: a fixed value, so
258
- // the sun's shadow stays the same as the camera and its camera-relative rig turn.
259
- const strength = clamp(settings.sunShadow.strength, 0, 1);
260
- catcherRef.current.material.opacity = strength;
261
- // Divided by the sun's height so a roof loses exactly `strength`; the shader weighs each face
262
- // by how squarely it faces the sun, and a face turned away loses nothing.
263
- SUN_SHADOW_STRENGTH.value =
264
- strength / Math.max(Math.sin(degToRad(settings.sunShadow.elevationDegrees)), 0.05);
188
+ const inputs = derivedRef.current;
189
+ if (inputs.pitch !== pitch ||
190
+ inputs.studio !== studio ||
191
+ inputs.sun !== settings.sun ||
192
+ inputs.strength !== settings.sunShadow.strength) {
193
+ inputs.pitch = pitch;
194
+ inputs.studio = studio;
195
+ inputs.sun = settings.sun;
196
+ inputs.strength = settings.sunShadow.strength;
197
+ applyDerivedRig(inputs, directional, catcherRef.current, scene);
265
198
  }
199
+ orientEnvironment(space, settings.environment.rotationDegrees, scene.environmentRotation);
266
200
  });
267
- return (_jsxs(_Fragment, { children: [_jsx("hemisphereLight", { ref: fillRef, color: LIGHT_DEFAULTS.skyColor, groundColor: LIGHT_DEFAULTS.groundColor, intensity: DEFAULT_INTENSITIES.hemisphereIntensity * Math.PI }), _jsx("directionalLight", { ref: directionalRef, color: LIGHT_DEFAULTS.directionalColor, intensity: DEFAULT_INTENSITIES.directionalIntensity * Math.PI }), _jsx("object3D", { ref: targetRef }), _jsx("directionalLight", { ref: sunRef, intensity: 0 }), _jsxs("mesh", { ref: catcherRef, position: [0, 0, CATCHER_ELEVATION], receiveShadow: true, renderOrder: CATCHER_RENDER_ORDER, raycast: () => null, visible: false, children: [_jsx("planeGeometry", { args: [1, 1] }), _jsx("shadowMaterial", { color: "#000000", depthWrite: false, onBeforeCompile: applySunShadowCatcher })] })] }));
201
+ return (_jsxs(_Fragment, { children: [_jsx("directionalLight", { ref: directionalRef, intensity: LIGHT_DEFAULTS.sun * Math.PI }), _jsx("object3D", { ref: targetRef }), _jsx("directionalLight", { ref: movingSunRef, intensity: 0, visible: false }), _jsxs("mesh", { ref: catcherRef, position: [0, 0, CATCHER_ELEVATION], receiveShadow: true, renderOrder: CATCHER_RENDER_ORDER, raycast: () => null, visible: false, children: [_jsx("planeGeometry", { args: [1, 1] }), _jsx("shadowMaterial", { color: "#000000", depthWrite: false, onBeforeCompile: applySunShadow })] })] }));
202
+ }
203
+ /**
204
+ * The shadow catcher's opacity, so the unlit floor darkens by the fraction a lit up-facing surface
205
+ * does.
206
+ *
207
+ * The lit surface loses `strength * share` of its light, a linear fraction. The catcher blends black
208
+ * into the encoded image, so the same fraction there is `1 - (1 - strength * share) ^ (1 / gamma)`.
209
+ * The catcher's shadow mask carries `strength` already, so that is divided out; at `strength` `0` the
210
+ * limit is `share / gamma`.
211
+ * @param strength - The sun shadow's strength, `0` to `1`.
212
+ * @param sunShare - The sun's share of a roof's light, `0` to `1`.
213
+ * @returns The opacity, `0` to `1`.
214
+ */
215
+ function catcherOpacity(strength, sunShare) {
216
+ if (strength <= 0)
217
+ return sunShare / DISPLAY_GAMMA;
218
+ const encodedLoss = 1 - (1 - strength * sunShare) ** (1 / DISPLAY_GAMMA);
219
+ return clamp(encodedLoss / strength, 0, 1);
220
+ }
221
+ /** The display's transfer curve, as a pure power: close enough to sRGB for a darkening fraction. */
222
+ const DISPLAY_GAMMA = 2.2;
223
+ /**
224
+ * Derives the sun's and the studio's intensities from {@link DerivedInputs} and writes them, with the
225
+ * sun's shadow. Run when an input moved, not every frame.
226
+ *
227
+ * The sun gives a roof `sun · cos θ` of its color, and the studio fills the rest, so a roof sums to
228
+ * `1`. A sun under the horizon gives a roof nothing, and the studio fills all of it.
229
+ * @param inputs - What this run was triggered by.
230
+ * @param directional - The sun.
231
+ * @param catcher - The shadow catcher, whose opacity follows the sun's share of a roof.
232
+ * @param scene - The scene, for the studio.
233
+ */
234
+ function applyDerivedRig(inputs, directional, catcher, scene) {
235
+ const { pitch, studio } = inputs;
236
+ const sun = clamp(inputs.sun, 0, 1);
237
+ const sunShare = sun * Math.max(Math.cos(pitch), 0);
238
+ directional.intensity = sun * Math.PI;
239
+ const environment = studio && sunShare < 1 ? studio.texture : null;
240
+ if (scene.environment !== environment)
241
+ scene.environment = environment;
242
+ scene.environmentIntensity = studio ? (1 - sunShare) / studio.up : 0;
243
+ const strength = clamp(inputs.strength, 0, 1);
244
+ directional.shadow.intensity = strength;
245
+ catcher.material.opacity = catcherOpacity(strength, sunShare);
268
246
  }
269
247
  /**
270
248
  * A fresh rig from the defaults, its nested groups copied too, so each mount owns its own.
@@ -286,17 +264,9 @@ function copyDefaults() {
286
264
  * @param values - What the caller gave, any subset of it.
287
265
  */
288
266
  function applyLightValues(settings, values) {
289
- if (values.contrast !== undefined)
290
- settings.contrast = values.contrast;
291
- if (values.skyColor !== undefined)
292
- settings.skyColor = values.skyColor;
293
- if (values.groundColor !== undefined)
294
- settings.groundColor = values.groundColor;
295
- if (values.directionalColor !== undefined)
296
- settings.directionalColor = values.directionalColor;
267
+ if (values.sun !== undefined)
268
+ settings.sun = values.sun;
297
269
  const environment = values.environment ?? {};
298
- if (environment.share !== undefined)
299
- settings.environment.share = environment.share;
300
270
  if (environment.rotationDegrees !== undefined) {
301
271
  settings.environment.rotationDegrees = environment.rotationDegrees;
302
272
  }
@@ -347,9 +317,11 @@ function applyShadowValues(effects, values) {
347
317
  /**
348
318
  * Aims the directional light, in the plan's own space, where up is `+z`.
349
319
  *
350
- * With `trackPitch` on it copies the camera's backward axis, which is the pre-overhaul behavior.
351
- * Otherwise it takes the plan heading from the camera and holds the configured pitch. A fixed pitch
352
- * pins the exact-albedo surface to the up-facing one, which on a floor plan carries the brand color.
320
+ * By default it points from the fixed sun, so it stands still as the camera turns and agrees with
321
+ * the shadow. With `followCamera` on, and `trackPitch` on as well, it copies the camera's backward
322
+ * axis, which is the pre-overhaul behavior. With `followCamera` on alone it takes the plan heading
323
+ * from the camera and holds the configured pitch. Either fixed pitch pins the exact-albedo surface
324
+ * to the up-facing one, which on a floor plan carries the brand color.
353
325
  *
354
326
  * **The heading comes from the camera's up axis.** The forward axis points straight down at pitch
355
327
  * `0`, the default resting pitch, so its ground projection is zero there and the heading would be
@@ -366,11 +338,13 @@ function applyShadowValues(effects, values) {
366
338
  * `(-cos θ · heading, sin θ)`, so negating recovers the direction the camera is on.
367
339
  * @param camera - The scene camera.
368
340
  * @param space - The scene's space, for the plan-to-world mapping.
369
- * @param settings - The rig, for `trackPitch` and the pitch.
341
+ * @param settings - The rig, for the sun, `followCamera`, `trackPitch` and the pitch.
370
342
  * @param target - Receives the direction.
371
343
  * @returns `target`, unit length.
372
344
  */
373
345
  function aimDirectionalLight(camera, space, settings, target) {
346
+ if (!settings.followCamera)
347
+ return aimSun(settings, target);
374
348
  // Columns 1 and 2 of `matrixWorld` are the camera's up and backward axes. Read directly rather
375
349
  // than through `Camera.getWorldDirection`, which re-runs `updateWorldMatrix` and leaves
376
350
  // `matrixWorldNeedsUpdate` set on every call — which kept the scene dirty and no screenshot ever
@@ -389,215 +363,33 @@ function aimDirectionalLight(camera, space, settings, target) {
389
363
  .setZ(Math.cos(pitch));
390
364
  }
391
365
  /**
392
- * Sets a light's color from a hex string, parsing only when the string changed.
393
- *
394
- * `Color.set` converts sRGB to the working space, and a string moves only when a color controller
395
- * writes a new one.
396
- * @param target - The color to write.
397
- * @param hex - The CSS hex string to set it from.
398
- * @param applied - What each color was last set from.
399
- * @param key - Which entry of `applied` this color owns.
400
- */
401
- function applyColor(target, hex, applied, key) {
402
- if (applied[key] === hex)
403
- return;
404
- target.set(hex);
405
- applied[key] = hex;
406
- }
407
- /**
408
- * The largest directional intensity (`d`, in `π` units) a wall facing the light can take at this
409
- * pitch and these colors before some channel of it clips — `contrast = 1`'s own `d`.
410
- *
411
- * **No closed form.** {@link intensitiesFromContrast} ties `h` to `d` through a `min` over channels,
412
- * which folds a channel selection into the middle of the wall's own expression; solving that
413
- * algebraically means guessing which channel governs *before* knowing `d`, and the answer can change
414
- * with `d`. Bisecting sidesteps the guess entirely and is exact for any sky, ground and directional
415
- * color, at the cost of a loop three's own frame budget does not notice.
416
- *
417
- * **The search interval's top is where `h` would reach `0`** — pure directional light, nothing from
418
- * the hemisphere — which is `1 / (max_c(k_c) · cos θ)`. Past it {@link intensitiesFromContrast} would
419
- * have to hand back a negative hemisphere intensity, which no real light has, so the search never
420
- * looks there. `litWallPeak` is monotone increasing in `d` once `h(d)` is substituted in (a fact
421
- * about this rig's own shape, not something this function re-derives), so a single bisection over
422
- * this interval finds the point where the lit wall reaches exactly `1`.
423
- *
424
- * **A shallow pitch may never reach `1` at all** — at or below `45°` a wall never receives more
425
- * directional light than a roof, so raising `d` only ever pulls the wall *toward* the roof's own
426
- * value, never past it. Detected by checking the interval's own top rather than by an angle test,
427
- * so the same check also covers a pitch just above `45°` whose colors still cannot clip a wall within
428
- * this interval. When that happens the interval's top is `d_max` outright: it is the most directional
429
- * light the rig can take at all, clipping or not, so it is also the most `contrast = 1` can mean.
430
- *
431
- * **The ceiling falls as the pitch steepens past that point**, which reads backward on first glance:
432
- * a steeper pitch sends relatively more of a fixed `d` into the wall (`sin θ` rising) and relatively
433
- * less into the roof (`cos θ` falling), so less directional intensity is needed before the wall
434
- * clips. `contrast = 1` is always the most the rig can take at its own pitch, but "the most" is a
435
- * smaller number at a grazing pitch than at a gentle one.
436
- * @param pitchRadians - The directional light's angle from the plan's up axis, as aimed.
437
- * @param sky - The hemisphere's sky color, linear.
438
- * @param ground - The hemisphere's ground color, linear.
439
- * @param directionalColor - The directional light's color, linear.
440
- * @param env - The HDRI's share of the light, and what it gives a roof and a wall.
441
- * @returns The directional intensity ceiling, in `π` units.
442
- */
443
- function maxDirectional(pitchRadians, sky, ground, directionalColor, env = NO_ENVIRONMENT) {
444
- const cos = Math.cos(pitchRadians);
445
- // Where `h` reaches `0` once the HDRI took its own share of each channel.
446
- let ceiling = Infinity;
447
- for (const channel of CHANNELS) {
448
- // Guards a grazing or past-vertical pitch, where `cos` is at or below `0`: without this the
449
- // interval's top would be infinite, negative, or both.
450
- const left = Math.max(1 - env.intensity * env.up[channel], 0);
451
- ceiling = Math.min(ceiling, left / Math.max(directionalColor[channel] * cos, MIN_PEAK));
452
- }
453
- if (litWallPeak(ceiling, pitchRadians, sky, ground, directionalColor, env) < 1)
454
- return ceiling;
455
- let low = 0;
456
- let high = ceiling;
457
- for (let iteration = 0; iteration < BISECTION_ITERATIONS; iteration++) {
458
- const mid = (low + high) / 2;
459
- if (litWallPeak(mid, pitchRadians, sky, ground, directionalColor, env) < 1)
460
- low = mid;
461
- else
462
- high = mid;
463
- }
464
- return (low + high) / 2;
465
- }
466
- /**
467
- * The hemisphere and directional intensities, in `π` units, that pin an up-facing surface (a roof)
468
- * to exactly the authored sky color on whichever channel would clip first.
469
- *
470
- * `d` is `contrast` of the way from `0` to {@link maxDirectional}'s own ceiling for this pitch and
471
- * these colors — the normalization that gives `contrast` its fixed `0`–`1` range, in place of an
472
- * intensity ratio whose usable span moved with the pitch. `h` follows by solving three's own roof
473
- * expression, `h·s + d·k·cos θ`, for the value that lands each channel on exactly `1` and taking the
474
- * **minimum** across channels: the same "pin the brightest channel, leave the rest a shade under"
475
- * rule the roof pin has always used, read off in the other direction — the channel needing the least
476
- * `h` to reach `1` is the one that would otherwise run past it, so giving every channel that same,
477
- * smaller `h` leaves it exactly on `1` and the others a shade under, which reads as a faint tint
478
- * rather than a lost highlight, and holds even for a tinted sky.
479
- * @param contrast - `0` to `1`, already assumed in range.
480
- * @param pitchRadians - The directional light's angle from the plan's up axis, as aimed.
481
- * @param sky - The hemisphere's sky color, linear.
482
- * @param ground - The hemisphere's ground color, linear.
483
- * @param directionalColor - The directional light's color, linear.
484
- * @param env - The HDRI's share of the light, and what it gives a roof and a wall.
485
- * @returns The hemisphere and directional intensities, in `π` units.
486
- */
487
- function intensitiesFromContrast(contrast, pitchRadians, sky, ground, directionalColor, env = NO_ENVIRONMENT) {
488
- const directionalIntensity = contrast * maxDirectional(pitchRadians, sky, ground, directionalColor, env);
489
- const hemisphereIntensity = hemisphereForDirectional(directionalIntensity, pitchRadians, sky, directionalColor, env);
490
- return { hemisphereIntensity, directionalIntensity };
491
- }
492
- /**
493
- * The hemisphere intensity that pins a roof to exactly `1` on its brightest channel, given a
494
- * directional intensity already chosen.
495
- *
496
- * Solving `h·s_c + d·k_c·cos θ = 1` for `h` gives one candidate per channel; the **minimum** of them
497
- * is what leaves every channel at or under `1` (see {@link intensitiesFromContrast}'s own doc for
498
- * why the minimum, not the maximum, is the pinning rule stated in terms of `h`).
499
- * @param directionalIntensity - `d`, in `π` units.
500
- * @param pitchRadians - The directional light's angle from the plan's up axis, as aimed.
501
- * @param sky - The hemisphere's sky color, linear.
502
- * @param directionalColor - The directional light's color, linear.
503
- * @param env - The HDRI's share of the light, and what it gives a roof and a wall.
504
- * @returns The hemisphere intensity, in `π` units.
505
- */
506
- function hemisphereForDirectional(directionalIntensity, pitchRadians, sky, directionalColor, env = NO_ENVIRONMENT) {
507
- const cos = Math.cos(pitchRadians);
508
- let hemisphereIntensity = Infinity;
509
- for (const channel of CHANNELS) {
510
- // Guards a black sky channel, which would otherwise divide by zero. A channel that dark can
511
- // never carry a meaningful hemisphere contribution anyway, so flooring the divisor costs nothing
512
- // real.
513
- const skyChannel = Math.max(sky[channel], MIN_SKY);
514
- hemisphereIntensity = Math.min(hemisphereIntensity, (1 -
515
- directionalIntensity * directionalColor[channel] * cos -
516
- env.intensity * env.up[channel]) /
517
- skyChannel);
518
- }
519
- // An HDRI share of `1` leaves the hemisphere at `0`, its floor.
520
- return Math.max(hemisphereIntensity, 0);
521
- }
522
- /**
523
- * The peak channel of a wall facing the light, given a directional intensity already chosen and the
524
- * hemisphere intensity that pairs with it.
525
- * @param directionalIntensity - `d`, in `π` units.
526
- * @param pitchRadians - The directional light's angle from the plan's up axis, as aimed.
527
- * @param sky - The hemisphere's sky color, linear.
528
- * @param ground - The hemisphere's ground color, linear.
529
- * @param directionalColor - The directional light's color, linear.
530
- * @param env - The HDRI's share of the light, and what it gives a roof and a wall.
531
- * @returns The lit wall's brightest channel.
532
- */
533
- function litWallPeak(directionalIntensity, pitchRadians, sky, ground, directionalColor, env = NO_ENVIRONMENT) {
534
- const hemisphereIntensity = hemisphereForDirectional(directionalIntensity, pitchRadians, sky, directionalColor, env);
535
- const sin = Math.sin(pitchRadians);
536
- let peak = -Infinity;
537
- for (const channel of CHANNELS) {
538
- const wallMix = (ground[channel] + sky[channel]) / 2;
539
- peak = Math.max(peak, hemisphereIntensity * wallMix +
540
- directionalIntensity * directionalColor[channel] * sin +
541
- env.intensity * env.wall[channel]);
542
- }
543
- return peak;
544
- }
545
- /**
546
- * The rig this design agreed, and what each mount starts from.
547
- *
548
- * At any `contrast` the roof lands on `1.00`. At `contrast = 1` the lit wall reaches `1.00` as well,
549
- * and the separation section 03 of the design target asks for disappears, so the default stays well
550
- * under it.
366
+ * The sun's default share of a facing surface's color. Fitted to the efp3d sandbox at matched poses:
367
+ * at `0.3` its booths' sunward, third and shaded sides land within 7 levels of 255, sunward a little
368
+ * lighter and shaded a little darker. The studio's light on a wall changes more with the wall's
369
+ * heading than the sun's does, so this moves every side together more than it moves them apart.
551
370
  */
371
+ const SUN_DEFAULT = 0.3;
372
+ /** The rig this design agreed, and what each mount starts from. */
552
373
  const LIGHT_DEFAULTS = {
374
+ followCamera: false,
553
375
  trackPitch: false,
554
376
  pitchDegrees: 38,
555
- contrast: 0.3,
556
- skyColor: '#ffffff',
557
- groundColor: '#b9c1cc',
558
- directionalColor: '#fff3e6',
377
+ sun: SUN_DEFAULT,
378
+ // The efp3d sandbox's studio, unturned: its scene and the plan share their axes once the plan
379
+ // stands upright.
559
380
  environment: {
560
- share: 0.5,
561
- rotationDegrees: 180,
381
+ rotationDegrees: 0,
562
382
  },
563
383
  sunShadow: {
564
384
  enabled: true,
565
- // An afternoon sun, low enough for long shadows across the floor.
566
- headingDegrees: -55,
567
- elevationDegrees: 48,
568
- strength: 0.3,
385
+ // The look-dev sandbox's sun: azimuth 143° clockwise from plan-up.
386
+ headingDegrees: -53,
387
+ elevationDegrees: 60,
388
+ // Measured against the look-dev sandbox: a surface in full shadow loses 5 to 6 percent of its
389
+ // encoded value there (14 of 240 on the floor), and 5.9 percent on this plan's floor here.
390
+ strength: 0.22,
569
391
  },
570
392
  };
571
- /** The color channels clipping is decided on, one at a time. */
572
- const CHANNELS = ['r', 'g', 'b'];
573
- // Declared before `DEFAULT_INTENSITIES` reads them at module init.
574
- const BLACK = new Color(0, 0, 0);
575
- const NO_ENVIRONMENT = { intensity: 0, up: BLACK, wall: BLACK };
576
- /** Bisection steps {@link maxDirectional} takes — cheap on a frame, and far past the precision the GUI's own slider step can show. */
577
- const BISECTION_ITERATIONS = 20;
578
- /**
579
- * The smallest sky channel {@link hemisphereForDirectional} divides by, so a black sky channel hands
580
- * back a large, finite hemisphere intensity rather than `Infinity`.
581
- */
582
- const MIN_SKY = 1e-6;
583
- /**
584
- * The smallest `directionalColor · cos θ` peak {@link maxDirectional} divides by, so a grazing or
585
- * past-vertical pitch hands back a large, finite ceiling rather than `Infinity` or a negative number.
586
- */
587
- const MIN_PEAK = 1e-6;
588
- /**
589
- * {@link LIGHT_DEFAULTS}' own intensities, computed once so a tree that mounts and never draws still
590
- * holds a sensible rig.
591
- */
592
- const DEFAULT_INTENSITIES = intensitiesFromContrast(LIGHT_DEFAULTS.contrast, degToRad(LIGHT_DEFAULTS.pitchDegrees), new Color(LIGHT_DEFAULTS.skyColor), new Color(LIGHT_DEFAULTS.groundColor), new Color(LIGHT_DEFAULTS.directionalColor));
593
393
  /** The camera's up axis, reused each frame so aiming allocates nothing. */
594
394
  const _up = new Vector3();
595
- /**
596
- * The brightest channel of a color.
597
- * @param color - The color.
598
- * @returns Its largest channel, never below `MIN_PEAK`.
599
- */
600
- function peakChannel(color) {
601
- return Math.max(color.r, color.g, color.b, MIN_PEAK);
602
- }
603
395
  const _cameraWorld = new Matrix4();