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(decal): the surface under a projector, cut to its box
esengine6b7efbe4b067
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 77443bd6d..0a598ee25 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -97,6 +97,26 @@ published separately; it ships inside the editor.Per-instance, not per-object-record, because the record was out of room at thetime. The entry below is the change that moved it.+- **A decal's geometry, cut.** What a projector produces here is not a sticker+ hovering in front of a wall — it is the wall, cut to the projector's box and+ drawn again with the decal's own material, won on depth by that material's+ bias. So a decal is ordinary geometry: lit and shadowed exactly as the surface+ under it, instanced, culled and picked like anything else, with no pass, no+ depth read and no G-buffer anywhere in it.++ `bakeDecalMesh` takes the surfaces under a projector and its transform — the+ box IS the entity's own transform, so a decal is placed with the gizmo+ everything else uses — and answers one mesh in the projector's space. Nothing+ authors one yet; that is the next piece.++ Two things only a test could have found, both from the placement an author+ actually makes. A receiver lying FLUSH with a face of the box — which is where+ a projector is put — had every vertex on a clip plane, and whether it counted+ as inside was decided by the last bit of the transform: a floor came out+ ±6e-16 either side and half the decal was clipped away. And a vertex exactly+ on a plane was emitted twice, fanning into zero-area triangles the mesh would+ have carried forever.+- **A surface can say it goes ON another one.** Two coplanar surfaces — a decalon a wall, a marking on a road, a patch on a floor — had no way to settle whichone the depth test keeps. Whichever drew first won, which is not a thing andiff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 7f41730b6..47b188cb4 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 114,"beta": 101,- "experimental": 1976,+ "experimental": 1985,"deprecated": 3},- "total": 2191,+ "total": 2200,"subsystems": [{"id": "ecs",@@ -356,6 +356,18 @@"MeshRenderers"]},+ {+ "id": "decal",+ "title": "Decals",+ "titleZh": "贴花",+ "tier": "experimental",+ "why": "the cut is proven and nothing authors one yet — the shape will follow what a projector panel turns out to need",+ "whyZh": "裁剪本身已经证明是对的,但还没有任何创作面去做一个贴花,所以这套接口的形状要跟着投影盒面板最终需要什么走",+ "entry": [+ "bakeDecalMesh",+ "clipToProjector"+ ]+ },{"id": "lightmap","title": "Baked lighting",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex f4e37ff03..347e74fe9 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1815 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1824 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1840,6 +1840,11 @@ sprite: number | undefined16```+## CLIP_EPSILON — const @experimental+```+0.00001+```+## COLLIDER3D_RING_SEGMENTS — const @experimental```24@@ -2374,6 +2379,17 @@ Depth = 2Nothing = 0```+## ClipTriangle — type @experimental+```+[ClipVertex, ClipVertex, ClipVertex]+```++## ClipVertex — interface @experimental+```+n: [number, number, number]+p: [number, number, number]+```+## CollectNavGeometryOptions — interface @experimental```layers: number | undefined@@ -2733,6 +2749,11 @@ EditorGridDataEditorViewData```+## DEFAULT_FACING_COSINE — const @experimental+```+0.2+```+## DEFAULT_FALLBACK_DT — const @experimental```number@@ -2862,6 +2883,18 @@ Int3 = 7Int4 = 8```+## DecalBakeOptions — interface @experimental+```+facing: number | undefined+```++## DecalReceiver — interface @experimental+```+indices: Uint32Array<ArrayBufferLike>+normals: Float32Array<ArrayBufferLike>+positions: Float32Array<ArrayBufferLike>+```+## DecodedChunk — interface @experimental```tiles: Uint16Array<ArrayBufferLike>@@ -4039,7 +4072,7 @@ number## GeometryOptions — interface @experimental```dynamic: boolean | undefined-indices: Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined+indices: Uint32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | undefinedlayout: VertexAttributeDescriptor[]vertices: Float32Array<ArrayBufferLike>```@@ -11325,6 +11358,11 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeDecalMesh — function @experimental+```+(receivers: readonly DecalReceiver[], projectorWorld: ArrayLike<number>, options?: DecalBakeOptions): MeshData | null+```+## bakeFingerprint — function @experimental```(inputs: BakeInputs): string@@ -11585,6 +11623,11 @@ BtPlugin(): void```+## clipToProjector — function @experimental+```+(triangles: readonly ClipTriangle[], minCosine?: number): ClipTriangle[]+```+## cloneComponentData — function @experimental```(data: Record<string, unknown>): Record<string, unknown>@@ -13510,6 +13553,11 @@ PrefabsPlugin(): string[]```+## projectorUV — function @experimental+```+(v: ClipVertex): [number, number]+```+## px — const @public```(n: number) => Dimensiondiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 5bc54fb24..bc3810122 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 99 beta · 1834 experimental · 3 deprecated+Symbols: 114 public · 99 beta · 1843 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1840,6 +1840,11 @@ sprite: number | undefined16```+## CLIP_EPSILON — const @experimental+```+0.00001+```+## COLLIDER3D_RING_SEGMENTS — const @experimental```24@@ -2374,6 +2379,17 @@ Depth = 2Nothing = 0```+## ClipTriangle — type @experimental+```+[ClipVertex, ClipVertex, ClipVertex]+```++## ClipVertex — interface @experimental+```+n: [number, number, number]+p: [number, number, number]+```+## CollectNavGeometryOptions — interface @experimental```layers: number | undefined@@ -2741,6 +2757,11 @@ EditorGridDataEditorViewData```+## DEFAULT_FACING_COSINE — const @experimental+```+0.2+```+## DEFAULT_FALLBACK_DT — const @experimental```number@@ -2870,6 +2891,18 @@ Int3 = 7Int4 = 8```+## DecalBakeOptions — interface @experimental+```+facing: number | undefined+```++## DecalReceiver — interface @experimental+```+indices: Uint32Array<ArrayBufferLike>+normals: Float32Array<ArrayBufferLike>+positions: Float32Array<ArrayBufferLike>+```+## DecodedChunk — interface @experimental```tiles: Uint16Array<ArrayBufferLike>@@ -4047,7 +4080,7 @@ number## GeometryOptions — interface @experimental```dynamic: boolean | undefined-indices: Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined+indices: Uint32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | undefinedlayout: VertexAttributeDescriptor[]vertices: Float32Array<ArrayBufferLike>```@@ -11533,6 +11566,11 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeDecalMesh — function @experimental+```+(receivers: readonly DecalReceiver[], projectorWorld: ArrayLike<number>, options?: DecalBakeOptions): MeshData | null+```+## bakeFingerprint — function @experimental```(inputs: BakeInputs): string@@ -11793,6 +11831,11 @@ BtPlugin(): void```+## clipToProjector — function @experimental+```+(triangles: readonly ClipTriangle[], minCosine?: number): ClipTriangle[]+```+## cloneComponentData — function @experimental```(data: Record<string, unknown>): Record<string, unknown>@@ -13753,6 +13796,11 @@ PrefabsPlugin(): string[]```+## projectorUV — function @experimental+```+(v: ClipVertex): [number, number]+```+## px — const @public```(n: number) => Dimensiondiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 4cd2b900b..38e48502d 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: 114 public · 96 beta · 1814 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1823 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1835,6 +1835,11 @@ sprite: number | undefined16```+## CLIP_EPSILON — const @experimental+```+0.00001+```+## COLLIDER3D_RING_SEGMENTS — const @experimental```24@@ -2369,6 +2374,17 @@ Depth = 2Nothing = 0```+## ClipTriangle — type @experimental+```+[ClipVertex, ClipVertex, ClipVertex]+```++## ClipVertex — interface @experimental+```+n: [number, number, number]+p: [number, number, number]+```+## CollectNavGeometryOptions — interface @experimental```layers: number | undefined@@ -2728,6 +2744,11 @@ EditorGridDataEditorViewData```+## DEFAULT_FACING_COSINE — const @experimental+```+0.2+```+## DEFAULT_FALLBACK_DT — const @experimental```number@@ -2857,6 +2878,18 @@ Int3 = 7Int4 = 8```+## DecalBakeOptions — interface @experimental+```+facing: number | undefined+```++## DecalReceiver — interface @experimental+```+indices: Uint32Array<ArrayBufferLike>+normals: Float32Array<ArrayBufferLike>+positions: Float32Array<ArrayBufferLike>+```+## DecodedChunk — interface @experimental```tiles: Uint16Array<ArrayBufferLike>@@ -4034,7 +4067,7 @@ number## GeometryOptions — interface @experimental```dynamic: boolean | undefined-indices: Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined+indices: Uint32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | undefinedlayout: VertexAttributeDescriptor[]vertices: Float32Array<ArrayBufferLike>```@@ -11320,6 +11353,11 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeDecalMesh — function @experimental+```+(receivers: readonly DecalReceiver[], projectorWorld: ArrayLike<number>, options?: DecalBakeOptions): MeshData | null+```+## bakeFingerprint — function @experimental```(inputs: BakeInputs): string@@ -11580,6 +11618,11 @@ BtPlugin(): void```+## clipToProjector — function @experimental+```+(triangles: readonly ClipTriangle[], minCosine?: number): ClipTriangle[]+```+## cloneComponentData — function @experimental```(data: Record<string, unknown>): Record<string, unknown>@@ -13515,6 +13558,11 @@ PrefabsPlugin(): string[]```+## projectorUV — function @experimental+```+(v: ClipVertex): [number, number]+```+## px — const @public```(n: number) => Dimensiondiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 4c595815c..d62eb04ed 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: 114 public · 94 beta · 1836 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1845 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1835,6 +1835,11 @@ sprite: number | undefined16```+## CLIP_EPSILON — const @experimental+```+0.00001+```+## COLLIDER3D_RING_SEGMENTS — const @experimental```24@@ -2369,6 +2374,17 @@ Depth = 2Nothing = 0```+## ClipTriangle — type @experimental+```+[ClipVertex, ClipVertex, ClipVertex]+```++## ClipVertex — interface @experimental+```+n: [number, number, number]+p: [number, number, number]+```+## CollectNavGeometryOptions — interface @experimental```layers: number | undefined@@ -2728,6 +2744,11 @@ EditorGridDataEditorViewData```+## DEFAULT_FACING_COSINE — const @experimental+```+0.2+```+## DEFAULT_FALLBACK_DT — const @experimental```number@@ -2857,6 +2878,18 @@ Int3 = 7Int4 = 8```+## DecalBakeOptions — interface @experimental+```+facing: number | undefined+```++## DecalReceiver — interface @experimental+```+indices: Uint32Array<ArrayBufferLike>+normals: Float32Array<ArrayBufferLike>+positions: Float32Array<ArrayBufferLike>+```+## DecodedChunk — interface @experimental```tiles: Uint16Array<ArrayBufferLike>@@ -4034,7 +4067,7 @@ number## GeometryOptions — interface @experimental```dynamic: boolean | undefined-indices: Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined+indices: Uint32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | undefinedlayout: VertexAttributeDescriptor[]vertices: Float32Array<ArrayBufferLike>```@@ -11574,6 +11607,11 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeDecalMesh — function @experimental+```+(receivers: readonly DecalReceiver[], projectorWorld: ArrayLike<number>, options?: DecalBakeOptions): MeshData | null+```+## bakeFingerprint — function @experimental```(inputs: BakeInputs): string@@ -11834,6 +11872,11 @@ BtPlugin(): void```+## clipToProjector — function @experimental+```+(triangles: readonly ClipTriangle[], minCosine?: number): ClipTriangle[]+```+## cloneComponentData — function @experimental```(data: Record<string, unknown>): Record<string, unknown>@@ -13774,6 +13817,11 @@ PrefabsPlugin(): string[]```+## projectorUV — function @experimental+```+(v: ClipVertex): [number, number]+```+## px — const @public```(n: number) => Dimensiondiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 52d6304e1..13578be03 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: 114 public · 94 beta · 1826 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1835 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1835,6 +1835,11 @@ sprite: number | undefined16```+## CLIP_EPSILON — const @experimental+```+0.00001+```+## COLLIDER3D_RING_SEGMENTS — const @experimental```24@@ -2369,6 +2374,17 @@ Depth = 2Nothing = 0```+## ClipTriangle — type @experimental+```+[ClipVertex, ClipVertex, ClipVertex]+```++## ClipVertex — interface @experimental+```+n: [number, number, number]+p: [number, number, number]+```+## CollectNavGeometryOptions — interface @experimental```layers: number | undefined@@ -2728,6 +2744,11 @@ EditorGridDataEditorViewData```+## DEFAULT_FACING_COSINE — const @experimental+```+0.2+```+## DEFAULT_FALLBACK_DT — const @experimental```number@@ -2857,6 +2878,18 @@ Int3 = 7Int4 = 8```+## DecalBakeOptions — interface @experimental+```+facing: number | undefined+```++## DecalReceiver — interface @experimental+```+indices: Uint32Array<ArrayBufferLike>+normals: Float32Array<ArrayBufferLike>+positions: Float32Array<ArrayBufferLike>+```+## DecodedChunk — interface @experimental```tiles: Uint16Array<ArrayBufferLike>@@ -4034,7 +4067,7 @@ number## GeometryOptions — interface @experimental```dynamic: boolean | undefined-indices: Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined+indices: Uint32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | undefinedlayout: VertexAttributeDescriptor[]vertices: Float32Array<ArrayBufferLike>```@@ -11348,6 +11381,11 @@ AudioPlugin(world: Pick<World, "tryGet">, avatar: AnimatorAvatar | null): JointResolver```+## bakeDecalMesh — function @experimental+```+(receivers: readonly DecalReceiver[], projectorWorld: ArrayLike<number>, options?: DecalBakeOptions): MeshData | null+```+## bakeFingerprint — function @experimental```(inputs: BakeInputs): string@@ -11608,6 +11646,11 @@ BtPlugin(): void```+## clipToProjector — function @experimental+```+(triangles: readonly ClipTriangle[], minCosine?: number): ClipTriangle[]+```+## cloneComponentData — function @experimental```(data: Record<string, unknown>): Record<string, unknown>@@ -13538,6 +13581,11 @@ PrefabsPlugin(): string[]```+## projectorUV — function @experimental+```+(v: ClipVertex): [number, number]+```+## px — const @public```(n: number) => Dimensiondiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 0a27a259d..7c3cdd62d 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -164,6 +164,18 @@ export {BakedLighting, type BakedLightingData, bakeFingerprint, type BakeInputs,bakeLightOf, bakeLightForward, type AuthoredLight, type BakeLightContribution,} from './lightmap';+/**+ * A decal's geometry: the surface under a projector, cut to its box. Ordinary+ * triangles, so nothing downstream — lighting, shadows, instancing, culling,+ * picking — has to learn what a decal is; what wins it against the surface it+ * was cut from is the depth bias its material carries.+ *+ * @experimental Pre-1.0: the cut follows what an authoring panel needs.+ */+export {+ bakeDecalMesh, clipToProjector, projectorUV, DEFAULT_FACING_COSINE, CLIP_EPSILON,+ type DecalReceiver, type DecalBakeOptions, type ClipVertex, type ClipTriangle,+} from './decal';/*** Nine coefficients, as the shader reads them. A panorama import and a probe* solve both produce these, and this is the one basis both go through.diff --git a/sdk/src/decal/bake.ts b/sdk/src/decal/bake.tsnew file mode 100644index 000000000..cb7a1d3ef--- /dev/null+++ b/sdk/src/decal/bake.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file bake.ts+ * @brief A projector and the surfaces under it, in: one mesh out.+ *+ * @details The mesh is in the PROJECTOR's own space, so the entity carrying the+ * decal draws it through the very transform that defined the box — move+ * the decal and its geometry moves with it, without a rebake, right up+ * until it leaves the surface it was cut from.+ */++import { invertMatrix4 } from '../math/mat4';+import { MeshChannel, MeshChannelType, type MeshData } from '../asset/meshFormat';+import { clipToProjector, projectorUV, DEFAULT_FACING_COSINE,+ type ClipTriangle, type ClipVertex } from './clip';++/** One surface the projector may print on, in WORLD space. */+export interface DecalReceiver {+ /** Three floats per vertex. */+ positions: Float32Array;+ /** Three floats per vertex, one per position. */+ normals: Float32Array;+ /** Three indices per triangle. */+ indices: Uint32Array;+}++export interface DecalBakeOptions {+ /** How far from facing the projector a surface may be. @see DEFAULT_FACING_COSINE */+ facing?: number;+}++/** Position (3f) + normal (3f) + uv (2f), interleaved — what a decal needs and+ * no more: it is lit like the surface and reads its texture through the box. */+const STRIDE = 8 * 4;++function mulPoint(m: Float32Array, x: number, y: number, z: number): [number, number, number] {+ return [+ m[0]! * x + m[4]! * y + m[8]! * z + m[12]!,+ m[1]! * x + m[5]! * y + m[9]! * z + m[13]!,+ m[2]! * x + m[6]! * y + m[10]! * z + m[14]!,+ ];+}++/**+ * A world normal into projector space.+ *+ * The TRANSPOSE of the projector's own 3x3, which is the inverse-transpose of+ * the inverse — so the engine's normal matrix, applied when the decal draws,+ * lands it back on the world normal it came from.+ */+function normalIntoProjector(m: Float32Array, x: number, y: number, z: number): [number, number, number] {+ const nx = m[0]! * x + m[1]! * y + m[2]! * z;+ const ny = m[4]! * x + m[5]! * y + m[6]! * z;+ const nz = m[8]! * x + m[9]! * y + m[10]! * z;+ const len = Math.hypot(nx, ny, nz) || 1;+ return [nx / len, ny / len, nz / len];+}++/**+ * The decal's geometry, or null when the projector prints on nothing.+ *+ * Null and not an empty mesh: a decal over thin air is a thing to report, and a+ * mesh with no triangles is a draw call that says nothing.+ */+export function bakeDecalMesh(+ receivers: readonly DecalReceiver[],+ projectorWorld: ArrayLike<number>,+ options: DecalBakeOptions = {},+): MeshData | null {+ // Whatever shape the caller's matrix came in: composeTRS — the SDK's own way+ // to build one — answers a plain array, and handing a matrix over should not+ // require converting it first.+ const world = projectorWorld instanceof Float32Array+ ? projectorWorld+ : Float32Array.from(projectorWorld);+ const inverse = invertMatrix4(world);+ const triangles: ClipTriangle[] = [];+ for (const r of receivers) {+ for (let i = 0; i + 2 < r.indices.length; i += 3) {+ const corner = (k: number): ClipVertex => {+ const at = r.indices[i + k]! * 3;+ return {+ p: mulPoint(inverse, r.positions[at]!, r.positions[at + 1]!, r.positions[at + 2]!),+ n: normalIntoProjector(world,+ r.normals[at]!, r.normals[at + 1]!, r.normals[at + 2]!),+ };+ };+ triangles.push([corner(0), corner(1), corner(2)]);+ }+ }++ const cut = clipToProjector(triangles, options.facing ?? DEFAULT_FACING_COSINE);+ if (cut.length === 0) return null;++ const vertexCount = cut.length * 3;+ const vertices = new Uint8Array(vertexCount * STRIDE);+ const floats = new Float32Array(vertices.buffer);+ const indices = new Uint32Array(vertexCount);+ const min: [number, number, number] = [Infinity, Infinity, Infinity];+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];++ let at = 0;+ for (const tri of cut) {+ for (const c of tri) {+ // Welding is left undone on purpose: a cut edge's two vertices carry+ // the same position and different normals often enough that merging+ // by position alone would flatten the shading the receiver had.+ floats[at * 8 + 0] = c.p[0];+ floats[at * 8 + 1] = c.p[1];+ floats[at * 8 + 2] = c.p[2];+ floats[at * 8 + 3] = c.n[0];+ floats[at * 8 + 4] = c.n[1];+ floats[at * 8 + 5] = c.n[2];+ const uv = projectorUV(c);+ floats[at * 8 + 6] = uv[0];+ floats[at * 8 + 7] = uv[1];+ for (let k = 0; k < 3; ++k) {+ min[k] = Math.min(min[k]!, c.p[k]!);+ max[k] = Math.max(max[k]!, c.p[k]!);+ }+ indices[at] = at;+ ++at;+ }+ }++ return {+ channels: [+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32, offset: 0 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32, offset: 12 },+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32, offset: 24 },+ ],+ vertexStride: STRIDE,+ vertexCount,+ vertices,+ indices,+ aabbMin: min,+ aabbMax: max,+ };+}diff --git a/sdk/src/decal/clip.ts b/sdk/src/decal/clip.tsnew file mode 100644index 000000000..4d9299103--- /dev/null+++ b/sdk/src/decal/clip.ts@@ -0,0 +1,146 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file clip.ts+ * @brief The geometry a decal IS: the receiving surface, cut to the projector's box.+ *+ * @details A decal is not a sticker floating in front of a wall — it is the wall,+ * drawn again with the decal's material and won on depth by the bias that+ * material carries. So what a projector produces is the receiver's own+ * triangles, clipped to the box and given the box's coordinates as UVs.+ *+ * Cut and not discarded per pixel: the result is ordinary geometry, which+ * is the whole reason a decal here needs no pass, no depth read and no+ * G-buffer, and is lit and shadowed exactly as the surface under it.+ */++/** A point in the projector's own space: the unit cube from -0.5 to 0.5. */+export interface ClipVertex {+ /** Position, projector-local. */+ p: [number, number, number];+ /** Normal, projector-local — carried through so the cut geometry lights+ * like the surface it was cut from rather than like the box. */+ n: [number, number, number];+}++/** One triangle of a receiver, already in the projector's space. */+export type ClipTriangle = [ClipVertex, ClipVertex, ClipVertex];++/**+ * How far from facing the projector a surface may be and still take the decal,+ * as the cosine of the angle. A wall at 90° to the projector catches the decal+ * as an infinitely stretched smear, which is what this refuses.+ */+export const DEFAULT_FACING_COSINE = 0.2;++/** The six half-spaces of the unit cube, as `axis` and which side keeps. */+const PLANES: ReadonlyArray<{ axis: 0 | 1 | 2; sign: 1 | -1 }> = [+ { axis: 0, sign: 1 }, { axis: 0, sign: -1 },+ { axis: 1, sign: 1 }, { axis: 1, sign: -1 },+ { axis: 2, sign: 1 }, { axis: 2, sign: -1 },++];++/**+ * How close to a face of the box a vertex may be and still count as on it.+ *+ * A projector placed so its box ENDS at the surface puts every receiver vertex+ * exactly on a face, where the last bit of the transform decides it: a floor at+ * y=0 came out ±6e-16 either side, and half the decal was clipped away.+ */+export const CLIP_EPSILON = 1e-5;++/** Signed distance into the half-space `sign * x <= 0.5` — positive is inside. */+function inside(v: ClipVertex, axis: 0 | 1 | 2, sign: 1 | -1): number {+ return 0.5 + CLIP_EPSILON - sign * v.p[axis];+}++function lerpVertex(a: ClipVertex, b: ClipVertex, t: number): ClipVertex {+ const mix = (x: number, y: number): number => x + (y - x) * t;+ return {+ p: [mix(a.p[0], b.p[0]), mix(a.p[1], b.p[1]), mix(a.p[2], b.p[2])],+ n: [mix(a.n[0], b.n[0]), mix(a.n[1], b.n[1]), mix(a.n[2], b.n[2])],+ };+}++/**+ * Sutherland-Hodgman against one half-space. A convex polygon stays convex and+ * stays one polygon, which is why the box is clipped plane by plane rather than+ * by a general boolean.+ */+function clipToPlane(poly: ClipVertex[], axis: 0 | 1 | 2, sign: 1 | -1): ClipVertex[] {+ if (poly.length === 0) return poly;+ const out: ClipVertex[] = [];+ for (let i = 0; i < poly.length; ++i) {+ const cur = poly[i]!;+ const next = poly[(i + 1) % poly.length]!;+ const dc = inside(cur, axis, sign);+ const dn = inside(next, axis, sign);+ if (dc >= 0) out.push(cur);+ // STRICTLY straddling, both ends off the plane: an end ON it is its own+ // crossing and is already in `out` (or will be next turn), and adding it+ // twice is a duplicate the fan turns into a zero-area triangle.+ if ((dc > 0 && dn < 0) || (dc < 0 && dn > 0)) {+ const t = dc / (dc - dn);+ out.push(lerpVertex(cur, next, t));+ }+ }+ return out;+}++/**+ * Twice a triangle's area, in the box's own units. Squared-free and 3D, since a+ * cut polygon is tilted in general.+ */+function area2(t: ClipTriangle): number {+ const ux = t[1].p[0] - t[0].p[0], uy = t[1].p[1] - t[0].p[1], uz = t[1].p[2] - t[0].p[2];+ const wx = t[2].p[0] - t[0].p[0], wy = t[2].p[1] - t[0].p[1], wz = t[2].p[2] - t[0].p[2];+ return Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx);+}++/** Below this a fanned triangle is a sliver the cut invented, not geometry. The+ * box is one unit across, so this is a trillionth of what a whole decal is. */+const AREA_EPSILON = 1e-12;++/** Whether the triangle faces the projector closely enough to take the decal. */+function faces(tri: ClipTriangle, minCosine: number): boolean {+ // The average of the corner normals, against the projector's own -Z: a decal+ // projects ALONG -Z, so a surface it can print on has a normal opposing it.+ const nz = (tri[0].n[2] + tri[1].n[2] + tri[2].n[2]) / 3;+ return nz >= minCosine;+}++/**+ * The receiver triangles, cut to the box.+ *+ * Returns triangles in the same projector space, fanned from each clipped+ * polygon. A triangle wholly outside contributes nothing; one wholly inside+ * comes back unchanged, which is the common case for small geometry.+ */+export function clipToProjector(+ triangles: readonly ClipTriangle[],+ minCosine = DEFAULT_FACING_COSINE,+): ClipTriangle[] {+ const out: ClipTriangle[] = [];+ for (const tri of triangles) {+ if (!faces(tri, minCosine)) continue;+ let poly: ClipVertex[] = [tri[0], tri[1], tri[2]];+ for (const plane of PLANES) {+ poly = clipToPlane(poly, plane.axis, plane.sign);+ if (poly.length < 3) break;+ }+ for (let i = 2; i < poly.length; ++i) {+ const fan: ClipTriangle = [poly[0]!, poly[i - 1]!, poly[i]!];+ // A triangle with no area covers no pixel, and the cut makes them.+ // Dropped here so a decal's vertex count is what it draws, not what+ // the cut happened to produce.+ if (area2(fan) > AREA_EPSILON) out.push(fan);+ }+ }+ return out;+}++/** Where a clipped vertex reads the decal's texture: the box's own xy. */+export function projectorUV(v: ClipVertex): [number, number] {+ return [v.p[0] + 0.5, v.p[1] + 0.5];+}diff --git a/sdk/src/decal/index.ts b/sdk/src/decal/index.tsnew file mode 100644index 000000000..a0c75464d--- /dev/null+++ b/sdk/src/decal/index.ts@@ -0,0 +1,11 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.ts+ * @brief Decals: the surface under a projector, cut to its box and drawn again.+ */+export {+ clipToProjector, projectorUV, DEFAULT_FACING_COSINE, CLIP_EPSILON,+ type ClipVertex, type ClipTriangle,+} from './clip';+export { bakeDecalMesh, type DecalReceiver, type DecalBakeOptions } from './bake';diff --git a/sdk/tests/decal-bake.test.ts b/sdk/tests/decal-bake.test.tsnew file mode 100644index 000000000..349789dba--- /dev/null+++ b/sdk/tests/decal-bake.test.ts@@ -0,0 +1,131 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A projector over a floor: what comes out, and in whose space.+ *+ * The clip is tested on its own; this asks the part around it — that world+ * geometry arrives in the projector's space and comes back out through the very+ * transform that defined the box. A decal one transform off looks fine in a+ * screenshot taken from the angle it was authored at. Pure TS.+ */+import { describe, it, expect } from 'vitest';+import { bakeDecalMesh, type DecalReceiver } from '../src/decal/bake';+import { CLIP_EPSILON } from '../src/decal/clip';+import { composeTRS } from '../src/math/mat4';+import { MeshChannel } from '../src/asset/meshFormat';++/** A big flat floor at world y = 0, facing up. */+function floor(extent = 500): DecalReceiver {+ return {+ positions: new Float32Array([+ -extent, 0, -extent, extent, 0, -extent, extent, 0, extent, -extent, 0, extent,+ ]),+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+}++/** A projector of `size` standing at `at`, throwing straight DOWN (-Y). */+function projectorAbove(at: [number, number, number], size: number): number[] {+ // Its own -Z must point down, so it is pitched a quarter turn: x stays, and+ // local +Z becomes world +Y.+ const half = Math.SQRT1_2;+ return composeTRS(+ { x: at[0], y: at[1], z: at[2] },+ { x: -half, y: 0, z: 0, w: half }, // -90° about X+ { x: size, y: size, z: size },+ );+}++const positionsOf = (m: { vertices: Uint8Array; vertexCount: number }): number[][] => {+ const f = new Float32Array(m.vertices.buffer);+ const out: number[][] = [];+ for (let i = 0; i < m.vertexCount; ++i) out.push([f[i * 8]!, f[i * 8 + 1]!, f[i * 8 + 2]!]);+ return out;+};+const uvsOf = (m: { vertices: Uint8Array; vertexCount: number }): number[][] => {+ const f = new Float32Array(m.vertices.buffer);+ const out: number[][] = [];+ for (let i = 0; i < m.vertexCount; ++i) out.push([f[i * 8 + 6]!, f[i * 8 + 7]!]);+ return out;+};++describe('decal bake', () => {+ it('cuts a patch of floor the size of the projector', () => {+ const mesh = bakeDecalMesh([floor()], projectorAbove([0, 100, 0], 200));+ expect(mesh).not.toBeNull();+ // Whole triangles, and no more than the receiver could contribute: the+ // cut fans polygons, so a count is a range, not a number.+ expect(mesh!.vertexCount % 3).toBe(0);+ expect(mesh!.vertexCount).toBeGreaterThanOrEqual(6);+ expect(mesh!.vertexCount).toBeLessThanOrEqual(24);+ expect(mesh!.channels.map((c) => c.semantic))+ .toEqual([MeshChannel.Position, MeshChannel.Normal, MeshChannel.TexCoord0]);+ });++ it('puts the geometry in the PROJECTOR\'s space, inside the unit box', () => {+ const mesh = bakeDecalMesh([floor()], projectorAbove([300, 100, -120], 200))!;+ // The clip's own tolerance, plus what storing the result as float32+ // costs: a mesh file carries single precision and nothing else.+ const bound = 0.5 + CLIP_EPSILON + 1e-6;+ for (const p of positionsOf(mesh)) {+ for (const k of [0, 1, 2]) expect(Math.abs(p[k]!)).toBeLessThanOrEqual(bound);+ }+ // And its bounds say the same, which is what culling will read.+ expect(mesh.aabbMax[0]).toBeLessThanOrEqual(bound);+ expect(mesh.aabbMin[0]).toBeGreaterThanOrEqual(-bound);+ });++ it('spreads the texture across the whole box', () => {+ const uvs = uvsOf(bakeDecalMesh([floor()], projectorAbove([0, 100, 0], 200))!);+ const us = uvs.map((uv) => uv[0]!);+ const vs = uvs.map((uv) => uv[1]!);+ expect(Math.min(...us)).toBeCloseTo(0, 4);+ expect(Math.max(...us)).toBeCloseTo(1, 4);+ expect(Math.min(...vs)).toBeCloseTo(0, 4);+ expect(Math.max(...vs)).toBeCloseTo(1, 4);+ });++ it('prints nothing where there is nothing under it', () => {+ expect(bakeDecalMesh([floor(50)], projectorAbove([5000, 100, 0], 200))).toBeNull();+ expect(bakeDecalMesh([], projectorAbove([0, 100, 0], 200))).toBeNull();+ });++ it('refuses a floor it is edge-on to', () => {+ // Throwing sideways (-X) at a floor facing up: nothing to print on.+ const sideways = composeTRS({ x: 0, y: 100, z: 0 },+ { x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 },+ { x: 200, y: 200, z: 200 });+ expect(bakeDecalMesh([floor()], sideways)).toBeNull();+ });++ it('carries a normal that comes BACK to the world one it was cut from', () => {+ // Stored as the transpose of the projector's 3x3, so the engine's normal+ // matrix (the inverse-transpose of the model matrix) restores world +Y.+ const world = projectorAbove([0, 100, 0], 200);+ const mesh = bakeDecalMesh([floor()], world)!;+ const f = new Float32Array(mesh.vertices.buffer);+ const n: [number, number, number] = [f[3]!, f[4]!, f[5]!];+ // The projector's -90°-about-X turn maps world +Y to local +Z.+ expect(n[2]).toBeCloseTo(1, 4);+ expect(Math.abs(n[1]!)).toBeLessThan(1e-4);+ });++ it('cuts a tilted receiver too, and keeps its tilt', () => {+ const tilt = Math.SQRT1_2;+ const ramp: DecalReceiver = {+ positions: new Float32Array([+ -500, 0, 0, 500, 0, 0, 500, 500, 500, -500, 500, 500,+ ]),+ normals: new Float32Array([+ 0, tilt, -tilt, 0, tilt, -tilt, 0, tilt, -tilt, 0, tilt, -tilt,+ ]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+ const mesh = bakeDecalMesh([ramp], projectorAbove([0, 100, 100], 200));+ expect(mesh).not.toBeNull();+ const f = new Float32Array(mesh!.vertices.buffer);+ // Not the box's own facing: the ramp's tilt survived the cut.+ expect(Math.abs(f[4]!)).toBeGreaterThan(1e-3);+ });+});diff --git a/sdk/tests/decal-clip.test.ts b/sdk/tests/decal-clip.test.tsnew file mode 100644index 000000000..1e43cb385--- /dev/null+++ b/sdk/tests/decal-clip.test.ts@@ -0,0 +1,139 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The projector's cut: what a decal's geometry IS.+ *+ * None of this is a thing a screenshot can answer — a decal that leaks one+ * triangle past the box, or keeps a wall it is edge-on to, looks like a decal+ * until you walk around it. Pure TS.+ */+import { describe, it, expect } from 'vitest';+import {+ clipToProjector, projectorUV, DEFAULT_FACING_COSINE, CLIP_EPSILON,+ type ClipTriangle, type ClipVertex,+} from '../src/decal/clip';++/** A vertex facing the projector (normal along +Z, which opposes its -Z throw). */+const v = (x: number, y: number, z = 0, n: [number, number, number] = [0, 0, 1]): ClipVertex =>+ ({ p: [x, y, z], n });++const area = (t: ClipTriangle): number => {+ const [a, b, c] = t;+ const ux = b.p[0] - a.p[0], uy = b.p[1] - a.p[1];+ const wx = c.p[0] - a.p[0], wy = c.p[1] - a.p[1];+ return Math.abs(ux * wy - uy * wx) / 2;+};+const totalArea = (ts: ClipTriangle[]): number => ts.reduce((s, t) => s + area(t), 0);++describe('decal projector clip', () => {+ it('keeps a triangle wholly inside the box, unchanged', () => {+ const tri: ClipTriangle = [v(-0.2, -0.2), v(0.2, -0.2), v(0, 0.2)];+ const out = clipToProjector([tri]);+ expect(out).toHaveLength(1);+ expect(out[0]).toEqual(tri);+ });++ it('drops a triangle wholly outside it', () => {+ const tri: ClipTriangle = [v(2, 2), v(3, 2), v(2.5, 3)];+ expect(clipToProjector([tri])).toHaveLength(0);+ });++ it('cuts one that straddles the edge, keeping only what is inside', () => {+ // Half in, half out across x = 0.5.+ const tri: ClipTriangle = [v(0, -0.4), v(1.0, -0.4), v(0, 0.4)];+ const out = clipToProjector([tri]);+ expect(out.length).toBeGreaterThan(0);+ const bound = 0.5 + CLIP_EPSILON;+ for (const t of out) {+ for (const c of t) {+ expect(c.p[0]).toBeLessThanOrEqual(bound);+ expect(c.p[0]).toBeGreaterThanOrEqual(-bound);+ expect(c.p[1]).toBeLessThanOrEqual(bound);+ expect(c.p[2]).toBeLessThanOrEqual(bound);+ }+ }+ // And it kept the part that was inside rather than collapsing: the area+ // is what the original had within the box, not zero and not all of it.+ expect(totalArea(out)).toBeGreaterThan(0.05);+ expect(totalArea(out)).toBeLessThan(totalArea([tri]));+ });++ it('cuts a wall spanning the whole box down to exactly the box', () => {+ // Two triangles of a quad from -4 to 4, which the box crops to 1x1.+ const quad: ClipTriangle[] = [+ [v(-4, -4), v(4, -4), v(4, 4)],+ [v(-4, -4), v(4, 4), v(-4, 4)],+ ];+ expect(totalArea(clipToProjector(quad))).toBeCloseTo(1.0, 4);+ });++ it('refuses a surface too edge-on to print on', () => {+ // Facing +X: the projector throws along -Z and would smear it forever.+ const edgeOn: ClipTriangle = [+ v(-0.2, -0.2, 0, [1, 0, 0]), v(0.2, -0.2, 0, [1, 0, 0]), v(0, 0.2, 0, [1, 0, 0]),+ ];+ expect(clipToProjector([edgeOn])).toHaveLength(0);+ // And the threshold is a knob, not a law: asked to accept anything, it does.+ expect(clipToProjector([edgeOn], -1)).toHaveLength(1);+ });++ it('refuses the BACK of a surface it would otherwise print on', () => {+ const away: ClipTriangle = [+ v(-0.2, -0.2, 0, [0, 0, -1]), v(0.2, -0.2, 0, [0, 0, -1]), v(0, 0.2, 0, [0, 0, -1]),+ ];+ expect(clipToProjector([away])).toHaveLength(0);+ });++ it('carries the receiver normal through the cut, not the box one', () => {+ const tilted: [number, number, number] = [0, 0.6, 0.8];+ const tri: ClipTriangle = [v(-4, -4, 0, tilted), v(4, -4, 0, tilted), v(4, 4, 0, tilted)];+ for (const t of clipToProjector([tri])) {+ for (const c of t) {+ expect(c.n[1]).toBeCloseTo(0.6, 5);+ expect(c.n[2]).toBeCloseTo(0.8, 5);+ }+ }+ });++ it('reads the box corners as the texture corners', () => {+ expect(projectorUV(v(-0.5, -0.5))).toEqual([0, 0]);+ expect(projectorUV(v(0.5, 0.5))).toEqual([1, 1]);+ expect(projectorUV(v(0, 0))).toEqual([0.5, 0.5]);+ });++ it('clips depth too — a surface behind the box does not take it', () => {+ const behind: ClipTriangle = [v(-0.2, -0.2, 2), v(0.2, -0.2, 2), v(0, 0.2, 2)];+ expect(clipToProjector([behind])).toHaveLength(0);+ });++ it('keeps a receiver lying FLUSH with a face of the box', () => {+ // The usual placement — the box ends at the surface — puts every vertex+ // on a face, where the last bit of the transform decides it. Nudged to+ // both sides of the plane by less than the epsilon, it is still whole.+ const eps = 6e-16;+ const flush: ClipTriangle[] = [+ [v(-2.5, 2.5, -0.5 - eps), v(2.5, 2.5, -0.5 + eps), v(2.5, -2.5, -0.5 - eps)],+ [v(-2.5, 2.5, -0.5 + eps), v(2.5, -2.5, -0.5 - eps), v(-2.5, -2.5, -0.5 - eps)],+ ];+ expect(totalArea(clipToProjector(flush))).toBeCloseTo(1.0, 4);+ });++ it('emits no zero-area triangle, however the cut falls', () => {+ // A receiver lying flat ON a box face is every vertex on a clip plane at+ // once — the case that makes a naive clipper duplicate them.+ const flush: ClipTriangle[] = [+ [v(-2.5, 2.5, -0.5), v(2.5, 2.5, -0.5), v(2.5, -2.5, -0.5)],+ [v(-2.5, 2.5, -0.5), v(2.5, -2.5, -0.5), v(-2.5, -2.5, -0.5)],+ ];+ const out = clipToProjector(flush);+ for (const t of out) expect(area(t)).toBeGreaterThan(1e-9);+ // And it still covers the whole box, which is what says the cut was not+ // simply thrown away along with the slivers.+ expect(totalArea(out)).toBeCloseTo(1.0, 4);+ });++ it('states its own facing default rather than leaving it to a caller', () => {+ expect(DEFAULT_FACING_COSINE).toBeGreaterThan(0);+ expect(DEFAULT_FACING_COSINE).toBeLessThan(1);+ });+});diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjsindex ba0f1af65..9f6ffa3db 100644--- a/tools/apiSubsystems.mjs+++ b/tools/apiSubsystems.mjs@@ -303,6 +303,16 @@ export const SUBSYSTEMS = [whyZh: '导入链路已经端到端认证,但游戏用来驱动模型的运行时面(几何体、逐子网格材质、关节实体)还没有被拿来定级',entry: ['MeshRenderer', 'MeshRendererAPI', 'MeshRenderers'],},+ {+ id: 'decal',+ title: 'Decals',+ titleZh: '贴花',+ source: ['decal'],+ tier: 'experimental',+ why: 'the cut is proven and nothing authors one yet — the shape will follow what a projector panel turns out to need',+ whyZh: '裁剪本身已经证明是对的,但还没有任何创作面去做一个贴花,所以这套接口的形状要跟着投影盒面板最终需要什么走',+ entry: ['bakeDecalMesh', 'clipToProjector'],+ },{id: 'lightmap',title: 'Baked lighting',diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 9b8727b4c..70a54bd63 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,9 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(decal): the surface under a projector, cut to its box':+ { note: "A decal's geometry, cut." },+'feat(render): a material can say its surface goes ON another one':{ note: 'A surface can say it goes ON another one.' },