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): the project design resolution is known to scripts before they run, assetManager has a downloader and factory, and a node made between frames joins the running world

yhh8b873e0ca98a
diff --git a/desktop b/desktop
index 9f825d2dc..637a1be7a 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 9f825d2dc82efcbacc8be780a84acc86f8fe5f91
+Subproject commit 637a1be7a795d182f93565cc73dab3418273c5a0
diff --git a/sdk/src/cocos/assetManager.ts b/sdk/src/cocos/assetManager.ts
index 45350a90b..cbef16cb9 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, Prefab, TextAsset } from './assets';
+import { Asset, JsonAsset, Material, Prefab, TextAsset } from './assets';
import { getCurrentWorld } from './node';
import { assetsFor, loadPrefab } from './prefabs';
@@ -110,6 +110,13 @@ async function loadEntry(entry: ResourceEntry, type: AssetCtor | null): Promise<
a.text = await response.text();
return a;
}
+ 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
+ // properties and holds them, so what loads it carries on
+ if (type && type !== Material && !(Material.prototype instanceof type)) break;
+ return new Material(entry.path);
+ }
default:
}
throw new Error(`cocos compat: loading "${entry.path}" (${entry.kind}${type ? `, as ${type.name}` : ''}) is not supported by the compatibility layer yet; prefabs, JSON and text are`);
@@ -207,12 +214,43 @@ bundles.add('resources', resources);
class AssetManager {
/** The cache class, as `AssetManager.Cache`: scripts derive their own caches from it. */
static readonly Cache = Cache;
+ static readonly Bundle = Bundle;
+ /** The names Cocos gives its own bundles. */
+ static readonly BuiltinBundleName = Object.freeze({ INTERNAL: 'internal', MAIN: 'main', RESOURCES: 'resources', START_SCENE: 'start-scene' });
+ /** The one asset manager, as `AssetManager.instance`: the same object the module exports as `assetManager`. */
+ static get instance(): AssetManager { return assetManager; }
+ /** `factory`: how a downloaded file is made into an object, by kind. The registrations a game makes are held; files here are made by the layer's own loaders. */
+ readonly factory = {
+ _creators: {} as Record<string, unknown>,
+ register(type: string | Record<string, unknown>, handler?: unknown): void {
+ if (typeof type === 'string') this._creators[type] = handler;
+ else Object.assign(this._creators, type);
+ },
+ };
readonly assets = loaded;
readonly bundles = bundles;
readonly resources = resources;
readonly presets: Record<string, { priority: number; maxConcurrency: number }> = {
default: { priority: 0, maxConcurrency: 6 }, preload: { priority: -1, maxConcurrency: 2 }, scene: { priority: 1, maxConcurrency: 6 }, bundle: { priority: 2, maxConcurrency: 6 }, remote: { priority: 0, maxConcurrency: 6 },
};
+ /**
+ * `assetManager.downloader`: how Cocos fetches a file of each kind. Here a file is read from the project or by URL, so it takes the registrations
+ * a game makes (its own scheme for remote bundles) and holds them, and says what it is told about where remote bundles live.
+ */
+ readonly downloader = {
+ remoteServerAddress: '',
+ bundleVers: {} as Record<string, string>,
+ maxConcurrency: 6,
+ maxRequestsPerFrame: 6,
+ _downloaders: {} as Record<string, unknown>,
+ _remoteBundles: [] as string[],
+ register(type: string | Record<string, unknown>, handler?: unknown): void {
+ if (typeof type === 'string') this._downloaders[type] = handler;
+ else Object.assign(this._downloaders, type);
+ },
+ loadSubpackage(_name: string, _onProgress?: unknown, _onComplete?: unknown): void { /* every file is in the project */ },
+ };
+
readonly cacheManager = {
cacheDir: '', cachedFiles: new Cache<unknown>(), tempFiles: new Cache<unknown>(), cacheInterval: 500, cacheEnabled: false,
clearCache(): void { this.cachedFiles.clear(); },
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index d60dcda4c..e4fc5b997 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -53,8 +53,14 @@ function releaseDetached(world: World, entity: Entity): void {
setEntityActive(world, entity, wasActive);
}
-export function setCurrentWorld(world: World | null): World | null { const previous = currentWorld; currentWorld = world; return previous; }
-export function getCurrentWorld(): World | null { return currentWorld; }
+/** The world a script last ran in: what an `await`, a timer or a callback — which run between frames — still belong to. */
+let lastWorld: World | null = null;
+export function setCurrentWorld(world: World | null): World | null { const previous = currentWorld; currentWorld = world; if (world) lastWorld = world; return previous; }
+/**
+ * The world being run now; between frames (a continuation after an `await`, a timer), the one scripts last ran in, while it is still running.
+ * Cocos has one running game, so a node made in a callback belongs to it.
+ */
+export function getCurrentWorld(): World | null { return currentWorld ?? (lastWorld?.hasCpp ? lastWorld : null); }
const cache = new WeakMap<World, Map<Entity, Node>>();
@@ -108,11 +114,12 @@ export class Node {
this._entity = entity;
return;
}
- if (!currentWorld) throw new Error('cocos compat: new Node() outside a running scene (no world is current)');
- this._world = currentWorld;
- this._entity = currentWorld.spawn(name ?? 'New Node');
- let perWorld = cache.get(currentWorld);
- if (!perWorld) cache.set(currentWorld, (perWorld = new Map()));
+ const running = getCurrentWorld();
+ if (!running) throw new Error('cocos compat: new Node() outside a running scene (no world is current)');
+ this._world = running;
+ this._entity = running.spawn(name ?? 'New Node');
+ let perWorld = cache.get(running);
+ if (!perWorld) cache.set(running, (perWorld = new Map()));
perWorld.set(this._entity, this);
}
diff --git a/sdk/src/cocos/ui/pass.ts b/sdk/src/cocos/ui/pass.ts
index 111a6db91..d16b6e523 100644
--- a/sdk/src/cocos/ui/pass.ts
+++ b/sdk/src/cocos/ui/pass.ts
@@ -12,6 +12,7 @@ import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../../ecs
import { Res } from '../../ecs/resource';
import { UICameraInfo } from '../../ui/core/ui-camera-info';
import { ScreenLayout, type ScreenLayoutData } from '../../ui/core/screen-layout';
+import { ScreenScaling, type ScreenScalingData } from '../../camera/ScreenScaling';
import { setCurrentWorld } from '../node';
import { declareWidget } from './widget';
import { alignAllRectAnchors } from '../../ui/layout/rect-anchors';
@@ -20,7 +21,7 @@ import { declareControls } from './controls';
import { declareGraphics } from './graphics';
import { declareEditBox } from './editBox';
import { declareScrollView } from './scrollView';
-import { getVisibleSize, setSafeInsets, setScreenLayout, setUiCameraData, setVisibleSize, setWindowPixels, visibleSizeGeneration } from './screen';
+import { getVisibleSize, setProjectDesign, setSafeInsets, setScreenLayout, setUiCameraData, setVisibleSize, setWindowPixels, visibleSizeGeneration } from './screen';
import { declarePages } from './pages';
import { declareMisc } from './misc';
@@ -42,8 +43,9 @@ export function declareUiPass(): void {
declareMisc();
declareScrollView();
const system = defineSystem(
- [Res(UICameraInfo), Res(ScreenLayout), GetWorld()],
- (camera, screen, world) => {
+ [Res(UICameraInfo), Res(ScreenLayout), Res(ScreenScaling), GetWorld()],
+ (camera, screen, scaling: ScreenScalingData | undefined, world) => {
+ if (scaling) setProjectDesign(scaling.designWidth, scaling.designHeight, scaling.scaleMode);
// The camera is kept for the conversions a Cocos `Camera` offers. What the player sees, and the window, are the screen's: the
// layout box UI is placed within, and the framebuffer it projects onto.
setUiCameraData(camera ?? null);
@@ -69,4 +71,13 @@ export function declareUiPass(): void {
{ name: 'Cocos:UiPass', touches: { opaque: true } },
);
addSystemToSchedule(Schedule.Last, system);
+ addSystemToSchedule(Schedule.PreUpdate, defineSystem(
+ [Res(ScreenScaling), Res(ScreenLayout)],
+ (scaling: ScreenScalingData | undefined, screen: ScreenLayoutData | undefined) => {
+ if (scaling) setProjectDesign(scaling.designWidth, scaling.designHeight, scaling.scaleMode);
+ // what a script reads in start(): the sizes are known before the first frame's pass
+ if (screen?.valid) { setVisibleSize(screen.right - screen.left, screen.top - screen.bottom); setWindowPixels(screen.viewportW, screen.viewportH); }
+ },
+ { name: 'Cocos:ProjectDesign', touches: { opaque: true } },
+ ));
}
diff --git a/sdk/src/cocos/ui/screen.ts b/sdk/src/cocos/ui/screen.ts
index 79c61e4ae..52a3439d2 100644
--- a/sdk/src/cocos/ui/screen.ts
+++ b/sdk/src/cocos/ui/screen.ts
@@ -25,6 +25,12 @@ let windowW = 960;
let windowH = 640;
const listeners: Array<(kind: 'visible' | 'window') => void> = [];
+let projectDesign: { width: number; height: number; scaleMode: number } | null = null;
+/** @internal The project's own design resolution and fit (the engine's screen scaling), which a script that never set one reads. */
+export function setProjectDesign(width: number, height: number, scaleMode: number): void { projectDesign = scaleMode >= 0 ? { width, height, scaleMode } : null; }
+/** @internal */
+export function getProjectDesign(): { width: number; height: number; scaleMode: number } | null { return projectDesign; }
+
let screenLayout: ScreenLayoutData | null = null;
/** @internal The layout the pass last saw, for an alignment a script asks for now. */
export function setScreenLayout(layout: ScreenLayoutData | null): void { screenLayout = layout; }
diff --git a/sdk/src/cocos/view.ts b/sdk/src/cocos/view.ts
index 0d56319ac..7343630b6 100644
--- a/sdk/src/cocos/view.ts
+++ b/sdk/src/cocos/view.ts
@@ -14,7 +14,7 @@
import { platformDevicePixelRatio } from '../platform';
import { Emitter } from './emitter';
import { Rect, Size, Vec2 } from './math';
-import { getVisibleSize, getWindowPixels, onScreenChange } from './ui/screen';
+import { getProjectDesign, getVisibleSize, getWindowPixels, onScreenChange } from './ui/screen';
const ResolutionPolicy = Object.freeze({ EXACT_FIT: 0, NO_BORDER: 1, SHOW_ALL: 2, FIXED_HEIGHT: 3, FIXED_WIDTH: 4, UNKNOWN: 5 });
@@ -46,13 +46,23 @@ export class View extends Emitter {
getVisibleOriginInPixel(): Vec2 { const v = this.getVisibleSizeInPixel(); return new Vec2(-v.width / 2, -v.height / 2); }
getViewportRect(): Rect { const w = getWindowPixels(); return new Rect(0, 0, w.width, w.height); }
- getDesignResolutionSize(): Size { return this.design_ ? this.design_.clone() : this.getVisibleSize(); }
+ /** What the script set; else the project's own design resolution (the engine's screen scaling); else the visible size. */
+ getDesignResolutionSize(): Size {
+ if (this.design_) return this.design_.clone();
+ const project = getProjectDesign();
+ return project ? new Size(project.width, project.height) : this.getVisibleSize();
+ }
setDesignResolutionSize(width: number, height: number, policy: number = this.policy_): void {
this.design_ = new Size(width, height);
this.policy_ = policy;
this.emit('design-resolution-changed');
}
- getResolutionPolicy(): number { return this.policy_; }
+ getResolutionPolicy(): number {
+ if (this.policy_ !== ResolutionPolicy.UNKNOWN) return this.policy_;
+ const project = getProjectDesign();
+ // the engine's camera scale mode: fixed width (0) and fixed height (1) are Cocos's FIXED_WIDTH and FIXED_HEIGHT
+ return project?.scaleMode === 0 ? ResolutionPolicy.FIXED_WIDTH : project?.scaleMode === 1 ? ResolutionPolicy.FIXED_HEIGHT : this.policy_;
+ }
setResolutionPolicy(policy: number): void { this.policy_ = policy; }
/** The window in CSS pixels. */