From e72e21086b622140550fa03e97b4fc79bdd33481 Mon Sep 17 00:00:00 2001 From: shabai517 Date: Thu, 1 Oct 2026 00:43:11 +0800 Subject: [PATCH] =?UTF-8?q?feat(light):=20RectLight=20=E2=80=94=20analytic?= =?UTF-8?q?=20rectangular=20area=20light?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diffuse uses Lambert's polygon form factor with an analytic sphere-proxy horizon clip; specular uses a most-representative-point GGX lobe. No lookup textures and no shadows. Adds RectLightUtil (CPU mirror), a demo, a 7-case test (brute-force integration reference + GPU readback). Co-Authored-By: Claude Fable 5.1 --- samples/lights/Sample_RectLight.ts | 135 +++++++++++ src/assets/shader/ShaderLib.ts | 2 + src/assets/shader/core/struct/ClusterLight.ts | 1 + src/assets/shader/lighting/BxDF_frag.ts | 4 + .../shader/lighting/LightingFunction_frag.ts | 2 + src/assets/shader/lighting/RectLight_frag.ts | 128 ++++++++++ src/components/lights/LightData.ts | 2 + src/components/lights/RectLight.ts | 101 ++++++++ src/index.ts | 3 + src/util/RectLightUtil.ts | 162 +++++++++++++ test/components/Light_RectLight.test.ts | 226 ++++++++++++++++++ 11 files changed, 766 insertions(+) create mode 100644 samples/lights/Sample_RectLight.ts create mode 100644 src/assets/shader/lighting/RectLight_frag.ts create mode 100644 src/components/lights/RectLight.ts create mode 100644 src/util/RectLightUtil.ts create mode 100644 test/components/Light_RectLight.test.ts diff --git a/samples/lights/Sample_RectLight.ts b/samples/lights/Sample_RectLight.ts new file mode 100644 index 000000000..03baebc74 --- /dev/null +++ b/samples/lights/Sample_RectLight.ts @@ -0,0 +1,135 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { + BoxGeometry, CameraUtil, Color, Engine3D, HoverCameraController, LitMaterial, MeshRenderer, Object3D, + RectLight, Scene3D, SphereGeometry, TorusGeometry, UnLitMaterial, Vector3, View3D, +} from '@orillusion/core'; + +/** + * RectLight demo: a dark studio lit only by three rectangular panels. + * + * - a warm key panel on the left, a cool one on the right and a magenta + * strip that swings over the stage; + * - the floor is glossy, so each panel shows up as a stretched rectangular + * reflection, while the back wall and the matte spheres show the soft, + * size-dependent diffuse falloff; + * - the sphere row sweeps roughness from mirror-like to matte. + * + * The light itself is invisible; each panel here also carries a thin unlit + * box so you can see where the emitter is. + */ +class Sample_RectLight { + private scene: Scene3D; + private panels: { obj: Object3D; light: RectLight; face: Object3D; mat: UnLitMaterial }[] = []; + private readonly state = { swing: true, swingSpeed: 0.6 }; + + async run() { + const engine = await Engine3D.init({ renderLoop: () => this.update() }); + this.scene = new Scene3D(); + + const camera = CameraUtil.createCamera3DObject(this.scene); + camera.perspective(50, engine.aspect, 0.1, 500); + camera.object3D.addComponent(HoverCameraController).setCamera(20, -18, 30, new Vector3(0, 3, 0)); + + this.buildStage(); + this.addPanel('key (warm)', new Color(1.0, 0.72, 0.45), 6, new Vector3(-9, 5, 3), new Vector3(0, 2, 0), 5, 4); + this.addPanel('fill (cool)', new Color(0.45, 0.7, 1.0), 5, new Vector3(9, 4, 4), new Vector3(0, 2, 0), 3, 6); + this.addPanel('strip (magenta)', new Color(1.0, 0.25, 0.8), 8, new Vector3(0, 8, -2), new Vector3(0, 0, -2), 10, 1); + + const view = new View3D(); + view.scene = this.scene; + view.camera = camera; + engine.startRenderView(view); + this.initGUI(); + } + + private mesh(geo: any, mat: any, x: number, y: number, z: number): Object3D { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = geo; mr.material = mat; + o.x = x; o.y = y; o.z = z; + this.scene.addChild(o); + return o; + } + + private lit(r: number, g: number, b: number, roughness: number, metallic = 0): LitMaterial { + const m = new LitMaterial(); + m.baseColor = new Color(r, g, b, 1); + m.roughness = roughness; m.metallic = metallic; + return m; + } + + private buildStage() { + this.mesh(new BoxGeometry(60, 0.4, 60), this.lit(0.35, 0.35, 0.37, 0.35), 0, -0.2, 0); // glossy floor + this.mesh(new BoxGeometry(60, 24, 0.4), this.lit(0.7, 0.7, 0.7, 1.0), 0, 12, -12); // matte back wall + const ball = new SphereGeometry(1.2, 48, 48); + for (let i = 0; i < 6; i++) { + this.mesh(ball, this.lit(0.85, 0.85, 0.85, 0.1 + i * 0.18, 1), (i - 2.5) * 3, 1.2, 1); // metal, roughness sweep + this.mesh(ball, this.lit(0.8, 0.8, 0.8, 0.2 + i * 0.16, 0), (i - 2.5) * 3, 1.2, -3); // dielectric + } + const torus = this.mesh(new TorusGeometry(2, 0.6, 48, 64), this.lit(0.9, 0.75, 0.4, 0.4, 1), 0, 3.4, -7); + torus.rotationX = 70; + } + + private addPanel(name: string, color: Color, intensity: number, pos: Vector3, target: Vector3, width: number, height: number) { + const obj = new Object3D(); + obj.name = name; + const light = obj.addComponent(RectLight); + light.lightColor = color; + light.intensity = intensity; + light.width = width; light.height = height; + light.range = 45; + this.scene.addChild(obj); + obj.transform.lookAt(pos, target); + + // Visible emitter: a thin unlit box in the light's own plane. + const face = new Object3D(); + const mr = face.addComponent(MeshRenderer); + mr.geometry = new BoxGeometry(1, 1, 0.05); + const mat = new UnLitMaterial(); + mr.material = mat; + mr.castShadow = false; + obj.addChild(face); + const panel = { obj, light, face, mat }; + this.panels.push(panel); + this.syncFace(panel); + } + + private syncFace(p: { light: RectLight; face: Object3D; mat: UnLitMaterial }) { + p.face.localScale = new Vector3(p.light.width, p.light.height, 1); + const c = p.light.lightColor, k = Math.min(p.light.intensity, 12) / 4; + p.mat.baseColor = new Color(c.r * k, c.g * k, c.b * k, 1); + } + + private time = 0; + private update() { + const strip = this.panels[2]; + if (!strip || !this.state.swing) return; + this.time += 0.016 * this.state.swingSpeed; + const x = Math.sin(this.time) * 7; + strip.obj.transform.lookAt(new Vector3(x, 8, -2 + Math.cos(this.time * 0.7) * 3), new Vector3(x * 0.3, 0, -2)); + } + + private initGUI() { + GUIHelp.init(); + for (const p of this.panels) { + const f = GUIHelp.addFolder(p.obj.name); + const proxy = { + enable: true, intensity: p.light.intensity, width: p.light.width, height: p.light.height, range: p.light.range, + color: [p.light.lightColor.r * 255, p.light.lightColor.g * 255, p.light.lightColor.b * 255], + }; + f.add(proxy, 'enable').onChange((v: boolean) => { p.light.enable = v; p.face.transform.enable = v; }); + f.add(proxy, 'intensity', 0, 20, 0.1).onChange((v: number) => { p.light.intensity = v; this.syncFace(p); }); + f.add(proxy, 'width', 0.2, 16, 0.1).onChange((v: number) => { p.light.width = v; this.syncFace(p); }); + f.add(proxy, 'height', 0.2, 16, 0.1).onChange((v: number) => { p.light.height = v; this.syncFace(p); }); + f.add(proxy, 'range', 5, 80, 1).onChange((v: number) => { p.light.range = v; }); + f.addColor(proxy, 'color').onChange((v: number[]) => { p.light.lightColor = new Color(v[0] / 255, v[1] / 255, v[2] / 255, 1); this.syncFace(p); }); + f.open(); + } + const s = GUIHelp.addFolder('strip animation'); + s.add(this.state, 'swing'); + s.add(this.state, 'swingSpeed', 0, 3, 0.05); + s.open(); + } +} + +new Sample_RectLight().run(); diff --git a/src/assets/shader/ShaderLib.ts b/src/assets/shader/ShaderLib.ts index 2fb2a930e..fb778b9a2 100644 --- a/src/assets/shader/ShaderLib.ts +++ b/src/assets/shader/ShaderLib.ts @@ -37,6 +37,7 @@ import { Clearcoat_frag } from './materials/program/Clearcoat_frag'; import { Sheen_frag } from './materials/program/Sheen_frag'; import { Iridescence_frag } from './materials/program/Iridescence_frag'; import { Anisotropy_frag } from './materials/program/Anisotropy_frag'; +import { RectLight_frag } from './lighting/RectLight_frag'; import { Lit_shader } from './materials/Lit_shader'; import { PBRLItShader } from './materials/PBRLItShader'; import { BxdfDebug_frag } from './materials/program/BxdfDebug_frag'; @@ -134,6 +135,7 @@ export class ShaderLib { ShaderLib.register('Sheen_frag', Sheen_frag); ShaderLib.register('Iridescence_frag', Iridescence_frag); ShaderLib.register('Anisotropy_frag', Anisotropy_frag); + ShaderLib.register('RectLight_frag', RectLight_frag); ShaderLib.register('LitShader', Lit_shader); ShaderLib.register('PBRLItShader', PBRLItShader); diff --git a/src/assets/shader/core/struct/ClusterLight.ts b/src/assets/shader/core/struct/ClusterLight.ts index b7eb85148..9583b6165 100644 --- a/src/assets/shader/core/struct/ClusterLight.ts +++ b/src/assets/shader/core/struct/ClusterLight.ts @@ -7,6 +7,7 @@ export let ClusterLight: string = /*wgsl*/ ` const PointLightType = 1; const DirectLightType = 2; const SpotLightType = 3; + const RectLightType = 5; struct ClusterBox { minPoint:vec4, diff --git a/src/assets/shader/lighting/BxDF_frag.ts b/src/assets/shader/lighting/BxDF_frag.ts index 2a096c1c0..3ffd68035 100644 --- a/src/assets/shader/lighting/BxDF_frag.ts +++ b/src/assets/shader/lighting/BxDF_frag.ts @@ -143,6 +143,10 @@ export let BxDF_frag: string = /*wgsl*/ ` specColor += spotLighting( ORI_VertexVarying.vWorldPos.xyz, light ,iblSpecularResult) ; break; } + case RectLightType: { + specColor += rectLighting( ORI_VertexVarying.vWorldPos.xyz, light ) ; + break; + } default: { break; } diff --git a/src/assets/shader/lighting/LightingFunction_frag.ts b/src/assets/shader/lighting/LightingFunction_frag.ts index 4dac241ae..2811b7dfa 100644 --- a/src/assets/shader/lighting/LightingFunction_frag.ts +++ b/src/assets/shader/lighting/LightingFunction_frag.ts @@ -220,6 +220,8 @@ fn spotLighting( WP:vec3, light:LightData , iblSpecularResult : vec3f) -> v return color ; } +#include "RectLight_frag" + fn sphere_unit( radius:f32 , intensity:f32 ) -> f32 { return intensity / (4.0 * PI2 * radius * radius) ; } diff --git a/src/assets/shader/lighting/RectLight_frag.ts b/src/assets/shader/lighting/RectLight_frag.ts new file mode 100644 index 000000000..b64db10d8 --- /dev/null +++ b/src/assets/shader/lighting/RectLight_frag.ts @@ -0,0 +1,128 @@ +/** + * Rectangular area light, evaluated analytically (no lookup textures). + * + * - Diffuse: Lambert's polygon formula gives the exact vector form factor of + * the quad; the part below the surface horizon is handled by replacing the + * quad with a sphere of the same form factor and clipping that analytically. + * - Specular: most-representative-point — the point of the rectangle closest + * to the reflection ray stands in for the whole light, with the GGX lobe + * re-normalised for the light's angular size. + * + * `LightData` packing for this type: `position` = centre, `direction` = the + * emitting face normal, `lightTangent` = the rectangle's up axis, + * `innerCutOff` / `outerCutOff` = half width / half height, `range` = the + * distance at which the contribution is windowed to zero. + * CPU mirror: `RectLightUtil`. + * @internal + */ +export let RectLight_frag: string = /*wgsl*/ ` + fn rectEdgeTerm(a: vec3, b: vec3) -> vec3 { + let c = cross(a, b); + let s = length(c); + let theta = acos(clamp(dot(a, b), -1.0, 1.0)); + if (s < 1e-5) { + return c; + } + return c * (theta / s); + } + + /// Unclipped vector form factor of the quad p0..p3 seen from the origin. + fn rectFormFactorVector(p0: vec3, p1: vec3, p2: vec3, p3: vec3) -> vec3 { + let v0 = normalize(p0); + let v1 = normalize(p1); + let v2 = normalize(p2); + let v3 = normalize(p3); + let sum = rectEdgeTerm(v0, v1) + rectEdgeTerm(v1, v2) + rectEdgeTerm(v2, v3) + rectEdgeTerm(v3, v0); + return sum * (0.5 / 3.14159265359); + } + + /// Form factor of a sphere subtending sin^2(sigma) = sinSigmaSqr whose centre + /// is at angle theta from the normal, clipped by the horizon. + fn rectSphereFormFactor(cosTheta: f32, sinSigmaSqrIn: f32) -> f32 { + let sinSigmaSqr = clamp(sinSigmaSqrIn, 1e-7, 0.9999); + if (cosTheta * cosTheta > sinSigmaSqr) { + return sinSigmaSqr * saturate(cosTheta); + } + let sinTheta = sqrt(max(1.0 - cosTheta * cosTheta, 1e-7)); + let x = sqrt(1.0 / sinSigmaSqr - 1.0); + let y = clamp(-x * (cosTheta / sinTheta), -1.0, 1.0); + let sinThetaSqrtY = sinTheta * sqrt(max(1.0 - y * y, 0.0)); + let illum = (cosTheta * acos(y) - x * sinThetaSqrtY) * sinSigmaSqr + atan(sinThetaSqrtY / x); + return max(illum, 0.0) / 3.14159265359; + } + + fn rectLighting(WP: vec3, light: LightData) -> vec3 { + let C = light.position.xyz; + let n = normalize(light.direction.xyz); + let toP = WP - C; + // Single sided: nothing behind the emitting face. + if (dot(toP, n) <= 1e-5) { + return vec3(0.0); + } + let distC = length(toP); + let w = distC / max(light.range, 1e-4); + let w2 = w * w; + var falloff = saturate(1.0 - w2 * w2); + falloff = falloff * falloff; + if (falloff <= 0.0) { + return vec3(0.0); + } + + var up = light.lightTangent.xyz - n * dot(light.lightTangent.xyz, n); + up = normalize(up); + let right = cross(up, n); + let hw = light.innerCutOff; + let hh = light.outerCutOff; + let ex = right * hw; + let ey = up * hh; + let c = C - WP; + + var Fv = rectFormFactorVector(c - ex - ey, c + ex - ey, c + ex + ey, c - ex + ey); + if (dot(Fv, c) < 0.0) { + Fv = -Fv; + } + let len = length(Fv); + if (len < 1e-7) { + return vec3(0.0); + } + let N = fragData.N; + let V = fragData.V; + let formFactor = rectSphereFormFactor(dot(N, Fv) / len, len); + let radiance = light.lightColor.rgb * max(light.intensity, 0.0) * falloff; + let NdotV = max(dot(N, V), 0.05); + + // ---- diffuse ---- + let KD = (vec3(1.0) - F_Function(NdotV, fragData.F0)) * (1.0 - fragData.Metallic); + var color = KD * fragData.Albedo.rgb * radiance * formFactor; + + // ---- specular: most representative point ---- + let R = reflect(-V, N); + let denom = dot(R, n); + var hit = WP + R * distC; + if (denom < -1e-4) { + hit = WP + R * (dot(c, n) / denom); + } + hit = hit - n * dot(hit - C, n); + let d = hit - C; + let mrp = C + right * clamp(dot(d, right), -hw, hw) + up * clamp(dot(d, up), -hh, hh); + let toL = mrp - WP; + let distL = max(length(toL), 1e-4); + let L = toL / distL; + let NdotL = dot(N, L); + if (NdotL > 0.0) { + let H = normalize(V + L); + let NdotH = saturate(dot(N, H)); + let HdotL = saturate(dot(H, L)); + let rough = clamp(fragData.Roughness, 0.045, 1.0); + let alpha = rough * rough; + let sourceRadius = sqrt(4.0 * hw * hh / 3.14159265359); + let alphaPrime = saturate(alpha + sourceRadius / (2.0 * distL)); + let norm = (alpha * alpha) / (alphaPrime * alphaPrime); + let D = D_Function(NdotH, rough) * norm; + let G = G_Function(NdotL, NdotV, rough); + let F = F_Function(HdotL, fragData.F0); + color += radiance * (3.14159265359 * len) * D * G * F / (4.0 * NdotV); + } + return color; + } +`; diff --git a/src/components/lights/LightData.ts b/src/components/lights/LightData.ts index 8bc13a300..59c3380d2 100644 --- a/src/components/lights/LightData.ts +++ b/src/components/lights/LightData.ts @@ -12,6 +12,7 @@ import { Struct } from '../../util/struct/Struct'; *DirectionLight| *SpotLight| *SkyLight| + *RectLight| * @group Lights */ export enum LightType { @@ -20,6 +21,7 @@ export enum LightType { DirectionLight, SpotLight, SkyLight, + RectLight, } /** diff --git a/src/components/lights/RectLight.ts b/src/components/lights/RectLight.ts new file mode 100644 index 000000000..e63967767 --- /dev/null +++ b/src/components/lights/RectLight.ts @@ -0,0 +1,101 @@ +import { UUID } from '../../util/Global'; +import { RegisterComponent } from '../../util/SerializeDecoration'; +import { LightBase } from './LightBase'; +import { LightType } from './LightData'; + +/** + * Rectangular area light. + * + * A flat `width` × `height` panel that emits from one face, along the + * object's forward axis — a window, a softbox, a ceiling panel or a screen. + * Unlike a point or spot light it has a real size: nearby surfaces receive + * soft, wrap-around diffuse light and glossy surfaces show a rectangular + * highlight. + * + * `intensity` is the panel's radiance, so making the panel larger makes the + * scene brighter (like a real softbox). `range` fades the contribution to + * zero and bounds the light for cluster culling. + * + * Limitations: no shadows, and the light itself is not drawn — add an unlit + * quad at the same transform if the panel should be visible. + * @group Lights + */ +@RegisterComponent(RectLight, 'RectLight') +export class RectLight extends LightBase { + private _width: number = 2; + private _height: number = 1; + + constructor() { + super(); + } + + public init(): void { + super.init(); + this.lightData.lightType = LightType.RectLight; + this.lightData.range = 20; + this.lightData.intensity = 5; + this.syncSize(); + if (this.object3D.name == "") { + this.object3D.name = "RectLight" + UUID(); + } + } + + public start(): void { + super.start(); + this.lightData.lightType = LightType.RectLight; + this.syncSize(); + } + + // The shader reads the half extents from the two spot-cone slots, which a + // rect light does not otherwise use. + private syncSize() { + this.lightData.innerAngle = this._width * 0.5; + this.lightData.outerAngle = this._height * 0.5; + this.onChange(); + } + + /** Panel width in world units (along the object's right axis). */ + public get width(): number { + return this._width; + } + + public set width(value: number) { + this._width = Math.max(value, 1e-4); + this.syncSize(); + } + + /** Panel height in world units (along the object's up axis). */ + public get height(): number { + return this._height; + } + + public set height(value: number) { + this._height = Math.max(value, 1e-4); + this.syncSize(); + } + + /** Distance from the panel centre at which the light has faded to zero. */ + public get range(): number { + return this.lightData.range as number; + } + + public set range(value: number) { + this.lightData.range = value; + this.onChange(); + } + + /** Rect lights do not cast shadows; the flag is ignored. */ + public set castShadow(value: boolean) { + this._castShadow = false; + } + + public get castShadow(): boolean { + return false; + } + + public debug() { + } + + public debugDraw(show: boolean) { + } +} diff --git a/src/index.ts b/src/index.ts index f41dddd2a..180b6d6a9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -89,6 +89,7 @@ export * from "./assets/shader/lighting/IESProfiles_frag" export * from "./assets/shader/lighting/IrradianceVolumeData_frag" export * from "./assets/shader/lighting/Irradiance_frag" export * from "./assets/shader/lighting/LightingFunction_frag" +export * from "./assets/shader/lighting/RectLight_frag" export * from "./assets/shader/lighting/UnLit_frag" export * from "./assets/shader/materials/ColorLitShader" export * from "./assets/shader/materials/GIProbeShader" @@ -197,6 +198,7 @@ export * from "./components/lights/Light" export * from "./components/lights/LightBase" export * from "./components/lights/LightData" export * from "./components/lights/PointLight" +export * from "./components/lights/RectLight" export * from "./components/lights/SpotLight" export * from "./components/matrix/WasmMatrix" export * from "./components/post/PostProcessingComponent" @@ -695,6 +697,7 @@ export * from "./util/LensUtil" export * from "./util/MotionBlurUtil" export * from "./util/Object3DUtil" export * from "./util/ProfilerUtil" +export * from "./util/RectLightUtil" export * from "./util/Reference" export * from "./util/SerializeDecoration" export * from "./util/StorageUtil" diff --git a/src/util/RectLightUtil.ts b/src/util/RectLightUtil.ts new file mode 100644 index 000000000..40768ca13 --- /dev/null +++ b/src/util/RectLightUtil.ts @@ -0,0 +1,162 @@ +type V3 = number[]; + +/** Geometry and radiometry of a rect light, as plain numbers. */ +export interface RectLightDesc { + /** Panel centre. */ + center: V3; + /** Unit normal of the emitting face. */ + normal: V3; + /** Panel up axis (need not be exactly perpendicular to `normal`). */ + up: V3; + width: number; + height: number; + /** Linear RGB colour. */ + color: V3; + intensity: number; + range: number; +} + +/** + * CPU mirror of `RectLight_frag`: analytic rectangular area light. + * @group Util + */ +export class RectLightUtil { + private static dot(a: V3, b: V3) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } + private static cross(a: V3, b: V3): V3 { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; } + private static len(a: V3) { return Math.hypot(a[0], a[1], a[2]); } + private static norm(a: V3): V3 { const l = RectLightUtil.len(a) || 1; return [a[0] / l, a[1] / l, a[2] / l]; } + private static add(a: V3, b: V3, s = 1): V3 { return [a[0] + b[0] * s, a[1] + b[1] * s, a[2] + b[2] * s]; } + private static clamp(v: number, lo: number, hi: number) { return Math.min(Math.max(v, lo), hi); } + + /** Orthonormal frame of the panel: `right`, `up`, `normal`. */ + public static frame(light: RectLightDesc): { right: V3; up: V3; normal: V3 } { + const U = RectLightUtil; + const normal = U.norm(light.normal); + const up = U.norm(U.add(light.up, normal, -U.dot(light.up, normal))); + return { right: U.cross(up, normal), up, normal }; + } + + /** The four corners in world space. */ + public static corners(light: RectLightDesc): V3[] { + const U = RectLightUtil; + const f = U.frame(light); + const hw = light.width * 0.5, hh = light.height * 0.5; + const c = light.center; + return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([sx, sy]) => U.add(U.add(c, f.right, sx * hw), f.up, sy * hh)); + } + + /** + * Unclipped vector form factor of the panel seen from `P` (Lambert's + * polygon formula). Its length is the form factor toward the panel, its + * direction the mean incoming light direction. + */ + public static formFactorVector(P: V3, light: RectLightDesc): V3 { + const U = RectLightUtil; + const v = U.corners(light).map((q) => U.norm(U.add(q, P, -1))); + let sum: V3 = [0, 0, 0]; + for (let i = 0; i < 4; i++) { + const a = v[i], b = v[(i + 1) % 4]; + const c = U.cross(a, b); + const s = U.len(c); + const theta = Math.acos(U.clamp(U.dot(a, b), -1, 1)); + sum = U.add(sum, c, s < 1e-5 ? 1 : theta / s); + } + let F: V3 = [sum[0] / (2 * Math.PI), sum[1] / (2 * Math.PI), sum[2] / (2 * Math.PI)]; + if (U.dot(F, U.add(light.center, P, -1)) < 0) F = [-F[0], -F[1], -F[2]]; + return F; + } + + /** Horizon-clipped form factor of a sphere with sin²σ = `sinSigmaSqr` at angle θ from the normal. */ + public static sphereFormFactor(cosTheta: number, sinSigmaSqr: number): number { + const s2 = RectLightUtil.clamp(sinSigmaSqr, 1e-7, 0.9999); + if (cosTheta * cosTheta > s2) return s2 * RectLightUtil.clamp(cosTheta, 0, 1); + const sinTheta = Math.sqrt(Math.max(1 - cosTheta * cosTheta, 1e-7)); + const x = Math.sqrt(1 / s2 - 1); + const y = RectLightUtil.clamp(-x * (cosTheta / sinTheta), -1, 1); + const sty = sinTheta * Math.sqrt(Math.max(1 - y * y, 0)); + const illum = (cosTheta * Math.acos(y) - x * sty) * s2 + Math.atan(sty / x); + return Math.max(illum, 0) / Math.PI; + } + + /** Distance window: 1 at the panel, 0 at `range`. */ + public static falloff(distance: number, range: number): number { + const w = distance / Math.max(range, 1e-4); + const f = RectLightUtil.clamp(1 - w * w * w * w, 0, 1); + return f * f; + } + + /** + * Form factor (0..1) of the panel for a surface point `P` with normal `N`: + * irradiance = π · radiance · formFactor. Zero behind the emitting face. + */ + public static formFactor(P: V3, N: V3, light: RectLightDesc): number { + const U = RectLightUtil; + if (U.dot(U.add(P, light.center, -1), U.norm(light.normal)) <= 1e-5) return 0; + const F = U.formFactorVector(P, light); + const len = U.len(F); + if (len < 1e-7) return 0; + return U.sphereFormFactor(U.dot(N, F) / len, len); + } + + /** Point of the panel that stands in for the whole light in the specular term. */ + public static representativePoint(P: V3, N: V3, V: V3, light: RectLightDesc): V3 { + const U = RectLightUtil; + const f = U.frame(light); + const c = U.add(light.center, P, -1); + const d2 = 2 * U.dot(V, N); + const R: V3 = [d2 * N[0] - V[0], d2 * N[1] - V[1], d2 * N[2] - V[2]]; + const denom = U.dot(R, f.normal); + let hit = U.add(P, R, U.len(c)); + if (denom < -1e-4) hit = U.add(P, R, U.dot(c, f.normal) / denom); + hit = U.add(hit, f.normal, -U.dot(U.add(hit, light.center, -1), f.normal)); + const d = U.add(hit, light.center, -1); + const hw = light.width * 0.5, hh = light.height * 0.5; + return U.add(U.add(light.center, f.right, U.clamp(U.dot(d, f.right), -hw, hw)), f.up, U.clamp(U.dot(d, f.up), -hh, hh)); + } + + /** + * Outgoing radiance toward `V` from a surface lit by the panel. + * `roughness` is the shader-side value (`fragData.Roughness`). + */ + public static shade(P: V3, N: V3, V: V3, albedo: V3, metallic: number, roughness: number, F0: V3, light: RectLightDesc): V3 { + const U = RectLightUtil; + const n = U.norm(light.normal); + const toP = U.add(P, light.center, -1); + if (U.dot(toP, n) <= 1e-5) return [0, 0, 0]; + const fall = U.falloff(U.len(toP), light.range); + if (fall <= 0) return [0, 0, 0]; + const Fv = U.formFactorVector(P, light); + const len = U.len(Fv); + if (len < 1e-7) return [0, 0, 0]; + const ff = U.sphereFormFactor(U.dot(N, Fv) / len, len); + const rad = light.color.map((ch) => ch * Math.max(light.intensity, 0) * fall); + const NdotV = Math.max(U.dot(N, V), 0.05); + const fresnel = (x: number) => { const f = Math.pow(2, (-5.55473 * x - 6.98316) * x); return F0.map((f0) => f + (1 - f) * f0); }; + const Fd = fresnel(NdotV); + const out = [0, 1, 2].map((i) => (1 - Fd[i]) * (1 - metallic) * albedo[i] * rad[i] * ff); + + const mrp = U.representativePoint(P, N, V, light); + const toL = U.add(mrp, P, -1); + const distL = Math.max(U.len(toL), 1e-4); + const L: V3 = [toL[0] / distL, toL[1] / distL, toL[2] / distL]; + const NdotL = U.dot(N, L); + if (NdotL > 0) { + const H = U.norm(U.add(V, L)); + const NdotH = U.clamp(U.dot(N, H), 0, 1); + const HdotL = U.clamp(U.dot(H, L), 0, 1); + const rough = U.clamp(roughness, 0.045, 1); + const alpha = rough * rough; + const sourceRadius = Math.sqrt((light.width * light.height) / Math.PI); + const alphaPrime = U.clamp(alpha + sourceRadius / (2 * distL), 0, 1); + const a2 = alpha * alpha; + const den = NdotH * NdotH * (a2 - 1) + 1; + const D = (a2 / (Math.PI * den * den)) * (a2 / (alphaPrime * alphaPrime)); + const K = ((1 + rough) * (1 + rough)) / 8; + const gsub = (x: number) => x / (x + (1 - x) * K); + const G = gsub(NdotL) * gsub(NdotV); + const Fs = fresnel(HdotL); + for (let i = 0; i < 3; i++) out[i] += (rad[i] * Math.PI * len * D * G * Fs[i]) / (4 * NdotV); + } + return out; + } +} diff --git a/test/components/Light_RectLight.test.ts b/test/components/Light_RectLight.test.ts new file mode 100644 index 000000000..1d7d93ec8 --- /dev/null +++ b/test/components/Light_RectLight.test.ts @@ -0,0 +1,226 @@ +import { test, expect, end, waitUntil, frames, readRegionRGBA16F } from '../util' +import { BoxGeometry, CameraUtil, Color, Engine3D, LightType, LitMaterial, MeshRenderer, Object3D, RectLight, RectLightDesc, RectLightUtil, Scene3D, Vector3, View3D } from '@orillusion/core'; + +const engine = await Engine3D.init({ canvasConfig: { devicePixelRatio: 1 } }); +engine.setting.render.tonemap.mode = 'None'; + +const panel = (center: number[], normal: number[], up: number[], width: number, height: number): RectLightDesc => + ({ center, normal, up, width, height, color: [1, 1, 1], intensity: 1, range: 1e6 }); + +/** + * Independent reference: brute-force quadrature of (1/π)∫ cosθ_surface · cosθ_light / r² dA + * over the panel, with the below-horizon part clamped away. Shares no code with the analytic path. + */ +function numericFormFactor(P: number[], N: number[], l: RectLightDesc, n = 400): number { + const f = RectLightUtil.frame(l); + let sum = 0; + const dA = (l.width / n) * (l.height / n); + for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) { + const sx = ((i + 0.5) / n - 0.5) * l.width, sy = ((j + 0.5) / n - 0.5) * l.height; + const q = [0, 1, 2].map((k) => l.center[k] + f.right[k] * sx + f.up[k] * sy); + const d = [q[0] - P[0], q[1] - P[1], q[2] - P[2]]; + const r2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2], r = Math.sqrt(r2); + const cosS = (d[0] * N[0] + d[1] * N[1] + d[2] * N[2]) / r; + const cosL = -(d[0] * f.normal[0] + d[1] * f.normal[1] + d[2] * f.normal[2]) / r; + if (cosS > 0 && cosL > 0) sum += (cosS * cosL / r2) * dA; + } + return sum / Math.PI; +} + +await test('form factor matches brute-force integration when the panel is fully above the horizon', async () => { + const P = [0, 0, 0], N = [0, 1, 0]; + const cases: RectLightDesc[] = [ + panel([0, 3, 0], [0, -1, 0], [0, 0, 1], 2, 1), // overhead, facing down + panel([1.5, 2, -1], [0, -1, 0], [1, 0, 0], 3, 2), // offset + panel([0, 4, 4], [0, -0.7071, -0.7071], [0, 0.7071, -0.7071], 4, 2), // tilted softbox + panel([0, 2.5, 3], [0, 0, -1], [0, 1, 0], 2, 3), // vertical window, bottom edge at y=1 + panel([0, 0.6, 0], [0, -1, 0], [0, 0, 1], 6, 6), // big and close + ]; + for (const l of cases) { + const a = RectLightUtil.formFactor(P, N, l), b = numericFormFactor(P, N, l); + console.log(`[RectLight] unclipped FF analytic ${a.toFixed(5)} numeric ${b.toFixed(5)}`); + expect(a).toSubequal(b, 2e-3); + } + // An effectively infinite ceiling fills the hemisphere. + expect(RectLightUtil.formFactor(P, N, panel([0, 1, 0], [0, -1, 0], [0, 0, 1], 4000, 4000)) > 0.995).tobe(true); +}) + +await test('horizon-crossing panels stay close to the reference; hidden and back-facing ones are dark', async () => { + const P = [0, 0, 0], N = [0, 1, 0]; + const crossing: RectLightDesc[] = [ + panel([0, 0, 3], [0, 0, -1], [0, 1, 0], 2, 4), // window half below the floor plane + panel([0, 0.5, 2], [0, 0, -1], [0, 1, 0], 3, 3), // a third below + panel([0, -0.5, 2], [0, 0, -1], [0, 1, 0], 3, 3), // mostly below + ]; + for (const l of crossing) { + const a = RectLightUtil.formFactor(P, N, l), b = numericFormFactor(P, N, l); + console.log(`[RectLight] clipped FF analytic ${a.toFixed(5)} numeric ${b.toFixed(5)}`); + expect(Math.abs(a - b) < 0.02 + 0.25 * b).tobe(true); + } + // Entirely below the horizon. + expect(RectLightUtil.formFactor(P, N, panel([0, -3, 3], [0, 0, -1], [0, 1, 0], 2, 2)) < 1e-3).tobe(true); + // Surface is behind the emitting face. + expect(RectLightUtil.formFactor(P, N, panel([0, 3, 0], [0, 1, 0], [0, 0, 1], 2, 1))).tobe(0); + // Distance window. + expect(RectLightUtil.falloff(0, 10)).tobe(1); + expect(RectLightUtil.falloff(10, 10)).tobe(0); + expect(RectLightUtil.falloff(5, 10) > 0.8).tobe(true); +}) + +await test('representative point: mirror hit inside the panel, clamped to the edge outside it', async () => { + const l = panel([0, 5, -5], [0, -0.7071, 0.7071], [0, 0.7071, 0.7071], 2, 2); + const V = [0, 0.7071, 0.7071]; + const hit = RectLightUtil.representativePoint([0, 0, 0], [0, 1, 0], V, l); + expect(hit[0]).toSubequal(0, 1e-3); expect(hit[1]).toSubequal(5, 1e-3); expect(hit[2]).toSubequal(-5, 1e-3); + // Shift the shading point sideways by 3: the reflection now misses, so the point clamps to the x = +1 edge. + const off = RectLightUtil.representativePoint([3, 0, 0], [0, 1, 0], V, l); + expect(Math.abs(off[0])).toSubequal(1, 1e-3); + // Mirror-like surface looking straight at a large panel reflects about radiance × F0. + const big = { ...panel([0, 2, 0], [0, -1, 0], [0, 0, 1], 3, 3), intensity: 2 }; + const c = RectLightUtil.shade([0, 0, 0], [0, 1, 0], [0, 1, 0], [1, 1, 1], 1, 0.05, [1, 1, 1], big); + console.log(`[RectLight] mirror reflection of radiance 2: ${c[0].toFixed(3)}`); + expect(c[0] > 1 && c[0] < 3.5).tobe(true); +}) + +// ---- GPU --------------------------------------------------------------------- +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(40, engine.aspect, 0.1, 200); +view.camera.lookAt(new Vector3(0, 10, 10), new Vector3(0, 0, 0)); +const floor = new Object3D(); +const fmr = floor.addComponent(MeshRenderer); +fmr.geometry = new BoxGeometry(60, 0.2, 60); +const mat = new LitMaterial(); +mat.baseColor = new Color(0.8, 0.6, 0.4, 1); +mat.roughness = 0.8; mat.metallic = 0; +mat.setUniformFloat('envIntensity', 0); +fmr.material = mat; +floor.y = -0.1; +view.scene.addChild(floor); +const lightObj = new Object3D(); +const light = lightObj.addComponent(RectLight); +view.scene.addChild(lightObj); +engine.startRenderView(view); + +const tonemapPost = (): any => (engine.getRenderJob(view) as any)?.graph?.getPass('PostPass')?.postList?.get('TonemapPost'); +async function centerPixel(): Promise { + await frames(); + const t: GPUTexture = tonemapPost().renderTexture.getGPUTexture(); + const x = (t.width >> 1) - 1, y = (t.height >> 1) - 1; + const img = await readRegionRGBA16F(engine.context3D.device, t, x, y, 2, 2); + return [0, 1, 2].map((c) => (img[0][0][c] + img[0][1][c] + img[1][0][c] + img[1][1][c]) / 4); +} +const desc = (): RectLightDesc => { + const d = light.lightData; + return { + center: [d.lightPosition.x, d.lightPosition.y, d.lightPosition.z], normal: [d.direction.x, d.direction.y, d.direction.z], + up: [d.lightTangent.x, d.lightTangent.y, d.lightTangent.z], width: light.width, height: light.height, + color: [light.lightColor.r, light.lightColor.g, light.lightColor.b], intensity: light.intensity, range: light.range, + }; +}; +const V = [0, Math.SQRT1_2, Math.SQRT1_2]; +let ambient: number[]; + +await test('RectLight API and LightData packing', async () => { + await waitUntil(() => tonemapPost()?.renderTexture, 15000); + expect(light.lightData.lightType).tobe(LightType.RectLight); + expect(light.width).tobe(2); expect(light.height).tobe(1); + light.width = 4; light.height = 3; + expect(light.lightData.innerAngle).tobe(2); expect(light.lightData.outerAngle).tobe(1.5); + light.castShadow = true; + expect(light.castShadow).tobe(false); + // rotationX = 90 turns the emitting face straight down. + lightObj.y = 4; lightObj.rotationX = 90; + await frames(); + console.log(`[RectLight] dir ${light.lightData.direction.toString()} up ${light.lightData.lightTangent.toString()}`); + expect(light.lightData.direction.y).toSubequal(-1, 1e-4); + light.intensity = 0; + ambient = await centerPixel(); + console.log(`[RectLight] ambient ${ambient.map((v) => v.toFixed(4))}`); + expect(ambient[0] < 0.05).tobe(true); +}) + +// Shader-side roughness: the default mask map's roughness channel is 0.5, and initFragData scales by 1.85. +async function compare(label: string, albedo: number[], metallic: number, roughness: number, tol: number) { + const gpu = (await centerPixel()).map((v, i) => v - ambient[i]); + const F0 = albedo.map((a) => 0.04 * (1 - metallic) + a * metallic); + const cpu = RectLightUtil.shade([0, 0, 0], [0, 1, 0], V, albedo, metallic, Math.min(Math.max(roughness * 0.5, 0.0001), 1) * 1.85, F0, desc()); + const msg = `${label}: gpu ${gpu.map((v) => v.toFixed(4))} cpu ${cpu.map((v) => v.toFixed(4))}`; + console.log('[RectLight] ' + msg); + for (let i = 0; i < 3; i++) if (!(Math.abs(gpu[i] - cpu[i]) < 0.004 + tol * cpu[i])) throw new Error('GPU/CPU mismatch — ' + msg); + expect(true).tobe(true); + return gpu; +} + +await test('GPU diffuse matches the CPU mirror for several panel placements', async () => { + const albedo = [0.8, 0.6, 0.4]; + light.intensity = 3; light.range = 40; + const overhead = await compare('overhead 4x3 @4', albedo, 0, 0.8, 0.04); + expect(overhead[0] > 0.1).tobe(true); + // Bigger panel → more light (radiance units). + light.width = 8; light.height = 6; + const bigger = await compare('overhead 8x6 @4', albedo, 0, 0.8, 0.04); + expect(bigger[0] > overhead[0] * 1.5).tobe(true); + // Off to the side and tilted toward the origin. + light.width = 4; light.height = 2; + lightObj.x = 5; lightObj.y = 3; lightObj.z = -2; + lightObj.transform.lookAt(new Vector3(5, 3, -2), new Vector3(0, 0, 0)); + await frames(); + await compare('tilted side', albedo, 0, 0.8, 0.04); + // Coloured. + light.lightColor = new Color(1, 0.2, 0.1, 1); + const red = await compare('coloured', albedo, 0, 0.8, 0.04); + expect(red[0] > red[2] * 4).tobe(true); + light.lightColor = new Color(1, 1, 1, 1); +}) + +await test('single sided, range window and disable all remove the light', async () => { + // Face away from the floor. + lightObj.x = 0; lightObj.y = 4; lightObj.z = 0; + lightObj.transform.lookAt(new Vector3(0, 4, 0), new Vector3(0, 0, 0)); + await frames(); + const lit = (await centerPixel())[0] - ambient[0]; + lightObj.transform.lookAt(new Vector3(0, 4, 0), new Vector3(0, 8, 0.001)); + await frames(); + const away = (await centerPixel())[0] - ambient[0]; + console.log(`[RectLight] facing ${lit.toFixed(4)} away ${away.toFixed(4)}`); + expect(lit > 0.05).tobe(true); + expect(Math.abs(away) < 0.004).tobe(true); + lightObj.transform.lookAt(new Vector3(0, 4, 0), new Vector3(0, 0, 0)); + light.range = 3.9; + await frames(); + expect(Math.abs((await centerPixel())[0] - ambient[0]) < 0.004).tobe(true); + light.range = 40; + light.enable = false; + await frames(); + expect(Math.abs((await centerPixel())[0] - ambient[0]) < 0.004).tobe(true); + light.enable = true; + await frames(); + expect((await centerPixel())[0] - ambient[0]).toSubequal(lit, 0.01); +}) + +await test('GPU glossy reflection of the panel matches the CPU mirror', async () => { + mat.baseColor = new Color(0.9, 0.9, 0.9, 1); + mat.metallic = 1; mat.roughness = 0.2; + light.width = 4; light.height = 4; light.intensity = 3; + // Put the panel on the mirror direction of the camera. + lightObj.x = 0; lightObj.y = 6; lightObj.z = -6; + lightObj.transform.lookAt(new Vector3(0, 6, -6), new Vector3(0, 0, 0)); + await frames(); + // The metal reflects a little environment even with the light off: re-measure the floor. + light.intensity = 0; + ambient = await centerPixel(); + light.intensity = 3; + const on = await compare('glossy on-axis', [0.9, 0.9, 0.9], 1, 0.2, 0.05); + expect(on[0] > 0.3).tobe(true); + // Slide the panel far off the reflection ray: the highlight leaves the centre pixel. + lightObj.x = 14; + lightObj.transform.lookAt(new Vector3(14, 6, -6), new Vector3(0, 0, 0)); + await frames(); + const offAxis = await compare('glossy off-axis', [0.9, 0.9, 0.9], 1, 0.2, 0.08); + expect(offAxis[0] < on[0] * 0.2).tobe(true); +}) + +Engine3D.pause(); +setTimeout(end, 500)