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): resources.load gives images, sprite frames and audio by path, Sprite takes a spriteFrame, Node has getParent; the script entry leaves out the editor's own scripts
yhh9098a5c51834
diff --git a/desktop b/desktopindex 79e718736..ebafd0d4d 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 79e718736e7162f6246787a1dfdbc82dc02d0b4d+Subproject commit ebafd0d4d63941c41db051c1d412a05b1b4553fadiff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex 9dca2d117..1d5b8bee2 100644--- a/pipeline/src/import/cocos/importProject.ts+++ b/pipeline/src/import/cocos/importProject.ts@@ -31,7 +31,7 @@ import { convertPass, isOutlinePass, type PassConversion } from './effectConvert* importer that made less (or differently), and is brought up to date when it is opened. Raise it when the converted output changes in a* way an existing project needs to pick up: a new generated file, a field a document or a manifest now carries.*/-export const COCOS_IMPORT_REVISION = 7;+export const COCOS_IMPORT_REVISION = 8;/** Whether the project at @p projectRoot was written by an importer of this revision. A project that was not converted has nothing to bring up. */export function cocosImportIsCurrent(projectRoot: string): boolean {@@ -973,8 +973,10 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo// configuration, its helpers on `window`) is named by no scene, and what loads next reads them. Those run first.// And every script that declares a component class: a game finds its classes by name too (a view is opened by its class's name), and a// class no scene names is still there in Cocos.- const everyClass = new Set([...usedScripts, ...[...scripts.values()].map((c) => c.rel)]);- const starters = globalDefiningScripts(index).filter((rel) => !everyClass.has(rel));+ // The editor's own scripts (its debug tools) are not the project's and are not on disk beside it.+ const ours = (rel: string): boolean => !rel.startsWith(`${INTERNAL_FOLDER}/`);+ const everyClass = new Set([...usedScripts, ...[...scripts.values()].map((c) => c.rel)].filter(ours));+ const starters = globalDefiningScripts(index).filter((rel) => ours(rel) && !everyClass.has(rel));const loads = [...starters, ...[...everyClass].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 a require takes just as well.diff --git a/pipeline/tests/cocos-internal-assets.test.ts b/pipeline/tests/cocos-internal-assets.test.tsindex d90d97ab2..97f305ff9 100644--- a/pipeline/tests/cocos-internal-assets.test.ts+++ b/pipeline/tests/cocos-internal-assets.test.ts@@ -10,8 +10,16 @@ import path from 'node:path';import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { importCocosProject } from '../src/import/cocos';import { buildCocosAssetIndex, cocosEditorAssets, INTERNAL_FOLDER } from '../src/import/cocos/assets';+import { compressUuid } from '../src/import/cocos/scripts';const BAR = '24a704da-2867-446d-8d1a-5e920c75e09d';+const HERO = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';+const DEBUG = 'ffffffff-ffff-4fff-8fff-ffffffffffff';+const component = (name: string): string => `import { _decorator, Component } from 'cc';+const { ccclass } = _decorator;+@ccclass('${name}')+export class ${name} extends Component {}+`;const meta = (uuid: string, importer: string, subMetas: object = {}): object => ({ ver: '1', importer, uuid, subMetas, userData: {} });describe('built-in editor assets', () => {@@ -25,6 +33,10 @@ describe('built-in editor assets', () => {mkdirSync(path.join(editor, 'default_ui'), { recursive: true });writeFileSync(path.join(editor, 'default_ui', 'default_progressbar.png'), 'png');writeFileSync(path.join(editor, 'default_ui', 'default_progressbar.png.meta'), JSON.stringify(meta('bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb', 'image', { f9941: { importer: 'sprite-frame', uuid: BAR, name: 'spriteFrame', userData: {} } })));+ // the editor's own tools hold a component class too+ mkdirSync(path.join(editor, 'tools'), { recursive: true });+ writeFileSync(path.join(editor, 'tools', 'debug-view.ts'), component('DebugView'));+ writeFileSync(path.join(editor, 'tools', 'debug-view.ts.meta'), JSON.stringify(meta(DEBUG, 'typescript')));process.env.COCOS_EDITOR_ASSETS = editor;const dir = path.join(root, 'creator', 'assets');@@ -36,6 +48,11 @@ describe('built-in editor assets', () => {{ __type__: 'cc.Node', _name: 'Bar', _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: 3 }], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: unit, _layer: 1 },{ __type__: 'cc.Sprite', node: { __id__: 2 }, _enabled: true, _color: { __type__: 'cc.Color', r: 255, g: 255, b: 255, a: 255 }, _spriteFrame: { __uuid__: `${BAR}`, __expectedType__: 'cc.SpriteFrame' }, _type: 1, _sizeMode: 0 },];+ scene.push({ __type__: 'cc.Node', _name: 'Hero', _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: 5 }], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: unit, _layer: 1 });+ scene.push({ __type__: compressUuid(HERO), node: { __id__: 4 }, _enabled: true } as never);+ (scene[1] as { _children: unknown[] })._children.push({ __id__: 4 });+ writeFileSync(path.join(dir, 'Hero.ts'), component('Hero'));+ writeFileSync(path.join(dir, 'Hero.ts.meta'), JSON.stringify(meta(HERO, 'typescript')));writeFileSync(path.join(dir, 'main.scene'), JSON.stringify(scene));writeFileSync(path.join(dir, 'main.scene.meta'), JSON.stringify(meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene')));writeFileSync(path.join(root, 'creator', 'package.json'), JSON.stringify({ creator: { version: '3.7.3' } }));@@ -63,6 +80,12 @@ describe('built-in editor assets', () => {expect(index.byUuid.get(BAR)!.rel).toBe(`${INTERNAL_FOLDER}/default_ui/default_progressbar.png`);});+ it("leaves the editor's own scripts out of the entry, which loads the project's", () => {+ const entry = readFileSync(path.join(root, 'out', 'src', 'cocos-scripts.ts'), 'utf8');+ expect(entry).toContain('Hero');+ expect(entry).not.toContain(INTERNAL_FOLDER);+ });+it('brings the image in and points the sprite at it', () => {const scene = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8')) as { entities: Array<{ name: string; components: Array<{ type: string; data: Record<string, unknown> }> }> };const sprite = scene.entities.find((e) => e.name === 'Bar')!.components.find((c) => c.type === 'Sprite')!;diff --git a/sdk/src/cocos/assetManager.ts b/sdk/src/cocos/assetManager.tsindex 5ea8f29da..34b378d63 100644--- a/sdk/src/cocos/assetManager.ts+++ b/sdk/src/cocos/assetManager.ts@@ -17,7 +17,7 @@*/import { platformFetch } from '../platform';import { log } from '../util/logger';-import { Asset, JsonAsset, Material, Prefab, TextAsset } from './assets';+import { Asset, AudioClip, ImageAsset, JsonAsset, Material, Prefab, SpriteFrame, TextAsset, Texture2D } from './assets';import { getCurrentWorld } from './node';import { assetsFor, loadPrefab, onNewSession } from './prefabs';@@ -63,7 +63,7 @@ async function theManifest(): Promise<ResourceManifest> {if (manifest) return manifest;manifestLoad ??= (async () => {const assets = assetsFor(getCurrentWorld());- if (!assets) throw new Error('the engine\'s asset loader is not running');+ if (!assets) throw new Error("the engine's asset loader is not running");const loaded = await assets.loadJson<ResourceManifest>(MANIFEST_PATH);manifest = loaded.data;return manifest;@@ -111,7 +111,7 @@ async function loadEntry(entry: ResourceEntry, type: AssetCtor | null): Promise<return loadPrefab(entry.path);}case 'json': {- if (!assets) throw new Error('the engine\'s asset loader is not running');+ if (!assets) throw new Error("the engine's asset loader is not running");const a = new JsonAsset(entry.path);a.json = (await assets.loadJson(entry.path)).data;return a;@@ -123,6 +123,28 @@ async function loadEntry(entry: ResourceEntry, type: AssetCtor | null): Promise<a.text = await response.text();return a;}+ case 'texture': {+ if (!assets) throw new Error("the engine's asset loader is not running");+ // The asked-for class decides what a script gets: a frame is the usual ask, an image the Cocos default.+ const wantsFrame = !!type && (type === SpriteFrame || SpriteFrame.prototype instanceof type);+ const wantsTexture = !!type && type !== ImageAsset && (type === Texture2D || Texture2D.prototype instanceof type);+ const loadedTexture = await assets.loadTexture(entry.path);+ const image = wantsFrame || wantsTexture ? new Texture2D(entry.path) : new ImageAsset(entry.path);+ image._handle = loadedTexture.handle;+ image.width = loadedTexture.width;+ image.height = loadedTexture.height;+ if (!wantsFrame) return image;+ const frame = new SpriteFrame(entry.path);+ frame.texture = image as Texture2D;+ return frame;+ }+ case 'audio': {+ if (type && type !== AudioClip && !(AudioClip.prototype instanceof type)) break;+ if (!assets) throw new Error("the engine's asset loader is not running");+ const clip = new AudioClip(entry.path);+ clip._bufferId = (await assets.loadAudio(entry.path)).bufferId;+ return clip;+ }case 'mtl':case 'material': {// a Cocos material file is not converted: a script that asks for one gets a Material with no engine material behind it, which takes@@ -132,7 +154,7 @@ async function loadEntry(entry: ResourceEntry, type: AssetCtor | null): Promise<}default:}- throw new UnsupportedAssetKind(`cocos compat: loading "${entry.path}" (${entry.kind}${type ? `, as ${type.name}` : ''}) is not supported by the compatibility layer yet; prefabs, JSON and text are`);+ throw new UnsupportedAssetKind(`cocos compat: loading "${entry.path}" (${entry.kind}${type ? `, as ${type.name}` : ''}) is not supported by the compatibility layer yet; prefabs, JSON, text, images and audio are`);}export class Bundle {diff --git a/sdk/src/cocos/assets.ts b/sdk/src/cocos/assets.tsindex ebdf81bd0..eb2efdf74 100644--- a/sdk/src/cocos/assets.ts+++ b/sdk/src/cocos/assets.ts@@ -25,9 +25,27 @@ export class Asset {get loaded(): boolean { return true; }destroy(): boolean { return true; }}-export class ImageAsset extends Asset {}-export class Texture2D extends Asset {}-export class SpriteFrame extends Asset {}+/** A decoded image: the engine's texture the file loaded to (a handle), and its size. @internal for the handle */+export class ImageAsset extends Asset {+ /** The engine texture handle; 0 before the load has bound one. @internal */+ _handle = 0;+ width = 0;+ height = 0;+}+export class Texture2D extends ImageAsset {+ get image(): ImageAsset { return this; }+ getHash(): number { return this._handle; }+}+/** A texture to draw from. The importer keeps one frame per image, so the frame is the whole of its texture. */+export class SpriteFrame extends Asset {+ /** The texture this frame draws from, once bound. @internal */+ texture: Texture2D | null = null;+ get width(): number { return this.texture?.width ?? 0; }+ get height(): number { return this.texture?.height ?? 0; }+ getOriginalSize(): { width: number; height: number } { return { width: this.width, height: this.height }; }+ get originalSize(): { width: number; height: number } { return this.getOriginalSize(); }+ get rect(): { x: number; y: number; width: number; height: number } { return { x: 0, y: 0, width: this.width, height: this.height }; }+}export class SpriteAtlas extends Asset {}/** Prepared prefabs by path: shared by every `Prefab` handle that names the path. */export const preparedPrefabs = new Map<string, unknown>();@@ -42,7 +60,10 @@ export class Prefab extends Asset {/** Why preparing failed, when it did. @internal */_failed = '';}-export class AudioClip extends Asset {}+export class AudioClip extends Asset {+ /** The engine's audio buffer id, once the clip has loaded. @internal */+ _bufferId = '';+}/** A property value as the engine's material takes it: a number, or a vector of up to four. Colours are 0..255 here and 0..1 there. */function uniformOf(value: unknown): number | { x: number; y: number; z: number; w: number } | null {if (typeof value === 'number') return value;diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.tsindex 00a52c337..5530bf1e4 100644--- a/sdk/src/cocos/node.ts+++ b/sdk/src/cocos/node.ts@@ -156,6 +156,7 @@ export class Node {return p && p !== INVALID_ENTITY ? Node.for(this._world, p) : null;}set parent(value: Node | null) { this.setParent(value); }+ getParent(): Node | null { return this.parent; }get children(): Node[] {const ids = this._world.tryGet(this._entity, Children)?.entities ?? [];diff --git a/sdk/src/cocos/ui/sprite.ts b/sdk/src/cocos/ui/sprite.tsindex 3fed1e6c4..063fb2d43 100644--- a/sdk/src/cocos/ui/sprite.ts+++ b/sdk/src/cocos/ui/sprite.ts@@ -13,6 +13,7 @@ import { SpriteDrawMode } from '../../wasm/wasm.generated';import type { World } from '../../ecs/world';import type { Entity } from '../../types';import { Color } from '../math';+import { SpriteFrame } from '../assets';import { Component } from '../component';import { UIRenderer } from './renderer';import { registerBuiltinComponent } from '../builtins';@@ -47,7 +48,21 @@ export class Sprite extends UIRenderer {get type(): number { return toCocosType(this.data_().drawMode); }set type(v: number) { this.patch_({ drawMode: toEngineDrawMode(v) }); }- /** The frame is set by the asset layer; the engine draws whatever texture the sprite holds. */+ private frame_: SpriteFrame | null = null;+ /**+ * The frame the sprite draws. Its texture is the engine sprite's texture; a frame that has not bound one is not drawn, and the sprite+ * keeps its size unless the size mode asks for the image's own.+ */+ get spriteFrame(): SpriteFrame | null { return this.frame_; }+ set spriteFrame(v: SpriteFrame | null) {+ this.frame_ = v;+ const texture = v?.texture;+ const patch: Partial<ReturnType<Sprite['data_']>> = { texture: texture?._handle ?? 0 };+ if (texture && this.sizeMode !== SizeMode.CUSTOM) patch.size = { x: texture.width, y: texture.height };+ this.patch_(patch);+ }++ /** The size mode decides whether the node takes the image's size. */sizeMode = SizeMode.CUSTOM;/** Not carried: the engine has no grayscale draw for a sprite. */grayscale = false;diff --git a/sdk/tests/cocos/globals.test.ts b/sdk/tests/cocos/globals.test.tsindex 82e268534..21ae3141c 100644--- a/sdk/tests/cocos/globals.test.ts+++ b/sdk/tests/cocos/globals.test.ts@@ -139,7 +139,7 @@ describe('resources and assetManager', () => {const prepared = { ref: 'bullet.esprefab', scene: { version: 4, name: 'bullet', entities: [] } as never, rootId: 0, missing: [], release() {} };beforeEach(() => {setResourceManifest({- resources: { 'prefab/bullet': { path: 'bullet.esprefab', kind: 'prefab' }, 'icon/gold': { path: 'gold.png', kind: 'texture' } },+ resources: { 'prefab/bullet': { path: 'bullet.esprefab', kind: 'prefab' }, 'icon/gold': { path: 'gold.png', kind: 'texture' }, 'model/ship': { path: '', kind: 'fbx' } },hero: { 'skin/red': { path: 'red.esprefab', kind: 'prefab' } },});providePrefab('bullet.esprefab', prepared);@@ -170,8 +170,11 @@ describe('resources and assetManager', () => {it('says what is missing or not supported, instead of answering an empty asset', async () => {const missing = await load<unknown>((cb) => resources.load('nope', cb));expect(missing.err?.message).toMatch(/no asset "nope"/);+ const model = await load<unknown>((cb) => resources.load('model/ship', cb));+ expect(model.err?.message).toMatch(/not supported/);+ // an image needs the engine's loader to become a texture, and says so when there is noneconst texture = await load<unknown>((cb) => resources.load('icon/gold', cb));- expect(texture.err?.message).toMatch(/not supported/);+ expect(texture.err?.message).toMatch(/asset loader/);});it('has bundles by name, from the manifest', async () => {diff --git a/sdk/tests/cocos/ui-adapters-wasm.test.ts b/sdk/tests/cocos/ui-adapters-wasm.test.tsindex bde1334f9..7fda1e1ef 100644--- a/sdk/tests/cocos/ui-adapters-wasm.test.ts+++ b/sdk/tests/cocos/ui-adapters-wasm.test.ts@@ -16,7 +16,7 @@ import { AppContext, setDefaultContext } from '../../src/ecs/context';import { Text } from '../../src/ui/core/text';import { TextOverflow } from '../../src/ui/core/text';import { GroupOpacity } from '../../src/ecs/component';-import { Color, Label, LabelOutline, LabelShadow, Node, Size, Sprite, UIOpacity, UITransform, Vec2, Vec3, setCurrentWorld } from '../../src/cocos';+import { Color, Label, LabelOutline, LabelShadow, Node, Size, Sprite, SpriteFrame, Texture2D, UIOpacity, UITransform, Vec2, Vec3, setCurrentWorld } from '../../src/cocos';import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';describe.skipIf(!HAS_WASM)('built-in UI components on the engine', () => {@@ -163,6 +163,23 @@ describe.skipIf(!HAS_WASM)('built-in UI components on the engine', () => {expect(W().get(n._entity, EngineSprite).enabled).toBe(false);});+ it('draws the texture of the frame it is given, and lets go of it when given none', () => {+ connect();+ const n = node('f');+ const sprite = n.addComponent(Sprite)!;+ const texture = new Texture2D('gold.png');+ texture._handle = 7;+ texture.width = 64;+ texture.height = 32;+ const frame = new SpriteFrame('gold.png');+ frame.texture = texture;+ sprite.spriteFrame = frame;+ expect(sprite.spriteFrame).toBe(frame);+ expect(W().get(n._entity, EngineSprite).texture).toBe(7);+ sprite.spriteFrame = null;+ expect(W().get(n._entity, EngineSprite).texture).toBe(0);+ });+it('is the engine\'s GroupOpacity, in Cocos\'s 0..255', () => {connect();const n = node('p');