import { CameraHelper, Color, DirectionalLight, DirectionalLightHelper, Light as ThreeLight, OrthographicCamera, PointLight, SpotLight, Vector3 } from "three"; import { serializable } from "../engine/engine_serialization_decorator.js"; import { FrameEvent } from "../engine/engine_setup.js"; import { setWorldPositionXYZ } from "../engine/engine_three_utils.js"; import type { ILight } from "../engine/engine_types.js"; import { getParam } from "../engine/engine_utils.js"; import { type NeedleXREventArgs } from "../engine/xr/api.js"; import { Behaviour, GameObject } from "./Component.js"; import { WebARSessionRoot } from "./webxr/WebARSessionRoot.js"; // https://threejs.org/examples/webgl_shadowmap_csm.html function toDegrees(radians) { return radians * 180 / Math.PI; } function toRadians(degrees) { return degrees * Math.PI / 180; } const shadowMaxDistance = 300; const debug = getParam("debuglights"); /** * Defines the type of light in a scene. */ export enum LightType { /** Spot light that emits light in a cone shape */ Spot = 0, /** Directional light that emits parallel light rays in a specific direction */ Directional = 1, /** Point light that emits light in all directions from a single point */ Point = 2, /** Area light */ Area = 3, /** Rectangle shaped area light that only affects baked lightmaps and light probes */ Rectangle = 3, /** Disc shaped area light that only affects baked lightmaps and light probes */ Disc = 4, } /** * Defines how a light contributes to the scene lighting. */ export enum LightmapBakeType { /** Light affects the scene in real-time with no baking */ Realtime = 4, /** Light is completely baked into lightmaps and light probes */ Baked = 2, /** Combines aspects of realtime and baked lighting */ Mixed = 1, } /** * Defines the shadow casting options for a Light. * @enum {number} */ enum LightShadows { /** No shadows are cast */ None = 0, /** Hard-edged shadows without filtering */ Hard = 1, /** Soft shadows with PCF filtering */ Soft = 2, } /** * The Light component creates a light source in the scene. * Supports directional, spot, and point light types with various customization options. * Lights can cast shadows with configurable settings and can be set to baked or realtime rendering. * * Debug mode can be enabled with the URL parameter `?debuglights`, which shows * additional console output and visual helpers for lights. * * @category Rendering * @group Components */ export class Light extends Behaviour implements ILight { /** * The type of light (spot, directional, point, etc.) */ @serializable() private type: LightType = 0; /** * The maximum distance the light affects */ public range: number = 1; /** * The full outer angle of the spotlight cone in degrees */ public spotAngle: number = 1; /** * The angle of the inner cone in degrees for soft-edge spotlights */ public innerSpotAngle: number = 1; /** * The color of the light */ @serializable(Color) set color(val: Color) { this._color = val; if (this.light !== undefined) { this.light.color = val; } } get color(): Color { if (this.light) return this.light.color; return this._color; } public _color: Color = new Color(0xffffff); /** * The near plane distance for shadow projection */ @serializable() set shadowNearPlane(val: number) { if (val === this._shadowNearPlane) return; this._shadowNearPlane = val; if (this.light?.shadow?.camera !== undefined) { const cam = this.light.shadow.camera as OrthographicCamera; cam.near = val; } } get shadowNearPlane(): number { return this._shadowNearPlane; } private _shadowNearPlane: number = .1; /** * Shadow bias value to reduce shadow acne and peter-panning */ @serializable() set shadowBias(val: number) { if (val === this._shadowBias) return; this._shadowBias = val; if (this.light?.shadow?.bias !== undefined) { this.light.shadow.bias = val; this.light.shadow.needsUpdate = true; } } get shadowBias(): number { return this._shadowBias; } private _shadowBias: number = 0; /** * Shadow normal bias to reduce shadow acne on sloped surfaces */ @serializable() set shadowNormalBias(val: number) { if (val === this._shadowNormalBias) return; this._shadowNormalBias = val; if (this.light?.shadow?.normalBias !== undefined) { this.light.shadow.normalBias = val; this.light.shadow.needsUpdate = true; } } get shadowNormalBias(): number { return this._shadowNormalBias; } private _shadowNormalBias: number = 0; /** when enabled this will remove the multiplication when setting the shadow bias settings initially */ private _overrideShadowBiasSettings: boolean = false; /** * Shadow casting mode (None, Hard, or Soft) */ @serializable() set shadows(val: LightShadows) { this._shadows = val; if (this.light) { this.light.castShadow = val !== LightShadows.None; this.updateShadowSoftHard(); } } get shadows(): LightShadows { return this._shadows; } private _shadows: LightShadows = 1; /** * Determines if the light contributes to realtime lighting, baked lighting, or a mix */ @serializable() private lightmapBakeType: LightmapBakeType = LightmapBakeType.Realtime; /** * Brightness of the light. In WebXR experiences, the intensity is automatically * adjusted based on the AR session scale to maintain consistent lighting. */ @serializable() set intensity(val: number) { this._intensity = val; if (this.light) { let factor: number = 1; if (this.context.isInXR && this._webARRoot) { const scaleFactor = this._webARRoot?.arScale; if (typeof scaleFactor === "number" && scaleFactor > 0) { factor /= scaleFactor; } } this.light.intensity = val * factor; } if (debug) console.log("Set light intensity to " + this._intensity, val, this) } get intensity(): number { return this._intensity; } private _intensity: number = -1; /** * Maximum distance the shadow is projected */ @serializable() get shadowDistance(): number { const light = this.light; if (light?.shadow) { const cam = light.shadow.camera as OrthographicCamera; return cam.far; } return -1; } set shadowDistance(val: number) { this._shadowDistance = val; const light = this.light; if (light?.shadow) { const cam = light.shadow.camera as OrthographicCamera; cam.far = val; cam.updateProjectionMatrix(); } } private _shadowDistance?: number; // set from additional component private shadowWidth?: number; private shadowHeight?: number; /** * Resolution of the shadow map in pixels (width and height) */ @serializable() get shadowResolution(): number { const light = this.light; if (light?.shadow) { return light.shadow.mapSize.x; } return -1; } set shadowResolution(val: number) { if (val === this._shadowResolution) return; this._shadowResolution = val; const light = this.light; if (light?.shadow) { light.shadow.mapSize.set(val, val); light.shadow.needsUpdate = true; } } private _shadowResolution?: number = undefined; /** * Whether this light's illumination is entirely baked into lightmaps */ get isBaked() { return this.lightmapBakeType === LightmapBakeType.Baked; } /** * Checks if the GameObject itself is a {@link ThreeLight} object */ private get selfIsLight(): boolean { if (this.gameObject["isLight"] === true) return true; switch (this.gameObject.type) { case "SpotLight": case "PointLight": case "DirectionalLight": return true; } return false; } /** * The underlying three.js {@link ThreeLight} instance */ private light: ThreeLight | undefined = undefined; /** * Gets the world position of the light * @param vec Vector3 to store the result * @returns The world position as a Vector3 */ public getWorldPosition(vec: Vector3): Vector3 { if (this.light) { if (this.type === LightType.Directional) { return this.light.getWorldPosition(vec).multiplyScalar(1); } return this.light.getWorldPosition(vec); } return vec; } // public updateIntensity() { // this.intensity = this._intensity; // } awake() { this.color = new Color(this.color ?? 0xffffff); if (debug) console.log(this.name, this); } onEnable(): void { if (debug) console.log("ENABLE LIGHT", this.name); this.createLight(); if (this.isBaked) return; else if (this.light) { this.light.visible = true; this.light.intensity = this._intensity; if (debug) console.log("Set light intensity to " + this.light.intensity, this.name) if (this.selfIsLight) { // nothing to do } else if (this.light.parent !== this.gameObject) this.gameObject.add(this.light); } if (this.type === LightType.Directional) this.startCoroutine(this.updateMainLightRoutine(), FrameEvent.LateUpdate); } onDisable() { if (debug) console.log("DISABLE LIGHT", this.name); if (this.light) { if (this.selfIsLight) this.light.intensity = 0; else this.light.visible = false; } } private _webXRStartedListener?: Function; private _webXREndedListener?: Function; private _webARRoot?: WebARSessionRoot; onEnterXR(_args: NeedleXREventArgs): void { this._webARRoot = GameObject.getComponentInParent(this.gameObject, WebARSessionRoot) ?? undefined; // this.startCoroutine(this._updateLightIntensityInARRoutine()); } // private *_updateLightIntensityInARRoutine() { // while (this.context.isInAR) { // yield; // // this.updateIntensity(); // for (let i = 0; i < 30; i++) yield; // } // } onLeaveXR(_args: NeedleXREventArgs): void { // this.updateIntensity(); } /** * Creates the appropriate three.js light based on the configured light type * and applies all settings like shadows, intensity, and color. */ createLight() { const lightAlreadyCreated = this.selfIsLight; if (lightAlreadyCreated && !this.light) { this.light = this.gameObject as unknown as ThreeLight; this.light.name = this.name; this._intensity = this.light.intensity; switch (this.type) { case LightType.Directional: this.setDirectionalLight(this.light as DirectionalLight); break; } } else if (!this.light) { switch (this.type) { case LightType.Directional: // console.log(this); const dirLight = new DirectionalLight(this.color, this.intensity * Math.PI); // directional light target is at 0 0 0 by default dirLight.position.set(0, 0, -shadowMaxDistance * .5).applyQuaternion(this.gameObject.quaternion); this.gameObject.add(dirLight.target); setWorldPositionXYZ(dirLight.target, 0, 0, 0); this.light = dirLight; this.gameObject.position.set(0, 0, 0); this.gameObject.rotation.set(0, 0, 0); if (debug) { const spotLightHelper = new DirectionalLightHelper(this.light as DirectionalLight, .2, this.color); this.context.scene.add(spotLightHelper); // const bh = new BoxHelper(this.context.scene, 0xfff0000); // this.context.scene.add(bh); } break; case LightType.Spot: const spotLight = new SpotLight(this.color, this.intensity * Math.PI, this.range, toRadians(this.spotAngle / 2), 1 - toRadians(this.innerSpotAngle / 2) / toRadians(this.spotAngle / 2), 2); spotLight.position.set(0, 0, 0); spotLight.rotation.set(0, 0, 0); this.light = spotLight; const spotLightTarget = spotLight.target; spotLight.add(spotLightTarget); spotLightTarget.position.set(0, 0, this.range); spotLightTarget.rotation.set(0, 0, 0); break; case LightType.Point: const pointLight = new PointLight(this.color, this.intensity * Math.PI, this.range); this.light = pointLight; // const pointHelper = new PointLightHelper(pointLight, this.range, this.color); // scene.add(pointHelper); break; } } if (this.light) { if (this._intensity >= 0) this.light.intensity = this._intensity; else this._intensity = this.light.intensity; if (this.shadows !== LightShadows.None) { this.light.castShadow = true; } else this.light.castShadow = false; if (this.light.shadow) { // shadow intensity is currently not a thing: https://github.com/mrdoob/three.js/pull/14087 if (this._shadowResolution !== undefined && this._shadowResolution > 4) { this.light.shadow.mapSize.width = this._shadowResolution; this.light.shadow.mapSize.height = this._shadowResolution; } else { this.light.shadow.mapSize.width = 2048; this.light.shadow.mapSize.height = 2048; } // this.light.shadow.needsUpdate = true; // console.log(this.light.shadow.mapSize); // return; if (debug) console.log("Override shadow bias?", this._overrideShadowBiasSettings, this.shadowBias, this.shadowNormalBias); this.light.shadow.bias = this.shadowBias; this.light.shadow.normalBias = this.shadowNormalBias; this.updateShadowSoftHard(); const cam = this.light.shadow.camera as OrthographicCamera; cam.near = this.shadowNearPlane; // use shadow distance that was set explictly (if any) if (this._shadowDistance !== undefined && typeof this._shadowDistance === "number") cam.far = this._shadowDistance; else // otherwise fallback to object scale and max distance cam.far = shadowMaxDistance * Math.abs(this.gameObject.scale.z); // width and height this.gameObject.scale.set(1, 1, 1); if (this.shadowWidth !== undefined) { cam.left = -this.shadowWidth / 2; cam.right = this.shadowWidth / 2; } else { const sx = this.gameObject.scale.x; cam.left *= sx; cam.right *= sx; } if (this.shadowHeight !== undefined) { cam.top = this.shadowHeight / 2; cam.bottom = -this.shadowHeight / 2; } else { const sy = this.gameObject.scale.y; cam.top *= sy; cam.bottom *= sy; } this.light.shadow.needsUpdate = true; if (debug) this.context.scene.add(new CameraHelper(cam)); } if (this.isBaked) { this.light.removeFromParent(); } else if (!lightAlreadyCreated) this.gameObject.add(this.light); } } /** * Coroutine that updates the main light reference in the context * if this directional light should be the main light */ *updateMainLightRoutine() { while (true) { if (this.type === LightType.Directional) { if (!this.context.mainLight || this.intensity > this.context.mainLight.intensity) { this.context.mainLight = this; } yield; } break; } } /** * Controls whether the renderer's shadow map type can be changed when soft shadows are used */ static allowChangingRendererShadowMapType: boolean = true; /** * Updates shadow settings based on whether the shadows are set to hard or soft */ private updateShadowSoftHard() { if (!this.light) return; if (!this.light.shadow) return; if (this.shadows === LightShadows.Soft) { // const radius = this.light.shadow.mapSize.width / 1024 * 5; // const samples = Mathf.clamp(Math.round(radius), 2, 10); // this.light.shadow.radius = radius; // this.light.shadow.blurSamples = samples; // if (isMobileDevice()) { // this.light.shadow.radius *= .5; // this.light.shadow.blurSamples = Math.floor(this.light.shadow.blurSamples * .5); // } // if (Light.allowChangingRendererShadowMapType) { // if(this.context.renderer.shadowMap.type !== VSMShadowMap){ // if(isLocalNetwork()) console.warn("Changing renderer shadow map type to VSMShadowMap because a light with soft shadows enabled was found (this will cause all shadow receivers to also cast shadows). If you don't want this behaviour either set the shadow type to hard or set Light.allowChangingRendererShadowMapType to false.", this); // this.context.renderer.shadowMap.type = VSMShadowMap; // } // } } else { this.light.shadow.radius = 1; this.light.shadow.blurSamples = 1; } } /** * Configures a directional light by adding and positioning its target * @param dirLight The directional light to set up */ private setDirectionalLight(dirLight: DirectionalLight) { dirLight.add(dirLight.target); dirLight.target.position.set(0, 0, -1); // dirLight.position.add(vec.set(0,0,1).multiplyScalar(shadowMaxDistance*.1).applyQuaternion(this.gameObject.quaternion)); } } const vec = new Vector3(0, 0, 0);