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(assets): a glTF's images and colours, as products
esengine2c68964b4bac
diff --git a/desktop/public/scenes/lit-triangles.esprefab b/desktop/public/scenes/lit-triangles.esprefabnew file mode 100644index 000000000..1101c73ee--- /dev/null+++ b/desktop/public/scenes/lit-triangles.esprefab@@ -0,0 +1,27 @@+{+ "version": "2",+ "name": "lit-triangles",+ "rootEntityId": "0",+ "entities": [+ {+ "prefabEntityId": "0",+ "name": "lit-triangles",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "scenes/lit-triangles.esmesh",+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/mesh-textured.esscene b/desktop/public/scenes/mesh-textured.esscenenew file mode 100644index 000000000..626de7d72--- /dev/null+++ b/desktop/public/scenes/mesh-textured.esscene@@ -0,0 +1,17 @@+{+ "version": 1,+ "name": "MeshTextured",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }+ ],+ "visible": true+ }+ ]+}diff --git a/desktop/public/scenes/mesh-textured.textures.json b/desktop/public/scenes/mesh-textured.textures.jsonnew file mode 100644index 000000000..0967ef424--- /dev/null+++ b/desktop/public/scenes/mesh-textured.textures.json@@ -0,0 +1 @@+{}diff --git a/desktop/public/scenes/textured-quad.esmesh b/desktop/public/scenes/textured-quad.esmeshnew file mode 100644index 000000000..fe70e22ddBinary files /dev/null and b/desktop/public/scenes/textured-quad.esmesh differdiff --git a/desktop/public/scenes/textured-quad.esprefab b/desktop/public/scenes/textured-quad.esprefabnew file mode 100644index 000000000..66d0dea6b--- /dev/null+++ b/desktop/public/scenes/textured-quad.esprefab@@ -0,0 +1,34 @@+{+ "version": "2",+ "name": "textured-quad",+ "rootEntityId": "0",+ "entities": [+ {+ "prefabEntityId": "0",+ "name": "textured-quad",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "scenes/textured-quad.esmesh",+ "texture": "scenes/textured-quad_0.png",+ "color": {+ "r": 0.5,+ "g": 0.5,+ "b": 1,+ "a": 1+ },+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/textured-quad.gltf b/desktop/public/scenes/textured-quad.gltfnew file mode 100644index 000000000..cab217e0c--- /dev/null+++ b/desktop/public/scenes/textured-quad.gltf@@ -0,0 +1,124 @@+{+ "asset": {+ "version": "2.0",+ "generator": "estella test fixture"+ },+ "buffers": [+ {+ "byteLength": 92,+ "uri": "data:application/octet-stream;base64,AABIwwAAyEIAAAAAAABIQwAAyEIAAAAAAABIwwAAyMIAAAAAAABIQwAAyMIAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AACAPwAAgD8AAAIAAQABAAIAAwA="+ }+ ],+ "bufferViews": [+ {+ "buffer": 0,+ "byteOffset": 0,+ "byteLength": 48+ },+ {+ "buffer": 0,+ "byteOffset": 48,+ "byteLength": 32+ },+ {+ "buffer": 0,+ "byteOffset": 80,+ "byteLength": 12+ }+ ],+ "accessors": [+ {+ "bufferView": 0,+ "componentType": 5126,+ "count": 4,+ "type": "VEC3",+ "min": [+ -200,+ -100,+ 0+ ],+ "max": [+ 200,+ 100,+ 0+ ]+ },+ {+ "bufferView": 1,+ "componentType": 5126,+ "count": 4,+ "type": "VEC2"+ },+ {+ "bufferView": 2,+ "componentType": 5123,+ "count": 6,+ "type": "SCALAR"+ }+ ],+ "images": [+ {+ "mimeType": "image/png",+ "uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAGElEQVR4AQXBAQEAAAjDIG7/zhNE0k3CAz7tBf7utunjAAAAAElFTkSuQmCC"+ }+ ],+ "samplers": [+ {+ "magFilter": 9729,+ "minFilter": 9729+ }+ ],+ "textures": [+ {+ "sampler": 0,+ "source": 0+ }+ ],+ "materials": [+ {+ "name": "Quadrants",+ "pbrMetallicRoughness": {+ "baseColorFactor": [+ 0.5,+ 0.5,+ 1,+ 1+ ],+ "baseColorTexture": {+ "index": 0+ },+ "metallicFactor": 0,+ "roughnessFactor": 1+ }+ }+ ],+ "meshes": [+ {+ "name": "TexturedQuad",+ "primitives": [+ {+ "attributes": {+ "POSITION": 0,+ "TEXCOORD_0": 1+ },+ "indices": 2,+ "material": 0,+ "mode": 4+ }+ ]+ }+ ],+ "nodes": [+ {+ "mesh": 0+ }+ ],+ "scenes": [+ {+ "nodes": [+ 0+ ]+ }+ ],+ "scene": 0+}diff --git a/desktop/public/scenes/textured-quad_0.png b/desktop/public/scenes/textured-quad_0.pngnew file mode 100644index 000000000..8fd9384fdBinary files /dev/null and b/desktop/public/scenes/textured-quad_0.png differdiff --git a/desktop/public/scenes/two-triangles.esprefab b/desktop/public/scenes/two-triangles.esprefabnew file mode 100644index 000000000..dbafee4b4--- /dev/null+++ b/desktop/public/scenes/two-triangles.esprefab@@ -0,0 +1,27 @@+{+ "version": "2",+ "name": "two-triangles",+ "rootEntityId": "0",+ "entities": [+ {+ "prefabEntityId": "0",+ "name": "two-triangles",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "scenes/two-triangles.esmesh",+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/white-triangles.esprefab b/desktop/public/scenes/white-triangles.esprefabnew file mode 100644index 000000000..b3b26783d--- /dev/null+++ b/desktop/public/scenes/white-triangles.esprefab@@ -0,0 +1,27 @@+{+ "version": "2",+ "name": "white-triangles",+ "rootEntityId": "0",+ "entities": [+ {+ "prefabEntityId": "0",+ "name": "white-triangles",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "scenes/white-triangles.esmesh",+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjsindex 770790e32..fa18ef0a6 100644--- a/desktop/scripts/headless-verify.mjs+++ b/desktop/scripts/headless-verify.mjs@@ -19,6 +19,7 @@* ESTELLA_VERIFY_STEPS fixed-dt frames to advance before capture (default 30)* ESTELLA_VERIFY_GRID editor-grid on/off pixel-diff assertion (value = spacing)* ESTELLA_VERIFY_DEPTH_LAYERS bitmask of layers resolved by depth (2.5D)+ * ESTELLA_VERIFY_PREFAB .esprefab instantiated into the scene after load*/import { app, BrowserWindow } from 'electron';import http from 'node:http';@@ -126,7 +127,8 @@ function finish(result, server) {// scene — the shape of a check that cannot fail.const meshOk = (!result.meshResident || result.meshResident.frozen > 0)&& (!result.meshAsset || result.meshAsset.pointed > 0)- && (!result.meshMaterial || result.meshMaterial.applied > 0);+ && (!result.meshMaterial || result.meshMaterial.applied > 0)+ && (!result.meshPrefab || result.meshPrefab.spawned > 0);const renderedOk = result.capture?.rendered ?? false;const ok = result.ok && renderedOk && (result.expect?.ok ?? true) &&(result.resize?.ok ?? true) && (result.preview?.ok ?? true) && (result.grid?.ok ?? true) &&@@ -166,6 +168,7 @@ app.whenReady().then(async () => {let meshResident = null;let meshAsset = null;let meshMaterial = null;+ let meshPrefab = null;await exec('window.__estellaHeadless.ready');const entityCount = await exec(`window.__estellaHeadless.api.loadScene(${JSON.stringify(SCENE)}, ${JSON.stringify(MANIFEST)})`,@@ -261,6 +264,18 @@ app.whenReady().then(async () => {})()`);}+ // ESTELLA_VERIFY_PREFAB=<path> instantiates a prefab into the scene. For an+ // import's products this is the whole chain: the prefab names the geometry,+ // the image and the tint, and nothing here repeats what it should say.+ if (process.env.ESTELLA_VERIFY_PREFAB) {+ meshPrefab = await exec(`(async () => {+ const spawned = await window.__estellaHeadless.loadPrefabAsset(+ ${JSON.stringify(process.env.ESTELLA_VERIFY_PREFAB)});+ await window.__estellaHeadless.api.step(2, 1 / 60);+ return { spawned };+ })()`);+ }+// ESTELLA_VERIFY_MESH_MATERIAL=<path> puts a material on the scene's meshes,// through the asset layer, after the geometry is in place.if (process.env.ESTELLA_VERIFY_MESH_MATERIAL) {@@ -496,7 +511,7 @@ app.whenReady().then(async () => {return { differingPixels: differing, ok: differing > 300 };`);}- finish({ ok: true, entityCount, drawCalls, capture, expect, resize, preview, grid, deviceLoss, meshResident, meshAsset, meshMaterial }, server);+ finish({ ok: true, entityCount, drawCalls, capture, expect, resize, preview, grid, deviceLoss, meshResident, meshAsset, meshMaterial, meshPrefab }, server);} catch (e) {finish({ ok: false, error: String((e && e.stack) || e) }, server);}diff --git a/desktop/scripts/make-mesh-fixture.mjs b/desktop/scripts/make-mesh-fixture.mjsindex 8788fe086..8767d0756 100644--- a/desktop/scripts/make-mesh-fixture.mjs+++ b/desktop/scripts/make-mesh-fixture.mjs@@ -1,12 +1,12 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file Imports the glTF fixtures behind the `mesh-asset` and `mesh-lit` gates.+ * @file Imports the glTF fixtures behind the mesh render gates.** Through the shipped importer (`estella import-gltf`), not a copy of it: the* fixture is then a product of the path a user takes, so the gate that asserts- * three points of the frame is asserting the importer as well — get an accessor,- * a byte stride or a colour conversion wrong and the pixels move. The glTF holds+ * points of the frame is asserting the importer as well — get an accessor, a+ * byte stride or a colour conversion wrong and the pixels move. The glTF holds* the geometry scenes/mesh2d.esscene inlines, which is why those points hold.** node scripts/make-mesh-fixture.mjs@@ -21,11 +21,16 @@ const cli = path.join(HERE, '..', '..', 'pipeline', 'bin', 'estella.mjs');// two-triangles: the mesh2d geometry, so a file drawing what the scene draws is// the claim. lit-triangles: the same shape with per-face NORMALS and one white-// colour, so on screen only the lighting can separate its halves.-for (const name of ['two-triangles.gltf', 'lit-triangles.gltf', 'white-triangles.gltf']) {- const run = spawnSync(process.execPath, [cli, 'import-gltf', path.join(scenes, name)], {- stdio: 'inherit',- cwd: path.join(HERE, '..', '..'),- });+// colour. textured-quad: an inline image and a baseColor factor.+//+// public/ stands in for the project root, so the prefab's refs read `scenes/…`+// — the spelling a component carries, resolved from the served root.+for (const name of ['two-triangles.gltf', 'lit-triangles.gltf', 'white-triangles.gltf',+ 'textured-quad.gltf']) {+ const run = spawnSync(process.execPath,+ [cli, 'import-gltf', path.join(scenes, name), '--project', path.join(HERE, '..', 'public')], {+ stdio: 'inherit',+ cwd: path.join(HERE, '..', '..'),+ });if (run.status !== 0) process.exit(run.status ?? 1);}diff --git a/desktop/src/headless.ts b/desktop/src/headless.tsindex 44e259e0a..7c5f9a0fb 100644--- a/desktop/src/headless.ts+++ b/desktop/src/headless.ts@@ -13,7 +13,7 @@import { EngineHost } from './engine/EngineHost';import {DeviceStatus, getDeviceStatus, getDeviceLostReport, recoverDevice, finishDeviceRecovery,- getContextLossGuardInfo, Assets,+ getContextLossGuardInfo, Assets, instantiatePrefab, type PrefabData,} from 'esengine';// From EditorSession: importing it constructs the default session (which wires the// Reconciler + SceneStore to the model) before the engine boots below.@@ -47,6 +47,8 @@ declare global {loadMeshAsset: (path: string) => Promise<number>;/** Loads an .esmaterial and points every Mesh2D at it; returns how many. */loadMaterialAsset: (path: string) => Promise<number>;+ /** Instantiates an .esprefab into the scene; returns how many entities it brought. */+ loadPrefabAsset: (path: string) => Promise<number>;};}}@@ -190,6 +192,18 @@ window.__estellaHeadless = {if (!material?.handle) return 0;return m.mesh2d_setMaterialAll(registry, material.handle);},+ // A prefab brings its own asset refs, so this door hands the file to the+ // engine's own instantiation and asserts nothing about what it names: the+ // claim is about an import's products, not a scene written to match them.+ loadPrefabAsset: async (path: string) => {+ const assets = EngineHost.getResource(Assets);+ const world = EngineHost.mutableWorld();+ if (!assets || !world) return 0;++ const prefab = await assets.loadPrefab(path);+ const result = await instantiatePrefab(world, prefab.data as PrefabData, { assets });+ return result.entities.size;+ },};// Referenced so the unused-import check sees it; DeviceStatus is the vocabularydiff --git a/desktop/tests/gltf-import.test.ts b/desktop/tests/gltf-import.test.tsnew file mode 100644index 000000000..d37f4b17b--- /dev/null+++ b/desktop/tests/gltf-import.test.ts@@ -0,0 +1,219 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file glTF material/image import: what the products say about each other.+ *+ * The pixels a gate asserts prove the chain end to end, but only for one file.+ * These cover the shapes that file is not: an image in a GLB chunk, an image+ * already on disk, a primitive with no material, several primitives at once.+ */+import { describe, it, expect } from 'vitest';+import {+ importGltfMeshes, assembleGltfPrefab, type ImportedMesh,+} from '../../pipeline/src/assets/gltfImport';+import { MeshChannel } from 'esengine';++const PNG_1PX = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';++/** POSITION x3 (VEC3) + TEXCOORD_0 x3 (VEC2) + 3 indices, as one data-uri buffer. */+function geometryBuffer(): { uri: string; views: unknown[]; accessors: unknown[] } {+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);+ const uvs = new Float32Array([0, 0, 1, 0, 0, 1]);+ const indices = new Uint16Array([0, 1, 2]);+ const bytes = Buffer.concat([+ Buffer.from(positions.buffer), Buffer.from(uvs.buffer), Buffer.from(indices.buffer),+ ]);+ return {+ uri: `data:application/octet-stream;base64,${bytes.toString('base64')}`,+ views: [+ { buffer: 0, byteOffset: 0, byteLength: 36 },+ { buffer: 0, byteOffset: 36, byteLength: 24 },+ { buffer: 0, byteOffset: 60, byteLength: 6 },+ ],+ accessors: [+ { bufferView: 0, componentType: 5126, count: 3, type: 'VEC3' },+ { bufferView: 1, componentType: 5126, count: 3, type: 'VEC2' },+ { bufferView: 2, componentType: 5123, count: 3, type: 'SCALAR' },+ ],+ };+}++function gltf(extra: Record<string, unknown>, primitives?: unknown[]): Uint8Array {+ const geo = geometryBuffer();+ const doc = {+ asset: { version: '2.0' },+ buffers: [{ byteLength: 66, uri: geo.uri }],+ bufferViews: geo.views,+ accessors: geo.accessors,+ meshes: [{+ name: 'Tri',+ primitives: primitives ?? [{+ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4,+ }],+ }],+ ...extra,+ };+ return new TextEncoder().encode(JSON.stringify(doc));+}++/** The material every case below varies from: one baseColor image, one factor. */+function withInlineImage(): Record<string, unknown> {+ return {+ images: [{ mimeType: 'image/png', uri: `data:image/png;base64,${PNG_1PX}` }],+ textures: [{ source: 0 }],+ materials: [{+ name: 'Base',+ pbrMetallicRoughness: {+ baseColorFactor: [0.25, 0.5, 0.75, 1], baseColorTexture: { index: 0 },+ metallicFactor: 0,+ },+ }],+ };+}++function texCoords(mesh: ImportedMesh): number[] {+ const channel = mesh.data.channels.find(c => c.semantic === MeshChannel.TexCoord0)!;+ const view = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);+ const out: number[] = [];+ for (let i = 0; i < mesh.vertexCount; i++) {+ const at = i * mesh.data.vertexStride + channel.offset;+ out.push(view.getFloat32(at, true), view.getFloat32(at + 4, true));+ }+ return out;+}++describe('glTF material import', () => {+ it('extracts an inline image and names it in the material', () => {+ const { meshes, textures, warnings } = importGltfMeshes(gltf(withInlineImage()), 'model');+ expect(warnings).toEqual([]);+ expect(textures).toHaveLength(1);+ expect(textures[0]!.name).toBe('model_0.png');+ expect(textures[0]!.bytes.length).toBeGreaterThan(0);+ expect(meshes[0]!.material).toMatchObject({+ baseColor: [0.25, 0.5, 0.75, 1],+ baseColorTexture: { file: 'model_0.png', external: false },+ });+ });++ it('references an image already on disk instead of copying it', () => {+ const doc = withInlineImage();+ doc.images = [{ uri: 'textures/diffuse%20map.png' }];+ const { meshes, textures } = importGltfMeshes(gltf(doc), 'model');+ expect(textures).toEqual([]);+ expect(meshes[0]!.material?.baseColorTexture)+ .toEqual({ file: 'textures/diffuse map.png', external: true });+ });++ it('reads an image out of a GLB binary chunk', () => {+ const png = Buffer.from(PNG_1PX, 'base64');+ const geo = geometryBuffer();+ const bin = Buffer.concat([Buffer.from(geo.uri.split(',')[1]!, 'base64'), png]);+ const json = Buffer.from(JSON.stringify({+ asset: { version: '2.0' },+ buffers: [{ byteLength: bin.length }],+ bufferViews: [+ ...(geo.views as { byteLength: number }[]),+ { buffer: 0, byteOffset: 66, byteLength: png.length },+ ],+ accessors: geo.accessors,+ images: [{ mimeType: 'image/png', bufferView: 3 }],+ textures: [{ source: 0 }],+ materials: [{ pbrMetallicRoughness: { baseColorTexture: { index: 0 } } }],+ meshes: [{ primitives: [{+ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4,+ }] }],+ }));+ const pad = (b: Buffer, fill: number) =>+ Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4, fill)]);+ const jsonChunk = pad(json, 0x20);+ const binChunk = pad(bin, 0);+ const header = Buffer.alloc(12);+ header.writeUInt32LE(0x46546c67, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(12 + 8 + jsonChunk.length + 8 + binChunk.length, 8);+ const chunk = (body: Buffer, kind: number) => {+ const head = Buffer.alloc(8);+ head.writeUInt32LE(body.length, 0);+ head.writeUInt32LE(kind, 4);+ return Buffer.concat([head, body]);+ };+ const glb = Buffer.concat([+ header, chunk(jsonChunk, 0x4e4f534a), chunk(binChunk, 0x004e4942),+ ]);++ const { meshes, textures } = importGltfMeshes(new Uint8Array(glb), 'robot');+ expect(textures).toHaveLength(1);+ expect(textures[0]!.name).toBe('robot_0.png');+ expect(Buffer.from(textures[0]!.bytes).equals(png)).toBe(true);+ expect(meshes[0]!.material?.baseColorTexture?.file).toBe('robot_0.png');+ });++ it('reports the PBR channels it cannot draw rather than dropping them', () => {+ const doc = withInlineImage();+ doc.materials = [{+ name: 'Metal',+ pbrMetallicRoughness: { metallicFactor: 1, roughnessFactor: 0.3 },+ normalTexture: { index: 0 }, emissiveFactor: [1, 0, 0],+ alphaMode: 'MASK', alphaCutoff: 0.4, doubleSided: false,+ extensions: { KHR_materials_clearcoat: {} },+ }];+ const { warnings } = importGltfMeshes(gltf(doc), 'model');+ const line = warnings.join('\n');+ expect(line).toContain('metallic-roughness');+ expect(line).toContain('normal map');+ expect(line).toContain('emissive');+ expect(line).toContain('alpha cutoff 0.4');+ expect(line).toContain('backfaces are not culled');+ expect(line).toContain('KHR_materials_clearcoat');+ });++ it("flips V, because glTF's uv origin is the image's top-left", () => {+ const { meshes } = importGltfMeshes(gltf(withInlineImage()), 'model');+ expect(texCoords(meshes[0]!)).toEqual([0, 1, 1, 1, 0, 0]);+ });+});++describe('glTF prefab assembly', () => {+ const meshesOf = (bytes: Uint8Array) => importGltfMeshes(bytes, 'model').meshes;++ it('makes the single primitive the root itself', () => {+ const prefab = assembleGltfPrefab('model', meshesOf(gltf(withInlineImage())),+ { prefix: 'assets/models/' });+ expect(prefab.entities).toHaveLength(1);+ expect(prefab.rootEntityId).toBe('0');+ expect(prefab.entities[0]!.components[1]).toEqual({+ type: 'Mesh2D',+ data: {+ mesh: 'assets/models/model.esmesh',+ texture: 'assets/models/model_0.png',+ color: { r: 0.25, g: 0.5, b: 0.75, a: 1 },+ enabled: true,+ },+ });+ });++ it('holds several primitives under one root', () => {+ const two = [+ { attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4 },+ { attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, mode: 4 },+ ];+ const prefab = assembleGltfPrefab('model', meshesOf(gltf(withInlineImage(), two)));+ expect(prefab.entities.map(e => e.prefabEntityId)).toEqual(['0', '1', '2']);+ expect(prefab.entities[0]!.children).toEqual(['1', '2']);+ expect(prefab.entities[1]!.parent).toBe('0');+ // The second primitive names no material: no texture, no tint, engine defaults.+ expect(prefab.entities[2]!.components[1]!.data).toEqual({+ mesh: 'model_0_1.esmesh', enabled: true,+ });+ });++ it('spells an external image through the project resolver', () => {+ const doc = withInlineImage();+ doc.images = [{ uri: '../textures/skin.png' }];+ const prefab = assembleGltfPrefab('model', meshesOf(gltf(doc)), {+ prefix: 'assets/models/',+ external: uri => `assets/${uri.replace('../', '')}`,+ });+ expect(prefab.entities[0]!.components[1]!.data.texture).toBe('assets/textures/skin.png');+ });+});diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex f4e7b4915..0c9bb107d 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -13,7 +13,7 @@ const PIPELINE = path.join(HERE, '..');const REPO = path.join(PIPELINE, '..');const USAGE = `usage: node pipeline/bin/estella.mjs export <projectDir> [options]- node pipeline/bin/estella.mjs import-gltf <file.gltf|file.glb> [outDir]+ node pipeline/bin/estella.mjs import-gltf <file.gltf|file.glb> [outDir] [--project <dir>]--platform <id> web | desktop | wechat | playable | android | ios (default web)--out <dir> output dir (default <projectDir>/dist-<platform>)@@ -34,8 +34,11 @@ second file — \`result.size\` carries the verdicts the build dialog draws, soand the editor cannot disagree about whether a build fits.import-gltf writes one \`.esmesh\` per triangle primitive next to the source (or-into outDir). A glTF holds many, so it is a source that PRODUCES assets rather-than one the engine loads — the products are what a scene references.`;+into outDir), the images the file carries inline, and one \`.esprefab\` naming+which geometry is drawn with which image and tint. A glTF holds many primitives,+so it is a source that PRODUCES assets rather than one the engine loads — the+products are what a scene references. Asset refs are project-relative, so the+project is found above the source unless --project says otherwise.`;/** Options take a value; these do not — without the distinction a trailing flag* swallows nothing, ends the loop, and a CI job silently gets no gate. */@@ -52,7 +55,12 @@ function parseArgs(argv) {console.error(USAGE);process.exit(2);}- return { command, source: path.resolve(projectDir), out: rest[0] ? path.resolve(rest[0]) : null };+ const flag = rest.indexOf('--project');+ const out = rest[0] && !rest[0].startsWith('--') ? path.resolve(rest[0]) : null;+ return {+ command, out, source: path.resolve(projectDir),+ project: flag >= 0 && rest[flag + 1] ? path.resolve(rest[flag + 1]) : null,+ };}if (command !== 'export' || !projectDir) {console.error(USAGE);@@ -110,9 +118,19 @@ async function loadPipeline(entry, outName) {return { mod, cleanup: () => rmSync(dir, { recursive: true, force: true }) };}+const PROJECT_FILES = ['project.esproject', 'project.esproj', 'project.json'];++/** The project directory a path sits in, walking up; null when it is outside one. */+function findProjectRoot(from) {+ for (let dir = from, prev = ''; dir !== prev; prev = dir, dir = path.dirname(dir)) {+ if (PROJECT_FILES.some((name) => existsSync(path.join(dir, name)))) return dir;+ }+ return null;+}+/** The project's raw settings file, for the fields read before the parser runs. */function projectSettings(projectDir) {- for (const name of ['project.esproject', 'project.esproj', 'project.json']) {+ for (const name of PROJECT_FILES) {const file = path.join(projectDir, name);if (existsSync(file)) {try {@@ -143,27 +161,56 @@ const opts = parseArgs(process.argv.slice(2));if (opts.command === 'import-gltf') {const { mod: importer, cleanup } = await loadPipeline(path.join(PIPELINE, 'src', 'assets', 'gltfImport.ts'), 'gltfImport.mjs');+ let imported = 0;try {- const dir = opts.out ?? path.dirname(opts.source);+ const sourceDir = path.dirname(opts.source);+ const dir = opts.out ?? sourceDir;const stem = path.basename(opts.source).replace(/\.(gltf|glb)$/i, '');- const { meshes, warnings } = importer.importGltfMeshes(+ // A component's asset ref is project-relative, so the products can only be+ // named once the project root is known; without one they are bare names.+ const root = opts.project ?? findProjectRoot(sourceDir);+ const projectRef = (abs) => path.relative(root, abs).split(path.sep).join('/');+ const refs = root+ ? { prefix: projectRef(dir) ? `${projectRef(dir)}/` : '',+ external: (uri) => projectRef(path.resolve(sourceDir, uri)) }+ : {};++ const { meshes, textures, warnings } = importer.importGltfMeshes(new Uint8Array(readFileSync(opts.source)), stem,(uri) => {- const abs = path.join(path.dirname(opts.source), uri);+ const abs = path.join(sourceDir, uri);return existsSync(abs) ? new Uint8Array(readFileSync(abs)) : null;},);for (const w of warnings) console.warn(` ! ${w}`);+ if (!root && meshes.length > 0) {+ console.warn(' ! no project found above the source — refs are bare file names'+ + ' (pass --project <dir>)');+ }+ const report = (file, what) =>+ console.log(`${path.relative(process.cwd(), file)}: ${what}`);+for (const mesh of meshes) {const outFile = path.join(dir, `${mesh.name}.esmesh`);writeFileSync(outFile, importer.encodeImportedMesh(mesh));- console.log(`${path.relative(process.cwd(), outFile)}: `- + `${mesh.vertexCount} vertices, ${mesh.triangleCount} triangles`);+ report(outFile, `${mesh.vertexCount} vertices, ${mesh.triangleCount} triangles`);+ }+ for (const texture of textures) {+ const outFile = path.join(dir, texture.name);+ writeFileSync(outFile, texture.bytes);+ report(outFile, `${texture.bytes.length} bytes`);+ }+ if (meshes.length > 0) {+ const outFile = path.join(dir, `${stem}.esprefab`);+ const prefab = importer.assembleGltfPrefab(stem, meshes, refs);+ writeFileSync(outFile, `${JSON.stringify(prefab, null, 2)}\n`);+ report(outFile, `${meshes.length} mesh entit${meshes.length === 1 ? 'y' : 'ies'}`);}- process.exit(meshes.length > 0 ? 0 : 1);+ imported = meshes.length;} finally {cleanup();}+ process.exit(imported > 0 ? 0 : 1);}const project = projectSettings(opts.projectDir);diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.tsindex ba976c6bd..20f435460 100644--- a/pipeline/src/assets/gltfImport.ts+++ b/pipeline/src/assets/gltfImport.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file glTF geometry → `.esmesh`.+ * @file glTF geometry and baseColor → `.esmesh`, images, and one `.esprefab`.** An import, not a cook. A glTF holds MANY primitives, so it is a source* that produces several engine assets rather than one file becoming@@ -9,7 +9,10 @@* disk, where a project can see them, reference them and diff them, and* the cook then ships them as the engine format they already are.*/-import { MeshChannel, MeshChannelType, packChannels, encodeMesh, type MeshData } from 'esengine';+import {+ MeshChannel, MeshChannelType, packChannels, encodeMesh, PREFAB_FORMAT_VERSION,+ type MeshData, type PrefabData, type PrefabEntityData,+} from 'esengine';/** One primitive's worth of geometry, named for the file it will be written to. */export interface ImportedMesh {@@ -18,10 +21,41 @@ export interface ImportedMesh {data: MeshData;vertexCount: number;triangleCount: number;+ /** The primitive's baseColor, absent when it names no material. */+ material?: ImportedMaterial;+}++/** Where a material's image comes from: a product this import writes, or a file already on disk. */+export interface ImportedImageRef {+ /** Product name (no directory) when written, else the glTF's own uri. */+ file: string;+ /** True for a uri the glTF points at — an existing file is referenced, never copied. */+ external: boolean;+}++/**+ * A glTF material in the terms a Mesh2D carries: the engine's mesh path is+ * `texture(uv) * vertexColor * tint`, which is what glTF calls baseColor. The+ * PBR channels around it have no consumer here and are reported, not dropped.+ */+export interface ImportedMaterial {+ name: string;+ /** baseColorFactor — the tint multiplied into the vertex colors. */+ baseColor: [number, number, number, number];+ baseColorTexture?: ImportedImageRef;+}++/** An image the glTF carries inline (GLB chunk or data uri), to be written beside the meshes. */+export interface ImportedTexture {+ /** `<stem>_<image index>.<ext>` — named for the source, since an inline image has no name. */+ name: string;+ bytes: Uint8Array;}export interface GltfImportResult {meshes: ImportedMesh[];+ /** Images extracted from the file itself; external ones stay where they are. */+ textures: ImportedTexture[];/** What was skipped and why — a silent drop is how half a model goes missing. */warnings: string[];}@@ -37,6 +71,8 @@ const TYPE_COMPONENTS: Record<string, number> = {SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16,};+interface GltfTextureRef { index: number; texCoord?: number }+interface GltfJson {accessors?: {bufferView?: number; byteOffset?: number; componentType: number; count: number;@@ -45,10 +81,28 @@ interface GltfJson {bufferViews?: { buffer: number; byteOffset?: number; byteLength: number; byteStride?: number }[];buffers?: { byteLength: number; uri?: string }[];meshes?: { name?: string; primitives: {- attributes: Record<string, number>; indices?: number; mode?: number;+ attributes: Record<string, number>; indices?: number; mode?: number; material?: number;}[] }[];+ materials?: {+ name?: string;+ pbrMetallicRoughness?: {+ baseColorFactor?: number[]; baseColorTexture?: GltfTextureRef;+ metallicFactor?: number; roughnessFactor?: number;+ metallicRoughnessTexture?: GltfTextureRef;+ };+ normalTexture?: GltfTextureRef; occlusionTexture?: GltfTextureRef;+ emissiveTexture?: GltfTextureRef; emissiveFactor?: number[];+ alphaMode?: string; alphaCutoff?: number; doubleSided?: boolean;+ extensions?: Record<string, unknown>;+ }[];+ textures?: { source?: number; sampler?: number }[];+ images?: { uri?: string; bufferView?: number; mimeType?: string; name?: string }[];}+const MIME_EXTENSION: Record<string, string> = {+ 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp', 'image/ktx2': '.ktx2',+};+/** Splits a `.glb` container into its JSON and binary chunks. */function parseGlb(bytes: Uint8Array): { json: GltfJson; bin: Uint8Array | null } {const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);@@ -133,6 +187,111 @@ function readComponent(dv: DataView, at: number, componentType: number): number}}+/** A bufferView's bytes as they lie — an image chunk, not an attribute stream. */+function sliceBufferView(json: GltfJson, bin: Uint8Array | null, buffers: (Uint8Array | null)[],+ index: number): Uint8Array | null {+ const view = json.bufferViews?.[index];+ if (!view) return null;+ const source = view.buffer === 0 && bin ? bin : buffers[view.buffer];+ if (!source) return null;+ const at = view.byteOffset ?? 0;+ return source.subarray(at, at + view.byteLength);+}++function dataUriMime(uri: string): string {+ const semi = uri.indexOf(';');+ const comma = uri.indexOf(',');+ const end = semi >= 0 && semi < comma ? semi : comma;+ return end > 5 ? uri.slice(5, end) : '';+}++interface MaterialContext {+ json: GltfJson;+ bin: Uint8Array | null;+ buffers: (Uint8Array | null)[];+ stem: string;+ textures: ImportedTexture[];+ warnings: string[];+}++/** Resolves a glTF texture index to the file a Mesh2D will sample, extracting inline images. */+function readTexture(ctx: MaterialContext, cache: Map<number, ImportedImageRef | null>,+ ref: GltfTextureRef, label: string): ImportedImageRef | null {+ if (ref.texCoord) ctx.warnings.push(`${label}: TEXCOORD_${ref.texCoord} is not imported (one UV set)`);+ const cached = cache.get(ref.index);+ if (cached !== undefined) return cached;++ const resolve = (): ImportedImageRef | null => {+ const source = ctx.json.textures?.[ref.index]?.source;+ const image = source !== undefined ? ctx.json.images?.[source] : undefined;+ if (!image || source === undefined) {+ ctx.warnings.push(`${label}: texture ${ref.index} has no image — skipped`);+ return null;+ }+ // An image already on disk is REFERENCED, never copied: a second copy is+ // a second thing to keep in sync with the file the artist edits.+ if (image.uri && !image.uri.startsWith('data:')) {+ return { file: decodeURIComponent(image.uri), external: true };+ }+ const bytes = image.uri+ ? decodeDataUri(image.uri)+ : image.bufferView !== undefined+ ? sliceBufferView(ctx.json, ctx.bin, ctx.buffers, image.bufferView)+ : null;+ if (!bytes) {+ ctx.warnings.push(`${label}: image ${source} could not be read — skipped`);+ return null;+ }+ const mime = image.mimeType ?? (image.uri ? dataUriMime(image.uri) : '');+ const ext = MIME_EXTENSION[mime];+ if (!ext) {+ ctx.warnings.push(`${label}: image ${source} has unsupported type ${mime || '(none)'} — skipped`);+ return null;+ }+ const name = `${ctx.stem}_${source}${ext}`;+ if (!ctx.textures.some(t => t.name === name)) ctx.textures.push({ name, bytes });+ return { file: name, external: false };+ };++ const resolved = resolve();+ cache.set(ref.index, resolved);+ return resolved;+}++/**+ * One glTF material as the baseColor a Mesh2D can carry. Everything a PBR+ * material says beyond that — metal, roughness, emission, a normal map, an alpha+ * cutoff — has no consumer in this engine yet, so it is reported rather than+ * quietly lost.+ */+function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedImageRef | null>,+ index: number): ImportedMaterial {+ const src = ctx.json.materials?.[index] ?? {};+ const label = src.name ? `material "${src.name}"` : `material ${index}`;+ const pbr = src.pbrMetallicRoughness ?? {};+ const factor = pbr.baseColorFactor ?? [1, 1, 1, 1];++ const unused: string[] = [];+ if (pbr.metallicRoughnessTexture || (pbr.metallicFactor ?? 1) !== 0 || (pbr.roughnessFactor ?? 1) !== 1) {+ unused.push('metallic-roughness');+ }+ if (src.normalTexture) unused.push('normal map');+ if (src.occlusionTexture) unused.push('occlusion');+ if (src.emissiveTexture || (src.emissiveFactor ?? [0, 0, 0]).some(v => v !== 0)) unused.push('emissive');+ if (src.alphaMode === 'MASK') unused.push(`alpha cutoff ${src.alphaCutoff ?? 0.5}`);+ if (src.doubleSided === false) unused.push('single-sided (backfaces are not culled)');+ for (const name of Object.keys(src.extensions ?? {})) unused.push(name);+ if (unused.length > 0) ctx.warnings.push(`${label}: ${unused.join(', ')} not imported`);++ const texture = pbr.baseColorTexture+ ? readTexture(ctx, textureCache, pbr.baseColorTexture, label) : null;+ return {+ name: src.name ?? `material_${index}`,+ baseColor: [factor[0] ?? 1, factor[1] ?? 1, factor[2] ?? 1, factor[3] ?? 1],+ ...(texture ? { baseColorTexture: texture } : {}),+ };+}+/*** A glTF's triangle geometry as `.esmesh` payloads. NORMAL is carried when the* source has it: the engine then draws the mesh with its lit variant, and the@@ -169,8 +328,21 @@ export function importGltfMeshes(});const meshes: ImportedMesh[] = [];+ const textures: ImportedTexture[] = [];const single = (json.meshes ?? []).reduce((n, m) => n + m.primitives.length, 0) === 1;+ const materialCtx: MaterialContext = { json, bin, buffers, stem, textures, warnings };+ const textureCache = new Map<number, ImportedImageRef | null>();+ const materialCache = new Map<number, ImportedMaterial>();+ const materialFor = (index: number): ImportedMaterial => {+ let material = materialCache.get(index);+ if (!material) {+ material = readMaterial(materialCtx, textureCache, index);+ materialCache.set(index, material);+ }+ return material;+ };+(json.meshes ?? []).forEach((mesh, meshIndex) => {mesh.primitives.forEach((prim, primIndex) => {const label = mesh.name ? `${mesh.name}[${primIndex}]` : `mesh ${meshIndex}[${primIndex}]`;@@ -230,7 +402,11 @@ export function importGltfMeshes(if (v > max[c]) max[c] = v;}dv.setFloat32(at + channels[1]!.offset, uvs ? uvs[i * 2] ?? 0 : 0, true);- dv.setFloat32(at + channels[1]!.offset + 4, uvs ? uvs[i * 2 + 1] ?? 0 : 0, true);+ // V is flipped at this boundary: glTF puts uv (0,0) at the+ // image's top-left, the engine's textures are uploaded+ // bottom-up, and the two conventions each look right alone.+ dv.setFloat32(at + channels[1]!.offset + 4,+ uvs ? 1 - (uvs[i * 2 + 1] ?? 0) : 0, true);for (let c = 0; c < 4; c++) {const v = colorsRaw? (c < colorComps ? colorsRaw[i * colorComps + c] ?? 1 : 1)@@ -249,6 +425,7 @@ export function importGltfMeshes(data: { channels, vertexStride, vertexCount, vertices, indices, aabbMin: min, aabbMax: max },vertexCount,triangleCount: indices.length / 3,+ ...(prim.material !== undefined ? { material: materialFor(prim.material) } : {}),});} catch (err) {warnings.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);@@ -259,10 +436,66 @@ export function importGltfMeshes(if (meshes.length === 0 && warnings.length === 0) {warnings.push('no triangle geometry found');}- return { meshes, warnings };+ return { meshes, textures, warnings };}/** The bytes to write for an imported mesh. */export function encodeImportedMesh(mesh: ImportedMesh): Uint8Array {return encodeMesh(mesh.data);}++/** How a product is spelled where a component refers to it. */+export interface ProductRefs {+ /** Prepended to every product name, e.g. `assets/models/` — the project-relative dir. */+ prefix?: string;+ /** An external image uri (relative to the glTF) → the ref a component carries. */+ external?: (uri: string) => string;+}++function meshEntity(id: string, mesh: ImportedMesh, refs: ProductRefs,+ parent: string | null): PrefabEntityData {+ const prefix = refs.prefix ?? '';+ const image = mesh.material?.baseColorTexture;+ const texture = image+ ? (image.external ? refs.external?.(image.file) ?? image.file : prefix + image.file)+ : null;+ const color = mesh.material?.baseColor;+ return {+ prefabEntityId: id,+ name: mesh.name,+ parent,+ children: [],+ visible: true,+ components: [+ { type: 'Transform', data: {} },+ { type: 'Mesh2D', data: {+ mesh: `${prefix}${mesh.name}.esmesh`,+ ...(texture ? { texture } : {}),+ ...(color ? { color: { r: color[0], g: color[1], b: color[2], a: color[3] } } : {}),+ enabled: true,+ } },+ ],+ };+}++/**+ * The import's assembly: which geometry is drawn with which image and tint. The+ * products are separate files and nothing else records how they go together, so+ * without this a model arrives as a pile of parts to be re-connected by hand.+ */+export function assembleGltfPrefab(name: string, meshes: ImportedMesh[],+ refs: ProductRefs = {}): PrefabData {+ // A single primitive needs no holder: the root IS the mesh, which is what a+ // scene wants to place. Several get one, since they are one model.+ const entities: PrefabEntityData[] = meshes.length === 1 && meshes[0]+ ? [meshEntity('0', meshes[0], refs, null)]+ : [+ {+ prefabEntityId: '0', name, parent: null, visible: true,+ children: meshes.map((_, i) => String(i + 1)),+ components: [{ type: 'Transform', data: {} }],+ },+ ...meshes.map((mesh, i) => meshEntity(String(i + 1), mesh, refs, '0')),+ ];+ return { version: PREFAB_FORMAT_VERSION, name, rootEntityId: '0', entities };+}diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 87fc7424a..41f5cfad4 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -27,7 +27,7 @@ export const TIERS = ['pr', 'nightly'];* Dawn adapter, so nothing here runs it. Where an adapter exists every scene* passes — both backends read the frame the same way, off the engine's buffer.*/-export const WEBGPU_GAP = 'no adapter on a CI runner; with one, all 53 pass (`--backend webgpu`)';+export const WEBGPU_GAP = 'no adapter on a CI runner; with one they all pass (`--backend webgpu`)';/*** Every pixel gate. `env` is handed to desktop/scripts/headless-verify.mjs@@ -128,6 +128,10 @@ export const SCENES = [// facing the viewer and +X, under a head-on directional light. Only a shader// reading them can tell the halves apart — which is what the two probes are.{ id: "mesh-lit", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_MESH_ASSET: "/scenes/lit-triangles.esmesh", ESTELLA_VERIFY_SCENE: "/scenes/mesh-lit.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-lit.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.30,\"y\":0.556,\"rgb\":[255,255,255],\"tol\":40},{\"x\":0.70,\"y\":0.556,\"rgb\":[0,0,0],\"tol\":40}]" } },+ // A whole glTF import on screen, through the prefab it produced: geometry, the+ // inline image, and the baseColor factor as the tint. The probes sit at the+ // texel centres of a 2x2 image, so a flipped V swaps colours between them.+ { id: "mesh-textured", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PREFAB: "/scenes/textured-quad.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/mesh-textured.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-textured.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.3333,\"y\":0.4167,\"rgb\":[128,0,0],\"tol\":40},{\"x\":0.6667,\"y\":0.4167,\"rgb\":[0,128,0],\"tol\":40},{\"x\":0.3333,\"y\":0.5833,\"rgb\":[0,0,255],\"tol\":40},{\"x\":0.6667,\"y\":0.5833,\"rgb\":[128,128,0],\"tol\":40}]" } },// Takes the GPU away for real and captures AFTER the cycle: the four points// sample the atlas, so they fail unless the content came back. A vertex-colour// scene passed with the re-upload deleted. No webgpu — no GL extension there.