A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): a light aims where its entity is turned
yhhd7b90cb33f51
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 620898f2e..5f091d9fd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,33 @@ published separately; it ships inside the editor.## [Unreleased]+### Changed++- **A light aims where its entity is turned.** A light carried its own aim —+ `direction` in the plane and a `directionZ` bolted on beside it — and the entity's+ rotation meant nothing to the renderer. So rotating a light did nothing, a torch+ parented to a character did not swing with it, an imported light had nowhere to put+ its orientation, and a spot's cone axis travelled to the shader in two unrelated+ slots. The camera has taken its orientation from its Transform all along; the light+ was the one thing in the engine that did not.++ A light's aim is its entity's forward now — the rotation applied to -Z, which is+ where an unrotated light has always shone. `Light2D.direction` and+ `Light2D.directionZ` are gone; the rotate gizmo aims a light, a parent turns it, and+ a rotation track animates it. The GPU wire format is untouched — only where the+ renderer reads the aim from changed.++ Scenes and prefabs written before this are upgraded on load: the pair becomes the+ rotation whose forward IS that direction, so every scene is lit exactly as it was.+ `upgradeEntityComponents` is that upgrade, and it is one function now rather than+ the SDK's half and the editor's — the editor had its own copy of the retired-component+ drop and none of the rest, so a scene opened in the editor and the same scene played+ were two different upgrades.++ `lightAimRotation` / `lightAimOf` name the convention on the SDK side (one place;+ the engine's is `lightForward`), and `q.rotationTo` joins the math module — the+ shortest turn from one direction to another, which is what naming an aim means.+### Added- **An entity's box has a third dimension, and one hit test uses it.** `EntityBox`diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex c19c6b650..24c40243c 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -19,6 +19,7 @@ import {pickEntitiesByRay, editorViewIsOrbited,moveEditorViewFocus, editorViewBoxExtent,editorViewAxes, editorViewAxisAngles, cameraFrustumCorners, type ScreenAxis,+ lightAimOf,rayPlaneHit, type WorldRay, type Vec3,type TilesetModel, type TileCollisionPiece, type TileGridParams,} from 'esengine';@@ -843,7 +844,7 @@ export const ViewportController = {const t = world.get(id, Transform);const l = world.get(id, Light2D) as {type: number; color: { r: number; g: number; b: number }; radius: number;- direction: { x: number; y: number }; outerAngle: number; enabled: boolean; intensity: number;+ outerAngle: number; enabled: boolean; intensity: number;};const toClient = this.projectorFor(id);const center = toClient(t.worldPosition.x, t.worldPosition.y);@@ -855,15 +856,17 @@ export const ViewportController = {const edge = toClient(t.worldPosition.x + l.radius, t.worldPosition.y);if (edge) radiusPx = Math.hypot(edge.x - center.x, edge.y - center.y);}- // Directional (1) / Spot (3) point along `direction`; flip world-Y to screen space. A Spot- // with no direction defaults to aiming down (matching the engine's collectLights fallback).+ // Directional (1) / Spot (3) aim along the entity's forward; flip world-Y to screen+ // space. An aim with nothing in the plane draws no arrow, and a Spot falls back to+ // down — both are what the engine's collectLights reads off the same rotation.let sdx = 0;let sdy = 0;if (l.type === 1 || l.type === 3) {- const len = Math.hypot(l.direction.x, l.direction.y);+ const aim = lightAimOf(t.worldRotation);+ const len = Math.hypot(aim.x, aim.y);if (len > 1e-4) {- sdx = l.direction.x / len;- sdy = -l.direction.y / len;+ sdx = aim.x / len;+ sdy = -aim.y / len;} else if (l.type === 3) {sdy = 1; // world (0,-1) → screen down}diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.tsindex b341598c4..2da87c3e3 100644--- a/desktop/src/engine/entitySources.ts+++ b/desktop/src/engine/entitySources.ts@@ -17,7 +17,7 @@import { projectPrefabSources, projectDesignSeed } from './projectSeams';import type { LucideIcon } from 'lucide-react';import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput, Grid3x3, MapPin, Scan, Sun } from 'lucide-react';-import { BUILTIN_MESH_TEMPLATES, BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, applyThemeToWorld, type PrefabData } from 'esengine';+import { BUILTIN_MESH_TEMPLATES, BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, applyThemeToWorld, lightAimRotation, type PrefabData } from 'esengine';import type { EntityId } from '@/types';import { ContributionRegistry } from '@/contrib/ContributionRegistry';import { componentByName, componentDefaults, readonlyFieldsFor, prettyLabel, componentCategory, userComponentNames } from './schema';@@ -283,7 +283,7 @@ export const ENTITY_SOURCES: EntitySource[] = [// lights a mesh from inside it. A key light aimed into the screen is what shaded// geometry needs, and nothing else in the picker offers one.presetSource('sun', 'Sun', componentCategory('Light2D'), Sun,- [['Transform', {}], ['Light2D', { type: 1, direction: { x: 0.3, y: -0.5 }, directionZ: -0.8 }]]),+ [['Transform', { rotation: lightAimRotation({ x: 0.3, y: -0.5, z: -0.8 }) }], ['Light2D', { type: 1 }]]),// Tilemap is asset-driven (it needs a tileset + orientation), so it can't build// synchronously like an anchor — picking it opens the New-Tilemap dialog. Listed here// anyway so the Create picker stays the one place every entity is born.diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex fe1e35e63..edbed8318 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -780,7 +780,6 @@ function isConditionallyHidden(compType: string, key: string, data: Record<strin// type: Point = 0, Directional = 1, Ambient = 2, Spot = 3.const type = Number(data.type) || 0;if (key === 'radius') return type === 1 || type === 2; // Point / Spot reach only- if (key === 'direction') return type === 0 || type === 2; // Directional / Spot aim onlyif (key === 'innerAngle' || key === 'outerAngle') return type !== 3; // Spot cone onlyif (key === 'shadowDistance') return type !== 1; // Directional shadow onlyif (key === 'shadowSoftness') return type === 2; // Ambient casts no shadowdiff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 58595fed5..f0dad70b8 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createStore } from 'zustand/vanilla';-import { getComponent, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, textureImportSettingsFrom, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot, Audio, applyAudioProjectConfig } from 'esengine';+import { getComponent, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, textureImportSettingsFrom, Renderer, migrateSceneData, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot, Audio, applyAudioProjectConfig } from 'esengine';import { applyImporterEdit } from './assetImporter';import { hasImporter, runImporters } from '../plugins/importers';import { importerDefaults } from '../../../pipeline/src/project/importSettings';@@ -122,27 +122,6 @@ function unknownComponentTypes(data: SceneData): string[] {return [...unknown];}-/**- * Drop components retired by an engine upgrade (see SDK RETIRED_COMPONENT_TYPES)- * from a raw scene, in place; returns the retired type names that were present.- * These are dead ENGINE types — unlike genuinely-unknown project components (kept- * verbatim so they round-trip), they carry no live system. Stripping them out of- * the source-of-truth model on open means a save cleans the file, and they never- * reach the "unknown project component" warning below. The SDK scene loader drops- * them too, so Play never warns "Unknown component type" on them.- */-function stripRetiredComponents(data: SceneData): string[] {- const dropped = new Set<string>();- for (const entity of data.entities ?? []) {- const comps = entity.components;- if (!comps) continue;- for (let i = comps.length - 1; i >= 0; i--) {- if (RETIRED_COMPONENT_TYPES.has(comps[i].type)) { dropped.add(comps[i].type); comps.splice(i, 1); }- }- }- return [...dropped];-}-class ProjectStoreImpl {private readonly store = createStore<{ project: ProjectState | null }>(() => ({ project: null }));/** Active Prefab Mode session, or null. Holds the id-preservation map@@ -488,8 +467,9 @@ class ProjectStoreImpl {return;}const { rel, text } = found;- const raw = JSON.parse(text) as SceneData;- const retired = stripRetiredComponents(raw);+ // The SDK's own upgrade rather than the editor's half of it: what a scene+ // becomes on load is what the editor has to show, and what a save writes back.+ const { data: raw, retired } = migrateSceneData(JSON.parse(text) as SceneData);if (retired.length > 0) {console.info(`[project] upgraded scene "${rel}": dropped retired engine component(s) ` +diff --git a/desktop/tests/inspector-conditional-fields.test.ts b/desktop/tests/inspector-conditional-fields.test.tsindex 04c5eb299..dc09c2c3a 100644--- a/desktop/tests/inspector-conditional-fields.test.ts+++ b/desktop/tests/inspector-conditional-fields.test.ts@@ -32,36 +32,37 @@ describe('conditional inspector fields', () => {});describe('Light2D type', () => {- it('Point: radius only, no direction / cone angles / directional shadow', () => {+ it('Point: radius only, no cone angles / directional shadow', () => {const k = keys('Light2D', { type: 0 });expect(k.has('radius')).toBe(true);- expect(k.has('direction')).toBe(false);expect(k.has('innerAngle')).toBe(false);expect(k.has('shadowDistance')).toBe(false);});- it('Directional: direction + directional shadow, no radius / cone angles', () => {+ it('Directional: directional shadow, no radius / cone angles', () => {const k = keys('Light2D', { type: 1 });- expect(k.has('direction')).toBe(true);expect(k.has('shadowDistance')).toBe(true);expect(k.has('radius')).toBe(false);expect(k.has('outerAngle')).toBe(false);});- it('Ambient: neither reach, aim, cone, nor shadows', () => {+ it('Ambient: neither reach, cone, nor shadows', () => {const k = keys('Light2D', { type: 2 });expect(k.has('radius')).toBe(false);- expect(k.has('direction')).toBe(false);expect(k.has('innerAngle')).toBe(false);expect(k.has('shadowSoftness')).toBe(false);expect(k.has('intensity')).toBe(true); // still tunable});- it('Spot: reach + aim + cone angles, no directional shadow', () => {+ it('Spot: reach + cone angles, no directional shadow', () => {const k = keys('Light2D', { type: 3 });expect(k.has('radius')).toBe(true);- expect(k.has('direction')).toBe(true);expect(k.has('innerAngle')).toBe(true);expect(k.has('outerAngle')).toBe(true);expect(k.has('shadowDistance')).toBe(false);});+ it('no type shows an aim field — a light is aimed by its Transform', () => {+ for (const type of [0, 1, 2, 3]) {+ expect(keys('Light2D', { type }).has('direction')).toBe(false);+ }+ });});describe('ParticleEmitter shape', () => {diff --git a/docs/astro/src/content/docs/graphics/lighting.mdx b/docs/astro/src/content/docs/graphics/lighting.mdxindex 7c5ba7e14..d8888a109 100644--- a/docs/astro/src/content/docs/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/graphics/lighting.mdx@@ -21,16 +21,19 @@ sprites stay unlit, and the ones you want lit get a lit material.Give an entity a `Light2D` component and pick a type:```typescript-import { defineSystem, Commands, Transform, Light2D, Light2DType } from 'esengine';+import { defineSystem, Commands, Transform, Light2D, Light2DType, lightAimRotation } from 'esengine';const addSun = defineSystem([Commands()], (cmds) => {cmds.spawn()- .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ // A light aims along its entity's forward, so the sun is aimed by turning it.+ .insert(Transform, {+ position: { x: 0, y: 0, z: 0 },+ rotation: lightAimRotation({ x: -1, y: -1, z: -1 }),+ }).insert(Light2D, {type: Light2DType.Directional,color: { r: 1, g: 0.95, b: 0.8, a: 1 },intensity: 1.2,- direction: { x: -1, y: -1 },});});```@@ -43,7 +46,6 @@ const addSun = defineSystem([Commands()], (cmds) => {| `color` | `{1,1,1,1}` | Light color, RGBA 0..1. || `intensity` | `1` | Brightness multiplier. || `radius` | `200` | Falloff reach in world units (Point / Spot). |-| `direction` | `{0,0}` | Aim direction (Directional / Spot). || `innerAngle` | `30` | Spot cone inner angle, degrees (full brightness inside). || `outerAngle` | `45` | Spot cone outer angle, degrees (falls to zero by here). || `shadowSoftness` | `0` | Shadow edge softness (light-source size); `0` = hard edge. |@@ -54,9 +56,9 @@ const addSun = defineSystem([Commands()], (cmds) => {| Type | Behavior ||---|---|-| **Directional** | A uniform light from one `direction`, like the sun — position doesn't matter, only the aim. |+| **Directional** | A uniform light along the entity's forward, like the sun — position doesn't matter, only the rotation. || **Point** | Radiates from the entity's position and falls off to nothing at `radius`. |-| **Spot** | A cone from the position along `direction`, full-bright within `innerAngle` and fading to the edge at `outerAngle`, out to `radius`. |+| **Spot** | A cone from the position along the entity's forward, full-bright within `innerAngle` and fading to the edge at `outerAngle`, out to `radius`. || **Ambient** | A flat base light added everywhere, regardless of position — use a low `intensity` so shaded areas aren't pure black. |```typescript@@ -64,8 +66,9 @@ const addSun = defineSystem([Commands()], (cmds) => {.insert(Light2D, { type: Light2DType.Point, radius: 320, intensity: 1.5,color: { r: 1, g: 0.7, b: 0.3, a: 1 } });-// A flashlight cone-.insert(Light2D, { type: Light2DType.Spot, direction: { x: 0, y: -1 },+// A flashlight cone, aimed down the screen by the entity it sits on+.insert(Transform, { rotation: lightAimRotation({ x: 0, y: -1, z: 0 }) })+.insert(Light2D, { type: Light2DType.Spot,innerAngle: 18, outerAngle: 34, radius: 500, intensity: 2 });// A dim ambient fill so nothing is fully black@@ -227,9 +230,9 @@ mesh standing above another darkens it.```typescriptcmds.spawn()+ .insert(Transform, { rotation: lightAimRotation({ x: 0.5, y: 0, z: -1 }) }) // where the rays lean.insert(Light2D, {type: Light2DType.Directional,- direction: { x: 0.5, y: 0 }, // where the rays leanmeshShadows: true,});```diff --git a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdxindex f0cc1af39..3bd7484b5 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx@@ -19,16 +19,19 @@ Estella 用 **`Light2D`** 光源和 **`ShadowCaster2D`** 遮挡体照亮 2D 场给一个实体加 `Light2D` 组件并选一个类型:```typescript-import { defineSystem, Commands, Transform, Light2D, Light2DType } from 'esengine';+import { defineSystem, Commands, Transform, Light2D, Light2DType, lightAimRotation } from 'esengine';const addSun = defineSystem([Commands()], (cmds) => {cmds.spawn()- .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ // 灯沿所在实体的朝前方向照射,所以太阳靠转动它来瞄准。+ .insert(Transform, {+ position: { x: 0, y: 0, z: 0 },+ rotation: lightAimRotation({ x: -1, y: -1, z: -1 }),+ }).insert(Light2D, {type: Light2DType.Directional,color: { r: 1, g: 0.95, b: 0.8, a: 1 },intensity: 1.2,- direction: { x: -1, y: -1 },});});```@@ -41,7 +44,6 @@ const addSun = defineSystem([Commands()], (cmds) => {| `color` | `{1,1,1,1}` | 光颜色,RGBA 0..1。 || `intensity` | `1` | 亮度倍数。 || `radius` | `200` | 衰减半径,世界单位(Point / Spot)。 |-| `direction` | `{0,0}` | 朝向(Directional / Spot)。 || `innerAngle` | `30` | 聚光锥内角,度(内部全亮)。 || `outerAngle` | `45` | 聚光锥外角,度(到这里衰减为零)。 || `shadowSoftness` | `0` | 阴影边缘柔和度(光源尺寸);`0` = 硬边。 |@@ -52,9 +54,9 @@ const addSun = defineSystem([Commands()], (cmds) => {| 类型 | 行为 ||---|---|-| **Directional(方向光)** | 来自单一 `direction` 的均匀光,像太阳——位置无关,只看朝向。 |+| **Directional(方向光)** | 沿实体朝前方向的均匀光,像太阳——位置无关,只看旋转。 || **Point(点光)** | 从实体位置向外辐射,到 `radius` 处衰减为零。 |-| **Spot(聚光)** | 从位置沿 `direction` 的一个锥,在 `innerAngle` 内全亮、到 `outerAngle` 衰减到边缘,直到 `radius`。 |+| **Spot(聚光)** | 从位置沿实体朝前方向的一个锥,在 `innerAngle` 内全亮、到 `outerAngle` 衰减到边缘,直到 `radius`。 || **Ambient(环境光)** | 处处叠加的平坦底光,与位置无关——用较低的 `intensity`,让阴影区不至于纯黑。 |```typescript@@ -62,8 +64,9 @@ const addSun = defineSystem([Commands()], (cmds) => {.insert(Light2D, { type: Light2DType.Point, radius: 320, intensity: 1.5,color: { r: 1, g: 0.7, b: 0.3, a: 1 } });-// 一束手电锥-.insert(Light2D, { type: Light2DType.Spot, direction: { x: 0, y: -1 },+// 一束手电锥,由它所在的实体朝下瞄准+.insert(Transform, { rotation: lightAimRotation({ x: 0, y: -1, z: 0 }) })+.insert(Light2D, { type: Light2DType.Spot,innerAngle: 18, outerAngle: 34, radius: 500, intensity: 2 });// 一点微弱环境光,让画面不至于全黑@@ -213,9 +216,9 @@ mesh 再画一遍,于是站得高的 mesh 会让下面的暗下来。```typescriptcmds.spawn()+ .insert(Transform, { rotation: lightAimRotation({ x: 0.5, y: 0, z: -1 }) }) // 光线偏向哪边.insert(Light2D, {type: Light2DType.Directional,- direction: { x: 0.5, y: 0 }, // 光线偏向哪边meshShadows: true,});```diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 62b316be6..fdbf09416 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 113,"beta": 73,- "experimental": 1588,+ "experimental": 1591,"deprecated": 3},- "total": 1774,+ "total": 1777,"subsystems": [{"id": "ecs",diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 60273d86a..cd5e248ea 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1571,20 +1571,6 @@"doc": "Falloff reach in world units (Point / Spot).","range": "≥ 0"},- {- "key": "direction",- "type": "Vec2",- "default": "(0, 0)",- "doc": "Aim direction (Directional / Spot).",- "advanced": true- },- {- "key": "directionZ",- "type": "number",- "default": "-1",- "doc": "Aim depth (Directional): -1 shines into the screen.",- "advanced": true- },{"key": "innerAngle","type": "number",@@ -1653,7 +1639,6 @@"color.a","intensity","radius",- "directionZ","innerAngle","outerAngle","shadowSoftness",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex b1390c5b7..23bfe70fd 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,11 +1,11 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 66 beta · 1474 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1477 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"9169449040ae1dcb"+"e868cc33a27b61d4"```## ANCHOR_AXES — const @experimental@@ -3928,6 +3928,11 @@ static new (opts?: KineticScrollOptions): KineticScrollstatic prototype: KineticScroll```+## LIGHT_FORWARD — const @experimental+```+Readonly<Vec3>+```+## LIGHT_TOKENS — const @experimental```ThemeTokens@@ -4004,8 +4009,6 @@ BuiltinComponentDef<Light2DData>## Light2DData — interface @experimental```color: Color-direction: Vec2-directionZ: numberdrawEnvironment: booleanenabled: booleanenvironment: number@@ -6628,6 +6631,7 @@ static prototype: SceneManagerStatedata: SceneDatafromVersion: numbermigrated: boolean+retired: string[]toVersion: number```@@ -10652,6 +10656,16 @@ InputRouterLifecyclePlugin```+## lightAimOf — function @experimental+```+(rotation: Quat): Vec3+```++## lightAimRotation — function @experimental+```+(aim: Vec3): Quat+```+## loadComponent — function @experimental```(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void@@ -11129,7 +11143,7 @@ PrefabsPlugin## q — const @experimental```-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }```## quat — const @experimentaldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 2947e1598..9dd14db56 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,11 +1,11 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 71 beta · 1493 experimental · 3 deprecated+Symbols: 113 public · 71 beta · 1496 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"9169449040ae1dcb"+"e868cc33a27b61d4"```## ANCHOR_AXES — const @experimental@@ -3936,6 +3936,11 @@ static new (opts?: KineticScrollOptions): KineticScrollstatic prototype: KineticScroll```+## LIGHT_FORWARD — const @experimental+```+Readonly<Vec3>+```+## LIGHT_TOKENS — const @experimental```ThemeTokens@@ -4012,8 +4017,6 @@ BuiltinComponentDef<Light2DData>## Light2DData — interface @experimental```color: Color-direction: Vec2-directionZ: numberdrawEnvironment: booleanenabled: booleanenvironment: number@@ -6821,6 +6824,7 @@ static prototype: SceneManagerStatedata: SceneDatafromVersion: numbermigrated: boolean+retired: string[]toVersion: number```@@ -10895,6 +10899,16 @@ InputRouterLifecyclePlugin```+## lightAimOf — function @experimental+```+(rotation: Quat): Vec3+```++## lightAimRotation — function @experimental+```+(aim: Vec3): Quat+```+## loadComponent — function @experimental```(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void@@ -11372,7 +11386,7 @@ PrefabsPlugin## q — const @experimental```-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }```## quat — const @experimentaldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex d1c572550..b9a581399 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 68 beta · 1473 experimental · 3 deprecated+Symbols: 113 public · 68 beta · 1476 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -3923,6 +3923,11 @@ static new (opts?: KineticScrollOptions): KineticScrollstatic prototype: KineticScroll```+## LIGHT_FORWARD — const @experimental+```+Readonly<Vec3>+```+## LIGHT_TOKENS — const @experimental```ThemeTokens@@ -3999,8 +4004,6 @@ BuiltinComponentDef<Light2DData>## Light2DData — interface @experimental```color: Color-direction: Vec2-directionZ: numberdrawEnvironment: booleanenabled: booleanenvironment: number@@ -6623,6 +6626,7 @@ static prototype: SceneManagerStatedata: SceneDatafromVersion: numbermigrated: boolean+retired: string[]toVersion: number```@@ -10647,6 +10651,16 @@ InputRouterLifecyclePlugin```+## lightAimOf — function @experimental+```+(rotation: Quat): Vec3+```++## lightAimRotation — function @experimental+```+(aim: Vec3): Quat+```+## loadComponent — function @experimental```(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void@@ -11134,7 +11148,7 @@ PrefabsPlugin## q — const @experimental```-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }```## quat — const @experimentaldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex f5c2cfe88..56afd54b9 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 66 beta · 1494 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1497 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -3923,6 +3923,11 @@ static new (opts?: KineticScrollOptions): KineticScrollstatic prototype: KineticScroll```+## LIGHT_FORWARD — const @experimental+```+Readonly<Vec3>+```+## LIGHT_TOKENS — const @experimental```ThemeTokens@@ -3999,8 +4004,6 @@ BuiltinComponentDef<Light2DData>## Light2DData — interface @experimental```color: Color-direction: Vec2-directionZ: numberdrawEnvironment: booleanenabled: booleanenvironment: number@@ -6868,6 +6871,7 @@ static prototype: SceneManagerStatedata: SceneDatafromVersion: numbermigrated: boolean+retired: string[]toVersion: number```@@ -10907,6 +10911,16 @@ InputRouterLifecyclePlugin```+## lightAimOf — function @experimental+```+(rotation: Quat): Vec3+```++## lightAimRotation — function @experimental+```+(aim: Vec3): Quat+```+## loadComponent — function @experimental```(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void@@ -11384,7 +11398,7 @@ PrefabsPlugin## q — const @experimental```-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }```## quat — const @experimentaldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex f61ffd2c4..a2c595665 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 66 beta · 1484 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1487 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -3930,6 +3930,11 @@ static new (opts?: KineticScrollOptions): KineticScrollstatic prototype: KineticScroll```+## LIGHT_FORWARD — const @experimental+```+Readonly<Vec3>+```+## LIGHT_TOKENS — const @experimental```ThemeTokens@@ -4006,8 +4011,6 @@ BuiltinComponentDef<Light2DData>## Light2DData — interface @experimental```color: Color-direction: Vec2-directionZ: numberdrawEnvironment: booleanenabled: booleanenvironment: number@@ -6630,6 +6633,7 @@ static prototype: SceneManagerStatedata: SceneDatafromVersion: numbermigrated: boolean+retired: string[]toVersion: number```@@ -10679,6 +10683,16 @@ InputRouterLifecyclePlugin```+## lightAimOf — function @experimental+```+(rotation: Quat): Vec3+```++## lightAimRotation — function @experimental+```+(aim: Vec3): Quat+```+## loadComponent — function @experimental```(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void@@ -11156,7 +11170,7 @@ PrefabsPlugin## q — const @experimental```-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }```## quat — const @experimentaldiff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex 120a694c2..dd7461a8c 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -17,6 +17,8 @@export { Filters } from './render/filters';+export { LIGHT_FORWARD, lightAimRotation, lightAimOf } from './render/lightAim';+export {SpriteFilter,type OutlineFilterOptions,diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.tsindex b0eaa70a3..e00559db4 100644--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts@@ -690,8 +690,6 @@ export interface Light2DPtrData {color: Color;intensity: number;radius: number;- direction: Vec2;- directionZ: number;innerAngle: number;outerAngle: number;shadowSoftness: number;@@ -711,17 +709,15 @@ export function fillLight2D(const color_ = out.color; color_.r = f32[(ptr + 4) >> 2]; color_.g = f32[((ptr + 4) >> 2) + 1]; color_.b = f32[((ptr + 4) >> 2) + 2]; color_.a = f32[((ptr + 4) >> 2) + 3];out.intensity = f32[(ptr + 20) >> 2];out.radius = f32[(ptr + 24) >> 2];- const direction_ = out.direction; direction_.x = f32[(ptr + 28) >> 2]; direction_.y = f32[((ptr + 28) >> 2) + 1];- out.directionZ = f32[(ptr + 36) >> 2];- out.innerAngle = f32[(ptr + 40) >> 2];- out.outerAngle = f32[(ptr + 44) >> 2];- out.shadowSoftness = f32[(ptr + 48) >> 2];- out.shadowDistance = f32[(ptr + 52) >> 2];- out.meshShadows = u8[ptr + 56] !== 0;- out.shadowExtent = f32[(ptr + 60) >> 2];- out.environment = u32[(ptr + 64) >> 2];- out.drawEnvironment = u8[ptr + 68] !== 0;- out.enabled = u8[ptr + 69] !== 0;+ out.innerAngle = f32[(ptr + 28) >> 2];+ out.outerAngle = f32[(ptr + 32) >> 2];+ out.shadowSoftness = f32[(ptr + 36) >> 2];+ out.shadowDistance = f32[(ptr + 40) >> 2];+ out.meshShadows = u8[ptr + 44] !== 0;+ out.shadowExtent = f32[(ptr + 48) >> 2];+ out.environment = u32[(ptr + 52) >> 2];+ out.drawEnvironment = u8[ptr + 56] !== 0;+ out.enabled = u8[ptr + 57] !== 0;}export function writeLight2D(@@ -732,17 +728,15 @@ export function writeLight2D(f32[(ptr + 4) >> 2] = data.color.r; f32[((ptr + 4) >> 2) + 1] = data.color.g; f32[((ptr + 4) >> 2) + 2] = data.color.b; f32[((ptr + 4) >> 2) + 3] = data.color.a;f32[(ptr + 20) >> 2] = data.intensity;f32[(ptr + 24) >> 2] = data.radius;- f32[(ptr + 28) >> 2] = data.direction.x; f32[((ptr + 28) >> 2) + 1] = data.direction.y;- f32[(ptr + 36) >> 2] = data.directionZ;- f32[(ptr + 40) >> 2] = data.innerAngle;- f32[(ptr + 44) >> 2] = data.outerAngle;- f32[(ptr + 48) >> 2] = data.shadowSoftness;- f32[(ptr + 52) >> 2] = data.shadowDistance;- u8[ptr + 56] = data.meshShadows ? 1 : 0;- f32[(ptr + 60) >> 2] = data.shadowExtent;- u32[(ptr + 64) >> 2] = data.environment;- u8[ptr + 68] = data.drawEnvironment ? 1 : 0;- u8[ptr + 69] = data.enabled ? 1 : 0;+ f32[(ptr + 28) >> 2] = data.innerAngle;+ f32[(ptr + 32) >> 2] = data.outerAngle;+ f32[(ptr + 36) >> 2] = data.shadowSoftness;+ f32[(ptr + 40) >> 2] = data.shadowDistance;+ u8[ptr + 44] = data.meshShadows ? 1 : 0;+ f32[(ptr + 48) >> 2] = data.shadowExtent;+ u32[(ptr + 52) >> 2] = data.environment;+ u8[ptr + 56] = data.drawEnvironment ? 1 : 0;+ u8[ptr + 57] = data.enabled ? 1 : 0;}export function createLight2DData(): Light2DPtrData {@@ -751,8 +745,6 @@ export function createLight2DData(): Light2DPtrData {color: { r: 0, g: 0, b: 0, a: 0 },intensity: 0,radius: 0,- direction: { x: 0, y: 0 },- directionZ: 0,innerAngle: 0,outerAngle: 0,shadowSoftness: 0,diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 23de78fd1..4baf0ff7f 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -15,7 +15,7 @@ import type { Dimension, Padding } from '../wasm/wasm.generated';* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to* run on mismatch, because mismatched offsets read the wrong heap bytes.*/-export const ABI_LAYOUT_HASH = '9169449040ae1dcb';+export const ABI_LAYOUT_HASH = 'e868cc33a27b61d4';/*** One asset-valued field of a component: which field, and what kind of@@ -392,8 +392,6 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {color: { r: 1, g: 1, b: 1, a: 1 },intensity: 1,radius: 200,- direction: { x: 0, y: 0 },- directionZ: -1,innerAngle: 30,outerAngle: 45,shadowSoftness: 0,@@ -408,13 +406,11 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {assetFields: [{ field: 'environment', type: 'environment' as AssetFieldType }],entityFields: [],colorFields: ['color'],- animatableFields: ['color.r', 'color.g', 'color.b', 'color.a', 'intensity', 'radius', 'directionZ', 'innerAngle', 'outerAngle', 'shadowSoftness', 'shadowDistance'],+ animatableFields: ['color.r', 'color.g', 'color.b', 'color.a', 'intensity', 'radius', 'innerAngle', 'outerAngle', 'shadowSoftness', 'shadowDistance'],fields: {type: { enum: [{ label: 'Point', value: 0 }, { label: 'Directional', value: 1 }, { label: 'Ambient', value: 2 }, { label: 'Spot', value: 3 }], tooltip: "Point, Directional, Ambient, or Spot." },intensity: { min: 0, tooltip: "Brightness multiplier of the light." },radius: { min: 0, tooltip: "Falloff reach in world units (Point / Spot)." },- direction: { tooltip: "Aim direction (Directional / Spot).", advanced: true },- directionZ: { tooltip: "Aim depth (Directional): -1 shines into the screen.", advanced: true },innerAngle: { min: 0, max: 180, unit: "°", advanced: true },outerAngle: { min: 0, max: 180, unit: "°", advanced: true },shadowSoftness: { min: 0, tooltip: "Shadow softness (light-source size); 0 = hard edge." },@@ -1206,8 +1202,6 @@ export interface Light2DData {color: Color;intensity: number;radius: number;- direction: Vec2;- directionZ: number;innerAngle: number;outerAngle: number;shadowSoftness: number;diff --git a/sdk/src/math/quat.ts b/sdk/src/math/quat.tsindex fa33206f5..822a08c1b 100644--- a/sdk/src/math/quat.ts+++ b/sdk/src/math/quat.ts@@ -114,6 +114,38 @@ export const q = {};},+ /**+ * The shortest turn taking `from` to `to`; either may be any length. A+ * direction is a way of naming a rotation, so it comes in here — what is+ * stored stays the rotation. Roll about the axis is unconstrained by the pair+ * and is left at none, which is what an aim has to say about it.+ */+ rotationTo(from: Vec3, to: Vec3): Quat {+ const fl = Math.hypot(from.x, from.y, from.z);+ const tl = Math.hypot(to.x, to.y, to.z);+ if (fl === 0 || tl === 0) return { w: 1, x: 0, y: 0, z: 0 };+ const f = { x: from.x / fl, y: from.y / fl, z: from.z / fl };+ const t = { x: to.x / tl, y: to.y / tl, z: to.z / tl };+ const d = f.x * t.x + f.y * t.y + f.z * t.z;+ if (d >= 1 - 1e-9) return { w: 1, x: 0, y: 0, z: 0 };+ // Opposite: every axis perpendicular to `from` is a half turn taking it to+ // `to`, so pick one that exists for any `from` rather than a fixed axis it+ // could be parallel to.+ if (d <= -1 + 1e-9) {+ const axis = Math.abs(f.x) > 0.9 ? { x: 0, y: 1, z: 0 } : { x: 1, y: 0, z: 0 };+ const px = f.y * axis.z - f.z * axis.y;+ const py = f.z * axis.x - f.x * axis.z;+ const pz = f.x * axis.y - f.y * axis.x;+ return this.normalize({ w: 0, x: px, y: py, z: pz });+ }+ return this.normalize({+ w: 1 + d,+ x: f.y * t.z - f.z * t.y,+ y: f.z * t.x - f.x * t.z,+ z: f.x * t.y - f.y * t.x,+ });+ },+/** Set the Z turn, keeping whatever the other two axes say — the 2D way in. */setAngleZ(a: Quat | undefined, deg: number): Quat {const e = a ? this.toEuler(a) : [0, 0, 0];diff --git a/sdk/src/prefab/migrate.ts b/sdk/src/prefab/migrate.tsindex 51839b4a5..9c87cd97b 100644--- a/sdk/src/prefab/migrate.ts+++ b/sdk/src/prefab/migrate.ts@@ -1,6 +1,11 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { PrefabData, PrefabEntityData, PrefabOverride } from './types';+import {+ needsComponentUpgrade,+ upgradeEntityComponents,+ type UpgradableEntity,+} from '../scene/legacyComponents';/*** Result of a migration pass over a prefab JSON blob. `migrated` is true@@ -45,8 +50,13 @@ export function migratePrefabData(raw: unknown): MigrationResult {// (a file authored as an old version but already string-id'd must still bump// to current, so "re-save" truly lands on the latest format).const isLegacy = needsMigration(obj) || fromVersion !== PREFAB_FORMAT_VERSION;+ // A prefab current in every other way can still hold component data written+ // for an older engine, and upgrading that rewrites records the caller owns —+ // so the copy is made here rather than editing under them.+ const staleComponents = !isLegacy+ && (obj['entities'] as UpgradableEntity[]).some(needsComponentUpgrade);- if (!isLegacy) {+ if (!isLegacy && !staleComponents) {return {data: obj as unknown as PrefabData,migrated: false,@@ -55,13 +65,18 @@ export function migratePrefabData(raw: unknown): MigrationResult {};}- const upgraded = upgradeNumericIds(obj);- upgraded.version = PREFAB_FORMAT_VERSION;+ const upgraded = isLegacy+ ? upgradeNumericIds(obj)+ : (JSON.parse(JSON.stringify(obj)) as PrefabData);+ // The same door a scene's components come through: a prefab holds the same+ // records, and an upgrade that ran on only one of the two is half an upgrade.+ for (const entity of upgraded.entities) upgradeEntityComponents(entity);+ if (isLegacy) upgraded.version = PREFAB_FORMAT_VERSION;return {data: upgraded,migrated: true,fromVersion,- toVersion: PREFAB_FORMAT_VERSION,+ toVersion: isLegacy ? PREFAB_FORMAT_VERSION : fromVersion,};}diff --git a/sdk/src/render/lightAim.ts b/sdk/src/render/lightAim.tsnew file mode 100644index 000000000..5851207c5--- /dev/null+++ b/sdk/src/render/lightAim.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file lightAim.ts+ * @brief A light aims along its entity's forward.+ * @details Where a light points is its Transform's rotation, the same fact a+ * camera's orientation is — so a light turns with its parent, a rotate+ * gizmo aims it, and an animation track can swing it. Naming a direction+ * instead is a way IN, and this is the one place on this side of the+ * boundary that says which direction "no rotation" means; the engine's is+ * `lightForward` in RenderFrame.cpp.+ */++import { q } from '../math/quat';+import type { Quat, Vec3 } from '../types';++/** The direction an unrotated light aims: into the screen, where a 2D scene's+ * light has always come from. */+export const LIGHT_FORWARD: Readonly<Vec3> = { x: 0, y: 0, z: -1 };++/**+ * The rotation that aims a light along `aim` (any length; zero gives no turn).+ * Roll about the aim is left at none — a cone and parallel rays have nothing to+ * say about it.+ *+ * @experimental+ */+export function lightAimRotation(aim: Vec3): Quat {+ return q.rotationTo(LIGHT_FORWARD, aim);+}++/**+ * Where a light with this rotation aims — the unit vector the engine lights along.+ *+ * @experimental+ */+export function lightAimOf(rotation: Quat): Vec3 {+ return q.rotate(rotation, LIGHT_FORWARD);+}diff --git a/sdk/src/scene/legacyComponents.ts b/sdk/src/scene/legacyComponents.tsnew file mode 100644index 000000000..461158793--- /dev/null+++ b/sdk/src/scene/legacyComponents.ts@@ -0,0 +1,129 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file legacyComponents.ts+ * @brief Component data written by an older engine, brought forward.+ * @details A scene and a prefab hold the same component records, so an upgrade+ * belongs to neither: one that runs on only one of them leaves the other+ * handing the engine data it no longer means. Both migrations call+ * {@link upgradeEntityComponents}, and it is idempotent — data already+ * current passes through untouched.+ */++import { q } from '../math/quat';+import { lightAimRotation } from '../render/lightAim';+import type { Vec3 } from '../types';++/** The serialized shape of one component: what a `.esscene` and a `.esprefab` both hold. */+export interface UpgradableComponent {+ type: string;+ data: Record<string, unknown>;+}++/** Anything carrying a list of components — a scene entity or a prefab entity. */+export interface UpgradableEntity {+ components: UpgradableComponent[];+}++/**+ * Engine components that no longer exist. A file written before their retirement+ * still names them; keeping them would only make the loader warn and skip.+ */+export const RETIRED_COMPONENT_TYPES: ReadonlySet<string> = new Set(['StateMachine', 'StateVisuals']);++/** Light kinds that aim: Directional (1) and Spot (3). Point and Ambient never did. */+const AIMED_LIGHT_TYPES = new Set([1, 3]);++const IDENTITY = { w: 1, x: 0, y: 0, z: 0 };++/**+ * Would {@link upgradeEntityComponents} change this entity? Its pair, so that a+ * caller who must copy before writing can ask first; every rule below is+ * answered here, which is why the two live together.+ */+export function needsComponentUpgrade(entity: UpgradableEntity): boolean {+ return entity.components.some((c) => RETIRED_COMPONENT_TYPES.has(c.type)+ || c.type === 'LocalTransform'+ || c.type === 'WorldTransform'+ || (c.type === 'UIMask' && typeof c.data['mode'] === 'string')+ || (c.type === 'Light2D' && ('direction' in c.data || 'directionZ' in c.data)));+}++/**+ * Move a light's aim onto the entity carrying it: `direction`/`directionZ` become+ * the rotation whose forward they are, replacing whatever rotation the file+ * carried — the renderer never read that one, so no frame moves.+ * Point and Ambient do not aim; their fields go and their rotation is left alone.+ */+function upgradeLightAim(entity: UpgradableEntity): boolean {+ const light = entity.components.find((c) => c.type === 'Light2D');+ if (!light) return false;+ const data = light.data;+ if (!('direction' in data) && !('directionZ' in data)) return false;++ const named = data['direction'] as { x?: unknown; y?: unknown } | undefined;+ const aim: Vec3 = {+ x: Number(named?.x ?? 0),+ y: Number(named?.y ?? 0),+ // The component's own default, for a file that named only the plane's half.+ z: 'directionZ' in data ? Number(data['directionZ']) : -1,+ };+ delete data['direction'];+ delete data['directionZ'];+ if (!AIMED_LIGHT_TYPES.has(Number(data['type'] ?? 0))) return true;++ // An aim of zero in all three named no direction at all, and the engine read+ // that as the one an unrotated light has — the rotation this returns.+ const rotation = lightAimRotation(aim);+ const stored = { x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w };+ const transform = entity.components.find((c) => c.type === 'Transform');+ if (transform) {+ transform.data['rotation'] = stored;+ } else if (Math.abs(q.dot(rotation, IDENTITY)) < 1 - 1e-9) {+ // No Transform is the identity rotation already, so one is added only for+ // an aim that identity does not give.+ entity.components.unshift({ type: 'Transform', data: { rotation: stored } });+ }+ return true;+}++/** Legacy spellings inside one component. */+function upgradeComponent(component: UpgradableComponent): boolean {+ let changed = false;+ if (component.type === 'LocalTransform' || component.type === 'WorldTransform') {+ component.type = 'Transform';+ changed = true;+ }+ if (component.type === 'UIMask') {+ const mask = component.data;+ if (mask['mode'] === 'scissor') { mask['mode'] = 0; changed = true; }+ else if (mask['mode'] === 'stencil') { mask['mode'] = 1; changed = true; }+ }+ return changed;+}++/**+ * Bring one entity's component data forward, in place: drop retired components,+ * normalize legacy spellings, move a light's aim onto its entity. Names of the+ * retired components dropped are added to `retired` when one is given — the+ * editor tells the user which its open upgraded away.+ *+ * @returns true when anything changed.+ */+export function upgradeEntityComponents(entity: UpgradableEntity, retired?: Set<string>): boolean {+ let changed = false;+ const live = entity.components.filter((c) => {+ if (!RETIRED_COMPONENT_TYPES.has(c.type)) return true;+ retired?.add(c.type);+ return false;+ });+ if (live.length !== entity.components.length) {+ entity.components = live;+ changed = true;+ }+ for (const component of entity.components) {+ if (upgradeComponent(component)) changed = true;+ }+ if (upgradeLightAim(entity)) changed = true;+ return changed;+}diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex ca0043500..bf09f1fd2 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -7,6 +7,7 @@import { World } from '../ecs/world';import { Entity, INVALID_ENTITY } from '../types';+import { upgradeEntityComponents } from './legacyComponents';import { isPrefabEntry, type SceneEntry } from './sceneEntry';import { validateScene } from './validateScene';import { getComponent, Name, Camera, RuntimeOnly } from '../ecs/component';@@ -308,6 +309,9 @@ export interface SceneMigrationResult {data: SceneData;/** True if any legacy shape was upgraded (callers may prompt a re-save). */migrated: boolean;+ /** Retired engine components dropped, by name — an editor says which it+ * upgraded away; a runtime load has no one to tell. */+ retired: string[];fromVersion: number;toVersion: number;}@@ -335,7 +339,7 @@ export function parseSceneFormatVersion(v: unknown): number {* StateMachine/StateVisuals pair is superseded by UIController($interaction) +* UIGear, which the widget prefabs now carry.*/-export const RETIRED_COMPONENT_TYPES: ReadonlySet<string> = new Set(['StateMachine', 'StateVisuals']);+export { RETIRED_COMPONENT_TYPES } from './legacyComponents';/*** Upgrade a SceneData to the current format. Total + idempotent: already-current@@ -360,37 +364,17 @@ export function migrateSceneData(raw: SceneData): SceneMigrationResult {const data: SceneData = JSON.parse(JSON.stringify(raw)) as SceneData;let migrated = false;+ const retired = new Set<string>();for (const entity of data.entities) {// Prefab-instance entries carry no `components` to migrate; the async// loader expands them first, so any seen here belong to the sync path// and are left untouched (spawnAndLoadEntities warns + skips them).if (isPrefabEntry(entity)) continue;- // Drop components retired by an engine upgrade before per-component- // normalization — keeping them would only make loadComponent warn + skip.- const live = entity.components.filter((c) => !RETIRED_COMPONENT_TYPES.has(c.type));- if (live.length !== entity.components.length) { entity.components = live; migrated = true; }- for (const comp of entity.components) {- if (normalizeLegacyComponent(comp)) migrated = true;- }+ if (upgradeEntityComponents(entity, retired)) migrated = true;}data.version = SCENE_FORMAT_VERSION;- return { data, migrated, fromVersion, toVersion: SCENE_FORMAT_VERSION };-}--/** Normalize legacy component spellings in place. Returns true if changed. */-function normalizeLegacyComponent(compData: SceneComponentData): boolean {- let changed = false;- if (compData.type === 'LocalTransform' || compData.type === 'WorldTransform') {- compData.type = 'Transform';- changed = true;- }- if (compData.type === 'UIMask') {- const maskData = compData.data as Record<string, unknown>;- if (maskData.mode === 'scissor') { maskData.mode = 0; changed = true; }- else if (maskData.mode === 'stencil') { maskData.mode = 1; changed = true; }- }- return changed;+ return { data, migrated, retired: [...retired], fromVersion, toVersion: SCENE_FORMAT_VERSION };}// =============================================================================diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.tsindex 96b599ba5..5959d5716 100644--- a/sdk/src/wasm/ptrLayouts.generated.ts+++ b/sdk/src/wasm/ptrLayouts.generated.ts@@ -203,17 +203,15 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {{ name: 'color', type: 'color', offset: 4 },{ name: 'intensity', type: 'f32', offset: 20 },{ name: 'radius', type: 'f32', offset: 24 },- { name: 'direction', type: 'vec2', offset: 28 },- { name: 'directionZ', type: 'f32', offset: 36 },- { name: 'innerAngle', type: 'f32', offset: 40 },- { name: 'outerAngle', type: 'f32', offset: 44 },- { name: 'shadowSoftness', type: 'f32', offset: 48 },- { name: 'shadowDistance', type: 'f32', offset: 52 },- { name: 'meshShadows', type: 'bool', offset: 56 },- { name: 'shadowExtent', type: 'f32', offset: 60 },- { name: 'environment', type: 'u32', offset: 64 },- { name: 'drawEnvironment', type: 'bool', offset: 68 },- { name: 'enabled', type: 'bool', offset: 69 },+ { name: 'innerAngle', type: 'f32', offset: 28 },+ { name: 'outerAngle', type: 'f32', offset: 32 },+ { name: 'shadowSoftness', type: 'f32', offset: 36 },+ { name: 'shadowDistance', type: 'f32', offset: 40 },+ { name: 'meshShadows', type: 'bool', offset: 44 },+ { name: 'shadowExtent', type: 'f32', offset: 48 },+ { name: 'environment', type: 'u32', offset: 52 },+ { name: 'drawEnvironment', type: 'bool', offset: 56 },+ { name: 'enabled', type: 'bool', offset: 57 },],},Mesh2D: {diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.tsindex df092dfb5..c1979c0fb 100644--- a/sdk/src/wasm/wasm.generated.ts+++ b/sdk/src/wasm/wasm.generated.ts@@ -375,8 +375,6 @@ export interface Light2D {color: Vec4;intensity: number;radius: number;- direction: Vec2;- directionZ: number;innerAngle: number;outerAngle: number;shadowSoftness: number;diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex 4d3a7bb5c..bb772c441 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -161,14 +161,6 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho},},"Light2D": {- "direction": {- "advanced": true,- "tooltip": "Aim direction (Directional / Spot).",- },- "directionZ": {- "advanced": true,- "tooltip": "Aim depth (Directional): -1 shines into the screen.",- },"drawEnvironment": {"tooltip": "Draw this environment as the sky behind the scene.",},diff --git a/sdk/tests/light-aim-upgrade.test.ts b/sdk/tests/light-aim-upgrade.test.tsnew file mode 100644index 000000000..cfb891c7a--- /dev/null+++ b/sdk/tests/light-aim-upgrade.test.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file light-aim-upgrade.test.ts+ * @brief A file that names a light's aim arrives aiming there.+ *+ * The engine reads a light's aim off its entity, so a scene naming+ * `direction`/`directionZ` has to load as the rotation whose forward IS+ * that direction. The pixel gates say so about frames; this says so about+ * the arithmetic, which is where an axis convention goes wrong in silence.+ */+import { describe, it, expect } from 'vitest';+import { migrateSceneData, type SceneData } from '../src/scene/scene';+import { migratePrefabData } from '../src/prefab/migrate';+import { lightAimOf, lightAimRotation, LIGHT_FORWARD } from '../src/render/lightAim';+import { q } from '../src/math/quat';+import type { Quat, Vec3 } from '../src/types';++const DIRECTIONAL = 1;+const POINT = 0;+const SPOT = 3;++const sceneWith = (components: { type: string; data: Record<string, unknown> }[]): SceneData =>+ ({+ version: 1,+ name: 'test',+ entities: [{ id: 0, name: 'Light', parent: null, children: [], components }],+ } as unknown as SceneData);++const componentsOf = (scene: SceneData) => scene.entities[0]!.components;+const find = (scene: SceneData, type: string) => componentsOf(scene).find((c) => c.type === type);++/** The unit vector a migrated entity's rotation lights along. */+function aimAfter(scene: SceneData): Vec3 {+ const rotation = find(scene, 'Transform')?.data['rotation'] as Quat | undefined;+ return lightAimOf(rotation ?? { w: 1, x: 0, y: 0, z: 0 });+}++const unit = (v: Vec3): Vec3 => {+ const len = Math.hypot(v.x, v.y, v.z);+ return { x: v.x / len, y: v.y / len, z: v.z / len };+};++const expectAim = (got: Vec3, want: Vec3) => {+ const w = unit(want);+ expect(got.x).toBeCloseTo(w.x, 6);+ expect(got.y).toBeCloseTo(w.y, 6);+ expect(got.z).toBeCloseTo(w.z, 6);+};++describe('a light aimed by fields becomes a light aimed by its entity', () => {+ it('turns every authored aim into the rotation with that forward', () => {+ // The whole space, not one case: a convention that is inverted or swapped+ // survives a single vector and dies here.+ const aims: Vec3[] = [+ { x: 0.3, y: -0.5, z: -0.8 },+ { x: 0, y: -1, z: -1 },+ { x: 1, y: 0, z: 0 },+ { x: -1, y: 0, z: 0 },+ { x: 0, y: 1, z: 0 },+ { x: 0.25, y: 0, z: -1 },+ { x: 0, y: 0, z: 1 },+ ];+ for (const aim of aims) {+ const { data } = migrateSceneData(sceneWith([+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } },+ { type: 'Light2D', data: { type: DIRECTIONAL, direction: { x: aim.x, y: aim.y }, directionZ: aim.z } },+ ]));+ expectAim(aimAfter(data), aim);+ }+ });++ it('reads a file that named only the plane at the component default', () => {+ const { data } = migrateSceneData(sceneWith([+ { type: 'Transform', data: {} },+ { type: 'Light2D', data: { type: DIRECTIONAL, direction: { x: 0.25, y: 0 } } },+ ]));+ expectAim(aimAfter(data), { x: 0.25, y: 0, z: -1 });+ });++ it('leaves an unrotated light unrotated — the 2D scene it was', () => {+ const { data } = migrateSceneData(sceneWith([+ { type: 'Light2D', data: { type: DIRECTIONAL, direction: { x: 0, y: 0 }, directionZ: -1 } },+ ]));+ // Nothing to turn, so nothing is added: no Transform is the identity already.+ expect(find(data, 'Transform')).toBeUndefined();+ expectAim(aimAfter(data), LIGHT_FORWARD);+ });++ it('reads an aim of nothing the way the engine did — into the screen', () => {+ const { data } = migrateSceneData(sceneWith([+ { type: 'Light2D', data: { type: DIRECTIONAL, direction: { x: 0, y: 0 }, directionZ: 0 } },+ ]));+ expectAim(aimAfter(data), LIGHT_FORWARD);+ });++ it('gives a light with no Transform the one its aim needs', () => {+ const { data } = migrateSceneData(sceneWith([+ { type: 'Light2D', data: { type: SPOT, direction: { x: 1, y: 0 } } },+ ]));+ expect(find(data, 'Transform')).toBeDefined();+ expectAim(aimAfter(data), { x: 1, y: 0, z: -1 });+ });++ it('drops the dead fields from a light that never aimed, and leaves its rotation', () => {+ const turned = q.fromEuler([0, 0, 90]);+ const { data } = migrateSceneData(sceneWith([+ { type: 'Transform', data: { rotation: turned } },+ { type: 'Light2D', data: { type: POINT, direction: { x: 1, y: 0 }, directionZ: -1 } },+ ]));+ expect(find(data, 'Light2D')!.data['direction']).toBeUndefined();+ expect(find(data, 'Light2D')!.data['directionZ']).toBeUndefined();+ expect(find(data, 'Transform')!.data['rotation']).toEqual(turned);+ });++ it('is idempotent — a migrated scene migrates to itself', () => {+ const once = migrateSceneData(sceneWith([+ { type: 'Light2D', data: { type: DIRECTIONAL, direction: { x: 0.3, y: -0.5 }, directionZ: -0.8 } },+ ]));+ expect(once.migrated).toBe(true);+ const twice = migrateSceneData(once.data);+ expect(twice.migrated).toBe(false);+ expectAim(aimAfter(twice.data), { x: 0.3, y: -0.5, z: -0.8 });+ });++ it('upgrades a light in a prefab through the same door', () => {+ const { data, migrated } = migratePrefabData({+ version: '2',+ rootEntityId: 'root',+ entities: [{+ prefabEntityId: 'root',+ name: 'Torch',+ parent: null,+ children: [],+ visible: true,+ components: [{ type: 'Light2D', data: { type: SPOT, direction: { x: 0, y: -1 } } }],+ }],+ });+ expect(migrated).toBe(true);+ const transform = data.entities[0]!.components.find((c) => c.type === 'Transform');+ expectAim(lightAimOf(transform!.data['rotation'] as Quat), { x: 0, y: -1, z: -1 });+ });+});++describe('the aim helpers', () => {+ it('round-trip: a rotation built from an aim lights along it', () => {+ for (const aim of [{ x: 1, y: 2, z: 3 }, { x: -4, y: 0, z: 0 }, { x: 0, y: 0, z: 5 }]) {+ expectAim(lightAimOf(lightAimRotation(aim)), aim);+ }+ });++ it('turns nothing for an aim of nothing, rather than producing NaN', () => {+ const rotation = lightAimRotation({ x: 0, y: 0, z: 0 });+ expect(rotation).toEqual({ w: 1, x: 0, y: 0, z: 0 });+ });++ it('rotationTo stays a unit quaternion, including the half turn', () => {+ for (const to of [{ x: 0, y: 0, z: 1 }, { x: 1, y: 1, z: 1 }, { x: 0, y: 0, z: -1 }]) {+ const r = q.rotationTo(LIGHT_FORWARD, to);+ expect(Math.hypot(r.w, r.x, r.y, r.z)).toBeCloseTo(1, 9);+ }+ });+});diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cppindex c7af766c9..cc265f43e 100644--- a/src/esengine/bindings/EditorAPI.generated.cpp+++ b/src/esengine/bindings/EditorAPI.generated.cpp@@ -2,10 +2,10 @@* @file EditorAPI.generated.cpp* @brief Auto-generated editor API with string-dispatched component access* @details Generated by EHT - DO NOT EDIT- * @schema_hash 77c5905fcad9c63e+ * @schema_hash 4fbe43821df1cf73*/-#define ES_EDITOR_API_SCHEMA_HASH "77c5905fcad9c63e"+#define ES_EDITOR_API_SCHEMA_HASH "4fbe43821df1cf73"#include <emscripten/bind.h>#include <string>@@ -293,9 +293,6 @@ std::string editor_getComponentSchema(const std::string& name) {{"key":"color.a","type":"color","group":"Light2D"},{"key":"intensity","type":"float","group":"Light2D"},{"key":"radius","type":"float","group":"Light2D"},- {"key":"direction.x","type":"float","group":"Light2D"},- {"key":"direction.y","type":"float","group":"Light2D"},- {"key":"directionZ","type":"float","group":"Light2D"},{"key":"innerAngle","type":"float","group":"Light2D"},{"key":"outerAngle","type":"float","group":"Light2D"},{"key":"shadowSoftness","type":"float","group":"Light2D"},@@ -1144,9 +1141,6 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::selse if (field == "color.a") { c.color.a = value; }else if (field == "intensity") { c.intensity = value; }else if (field == "radius") { c.radius = value; }- else if (field == "direction.x") { c.direction.x = value; }- else if (field == "direction.y") { c.direction.y = value; }- else if (field == "directionZ") { c.directionZ = value; }else if (field == "innerAngle") { c.innerAngle = value; }else if (field == "outerAngle") { c.outerAngle = value; }else if (field == "shadowSoftness") { c.shadowSoftness = value; }@@ -1600,9 +1594,6 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::stelse if (field == "color.a") { return c.color.a; }else if (field == "intensity") { return c.intensity; }else if (field == "radius") { return c.radius; }- else if (field == "direction.x") { return c.direction.x; }- else if (field == "direction.y") { return c.direction.y; }- else if (field == "directionZ") { return c.directionZ; }else if (field == "innerAngle") { return c.innerAngle; }else if (field == "outerAngle") { return c.outerAngle; }else if (field == "shadowSoftness") { return c.shadowSoftness; }diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex ce2c45cfc..11aded93e 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -476,8 +476,6 @@ struct Light2DJS {glm::vec4 color;f32 intensity;f32 radius;- glm::vec2 direction;- f32 directionZ;f32 innerAngle;f32 outerAngle;f32 shadowSoftness;@@ -494,8 +492,6 @@ void light2dApplyJS(esengine::ecs::Light2D& c, const Light2DJS& js) {c.color = js.color;c.intensity = js.intensity;c.radius = js.radius;- c.direction = js.direction;- c.directionZ = js.directionZ;c.innerAngle = js.innerAngle;c.outerAngle = js.outerAngle;c.shadowSoftness = js.shadowSoftness;@@ -519,8 +515,6 @@ Light2DJS light2dToJS(const esengine::ecs::Light2D& c) {js.color = c.color;js.intensity = c.intensity;js.radius = c.radius;- js.direction = c.direction;- js.directionZ = c.directionZ;js.innerAngle = c.innerAngle;js.outerAngle = c.outerAngle;js.shadowSoftness = c.shadowSoftness;@@ -1440,8 +1434,6 @@ EMSCRIPTEN_BINDINGS(esengine_components) {.field("color", &Light2DJS::color).field("intensity", &Light2DJS::intensity).field("radius", &Light2DJS::radius)- .field("direction", &Light2DJS::direction)- .field("directionZ", &Light2DJS::directionZ).field("innerAngle", &Light2DJS::innerAngle).field("outerAngle", &Light2DJS::outerAngle).field("shadowSoftness", &Light2DJS::shadowSoftness)@@ -2786,17 +2778,15 @@ static_assert(offsetof(esengine::ecs::Light2D, type) == 0, "ABI offset drift: esstatic_assert(offsetof(esengine::ecs::Light2D, color) == 4, "ABI offset drift: esengine::ecs::Light2D.color (EHT expected 4)");static_assert(offsetof(esengine::ecs::Light2D, intensity) == 20, "ABI offset drift: esengine::ecs::Light2D.intensity (EHT expected 20)");static_assert(offsetof(esengine::ecs::Light2D, radius) == 24, "ABI offset drift: esengine::ecs::Light2D.radius (EHT expected 24)");-static_assert(offsetof(esengine::ecs::Light2D, direction) == 28, "ABI offset drift: esengine::ecs::Light2D.direction (EHT expected 28)");-static_assert(offsetof(esengine::ecs::Light2D, directionZ) == 36, "ABI offset drift: esengine::ecs::Light2D.directionZ (EHT expected 36)");-static_assert(offsetof(esengine::ecs::Light2D, innerAngle) == 40, "ABI offset drift: esengine::ecs::Light2D.innerAngle (EHT expected 40)");-static_assert(offsetof(esengine::ecs::Light2D, outerAngle) == 44, "ABI offset drift: esengine::ecs::Light2D.outerAngle (EHT expected 44)");-static_assert(offsetof(esengine::ecs::Light2D, shadowSoftness) == 48, "ABI offset drift: esengine::ecs::Light2D.shadowSoftness (EHT expected 48)");-static_assert(offsetof(esengine::ecs::Light2D, shadowDistance) == 52, "ABI offset drift: esengine::ecs::Light2D.shadowDistance (EHT expected 52)");-static_assert(offsetof(esengine::ecs::Light2D, meshShadows) == 56, "ABI offset drift: esengine::ecs::Light2D.meshShadows (EHT expected 56)");-static_assert(offsetof(esengine::ecs::Light2D, shadowExtent) == 60, "ABI offset drift: esengine::ecs::Light2D.shadowExtent (EHT expected 60)");-static_assert(offsetof(esengine::ecs::Light2D, environment) == 64, "ABI offset drift: esengine::ecs::Light2D.environment (EHT expected 64)");-static_assert(offsetof(esengine::ecs::Light2D, drawEnvironment) == 68, "ABI offset drift: esengine::ecs::Light2D.drawEnvironment (EHT expected 68)");-static_assert(offsetof(esengine::ecs::Light2D, enabled) == 69, "ABI offset drift: esengine::ecs::Light2D.enabled (EHT expected 69)");+static_assert(offsetof(esengine::ecs::Light2D, innerAngle) == 28, "ABI offset drift: esengine::ecs::Light2D.innerAngle (EHT expected 28)");+static_assert(offsetof(esengine::ecs::Light2D, outerAngle) == 32, "ABI offset drift: esengine::ecs::Light2D.outerAngle (EHT expected 32)");+static_assert(offsetof(esengine::ecs::Light2D, shadowSoftness) == 36, "ABI offset drift: esengine::ecs::Light2D.shadowSoftness (EHT expected 36)");+static_assert(offsetof(esengine::ecs::Light2D, shadowDistance) == 40, "ABI offset drift: esengine::ecs::Light2D.shadowDistance (EHT expected 40)");+static_assert(offsetof(esengine::ecs::Light2D, meshShadows) == 44, "ABI offset drift: esengine::ecs::Light2D.meshShadows (EHT expected 44)");+static_assert(offsetof(esengine::ecs::Light2D, shadowExtent) == 48, "ABI offset drift: esengine::ecs::Light2D.shadowExtent (EHT expected 48)");+static_assert(offsetof(esengine::ecs::Light2D, environment) == 52, "ABI offset drift: esengine::ecs::Light2D.environment (EHT expected 52)");+static_assert(offsetof(esengine::ecs::Light2D, drawEnvironment) == 56, "ABI offset drift: esengine::ecs::Light2D.drawEnvironment (EHT expected 56)");+static_assert(offsetof(esengine::ecs::Light2D, enabled) == 57, "ABI offset drift: esengine::ecs::Light2D.enabled (EHT expected 57)");static_assert(offsetof(esengine::ecs::Mesh2D, texture) == 0, "ABI offset drift: esengine::ecs::Mesh2D.texture (EHT expected 0)");static_assert(offsetof(esengine::ecs::Mesh2D, normalMap) == 4, "ABI offset drift: esengine::ecs::Mesh2D.normalMap (EHT expected 4)");static_assert(offsetof(esengine::ecs::Mesh2D, color) == 8, "ABI offset drift: esengine::ecs::Mesh2D.color (EHT expected 8)");@@ -3029,7 +3019,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif// ABI Hash -- runtime handshake against the SDK bundle// =============================================================================-static const char* kEsAbiLayoutHash = "9169449040ae1dcb";+static const char* kEsAbiLayoutHash = "e868cc33a27b61d4";std::string esengineGetAbiLayoutHash() {return std::string(kEsAbiLayoutHash);diff --git a/src/esengine/ecs/components/Light2D.hpp b/src/esengine/ecs/components/Light2D.hppindex b6960ee9b..79518291c 100644--- a/src/esengine/ecs/components/Light2D.hpp+++ b/src/esengine/ecs/components/Light2D.hpp@@ -7,9 +7,10 @@* per-frame LightConstants UBO (binding 2); Lit2D-domain material shaders read them* via the injected applyLighting2D() helper. Point/Directional/Spot lights occupy a* light slot; Ambient lights sum into the ambient term. This component carries only- * the light's intrinsic parameters; Point/Spot read their world position from the- * entity's Transform (and are skipped without one), while Ambient/Directional have- * no spatial anchor and need no Transform.+ * the light's intrinsic parameters. Where a light sits and where it aims are the+ * entity's Transform: Point/Spot read their world position from it (and are skipped+ * without one), and Directional/Spot aim along the entity's forward — its rotation+ * applied to -Z, which is what an unrotated light has always shone along.** @author ESEngine Team* @date 2026@@ -28,7 +29,8 @@ namespace esengine::ecs {/*** @brief 2D light kind. Point uses the Transform position + radius falloff; Directional uses- * `direction` with no attenuation; Ambient adds a flat term independent of normal/position.+ * the Transform's forward with no attenuation; Ambient adds a flat term independent of+ * normal/position.*/ES_ENUM()enum class Light2DType : i32 {@@ -68,17 +70,6 @@ struct Light2D {ES_PROPERTY(animatable, min=0, tooltip="Falloff reach in world units (Point / Spot).")f32 radius{200.0f};- /** @brief Direction in the 2D plane: Directional light direction, or Spot cone axis- * ({0,0} = straight at the screen / cone aims down). Ignored by Point/Ambient. */- ES_PROPERTY(advanced, tooltip="Aim direction (Directional / Spot).")- glm::vec2 direction{0.0f, 0.0f};-- /** @brief The third component of a Directional light's aim, so a sun can be placed in a- * 3D scene rather than only tilted within the plane. -1 shines into the screen,- * which is where a 2D scene's light has always come from. */- ES_PROPERTY(animatable, advanced, tooltip="Aim depth (Directional): -1 shines into the screen.")- f32 directionZ{-1.0f};-/** @brief Spot inner cone angle in degrees (full angle; fully lit inside). */ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced)f32 innerAngle{30.0f};diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 1eb94ec09..d34755941 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -639,11 +639,13 @@ RenderFrameContext RenderFrame::makeContext() {};}-/// A directional light's aim depth. An aim of zero in all three has no direction to-/// give, so it keeps the one a 2D scene has always had rather than dividing by zero.-static f32 aimZ(const ecs::Light2D& light) {- const glm::vec3 aim(light.direction, light.directionZ);- return glm::dot(aim, aim) > 1e-8f ? light.directionZ : -1.0f;+/// Where a light aims: the entity's forward, its rotation applied to -Z. A light+/// without a Transform aims the way an unrotated one does, which is into the screen —+/// where a 2D scene's light comes from.+static glm::vec3 lightForward(ecs::Transform* transform) {+ if (!transform) return glm::vec3(0.0f, 0.0f, -1.0f);+ transform->ensureDecomposed();+ return transform->worldRotation * glm::vec3(0.0f, 0.0f, -1.0f);}void RenderFrame::collectLights(ecs::Registry& registry) {@@ -659,9 +661,9 @@ void RenderFrame::collectLights(ecs::Registry& registry) {std::vector<CollectedLight>& collected = light_scratch_;collected.clear();- // A light's Transform need is type-dependent: Ambient (a flat scene-wide term) and- // Directional (parallel rays; direction is intrinsic) have no spatial anchor and work- // without one — only Point/Spot sample a world position.+ // A light's Transform need is type-dependent. Ambient is a flat scene-wide term and+ // reads none of it; Directional takes only the rotation, so it works without one and+ // aims into the screen; Point/Spot need a position and are skipped without one.auto view = registry.view<ecs::Light2D>();for (auto entity : view) {const auto& light = view.get(entity);@@ -692,10 +694,11 @@ void RenderFrame::collectLights(ecs::Registry& registry) {// z=1 flags directional (no attenuation) in the shader; w carries the aim's third// component, which only a directional light has a use for — point and spot spend// that slot on their falloff radius.- gpu.posDir = glm::vec4(light.direction.x, light.direction.y, 1.0f, aimZ(light));+ const glm::vec3 aim = lightForward(registry.tryGet<ecs::Transform>(entity));+ gpu.posDir = glm::vec4(aim.x, aim.y, 1.0f, aim.z);if (light.meshShadows && shadow_light_slot_ < 0) {castsMeshShadow = true;- shadow_light_dir_ = glm::vec3(light.direction, aimZ(light));+ shadow_light_dir_ = aim;shadow_light_extent_ = std::max(light.shadowExtent, 0.0f);}} else { // Point / Spot — world position from the Transform, w=falloff radius.@@ -710,14 +713,18 @@ void RenderFrame::collectLights(ecs::Registry& registry) {// MESH_NORMALS half of the lighting loop.gpu.shadow.z = p.z;if (type == ecs::Light2DType::Spot) {- // The cone axis unnormalized, so the two halves can each normalize the- // vector they need: the plane's xy, and the whole of it in three.- glm::vec2 aim = light.direction;- if (glm::dot(aim, aim) <= 1e-8f) aim = glm::vec2(0.0f, -1.0f);- gpu.spot = glm::vec4(aim.x, aim.y,+ // Split across two slots because the two shading halves read different+ // parts: the plane's xy, and the whole of it in three.+ const glm::vec3 aim = lightForward(transform);+ // A cone aimed straight into the screen has no axis IN the plane, and the+ // plane's half of the shading has nowhere else to read one from — so it+ // keeps the direction an unrotated spot has always lit along.+ glm::vec2 planar(aim.x, aim.y);+ if (glm::dot(planar, planar) <= 1e-8f) planar = glm::vec2(0.0f, -1.0f);+ gpu.spot = glm::vec4(planar.x, planar.y,std::cos(glm::radians(light.innerAngle * 0.5f)),std::cos(glm::radians(light.outerAngle * 0.5f)));- gpu.shadow.w = light.directionZ;+ gpu.shadow.w = aim.z;}}collected.push_back({gpu, castsMeshShadow});