/** * `@voluma/vlam/relighting` — optional proxy-mesh screen-space relighting. * * This pre-v1 package composes a factor-map callback onto a standalone * `SplatMesh` or `UnifiedSplatMesh` display pass. It owns no caller * textures, proxy geometries, lights, scenes, or render targets. */ import * as THREE from 'three/webgpu'; import type { DisplayColorModifier } from '../core/splat-mesh-material'; import type { CollisionMeshTile } from '../formats/lcc/collision-mesh'; /** * Minimal renderer surface {@link renderRelightingFactorMap} needs. A real * `THREE.WebGPURenderer` satisfies this; tests can pass a stub. */ export type RelightingFactorRenderer = { autoClear: boolean; shadowMap: { enabled: boolean; autoUpdate?: boolean; }; getDrawingBufferSize(target: THREE.Vector2): THREE.Vector2; getRenderTarget(): THREE.RenderTarget | null; getActiveCubeFace(): number; getActiveMipmapLevel(): number; getMRT(): THREE.MRTNode | null; setMRT(mrt: THREE.MRTNode | null): void; setRenderTarget(target: THREE.RenderTarget | null, activeCubeFace?: number, activeMipmapLevel?: number): void; getClearColor(target: THREE.Color): THREE.Color; getClearAlpha(): number; setClearColor(color: THREE.ColorRepresentation, alpha?: number): void; clear(): void; render(scene: THREE.Object3D, camera: THREE.Camera): void; contextNode: unknown; }; /** * Renders `scene` from `camera` into `target` as a shadow-factor map: * resizes to the drawing buffer, clears **white + A0**, forces `autoClear` * and shadow maps on, and swaps in a passthrough `contextNode` so a host * ACES/sRGB wrap cannot turn the linear multiplier into speckle. * * Call each frame **before** `splats.update` / the main splat draw. Restore * is guaranteed even if `render` throws. */ export declare function renderRelightingFactorMap(renderer: RelightingFactorRenderer, scene: THREE.Scene, camera: THREE.Camera, target: THREE.RenderTarget): void; /** Defaults match PlayCanvas's 0.5-gray proxy convention. */ export declare const DEFAULT_RELIGHT_BLEND = 1; export declare const DEFAULT_RELIGHT_BRIGHTNESS = 2; export declare const DEFAULT_RELIGHT_BACKGROUND = 1; export declare const DEFAULT_RELIGHT_SOFTNESS = 0; /** Settings for a lit proxy RGBA factor map. */ export type RelightingSettings = { map: THREE.Texture; blend?: number; brightness?: number; background?: number; softness?: number; }; /** A live attachment update; omit `map` to retain the current caller-owned texture. */ export type RelightingUpdate = Partial; /** Resolved, live numeric relighting settings. */ export type RelightingUniforms = { blend: number; brightness: number; background: number; softness: number; }; /** Clamps the numeric relighting settings without taking ownership of the map. */ export declare function clampRelightingSettings(partial: Partial>, previous?: RelightingUniforms): RelightingUniforms; /** A target with the generic display-only callback contract. */ export type RelightingTarget = { displayColorModifier: DisplayColorModifier | null; }; /** Controller returned by {@link attachRelighting}. */ export type RelightingAttachment = { update(settings: RelightingUpdate): void; dispose(): void; }; /** * Adds a relighting factor map after any existing display-color callback. * Texture identity and callbacks rebuild the display material; numeric setting * changes mutate extension-owned uniforms only. Disposal restores the previous * callback only while this attachment remains installed. */ export declare function attachRelighting(target: RelightingTarget, initial: RelightingSettings): RelightingAttachment; /** Handle returned by {@link createRelightingProxy}. */ export interface RelightingProxy { /** World-space group of lit proxy meshes (hide from the main splat scene). */ readonly group: THREE.Group; /** * Configures a material for the relight coverage pass: gray albedo and * opaque alpha so uncovered RT pixels stay at clear-alpha 0. */ configureMaterial(material: THREE.Material): void; /** Disposes geometries and the default material owned by this helper. */ dispose(): void; } /** One independent shadow-casting light for {@link createRelightingShadowFactorMaterial}. */ export type RelightingLightContribution = { light: THREE.Light; /** Relative umbra weight. Default `1`. Values `<= 0` are skipped unless `fill` is set. */ intensity?: number; /** * Additive Lambert fill on top of the umbra factor (RGB may exceed 1). * Gated by `shadow()` (only when the light has `castShadow`), facing, and for spot/point lights the Frostbite * `distance` window (and the spot cone, `SpotLight.map` and `beamProfile`). * `0` / omitted = umbra only. The map and profile shape fill only, not the umbra. */ fill?: number; /** * Radial beam profile for a `SpotLight`'s fill (ignored for other lights): a * texture whose red channel multiplies fill along `u = angle / light.angle`, so * `u = 0` is the beam axis and `u = 1` the cone edge (`v` is ignored). Use it * for rotationally symmetric beams (reflector rings, measured lamp falloff) * without authoring a 2D `SpotLight.map`; build one with * {@link createRelightingBeamProfile}. Swapping the texture is live; adding or * removing it changes the compiled graph. */ beamProfile?: THREE.Texture | null; /** Blend from the plain cone (`0`) to the full `beamProfile` (`1`). Default `1`. Live. */ beamProfileStrength?: number; }; /** Options for {@link createRelightingShadowFactorMaterial}. */ export type RelightingShadowFactorOptions = { umbra?: number; receiveUpMin?: number; color?: THREE.Color; diffuse?: number; direction?: THREE.Vector3; /** * How independent contributions combine into one multiplier. * - `average` (default): intensity-weighted mean of shadows (fill lights). * - `min`: union of umbras — each caster keeps its own silhouette. Contribution * `intensity` scales umbra depth: `0` → none, `1` → default `umbra`, * `>1` → darker than default (`umbra_i = clamp(1 - I*(1-umbra), 0, 1)`). */ combine?: 'average' | 'min'; midLight?: THREE.Light; midRadius?: number; outerLight?: THREE.Light; outerRadius?: number; farLight?: THREE.Light; nearRadius?: number; }; /** * Cap on independent shadow lights (cascades of the first directional do not * count). Extra contributions are ignored. The compiled graph unrolls only * the live contribution count, not a padded 32-wide loop. */ export declare const MAX_RELIGHTING_SHADOW_LIGHTS = 32; /** * True when {@link createRelightingShadowFactorMaterial} renders real * `PointLight` cube shadows (via `pointShadow`). Hosts feature-detect this to * fall back to a wide-SpotLight approximation on older builds. A `PointLight` * also needs a `target` stub: three's `lightShadowMatrix` calls * `shadow.updateMatrices(light)` on frames without a shadow pass, and the base * `LightShadow` reads `light.target`. */ export declare const RELIGHTING_POINT_SHADOWS = true; /** * Bakes a radial beam profile for {@link RelightingLightContribution.beamProfile}. * * `profile` is either a function of `t = angle / cone half-angle` in `[0, 1]` * or evenly spaced samples from the beam axis (`t = 0`) to the cone edge * (`t = 1`), linearly interpolated. Values are clamped to `>= 0`; values above * 1 brighten fill. The result is a `resolution × 1` half-float red texture with * linear filtering and clamp-to-edge wrapping; the caller owns and disposes it. * * @example Reflector rings: bright core, dark gap, soft ring and a thin rim. * ```ts * const lobe = (t: number, center: number, width: number, gain: number) => * gain * Math.exp(-(((t - center) / width) ** 2)); * const rings = createRelightingBeamProfile((t) => * Math.min(1, 0.12 + lobe(t, 0, 0.2, 0.88) + lobe(t, 0.55, 0.16, 0.38) + lobe(t, 0.88, 0.045, 0.32)), * ); * ``` */ export declare function createRelightingBeamProfile(profile: ArrayLike | ((t: number) => number), resolution?: number): THREE.DataTexture; /** * Node material for a **shadow-factor** lighting RT used with * {@link attachRelighting}. * * Fragment output is `vec4(vec3(mix(umbra, 1, shadow)) + boost, 1)`: * - covered + lit → RGB ≈ 1 (identity modulate when brightness/background are 1) * - covered + umbra → RGB ≈ `umbra` (soft darken; never pure black) * - uncovered stays clear-alpha 0 from the RT clear * - with `diffuse` > 0, facing surfaces add `color * NdotL * diffuse` * (RGB may exceed 1; use a HalfFloat lighting RT) * * Pass one {@link THREE.Light} (demo / single-sun) or an array of * {@link RelightingLightContribution} so independent lights share one * multiplier. Default combine is intensity-weighted average * (`illum = sum(I_i * shadow_i) / sum(I_i)`); pass `combine: 'min'` for a * union of umbras so each caster keeps its silhouette. Spot / point lights * with `distance > 0` fade their umbra to lit via a Frostbite cutoff window * (steepened by `decay`) so the shadow map far plane is not a hard cliff. * Contribution `fill` adds occluded Lambert (range + cone for punctual lights) * on top of that identity so accent lights can light splats without wrapping * through collision. A spot's `map` (projected texture, as in three.js) tints * its fill and a contribution `beamProfile` shapes it radially; each adds one * sampled texture to the fragment stage, which WebGPU caps at 16 by default * alongside shadow maps. Cascades (`midLight` / `outerLight` / `farLight`) still * attach to the **first** directional only. At most * {@link MAX_RELIGHTING_SHADOW_LIGHTS} independent lights are used; extras * are ignored. Graph size follows the live contribution count (not a padded * loop of that width). * * By default, only **upward** proxy faces receive (`receiveUpMin`). Vertical * and noisy foliage triangles still **cast**, but they do not self-shadow — * that PCF acne reads as per-frame sparkle in trees. Pass `receiveUpMin: 0` * to receive on every face. Contribution `fill` does **not** use that slope * gate (stems would otherwise stay unlit in the factor map). * * Clear the lighting RT to **RGB 1, A 0** (not black). Softness / bilinear * samples at coverage edges otherwise pull in black and draw a dark outline * of every collision triangle. * * Prefer this over a lit MeshStandard / ShadowMaterial pass when the host wants * cast umbras without a static dark stamp on the whole collision footprint. * Assign to proxy meshes with `castShadow` and `receiveShadow` both true; the * umbra shape follows those triangles (splat foliage cannot cast). * * @param lights - Shadow-casting light, or intensity-weighted contributions. * The first entry is the innermost cascade when `midLight` / `outerLight` / * `farLight` are set. * @param options.umbra - Multiplier in full shadow, in `[0, 1]`. Default `0.45`. * @param options.receiveUpMin - World-up `normal.y` below which the face does * not receive. Default `0.25`. `0` disables the slope gate. * @param options.color - Light tint for the optional Lambert boost. Mutate * in place; the material holds this object. Default white. * @param options.diffuse - Lambert boost on top of identity. Default `0` * (shadow multiplier only). Facing, unshadowed coverage becomes * `1 + color * NdotL * diffuse`. * @param options.direction - World-space direction **toward** the light. * Mutate in place each frame as the sun moves. Default `(0, 1, 0)`. * @param options.midLight - Optional mid cascade (demo: ~50 m). Blend from * the first light over `nearRadius`. * @param options.midRadius - World metres where the mid cascade yields to * `outerLight` (or `farLight`). Default `50`. * @param options.outerLight - Optional outer cascade (demo: ~160 m) between * mid and scene-sized far. Blend from mid over `midRadius`, then to * `farLight` over `outerRadius`. * @param options.outerRadius - World metres where the outer cascade yields to * `farLight`. Default `160`. Ignored without `outerLight` and `farLight`. * @param options.farLight - Optional scene-sized cascade. Out-of-frustum * `shadow()` is 1 (lit), so inner maps can stay tight without clipping * distant umbras. Blend by camera distance. * @param options.nearRadius - World metres where the inner cascade yields to * `midLight` (or to `farLight` if there is no mid). Default `20` with * `midLight`, else `100`. */ export declare function createRelightingShadowFactorMaterial(lights: THREE.Light | RelightingLightContribution[], options?: RelightingShadowFactorOptions): THREE.MeshStandardNodeMaterial; /** * Retunes contribution `intensity` / `fill` / `beamProfile` / * `beamProfileStrength` on a material from * {@link createRelightingShadowFactorMaterial} without recompiling it. * Returns `false` when the new list would compile to a different graph * (other lights or order, a weight crossing zero, a `castShadow` change, a * spot `map` or `beamProfile` added or removed); * the caller then builds a new material. */ export declare function updateRelightingShadowFactorWeights(material: THREE.Material, lights: THREE.Light | RelightingLightContribution[]): boolean; /** * Builds a PlayCanvas-style relighting **proxy** from collision tiles or raw * geometries. The host places {@link RelightingProxy.group} on a dedicated * layer / scene with lights (never the main splat scene), renders that into * an RGBA RT matching the main camera, then calls * {@link attachRelighting} with the RT texture. * * Collision meshes are a convenient stand-in when their silhouette is good * enough; a denser reconstructed mesh is often better. This helper does not * own lights or the render target. * * When `matrixWorld` is set (e.g. streamed mesh world matrix with the LCC * Z-up→Y-up correction), it is **baked into the geometry** the same way the * demo collision BVH path does - so the proxy aligns with splats without * depending on a live Object3D transform. * * Coarse collision proxies leave hard coverage silhouettes; hosts should pass * `RelightingSettings.softness` (and often a half-res lighting RT) so those * edges do not look like a static shadow. * * For cast umbras **without** a static dark footprint, render the proxy with * {@link createRelightingShadowFactorMaterial} so RT RGB is a multiplier * (unshadowed ≈ 1), not a lit-gray appearance. */ export declare function createRelightingProxy(options?: { /** LCC collision tiles (source-local). Prefer with `matrixWorld`. */ tiles?: readonly CollisionMeshTile[]; /** Extra or alternative geometries already in the desired frame. */ geometries?: readonly THREE.BufferGeometry[]; /** * Source-local → world (e.g. streamed mesh `matrixWorld`). Baked into * tile / cloned geometries; leave unset when geometries are already world. */ matrixWorld?: THREE.Matrix4; /** Gray albedo in `[0, 1]`. Default `0.5` (PlayCanvas brightness 2). */ albedo?: number; }): RelightingProxy;