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.

fix(cocos): a prefab is handed over with the prefabs its scripts hold in Prefab fields, and Material.recompileShaders sets the shader's switches

yhh5e48605875ba
diff --git a/sdk/src/cocos/assets.ts b/sdk/src/cocos/assets.ts
index eb2efdf74..aad57d2fc 100644
--- a/sdk/src/cocos/assets.ts
+++ b/sdk/src/cocos/assets.ts
@@ -102,6 +102,15 @@ export class Material extends Asset {
if (this._handle > 0 && uniform !== null) EngineMaterial.setUniform(this._handle, name, uniform);
}
+ /**
+ * Switch the shader's macros. The engine keeps a material's switches on its record, and the permutation they pick is fixed when the shader is
+ * compiled, so the record answers now and the permutation changes where the engine next compiles the shader.
+ */
+ recompileShaders(defines: Record<string, unknown>, _passIndex?: number): void {
+ if (this._handle <= 0) return;
+ for (const [name, value] of Object.entries(defines)) EngineMaterial.setSwitch(this._handle, name, !!value && value !== '0');
+ }
+
/** What the property was last set to. @internal */
_give?: (name: string) => unknown;
diff --git a/sdk/src/cocos/prefabs.ts b/sdk/src/cocos/prefabs.ts
index f478bb0af..36ec27bac 100644
--- a/sdk/src/cocos/prefabs.ts
+++ b/sdk/src/cocos/prefabs.ts
@@ -26,6 +26,7 @@ import type { Entity } from '../types';
import { log } from '../util/logger';
import { Node, getCurrentWorld, markDetached, onWorldChanged } from './node';
import { Prefab, preparedPrefabs } from './assets';
+import { COMPONENT_PREFIX, classInfoNamed } from './registry';
const assetsOf = new WeakMap<World, AssetsClass>();
let currentAssets: AssetsClass | null = null;
@@ -51,6 +52,7 @@ export function requestPrepare(path: string): void {
/** Drop what the layer kept of the session that ended, and tell whoever else kept something. */
function endSession(): void {
preparedPrefabs.clear();
+ preparing.clear();
wanted.clear();
inFlight.clear();
currentAssets = null;
@@ -73,21 +75,57 @@ export function providePrefab(path: string, prepared: PreparedPrefab): void {
preparedPrefabs.set(path, prepared);
}
+/** The prefabs a prepared prefab's script components hold in `@property(Prefab)` fields: what Cocos loads before it hands the prefab over. */
+/** @internal */
+export function prefabsHeldBy(prepared: PreparedPrefab): string[] {
+ const held = new Set<string>();
+ for (const entity of prepared.scene.entities) {
+ for (const component of entity.components) {
+ if (!component.type.startsWith(COMPONENT_PREFIX)) continue;
+ const info = classInfoNamed(component.type.slice(COMPONENT_PREFIX.length));
+ for (const spec of info?.props ?? []) {
+ if (spec.kind !== 'asset' || typeof spec.type !== 'function' || !(spec.type === Prefab || spec.type.prototype instanceof Prefab)) continue;
+ const value = component.data[spec.name];
+ for (const path of Array.isArray(value) ? value : [value]) if (typeof path === 'string' && path !== '') held.add(path);
+ }
+ }
+ }
+ return [...held];
+}
+
+const preparing = new Map<string, Promise<void>>();
+
+/** Prepare a prefab and the prefabs its scripts hold, and answer when all of them are ready. A prefab that holds itself is waited for once. */
+function prepareWithHeld(assets: AssetsClass, path: string): Promise<void> {
+ if (preparedPrefabs.has(path)) return Promise.resolve();
+ let pending = preparing.get(path);
+ if (!pending) {
+ pending = preparePrefab(assets, path)
+ .then((p) => { preparedPrefabs.set(path, p); return p; })
+ .then(async (p) => {
+ // the held ones are best effort: one that cannot be prepared is reported where the script uses it, not here
+ await Promise.all(prefabsHeldBy(p).map((held) => prepareWithHeld(assets, held).catch(() => undefined)));
+ })
+ .finally(() => { preparing.delete(path); });
+ preparing.set(path, pending);
+ }
+ return pending;
+}
+
/** Prepare a prefab and answer when it is ready to `instantiate`. */
export function loadPrefab(path: string, world: World | null = getCurrentWorld()): Promise<Prefab> {
const assets = world ? assetsOf.get(world) : undefined;
if (assets) syncSession(assets);
if (preparedPrefabs.has(path)) return Promise.resolve(new Prefab(path));
if (!assets) return Promise.reject(new Error(`cocos compat: cannot load prefab "${path}": the engine's asset loader is not running`));
- return preparePrefab(assets, path).then((p) => { preparedPrefabs.set(path, p); return new Prefab(path); });
+ return prepareWithHeld(assets, path).then(() => new Prefab(path));
}
function drain(assets: AssetsClass): void {
for (const path of wanted) {
wanted.delete(path);
inFlight.add(path);
- preparePrefab(assets, path)
- .then((p) => { preparedPrefabs.set(path, p); })
+ prepareWithHeld(assets, path)
.catch((err) => { log.warn('cocos', `prefab "${path}" could not be prepared: ${String(err)}`); })
.finally(() => { inFlight.delete(path); });
}
diff --git a/sdk/tests/cocos/prefab-held.test.ts b/sdk/tests/cocos/prefab-held.test.ts
new file mode 100644
index 000000000..a2dd0a3fd
--- /dev/null
+++ b/sdk/tests/cocos/prefab-held.test.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A prefab is handed over with the prefabs its scripts hold: a List in a screen holds its row's prefab, and the screen's own code builds rows
+ * the moment it is up.
+ */
+import { describe, expect, it } from 'vitest';
+import { Component, Prefab, _decorator } from '../../src/cocos';
+import { prefabsHeldBy } from '../../src/cocos/prefabs';
+import type { PreparedPrefab } from '../../src/prefab/preparedPrefab';
+
+const { ccclass, property } = _decorator;
+
+describe('prefabs a prefab holds', () => {
+ it('names the paths in Prefab fields of its script components, lists too, and nothing else', () => {
+ @ccclass('HeldList')
+ class HeldList extends Component {
+ @property(Prefab) row: Prefab | null = null;
+ @property([Prefab]) more: Prefab[] = [];
+ @property(String) label = '';
+ }
+ expect(HeldList).toBeDefined();
+ const prepared = {
+ scene: { entities: [
+ { id: 1, name: 'a', parent: null, children: [], components: [
+ { type: 'Cocos.HeldList', data: { row: 'ui/row', more: ['ui/a', 'ui/b'], label: 'ui/not-a-prefab' } },
+ { type: 'Transform', data: {} },
+ ] },
+ ] },
+ } as unknown as PreparedPrefab;
+ expect(prefabsHeldBy(prepared).sort()).toEqual(['ui/a', 'ui/b', 'ui/row']);
+ });
+});