Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions samples/lights/Sample_RectLight.ts
Original file line number Diff line number Diff line change
@@ -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();
2 changes: 2 additions & 0 deletions src/assets/shader/ShaderLib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);

Expand Down
1 change: 1 addition & 0 deletions src/assets/shader/core/struct/ClusterLight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<f32>,
Expand Down
4 changes: 4 additions & 0 deletions src/assets/shader/lighting/BxDF_frag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
2 changes: 2 additions & 0 deletions src/assets/shader/lighting/LightingFunction_frag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ fn spotLighting( WP:vec3<f32>, 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) ;
}
Expand Down
128 changes: 128 additions & 0 deletions src/assets/shader/lighting/RectLight_frag.ts
Original file line number Diff line number Diff line change
@@ -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<f32>, b: vec3<f32>) -> vec3<f32> {
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<f32>, p1: vec3<f32>, p2: vec3<f32>, p3: vec3<f32>) -> vec3<f32> {
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<f32>, light: LightData) -> vec3<f32> {
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<f32>(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<f32>(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<f32>(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<f32>(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;
}
`;
2 changes: 2 additions & 0 deletions src/components/lights/LightData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Struct } from '../../util/struct/Struct';
*DirectionLight|
*SpotLight|
*SkyLight|
*RectLight|
* @group Lights
*/
export enum LightType {
Expand All @@ -20,6 +21,7 @@ export enum LightType {
DirectionLight,
SpotLight,
SkyLight,
RectLight,
}

/**
Expand Down
Loading
Loading