Skip to content

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.

feat(cocos-import): emit the compatibility layer's components — UITransform, Widget, Layout, Button and the project's own scripts as Cocos.<Class>, with node references resolved to the entities those nodes became

yhh3fa413a7724b
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index 828c6a939..d9d730bee 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -13,7 +13,7 @@
* UI maps there and `UITransform` is folded into it.
*/
import type { CocosAssetEntry, CocosAssetIndex } from './assets';
-import type { CocosComponent, CocosNode } from './document';
+import { type CocosComponent, type CocosNode } from './document';
import type { ImportReport } from './report';
export interface ComponentData {
@@ -39,6 +39,10 @@ export interface ComponentContext {
* outline's colour supplied at draw time. Such a font has to say so, in the channel flags BMFont gives that layout.
*/
drawsBakedOutline?(materialUuid: string): boolean;
+ /** The script class a compressed class id names, when the project has that script. */
+ scriptClass?(classId: string): { name: string } | undefined;
+ /** The project-relative ref of a prefab, queuing it for conversion; null when the project does not have it. */
+ prefabAssetRef?(uuid: string): string | null;
}
type Raw = Record<string, unknown>;
@@ -258,6 +262,94 @@ function camera(c: CocosComponent, ctx: ComponentContext): ComponentData {
};
}
+// ---------------------------------------------------------------------------
+// The compatibility layer's components: UI geometry, alignment, layout, buttons, and the project's own scripts.
+// ---------------------------------------------------------------------------
+
+/** Names of the components the layer declares for built-ins; a scene that holds one needs `esengine/cocos` loaded. */
+const LAYER = 'Cocos.';
+
+function uiTransformData(box: UiBox): ComponentData {
+ return { type: `${LAYER}UITransform`, data: { width: box.width, height: box.height, anchorX: box.ax, anchorY: box.ay } };
+}
+
+/** Copy the serialised fields named in @p map to the layer's names, leaving out the ones the file does not carry. */
+function renamed(c: CocosComponent, map: Record<string, string>): Raw {
+ const out: Raw = { enabled: c.enabled };
+ for (const [from, to] of Object.entries(map)) if (c.data[from] !== undefined) out[to] = c.data[from];
+ return out;
+}
+
+function widget(c: CocosComponent): ComponentData {
+ const data = renamed(c, {
+ _alignFlags: 'alignFlags', _left: 'left', _right: 'right', _top: 'top', _bottom: 'bottom',
+ _horizontalCenter: 'horizontalCenter', _verticalCenter: 'verticalCenter',
+ _isAbsLeft: 'isAbsLeft', _isAbsRight: 'isAbsRight', _isAbsTop: 'isAbsTop', _isAbsBottom: 'isAbsBottom',
+ _isAbsHorizontalCenter: 'isAbsHorizontalCenter', _isAbsVerticalCenter: 'isAbsVerticalCenter',
+ _alignMode: 'alignMode', _target: 'target',
+ });
+ return { type: `${LAYER}Widget`, data };
+}
+
+function layout(c: CocosComponent): ComponentData {
+ const data = renamed(c, {
+ _layoutType: 'type', _resizeMode: 'resizeMode', _paddingLeft: 'paddingLeft', _paddingRight: 'paddingRight',
+ _paddingTop: 'paddingTop', _paddingBottom: 'paddingBottom', _spacingX: 'spacingX', _spacingY: 'spacingY',
+ _verticalDirection: 'verticalDirection', _horizontalDirection: 'horizontalDirection', _affectedByScale: 'affectedByScale',
+ _startAxis: 'startAxis', _constraint: 'constraint', _constraintNum: 'constraintNum', _isAlign: 'isAlign',
+ });
+ if (isObj(c.data._cellSize)) {
+ data.cellWidth = num(c.data._cellSize.width, 40);
+ data.cellHeight = num(c.data._cellSize.height, 40);
+ }
+ return { type: `${LAYER}Layout`, data };
+}
+
+function button(c: CocosComponent, ctx: ComponentContext): ComponentData {
+ const data = renamed(c, {
+ _interactable: 'interactable', _transition: 'transition', _zoomScale: 'zoomScale', _duration: 'duration',
+ _normalColor: 'normalColor', _hoverColor: 'hoverColor', _pressedColor: 'pressedColor', _disabledColor: 'disabledColor',
+ _target: 'target',
+ });
+ // An editor-authored handler holds a node, which the data model keeps in a list of its own beside the rest of the record.
+ const events = Array.isArray(c.data.clickEvents) ? c.data.clickEvents.filter(isObj) : [];
+ data.clickTargets = events.map((e) => e.target ?? null);
+ data.clickHandlers = events.map((e) => {
+ const id = typeof e._componentId === 'string' ? e._componentId : '';
+ const known = id ? ctx.scriptClass?.(id)?.name : undefined;
+ return {
+ component: known ?? (typeof e.component === 'string' ? e.component : ''),
+ handler: typeof e.handler === 'string' ? e.handler : '',
+ customEventData: typeof e.customEventData === 'string' ? e.customEventData : '',
+ };
+ });
+ return { type: `${LAYER}Button`, data };
+}
+
+/** A script component's fields, with asset references turned into project paths. */
+function scriptValue(v: unknown, ctx: ComponentContext): unknown {
+ if (Array.isArray(v)) return v.map((x) => scriptValue(x, ctx));
+ if (!isObj(v)) return v;
+ if (typeof v.__uuid__ === 'string') {
+ const uuid = v.__uuid__;
+ const prefab = ctx.prefabAssetRef?.(uuid);
+ if (prefab) return prefab;
+ const entry = ctx.assets.byUuid.get(uuid);
+ return entry ? ctx.assetRef(entry) : '';
+ }
+ const out: Raw = {};
+ for (const [k, x] of Object.entries(v)) out[k] = scriptValue(x, ctx);
+ return out;
+}
+
+function script(c: CocosComponent, ctx: ComponentContext): ComponentData | null {
+ const cls = ctx.scriptClass?.(c.type);
+ if (!cls) return null;
+ const data: Raw = { enabled: c.enabled };
+ for (const [k, v] of Object.entries(c.data)) data[k] = scriptValue(v, ctx);
+ return { type: `${LAYER}${cls.name}`, data };
+}
+
/** Components that are folded into another, or carry nothing of their own. */
const FOLDED = new Set(['cc.UITransform', 'cc.LabelOutline', 'cc.LabelShadow']);
@@ -290,11 +382,26 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin
case 'cc.Camera':
out = camera(c, ctx);
break;
+ case 'cc.UITransform':
+ // Also the size the renderers below were given; this keeps the rectangle for a node that draws nothing.
+ if (box) components.push(uiTransformData(box));
+ break;
+ case 'cc.Widget':
+ out = widget(c);
+ break;
+ case 'cc.Layout':
+ out = layout(c);
+ break;
+ case 'cc.Button':
+ out = button(c, ctx);
+ break;
default:
+ out = c.type.startsWith('cc.') ? null : script(c, ctx);
break;
}
if (out) {
components.push(out);
+ if (out.type.startsWith(LAYER)) ctx.report.component(c.type.startsWith('cc.') ? c.type : `script:${out.type.slice(LAYER.length)}`, 'mapped');
continue;
}
if (FOLDED.has(c.type)) {
diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.ts
index 149d2a146..ea5419ec1 100644
--- a/pipeline/src/import/cocos/convert.ts
+++ b/pipeline/src/import/cocos/convert.ts
@@ -14,7 +14,7 @@
* `slot/localId`, a prefab's own entities are bare ids.
*/
import { convertNode, sameData, type ComponentContext, type ComponentData } from './components';
-import type { CocosDocument, CocosNode, CocosOverride } from './document';
+import { NODE_REF, type CocosDocument, type CocosNode, type CocosOverride } from './document';
import { ImportReport } from './report';
const SEP = '/';
@@ -261,6 +261,10 @@ function diff(pristine: Map<string, Flat>, patched: Map<string, Flat>, ctx: Conv
}
for (const [field, value] of Object.entries(c.data)) {
if (!sameData(b.data[field], value)) {
+ if (holdsRef(value)) {
+ ctx.report.note('override-node-reference', `${ctx.where}: ${addr} ${type}.${field}`);
+ continue;
+ }
out.push({ prefabEntityId: addr, type: 'property', componentType: type, propertyName: field, value });
}
}
@@ -288,6 +292,31 @@ function instanceOverrides(node: CocosNode, ctx: ConvertContext): PrefabOverride
return diff(flatten(pristine, quiet), flatten(patched, quiet), ctx);
}
+// ---------------------------------------------------------------------------
+// References to nodes, inside component data.
+// ---------------------------------------------------------------------------
+
+const isRef = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v) && NODE_REF in v;
+
+/** Whether a value holds a node reference anywhere inside it. */
+function holdsRef(v: unknown): boolean {
+ if (Array.isArray(v)) return v.some(holdsRef);
+ if (typeof v !== 'object' || v === null) return false;
+ return NODE_REF in v || Object.values(v).some(holdsRef);
+}
+
+/** Replace every node reference in @p v by what @p to makes of the node's id; a node the file does not hold gets @p missing. */
+function mapRefs(v: unknown, to: (id: string) => unknown, missing: unknown): unknown {
+ if (Array.isArray(v)) return v.map((x) => mapRefs(x, to, missing));
+ if (typeof v !== 'object' || v === null) return v;
+ if (isRef(v)) return typeof v[NODE_REF] === 'string' ? to(v[NODE_REF] as string) : missing;
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, mapRefs(x, to, missing)]));
+}
+
+function resolveRefs(components: ComponentData[], to: (id: string) => unknown, missing: unknown): void {
+ for (const c of components) for (const [k, v] of Object.entries(c.data)) if (holdsRef(v)) c.data[k] = mapRefs(v, to, missing);
+}
+
// ---------------------------------------------------------------------------
// Documents.
// ---------------------------------------------------------------------------
@@ -324,6 +353,9 @@ export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFi
}
};
walk(root, null);
+ // A reference to a node of this prefab is that node's prefab-local id; a prefab's refs are strings the loader maps.
+ const own = new Set(entities.map((e) => e.prefabEntityId));
+ for (const e of entities) resolveRefs(e.components, (id) => (own.has(id) ? id : ''), '');
return { version: '2', name: doc.name, rootEntityId: root.id, entities };
}
@@ -331,11 +363,18 @@ export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile
const entities: (SceneEntity | SceneInstanceEntry)[] = [];
ctx.report.documents.converted++;
let next = 0;
+ // Ids are given before any node is converted, so a reference to a node that comes later in the file has something to point at.
+ const ids = new Map<string, number>();
+ const assign = (n: CocosNode): void => {
+ ids.set(n.id, next++);
+ if (!n.instance) n.children.forEach(assign);
+ };
+ doc.roots.forEach(assign);
if (doc.globals.length) ctx.report.note('scene-globals-dropped', `${ctx.where}: ${doc.globals.join(',')}`);
const walk = (n: CocosNode, parent: SceneEntity | null): void => {
ctx.report.nodes++;
- const id = next++;
+ const id = ids.get(n.id)!;
const here = `${ctx.where}: ${n.name}`;
if (n.instance) {
ctx.report.prefabInstances++;
@@ -365,5 +404,7 @@ export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile
if (!n.instance) for (const c of n.children) walk(c, entity);
};
for (const r of doc.roots) walk(r, null);
+ // 0 is the engine's "no entity"; the loader maps the rest.
+ for (const e of entities) if ('components' in e) resolveRefs(e.components, (id) => ids.get(id) ?? 0, 0);
return { version: 4, name: doc.name, entities };
}
diff --git a/pipeline/src/import/cocos/document.ts b/pipeline/src/import/cocos/document.ts
index 829f6b5a5..b272a56ac 100644
--- a/pipeline/src/import/cocos/document.ts
+++ b/pipeline/src/import/cocos/document.ts
@@ -70,6 +70,9 @@ export interface CocosDocument {
type Raw = Record<string, unknown>;
+/** Key of a reference to a node inside a component's data: the value is that node's `CocosNode.id`. */
+export const NODE_REF = '__node__';
+
const BOOKKEEPING = new Set(['__type__', '_name', '_objFlags', 'node', '__prefab', '_id', '__editorExtras__']);
const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -118,6 +121,8 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
}
const seen = new Set<number>();
+ /** Which node an object in the file is, or belongs to: a `cc.Node` itself, or a component on one. */
+ const nodeAt = new Map<number, CocosNode>();
const usedIds = new Map<string, number>();
let duplicateIds = 0;
// Copy-pasted instances can carry the same fileId; the engine needs every entity in a prefab to have its own.
@@ -133,6 +138,7 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
const n = at(ref);
if (!n || n.__type__ !== 'cc.Node' || seen.has(idx)) return null;
seen.add(idx);
+ const rawComponents = Array.isArray(n._components) ? n._components : [];
const info = at(n._prefab);
const instRaw = info ? at(info.instance) : null;
// An instance node's PrefabInfo.fileId is the nested prefab's own root id, so two instances of one prefab share it;
@@ -153,6 +159,8 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
components: [],
children: [],
};
+ nodeAt.set(idx, node);
+ for (const cref of rawComponents) nodeAt.set(indexOf(cref), node);
for (const cref of Array.isArray(n._components) ? n._components : []) {
const c = at(cref);
@@ -195,5 +203,32 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
const n = readNode(r);
if (n) roots.push(n);
}
+ // A component's fields point at other objects in the file by index. Nodes and components become the id of their node, which is what
+ // a later stage can map to an entity; any other object (a click event, a nested serialised class) is read in place.
+ const resolveRefs = (value: unknown, stack: Set<number>): unknown => {
+ if (Array.isArray(value)) return value.map((v) => resolveRefs(v, stack));
+ if (!isObj(value)) return value;
+ if (typeof value.__id__ === 'number') {
+ const owner = nodeAt.get(value.__id__);
+ if (owner) return { [NODE_REF]: owner.id };
+ const target = objs[value.__id__];
+ if (!isObj(target) || stack.has(value.__id__) || target.__type__ === 'cc.Node') return null;
+ stack.add(value.__id__);
+ const out = resolveObject(target, stack);
+ stack.delete(value.__id__);
+ return out;
+ }
+ return resolveObject(value, stack);
+ };
+ const resolveObject = (o: Raw, stack: Set<number>): Raw => {
+ const out: Raw = {};
+ for (const [k, v] of Object.entries(o)) if (k !== '__type__' && !BOOKKEEPING.has(k)) out[k] = resolveRefs(v, stack);
+ return out;
+ };
+ const resolveNode = (node: CocosNode): void => {
+ for (const c of node.components) for (const [k, v] of Object.entries(c.data)) c.data[k] = resolveRefs(v, new Set());
+ node.children.forEach(resolveNode);
+ };
+ roots.forEach(resolveNode);
return { kind, name, roots, globals, duplicateIds };
}
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 66b51f030..fad585124 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -10,6 +10,7 @@
*/
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
+import { buildScriptIndex } from './scripts';
import { buildCocosAssetIndex, type CocosAssetEntry } from './assets';
import type { AssetHints, SliceBorder } from './components';
import { convertPrefab, convertScene, type ConvertContext } from './convert';
@@ -125,8 +126,11 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {
return doc;
};
+ const scripts = buildScriptIndex(index);
const ctx: ConvertContext = {
assets: index,
+ scriptClass: (classId) => scripts.get(classId),
+ prefabAssetRef: (uuid) => ctx.prefabRef(uuid),
report,
where: '',
assetRef(entry, slice, hints) {
diff --git a/pipeline/src/import/cocos/scripts.ts b/pipeline/src/import/cocos/scripts.ts
new file mode 100644
index 000000000..90629a7a7
--- /dev/null
+++ b/pipeline/src/import/cocos/scripts.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which script class a component of a Cocos scene is.
+ *
+ * A scene does not name a script component's class; it carries the script's uuid in a compressed form
+ * (five hex digits kept, the other twenty-seven as eighteen base64 characters). The uuid is the `.meta`
+ * of the script file, and the class name is what its `@ccclass('...')` says — which is also the name the
+ * compatibility layer registers the component under (`Cocos.<name>`).
+ *
+ * Read-only: scripts are read to find the name, never changed or copied.
+ */
+import { readFileSync } from 'node:fs';
+import type { CocosAssetIndex } from './assets';
+
+const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+/** Cocos's compressed uuid: what a script component's `__type__` is. */
+export function compressUuid(uuid: string): string {
+ const hex = uuid.replaceAll('-', '').toLowerCase();
+ if (hex.length !== 32) return uuid;
+ let out = hex.slice(0, 5);
+ for (let i = 5; i < 32; i += 3) {
+ const v = parseInt(hex.slice(i, i + 3), 16);
+ out += B64[v >> 6]! + B64[v & 63]!;
+ }
+ return out;
+}
+
+export interface ScriptClass {
+ /** The `@ccclass` name, which the layer registers as `Cocos.<name>`. */
+ name: string;
+ /** Path of the script, relative to the project's `assets`. */
+ rel: string;
+}
+
+const NAMED = /@ccclass\(\s*['"]([^'"]+)['"]\s*\)/;
+/** What may sit between the decorator and the class: other decorators, and comments. */
+const BETWEEN = String.raw`(?:\s*(?:@[^\r\n]*|//[^\r\n]*))*\s*`;
+/** `@ccclass` or `@ccclass()` takes the class's own name. */
+const UNNAMED = new RegExp(String.raw`@ccclass(?:\(\s*\))?(?![\w(])${BETWEEN}(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(\w+)`);
+
+/** The compressed uuid of every script that declares a component class, mapped to that class. */
+export function buildScriptIndex(assets: CocosAssetIndex): Map<string, ScriptClass> {
+ const out = new Map<string, ScriptClass>();
+ for (const entry of assets.byUuid.values()) {
+ if (!/\.(ts|js)$/.test(entry.rel) || entry.rel.endsWith('.d.ts')) continue;
+ if (entry.importer !== 'typescript' && entry.importer !== 'javascript') continue;
+ let text: string;
+ try {
+ text = readFileSync(entry.file, 'utf8');
+ } catch {
+ continue;
+ }
+ const name = NAMED.exec(text)?.[1] ?? UNNAMED.exec(text)?.[1];
+ if (!name) continue;
+ out.set(compressUuid(entry.uuid), { name, rel: entry.rel });
+ }
+ return out;
+}
diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.ts
new file mode 100644
index 000000000..4e80198ae
--- /dev/null
+++ b/pipeline/tests/cocos-import-layer.test.ts
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What the importer hands the runtime compatibility layer: UI geometry, alignment, layout, buttons, and the project's own
+ * scripts as components, with their references to other nodes pointing at the entities those nodes became.
+ *
+ * The scene is built by hand in Cocos's file shape (a flat array of objects pointing at each other by index), because the shape
+ * is the thing under test: a script component is named by its script's compressed uuid, and a node is named by an array index.
+ */
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { importCocosProject } from '../src/import/cocos';
+import { buildCocosAssetIndex } from '../src/import/cocos/assets';
+import { buildScriptIndex, compressUuid } from '../src/import/cocos/scripts';
+
+const HUD = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const OTHER = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const PLAIN = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const unit = { __type__: 'cc.Vec3', x: 1, y: 1, z: 1 };
+const zero = { __type__: 'cc.Vec3', x: 0, y: 0, z: 0 };
+const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };
+
+const node = (name: string, parent: number, children: number[], components: number[]): object => ({
+ __type__: 'cc.Node', _name: name, _parent: { __id__: parent }, _children: children.map((__id__) => ({ __id__ })), _active: true,
+ _components: components.map((__id__) => ({ __id__ })), _prefab: null, _lpos: zero, _lrot: ident, _lscale: unit, _layer: 33554432,
+});
+const ui = (n: number, w: number, h: number): object =>
+ ({ __type__: 'cc.UITransform', node: { __id__: n }, _enabled: true, _contentSize: { width: w, height: h }, _anchorPoint: { x: 0.5, y: 0.5 } });
+
+/** Objects are numbered as the comments say; the references between them are indices into this array. */
+const scene = [
+ { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } }, // 0
+ { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }] }, // 1
+ node('Canvas', 1, [3, 4], [5, 6]), // 2
+ node('Buy', 2, [], [7, 8]), // 3
+ node('Hud', 2, [], [9, 11]), // 4
+ ui(2, 960, 640), // 5
+ { __type__: 'cc.Widget', node: { __id__: 2 }, _enabled: true, _alignFlags: 45, _left: 10, _right: 10, _top: 5, _bottom: 5, _alignMode: 2, _isAbsLeft: true },
+ ui(3, 120, 48), // 7
+ { __type__: 'cc.Button', node: { __id__: 3 }, _enabled: true, _interactable: true, _transition: 3, _zoomScale: 1.1,
+ clickEvents: [{ __id__: 10 }], _normalColor: { __type__: 'cc.Color', r: 255, g: 255, b: 255, a: 255 } }, // 8
+ { __type__: compressUuid(HUD), node: { __id__: 4 }, _enabled: true, speed: 3, label: { __id__: 3 }, all: [{ __id__: 3 }, { __id__: 4 }],
+ buttonOf: { __id__: 8 }, icon: { __uuid__: PLAIN }, _hidden: { __id__: 99 } }, // 9
+ { __type__: 'cc.ClickEvent', target: { __id__: 4 }, component: '', _componentId: compressUuid(HUD), handler: 'onBuy', customEventData: 'gold' }, // 10
+ { __type__: 'cc.Layout', node: { __id__: 4 }, _enabled: true, _layoutType: 2, _resizeMode: 1, _spacingY: 8, _paddingTop: 4, _cellSize: { width: 50, height: 60 }, _verticalDirection: 1 }, // 11
+];
+
+describe('importing for the compatibility layer', () => {
+ let root: string;
+ let scenes: { entities: Array<{ id: number; name: string; components: Array<{ type: string; data: Record<string, any> }> }> };
+ let report: ReturnType<typeof importCocosProject>;
+
+ beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'cocos-layer-'));
+ const put = (rel: string, v: string | object): void => {
+ const f = path.join(root, 'creator', 'assets', rel);
+ mkdirSync(path.dirname(f), { recursive: true });
+ writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));
+ };
+ const meta = (uuid: string, importer: string): object => ({ ver: '1', importer, uuid, subMetas: {}, userData: {} });
+ put('main.scene', scene);
+ put('main.scene.meta', meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene'));
+ put('scripts/Hud.ts', "import { _decorator, Component } from 'cc';\nconst { ccclass } = _decorator;\n@ccclass('Hud')\nexport class Hud extends Component {}\n");
+ put('scripts/Hud.ts.meta', meta(HUD, 'typescript'));
+ put('scripts/Other.ts', "@ccclass\n@menu('x')\n// a comment between\n@executionOrder(-1)\nexport default class Other extends Component {}\n");
+ put('scripts/Other.ts.meta', meta(OTHER, 'typescript'));
+ put('art/plain.json', '{}');
+ put('art/plain.json.meta', meta(PLAIN, 'json'));
+ report = importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });
+ scenes = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8'));
+ });
+ afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+ const entity = (name: string) => scenes.entities.find((e) => e.name === name)!;
+ const comp = (name: string, type: string) => entity(name).components.find((c) => c.type === type)!;
+
+ it('keeps a node\'s rectangle as a component of its own, as well as the size its renderers got', () => {
+ expect(comp('Canvas', 'Cocos.UITransform').data).toEqual({ width: 960, height: 640, anchorX: 0.5, anchorY: 0.5 });
+ });
+
+ it('carries a widget\'s and a layout\'s settings under the names the layer uses', () => {
+ const w = comp('Canvas', 'Cocos.Widget').data;
+ expect([w.alignFlags, w.left, w.right, w.top, w.bottom, w.alignMode, w.enabled]).toEqual([45, 10, 10, 5, 5, 2, true]);
+ const l = comp('Hud', 'Cocos.Layout').data;
+ expect([l.type, l.resizeMode, l.spacingY, l.paddingTop, l.cellWidth, l.cellHeight, l.verticalDirection]).toEqual([2, 1, 8, 4, 50, 60, 1]);
+ });
+
+ it('splits a button\'s handlers into the entity they call and the rest, naming the script class from its uuid', () => {
+ const b = comp('Buy', 'Cocos.Button').data;
+ expect(b.transition).toBe(3);
+ expect(b.zoomScale).toBe(1.1);
+ expect(b.clickTargets).toEqual([entity('Hud').id]); // a node that comes LATER in the file
+ expect(b.clickHandlers).toEqual([{ component: 'Hud', handler: 'onBuy', customEventData: 'gold' }]);
+ });
+
+ it('turns a script component into Cocos.<class>, with node references pointing at the entities those nodes became', () => {
+ const h = comp('Hud', 'Cocos.Hud').data;
+ expect(h.speed).toBe(3);
+ expect(h.label).toBe(entity('Buy').id);
+ expect(h.all).toEqual([entity('Buy').id, entity('Hud').id]);
+ // a component reference is its node
+ expect(h.buttonOf).toBe(entity('Buy').id);
+ // a reference to something that is not in the file is the engine's "no entity", not a stale index
+ expect(h._hidden).toBeNull();
+ // an asset reference is the copied file's project path
+ expect(h.icon).toBe('assets/cocos/art/plain.json');
+ });
+
+ it('finds the class of a bare @ccclass among other decorators and comments', () => {
+ const classes = buildScriptIndex(buildCocosAssetIndex(path.join(root, 'creator', 'assets')));
+ expect(classes.get(compressUuid(OTHER))?.name).toBe('Other');
+ expect(report.components['script:Hud']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });
+ });
+
+ it('counts the components it maps', () => {
+ for (const type of ['cc.Widget', 'cc.Layout', 'cc.Button', 'cc.UITransform']) expect(report.components[type]!.unmapped).toBe(0);
+ });
+});
diff --git a/sdk/src/cocos/builtinScripts.ts b/sdk/src/cocos/builtinScripts.ts
index 79cb537e9..a581e93ad 100644
--- a/sdk/src/cocos/builtinScripts.ts
+++ b/sdk/src/cocos/builtinScripts.ts
@@ -12,6 +12,7 @@ import { getDefaultContext } from '../ecs/context';
import { declareButton } from './ui/button';
import { declareInputSystem } from './input';
import { declareUiPass } from './ui/pass';
+import { uiTransformDef } from './ui/uiTransform';
import { resetClassRegistry } from './registry';
const declared = new WeakSet<object>();
@@ -23,6 +24,8 @@ export function declareBuiltinScripts(): void {
declared.add(context);
declareButton();
declareInputSystem();
+ // A scene holds `Cocos.UITransform` before any script asks for one, so the component has to exist when it loads.
+ uiTransformDef();
declareUiPass();
}
diff --git a/sdk/tests/cocos/import-contract-wasm.test.ts b/sdk/tests/cocos/import-contract-wasm.test.ts
new file mode 100644
index 000000000..6a1bf70e9
--- /dev/null
+++ b/sdk/tests/cocos/import-contract-wasm.test.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A scene as the importer writes it, loaded into the real engine with the compatibility layer.
+ *
+ * The importer (pipeline/src/import/cocos) and the layer agree on a contract by name only: `Cocos.UITransform`, `Cocos.Widget`,
+ * `Cocos.Button`, `Cocos.<ScriptClass>`, with a node reference as the entity id the loader maps. This is the one place that agreement
+ * is exercised end to end, so a rename on either side fails here and not on a user's project.
+ */
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import type { ESEngineModule } from '../../src/wasm';
+import { App, flushPendingRegistrations } from '../../src/app/app';
+import { ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
+import { AppContext, setDefaultContext } from '../../src/ecs/context';
+import { loadSceneData } from '../../src/scene/scene';
+import type { SceneData } from '../../src/scene/scene';
+import { resetClassRegistry } from '../../src/cocos/registry';
+import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';
+import { Button, Component, Node, UITransform, Widget, _decorator, setCurrentWorld, setVisibleSize } from '../../src/cocos';
+import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
+
+const transform = { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } };
+
+describe.skipIf(!HAS_WASM)('the importer\'s scene in the compatibility layer', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let app: App | undefined;
+
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => {
+ setCurrentWorld(null);
+ app?.world.disconnectCpp();
+ registry?.delete();
+ app = undefined;
+ registry = undefined;
+ });
+
+ it('loads UI geometry, alignment, a button with a handler on a later node, and a script with node references', async () => {
+ setDefaultContext(new AppContext());
+ ensureBuiltinComponentsRegistered();
+ resetClassRegistry();
+ declareBuiltinScripts();
+
+ // The project's own script, as the layer's decorators declare it.
+ const seen: string[] = [];
+ @_decorator.ccclass('Hud')
+ class Hud extends Component {
+ @_decorator.property(Node) label: Node | null = null;
+ @_decorator.property([Node]) all: Node[] = [];
+ @_decorator.property speed = 1;
+ onBuy(_event: unknown, data: string): void { seen.push(data); }
+ }
+ // the decorator ran before the registry was reset above in some orders; declare is idempotent per name
+ void Hud;
+
+ registry = new module.Registry();
+ app = App.new();
+ app.connectCpp(registry as never, module);
+ flushPendingRegistrations(app);
+ setCurrentWorld(app.world);
+ setVisibleSize(960, 640);
+
+ const scene: SceneData = {
+ version: 4,
+ name: 'main',
+ entities: [
+ { id: 0, name: 'Canvas', parent: null, children: [1, 2], visible: true, components: [
+ transform,
+ { type: 'Cocos.UITransform', data: { width: 10, height: 10, anchorX: 0.5, anchorY: 0.5 } },
+ { type: 'Cocos.Widget', data: { enabled: true, alignFlags: 45, left: 0, right: 0, top: 0, bottom: 0, alignMode: 1 } },
+ ] },
+ { id: 1, name: 'Buy', parent: 0, children: [], visible: true, components: [
+ transform,
+ { type: 'Cocos.UITransform', data: { width: 120, height: 48, anchorX: 0.5, anchorY: 0.5 } },
+ { type: 'Cocos.Button', data: { enabled: true, interactable: true, transition: 3, zoomScale: 1.1, clickTargets: [2], clickHandlers: [{ component: 'Hud', handler: 'onBuy', customEventData: 'gold' }] } },
+ ] },
+ { id: 2, name: 'Hud', parent: 0, children: [], visible: true, components: [
+ transform,
+ { type: 'Cocos.Hud', data: { enabled: true, speed: 3, label: 1, all: [1, 2] } },
+ ] },
+ ],
+ } as never;
+ const map = loadSceneData(app.world, scene);
+ await app.tick(1 / 60);
+ await app.tick(1 / 60);
+
+ const canvas = Node.for(app.world, map.get(0)!);
+ const buy = Node.for(app.world, map.get(1)!);
+ const hud = Node.for(app.world, map.get(2)!);
+
+ // geometry and alignment: the canvas was authored 10x10 and stretches to the visible area
+ const t = canvas.getComponent(UITransform)!;
+ expect([t.width, t.height]).toEqual([960, 640]);
+ expect(canvas.position.x).toBe(480);
+
+ // a script with its fields, node references mapped to the entities the loader made
+ const script = hud.getComponent('Hud') as unknown as Hud;
+ expect(script.speed).toBe(3);
+ expect(script.label).toBe(buy);
+ expect(script.all).toEqual([buy, hud]);
+
+ // the button's handler finds the script on a node that was later in the file, by its class name
+ const button = buy.getComponent(Button)!;
+ expect(button.clickEvents).toHaveLength(1);
+ button.clickEvents[0]!.emit([{}]);
+ expect(seen).toEqual(['gold']);
+ void Widget;
+ });
+});