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(cocos): one script that fails to load no longer takes the others with it, a part of cc the layer lacks is a stand-in that survives use, and Director, AssetManager.Cache and the input dispatcher hook exist
yhh37f47920f027
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 81c5d6f67..ef72c4499 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ published separately; it ships inside the editor.- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.- **World content has a rectangle: `ContentRect`.** A size and the pivot the entity's transform sits on, which the `Sprite` and `Text` on the entity follow and which a `UIMask` on it clips to — no `UINode` needed, so a clipping region or a scroll viewport can stand in the world. `contentRectContains` tests a world point against it.+- **Cocos scripts load one by one.** Each script of a converted project loads on its own, so one whose module throws no longer stops the rest from registering their components. A part of the `cc` module the layer does not provide is a stand-in that survives being read, called and constructed (and says once that it is missing) rather than `undefined`. `Director` is a class scripts can patch, `AssetManager.Cache` exists, and `input._registerEventDispatcher` is accepted.- **A converted Cocos project links its images.** The source images, fonts and spine files are hard-linked into the converted project (copied only across drives), so a multi-gigabyte art folder is neither copied nor stored twice, and a re-import skips what is already linked. The project reads those files and never writes into them.- **A Cocos conversion shows its progress.** The importer reports the stage it is in and how far through it is, and the editor runs the conversion on a thread of its own with a progress bar over the window, instead of freezing until it ends.- **Bursts on a schedule.** `ParticleEmitter.bursts` is a list of `{ time, count }`: each releases its particles once the emitter has been emitting for `time` seconds, and a looping emitter repeats the list every `duration`. It runs beside `burstCount`, which still repeats one burst on an interval.diff --git a/pipeline/src/bundle/cocosCompat.ts b/pipeline/src/bundle/cocosCompat.tsindex cf97e27a4..76406f8cf 100644--- a/pipeline/src/bundle/cocosCompat.ts+++ b/pipeline/src/bundle/cocosCompat.ts@@ -61,13 +61,21 @@ const NAMED_CC_IMPORT = /^[ \t]*import\s*\{([^}]*)\}\s*from\s*(['"])(cc(?:\/env)*/export function readNamedImportsThroughNamespace(source: string): string {let n = 0;- return source.replace(NAMED_CC_IMPORT, (_all, list: string, quote: string, from: string) => {+ const reads: string[] = [];+ const rest = source.replace(NAMED_CC_IMPORT, (all, list: string, quote: string, from: string) => {const bindings = list.split(',').map((x) => x.trim()).filter((x) => x && !/^type\s/.test(x))- .map((x) => { const [name, alias] = x.split(/\s+as\s+/); return alias ? `${name!.trim()}: ${alias.trim()}` : name!.trim(); });- if (bindings.length === 0) return '';- const ns = `__cc${n++}`;- return `import * as ${ns} from ${quote}${from}${quote}; const { ${bindings.join(', ')} } = ${ns};`;+ .map((x) => { const [name, alias] = x.split(/\s+as\s+/); return { name: name!.trim(), local: (alias ?? name)!.trim() }; });+ if (bindings.length > 0) {+ const ns = '__cc' + n++;+ // a name the layer lacks is a stand-in that survives being used, so a script that reaches into it while its module loads does not stop the rest+ const each = bindings.map((b) => b.local + ' = ' + ns + '.' + b.name + ' ?? ' + ns + '.unsupported(' + JSON.stringify(b.name) + ')').join(', ');+ reads.push('import * as ' + ns + ' from ' + quote + from + quote + '; const ' + each + ';');+ }+ // the statement leaves its lines behind, so what follows keeps its line numbers+ return all.replace(/[^\n]/g, '');});+ // an import is hoisted: a script may use a name above the line that imports it, so the bindings go first, on the first line+ return reads.length > 0 ? reads.join(' ') + ' ' + rest : rest;}/** The source with every `const` that the script assigns to again read as `let`; the source itself when there is none. */diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex 643c062e7..089d4108f 100644--- a/pipeline/src/import/cocos/importProject.ts+++ b/pipeline/src/import/cocos/importProject.ts@@ -614,17 +614,27 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impoif (usedScripts.size > 0) {// The scripts stay where they are, unchanged; this file is how the new project's bundle reaches them.const entry = path.join(out, 'src', 'cocos-scripts.ts');- const imports = [...usedScripts].sort().map((rel) => {+ const loads = [...usedScripts].sort().map((rel) => {const target = path.join(assetsDir, rel.replace(/\.(ts|js)$/, ''));- // On another drive there is no relative path, only the absolute one, which an import takes just as well.+ // On another drive there is no relative path, only the absolute one, which a require takes just as well.const rel2 = path.relative(path.dirname(entry), target).split(path.sep).join('/');- return `import '${path.isAbsolute(rel2) || /^[A-Za-z]:/.test(rel2) || rel2.startsWith('.') ? rel2 : `./${rel2}`}';`;+ return "load(() => require('" + (path.isAbsolute(rel2) || /^[A-Za-z]:/.test(rel2) || rel2.startsWith('.') ? rel2 : "./" + rel2) + "'), '" + rel.replace(/'/g, "\\'") + "');";});+ // Each script is its own load: a project's scripts are evaluated together, and one whose module throws (a Cocos API this engine does not+ // have, a script that reaches for the page) must not take the others with it. Loaded in order, synchronously, so the components exist before the scene does.const text = ["// Generated by import-cocos. Brings the Cocos project's scripts into this project's bundle, read from where they are.",- "// Import this file from src/main.ts. Scripts resolve `cc` to the engine's compatibility layer.",+ "// src/main.ts loads this file. Scripts resolve `cc` to the engine's compatibility layer.","import 'esengine/cocos';",- ...imports, '',+ "declare const require: (id: string) => unknown;",+ "function load(script: () => unknown, name: string): void {",+ " try {",+ " script();",+ " } catch (err) {",+ " console.error('[cocos] the script ' + name + ' failed to load:', err);",+ " }",+ "}",+ ...loads, '',].join('\n');if (!opts.dryRun) writeOut(entry, text);report.note('cocos-scripts-entry', `${path.relative(out, entry).split(path.sep).join('/')}: ${usedScripts.size} script(s)`);diff --git a/pipeline/tests/cocos-compat-bundle.test.ts b/pipeline/tests/cocos-compat-bundle.test.tsindex cbd7cfcc5..7037753b0 100644--- a/pipeline/tests/cocos-compat-bundle.test.ts+++ b/pipeline/tests/cocos-compat-bundle.test.ts@@ -107,9 +107,12 @@ describe('a const the script assigns to again', () => {describe('named imports from cc', () => {it('are read from the layer namespace, so a name the layer lacks is undefined instead of a build error', async () => {const { readNamedImportsThroughNamespace } = await import('../src/bundle/cocosCompat');- const out = readNamedImportsThroughNamespace("import { _decorator, Node as N, type Vec3, gfx } from 'cc';\nimport { EDITOR } from 'cc/env';\nconst x = 1;");- expect(out).toContain("import * as __cc0 from 'cc'; const { _decorator, Node: N, gfx } = __cc0;");- expect(out).toContain("import * as __cc1 from 'cc/env'; const { EDITOR } = __cc1;");+ const out = readNamedImportsThroughNamespace("const { ccclass } = _decorator;\nimport { _decorator, Node as N, type Vec3, gfx } from 'cc';\nimport { EDITOR } from 'cc/env';\nconst x = 1;");+ // the bindings come first, on line one: a script may use a name above the import line that declares it+ expect(out.startsWith("import * as __cc0 from 'cc'; const _decorator = __cc0._decorator ?? __cc0.unsupported(\"_decorator\"), N = __cc0.Node ?? __cc0.unsupported(\"Node\"), gfx = __cc0.gfx ?? __cc0.unsupported(\"gfx\");")).toBe(true);+ expect(out).toContain("import * as __cc1 from 'cc/env'; const EDITOR = __cc1.EDITOR ?? __cc1.unsupported(\"EDITOR\");");+ expect(out.split('\n')).toHaveLength(4);+ expect(out).toContain('const { ccclass } = _decorator;');expect(out).toContain('const x = 1;');});});diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.tsindex 9c52e0c49..11e0ea90b 100644--- a/pipeline/tests/cocos-import-layer.test.ts+++ b/pipeline/tests/cocos-import-layer.test.ts@@ -139,10 +139,14 @@ describe('importing for the compatibility layer', () => {it('writes the entry that brings the scripts into the bundle, importing them where they are', () => {const entry = readFileSync(path.join(root, 'out', 'src', 'cocos-scripts.ts'), 'utf8');expect(entry).toContain("import 'esengine/cocos';");- const line = entry.split('\n').find((l) => l.endsWith("scripts/Hud';"))!;+ const line = entry.split('\n').find((l) => l.includes("scripts/Hud'"))!;expect(line).toBeDefined();+ // each script loads on its own, so one that throws does not stop the others+ expect(line).toMatch(/^load\(\(\) => require\('/);+ expect(entry).toContain('try {');// the path leads back to the Cocos project, which is not copied- expect(path.resolve(root, 'out', 'src', line.slice("import '".length, -2) + '.ts')).toBe(path.join(root, 'creator', 'assets', 'scripts', 'Hud.ts'));+ const target = /require\('([^']+)'\)/.exec(line)![1]!;+ expect(path.resolve(root, 'out', 'src', target + '.ts')).toBe(path.join(root, 'creator', 'assets', 'scripts', 'Hud.ts'));});it('lists what scripts load by path in a manifest, by bundle, and copies those files', () => {diff --git a/sdk/src/cocos/assetManager.ts b/sdk/src/cocos/assetManager.tsindex c73823416..45350a90b 100644--- a/sdk/src/cocos/assetManager.ts+++ b/sdk/src/cocos/assetManager.ts@@ -205,6 +205,8 @@ const resources = bundleOf('resources');bundles.add('resources', resources);class AssetManager {+ /** The cache class, as `AssetManager.Cache`: scripts derive their own caches from it. */+ static readonly Cache = Cache;readonly assets = loaded;readonly bundles = bundles;readonly resources = resources;diff --git a/sdk/src/cocos/director.ts b/sdk/src/cocos/director.tsindex 16761a9ac..c92de551f 100644--- a/sdk/src/cocos/director.ts+++ b/sdk/src/cocos/director.ts@@ -93,13 +93,22 @@ export function reportFrame(delta: number): void {totalFrames++;}-/** `Director`'s event names. */-export const Director = Object.freeze({- EVENT_BEFORE_UPDATE: 'director_before_update',- EVENT_AFTER_UPDATE: 'director_after_update',- EVENT_BEFORE_SCENE_LOADING: 'director_before_scene_loading',- EVENT_AFTER_SCENE_LAUNCH: 'director_after_scene_launch',-});+/**+ * `Director`: its event names, and the class the singleton `director` is an instance of. Scripts patch `Director.prototype.tick` to hook the+ * frame; here the frame is the engine's, so a patched `tick` is never called, but the patch itself has somewhere to land.+ */+export class Director {+ static readonly EVENT_BEFORE_UPDATE = 'director_before_update';+ static readonly EVENT_AFTER_UPDATE = 'director_after_update';+ static readonly EVENT_BEFORE_SCENE_LOADING = 'director_before_scene_loading';+ static readonly EVENT_AFTER_SCENE_LAUNCH = 'director_after_scene_launch';+ static readonly EVENT_BEFORE_DRAW = 'director_before_draw';+ static readonly EVENT_AFTER_DRAW = 'director_after_draw';+ static readonly EVENT_END_FRAME = 'director_end_frame';+ static get instance(): typeof director { return director; }+ static getInstance(): typeof director { return director; }+ tick(_now?: number): void { /* the engine runs the frame */ }+}/** A node by absolute path from the scene roots: `find('Canvas/Panel')`. A name with no slash searches the roots, then everything. */export function find(path: string, referenceNode?: Node): Node | null {diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.tsindex 3ac785417..7d7e302e8 100644--- a/sdk/src/cocos/index.ts+++ b/sdk/src/cocos/index.ts@@ -26,6 +26,7 @@ export {AnimationClip, SceneAsset, EffectAsset, Mesh,} from './assets';export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';+export { unsupported } from './unsupported';export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Camera, RichText, Mask, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, Graphics, Line, EditBox, PageView, PageViewIndicator, ScrollBar, SafeArea, WebView, getVisibleSize, setVisibleSize } from './ui';export { Touch, EventTouch } from './input';export { tween, Tween, tweenUtil, easing, updateTweens } from './tween';diff --git a/sdk/src/cocos/inputApi.ts b/sdk/src/cocos/inputApi.tsindex 7f8a70d1a..e071f1cf8 100644--- a/sdk/src/cocos/inputApi.ts+++ b/sdk/src/cocos/inputApi.ts@@ -115,6 +115,8 @@ class InputTarget extends Emitter {/** Whether the device sends orientation / motion; there is no sensor feed behind it. */setAccelerometerEnabled(_enabled: boolean): void { /* no sensor source */ }setAccelerometerInterval(_interval: number): void { /* no sensor source */ }+ /** Cocos's private hook for a game that routes input itself. Input here is the engine's pointer pipeline, which nothing else dispatches. */+ _registerEventDispatcher(_dispatcher: unknown): void { /* the engine dispatches */ }}/** The `Input` class scripts name for its `EventType`, and the instance `input`. */diff --git a/sdk/src/cocos/unsupported.ts b/sdk/src/cocos/unsupported.tsnew file mode 100644index 000000000..d3b8dbb43--- /dev/null+++ b/sdk/src/cocos/unsupported.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cocos/unsupported.ts+ * @brief What a script gets for a part of Cocos the layer does not provide, so one missing name does not take the whole project down.+ *+ * Cocos hands a script `undefined` for a name it does not export, and a project's scripts are evaluated together: the first one that+ * reaches into such a name while its module loads (`new gfx.Attribute(...)` to build a vertex format, say) throws, and every script+ * after it never registers. This is a stand-in that survives being read, called and constructed, answers with more of itself, and says+ * once, by name, that the part is not there. It does nothing: a script that really needs what it stands for will not work, but the+ * rest of the project still starts.+ */+import { log } from '../util/logger';++const told = new Set<string>();++function tell(name: string): void {+ const top = name.split(/[.(]/).slice(0, 2).join('.');+ if (told.has(top)) return;+ told.add(top);+ log.warn('cocos', `${top} is not provided by the compatibility layer; scripts that use it will not behave as they do in Cocos`);+}++/** A stand-in for `cc.<name>`, which the layer does not have. */+export function unsupported(name: string): any {+ const children = new Map<string, unknown>();+ const make = (path: string): unknown => {+ const target = function () { /* a stand-in */ } as unknown as Record<PropertyKey, unknown>;+ return new Proxy(target, {+ get(self, key) {+ if (key === 'prototype') return self.prototype;+ if (key === Symbol.toPrimitive) return () => '';+ if (typeof key === 'symbol' || key === 'then') return undefined;+ const child = `${path}.${key}`;+ let found = children.get(child);+ if (found === undefined) { found = make(child); children.set(child, found); }+ return found;+ },+ set: () => true,+ apply: () => { tell(path); return make(`${path}()`); },+ construct: () => { tell(path); return make(`${path}()`) as object; },+ });+ };+ return make(`cc.${name}`);+}diff --git a/sdk/tests/cocos/unsupported.test.ts b/sdk/tests/cocos/unsupported.test.tsnew file mode 100644index 000000000..765e51245--- /dev/null+++ b/sdk/tests/cocos/unsupported.test.ts@@ -0,0 +1,22 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { unsupported } from '../../src/cocos/unsupported';++describe('a part of Cocos the layer does not provide', () => {+ it('survives what a script does with it while its module loads', () => {+ const gfx = unsupported('gfx') as any;+ const format = [new gfx.Attribute('a_position', gfx.Format.RGB32F), gfx.Format.RG32F];+ expect(format).toHaveLength(2);+ expect(`${gfx.Format.RGB32F}`).toBe('');+ expect(gfx.Attribute).toBe(gfx.Attribute);+ expect(() => { gfx.useless(1).deeper.still(); gfx.flag = 3; })+ .not.toThrow();+ class Derived extends (unsupported('Base') as any) { }+ expect(() => new Derived()).not.toThrow();+ });++ it('is not a promise, so awaiting it does not hang', async () => {+ await expect(Promise.resolve(unsupported('x'))).resolves.toBeDefined();+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex f5171da17..bfe462725 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(cocos): one script that fails to load no longer takes the others with it, a part of cc the layer lacks is a stand-in that survives use, and Director, AssetManager.Cache and the input dispatcher hook exist':+ {"note":"Cocos scripts load one by one."},'feat(cocos): a converted project links its source images instead of copying them, so conversion does not store a multi-gigabyte art folder twice':{"note":"A converted Cocos project links its images."},'feat(cocos): the importer reports its progress by stage, so a long conversion can show a bar':