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): a scene's ambient light becomes an Ambient light entity, so a lit mesh is no longer black
yhh2c79d84bba0c
diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.tsindex b25082f6a..8d1eb51e7 100644--- a/pipeline/src/import/cocos/convert.ts+++ b/pipeline/src/import/cocos/convert.ts@@ -500,7 +500,9 @@ export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFileif (!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(',')}`);+ // what is left of the scene's settings is not carried: the ambient light is+ const dropped = doc.globals.filter((g) => !(g === 'ambient' && doc.ambient));+ if (dropped.length) ctx.report.note('scene-globals-dropped', `${ctx.where}: ${dropped.join(',')}`);const walk = (n: CocosNode, parent: SceneEntity | null): void => {ctx.report.nodes++;@@ -543,5 +545,16 @@ export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFileentities.length = 0;entities.push(...folded);if (ctx.design) for (const e of entities) if ('components' in e && e.parent === null) placeInDesign(e.components, ctx.design);+ // The scene's ambient light is a setting of the scene in Cocos and an entity in the engine: a mesh that is lit gets all it is lit by from it.+ if (doc.ambient) {+ const { color, intensity } = doc.ambient;+ entities.push({+ id: next++, name: 'Ambient', parent: null, children: [], visible: true,+ components: [+ { 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 } } },+ { type: 'Light', data: { type: 2, color: { r: color.r, g: color.g, b: color.b, a: 1 }, intensity, enabled: true } },+ ],+ });+ }return { version: 4, name: doc.name, entities };}diff --git a/pipeline/src/import/cocos/document.ts b/pipeline/src/import/cocos/document.tsindex 24631e6a6..58f7e26ad 100644--- a/pipeline/src/import/cocos/document.ts+++ b/pipeline/src/import/cocos/document.ts@@ -69,6 +69,8 @@ export interface CocosDocument {roots: CocosNode[];/** Scene-level settings (skybox, fog, shadows...) that were present and are not carried over. */globals: string[];+ /** The scene's ambient light, as the low-dynamic-range sky colour and the illumination it is lit by; absent when the scene sets none. */+ ambient?: { color: { r: number; g: number; b: number }; intensity: number };/** Node ids that had to be made unique because the file repeats them. */duplicateIds: number;}@@ -106,6 +108,7 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocumconst head = isObj(objs[0]) ? objs[0] : null;const globals: string[] = [];+ let ambient: CocosDocument['ambient'];let rootRefs: unknown[];let kind: CocosDocument['kind'];let name = fallbackName;@@ -121,6 +124,11 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocumrootRefs = Array.isArray(scene._children) ? scene._children : [];const g = at(scene._globals);if (g) for (const k of ['ambient', 'shadows', 'skybox', 'fog', 'octree', 'lightProbeInfo']) if (g[k]) globals.push(k);+ const amb = g ? at(g.ambient) : null;+ const sky = amb && isObj(amb._skyColorLDR) ? amb._skyColorLDR : null;+ if (amb && sky && typeof sky.x === 'number' && typeof sky.y === 'number' && typeof sky.z === 'number') {+ ambient = { color: { r: sky.x, g: sky.y, b: sky.z }, intensity: typeof amb._skyIllumLDR === 'number' ? amb._skyIllumLDR : 1 };+ }} else {throw new Error(`not a Cocos scene/prefab: first object is ${String(head?.__type__)}`);}@@ -251,5 +259,5 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocumnode.children.forEach(resolveNode);};roots.forEach(resolveNode);- return { kind, name, roots, globals, duplicateIds };+ return { kind, name, roots, globals, ambient, duplicateIds };}diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex c09b5d033..deca7a0e6 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 = 13;+export const COCOS_IMPORT_REVISION = 14;/** 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 {diff --git a/pipeline/tests/cocos-import-ambient.test.ts b/pipeline/tests/cocos-import-ambient.test.tsnew file mode 100644index 000000000..9cc455b90--- /dev/null+++ b/pipeline/tests/cocos-import-ambient.test.ts@@ -0,0 +1,46 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A Cocos scene's ambient light becomes an Ambient light entity, so a lit mesh has what it is lit by.+ */+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';++const scene = [+ { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },+ { __type__: 'cc.Scene', _name: 'main', _children: [], _globals: { __id__: 2 } },+ { __type__: 'cc.SceneGlobals', ambient: { __id__: 3 }, shadows: { __id__: 4 } },+ { __type__: 'cc.AmbientInfo', _skyColorLDR: { __type__: 'cc.Vec4', x: 0.5, y: 0.75, z: 1, w: 0.8 }, _skyIllumLDR: 0.8 },+ { __type__: 'cc.ShadowsInfo', _enabled: false },+];++describe('a Cocos scene with an ambient light', () => {+ let root: string;+ let doc: { entities: Array<{ name: string; components: Array<{ type: string; data: Record<string, any> }> }> };+ let report: Awaited<ReturnType<typeof importCocosProject>>;++ beforeAll(async () => {+ root = mkdtempSync(path.join(tmpdir(), 'cocos-ambient-'));+ const dir = path.join(root, 'creator', 'assets');+ mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, 'main.scene'), JSON.stringify(scene));+ writeFileSync(path.join(dir, 'main.scene.meta'), JSON.stringify({ ver: '1', importer: 'scene', uuid: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', subMetas: {}, userData: {} }));+ report = await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });+ doc = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8'));+ });+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));++ it('is an ambient Light with the sky colour and the illumination', () => {+ const ambient = doc.entities.find((e) => e.name === 'Ambient');+ const light = ambient?.components.find((c) => c.type === 'Light');+ expect(light?.data).toMatchObject({ type: 2, intensity: 0.8, color: { r: 0.5, g: 0.75, b: 1 } });+ });++ it('still says what of the scene settings it did not carry', () => {+ expect(report.notes['scene-globals-dropped']?.examples.join(' ')).toContain('shadows');+ expect(report.notes['scene-globals-dropped']?.examples.join(' ')).not.toContain('ambient');+ });+});