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(assets): a skinned model's bind pose comes in with it

esengine7f7770b3c317
diff --git a/desktop/src/engine/componentDocs.generated.ts b/desktop/src/engine/componentDocs.generated.ts
index 8dae41f64..40b67a9ba 100644
--- a/desktop/src/engine/componentDocs.generated.ts
+++ b/desktop/src/engine/componentDocs.generated.ts
@@ -32,6 +32,7 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
Light2D: 'reference/components/graphics/#light2d',
Marker: 'reference/components/world/#marker',
Mesh2D: 'reference/components/graphics/#mesh2d',
+ MeshSkin: 'reference/components/graphics/#meshskin',
MotorJoint: 'reference/components/physics/#motorjoint',
Name: 'reference/components/core/#name',
NavAgent: 'reference/components/gameplay/#navagent',
diff --git a/desktop/tests/gltf-import.test.ts b/desktop/tests/gltf-import.test.ts
index e3c0a3c49..4b0d06983 100644
--- a/desktop/tests/gltf-import.test.ts
+++ b/desktop/tests/gltf-import.test.ts
@@ -284,7 +284,7 @@ describe('glTF material import', () => {
expect(meshes[0]!.material?.baseColorTexture?.settings?.wrapMode).toBe('clamp');
});
- it('reports deformation it cannot carry: skins and morph targets', async () => {
+ it('reports deformation it cannot carry: morph targets, and joints nothing binds', async () => {
const doc = {
...withInlineImage(),
skins: [{}],
@@ -296,8 +296,7 @@ describe('glTF material import', () => {
}]), 'model');
const line = warnings.join('\n');
expect(line).toContain('2 morph target(s) not imported');
- expect(line).toContain('skinning is not imported');
- expect(line).toContain('1 skin(s) not imported');
+ expect(line).toContain('a skin naming joints');
});
it('reports a uv rewrite it does not apply', async () => {
@@ -672,6 +671,117 @@ describe('glTF animation import', () => {
});
});
+/**
+ * The triangle bound to two joints. Accessors 3/4 are JOINTS_0 (u16) and
+ * WEIGHTS_0; 5 is the skin's inverse bind matrices unless the caller drops it.
+ */
+function skinnedGltf(opts: { noBindMatrices?: boolean; skinOnNode?: boolean; weights?: boolean } = {}): Uint8Array {
+ const geo = geometryBuffer();
+ const geoBytes = Buffer.from(geo.uri.split(',')[1]!, 'base64');
+ const pad = Buffer.alloc((4 - (geoBytes.length % 4)) % 4);
+ const joints = Buffer.from(new Uint16Array([0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]).buffer);
+ const weights = Buffer.from(new Float32Array([
+ 0.75, 0.25, 0, 0, 1, 0, 0, 0, 0.5, 0.5, 0, 0,
+ ]).buffer);
+ // Joint 1's bind pose sits 30 along x; joint 0's is identity.
+ const bind = new Float32Array(32);
+ for (let j = 0; j < 2; j++) for (let c = 0; c < 4; c++) bind[j * 16 + c * 5] = 1;
+ bind[16 + 12] = 30;
+ const parts = [geoBytes, pad, joints, weights, Buffer.from(bind.buffer)];
+ const bytes = Buffer.concat(parts);
+ let at = geoBytes.length + pad.length;
+ const views: Record<string, unknown>[] = [];
+ for (const p of [joints, weights, Buffer.from(bind.buffer)]) {
+ views.push({ buffer: 0, byteOffset: at, byteLength: p.length });
+ at += p.length;
+ }
+
+ const doc: Record<string, unknown> = {
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews: [...(geo.views as Record<string, unknown>[]), ...views],
+ accessors: [
+ ...(geo.accessors as Record<string, unknown>[]),
+ { bufferView: 3, componentType: 5123, count: 3, type: 'VEC4' },
+ { bufferView: 4, componentType: 5126, count: 3, type: 'VEC4' },
+ { bufferView: 5, componentType: 5126, count: 2, type: 'MAT4' },
+ ],
+ meshes: [{
+ name: 'Tri',
+ primitives: [{
+ attributes: {
+ POSITION: 0, TEXCOORD_0: 1, JOINTS_0: 3,
+ ...(opts.weights === false ? {} : { WEIGHTS_0: 4 }),
+ },
+ indices: 2, mode: 4,
+ }],
+ }],
+ nodes: [
+ { name: 'Rig', children: [1, 2, 3] },
+ { name: 'Hip' },
+ { name: 'Knee', translation: [30, 0, 0] },
+ { name: 'Body', mesh: 0, ...(opts.skinOnNode === false ? {} : { skin: 0 }) },
+ ],
+ scenes: [{ nodes: [0] }],
+ scene: 0,
+ skins: [{
+ joints: [1, 2],
+ ...(opts.noBindMatrices ? {} : { inverseBindMatrices: 5 }),
+ }],
+ };
+ return new TextEncoder().encode(JSON.stringify(doc));
+}
+
+describe('glTF skinning import', () => {
+ it('carries the joint channel, the weights and the bind pose', async () => {
+ const { meshes, warnings } = await importGltfMeshes(skinnedGltf(), 'rig');
+ const mesh = meshes[0]!;
+
+ const joints = mesh.data.channels.find((c) => c.semantic === MeshChannel.Joints);
+ const weights = mesh.data.channels.find((c) => c.semantic === MeshChannel.Weights);
+ expect(joints).toMatchObject({ components: 4, type: 2 /* UInt16 */ });
+ expect(weights).toMatchObject({ components: 4, type: 0 /* Float32 */ });
+
+ const dv = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);
+ expect(dv.getUint16(joints!.offset + 2, true)).toBe(1);
+ expect(dv.getFloat32(weights!.offset, true)).toBeCloseTo(0.75, 6);
+
+ // The bind pose comes from the SKIN, and the joints are its node list.
+ expect(mesh.data.inverseBindMatrices).toHaveLength(32);
+ expect(mesh.data.inverseBindMatrices![16 + 12]).toBe(30);
+ expect(mesh.skinJoints).toEqual([1, 2]);
+ expect(warnings.filter((w) => /skin/i.test(w))).toEqual([]);
+ });
+
+ it('treats a missing bind accessor as an identity bind pose', async () => {
+ const { meshes } = await importGltfMeshes(skinnedGltf({ noBindMatrices: true }), 'rig');
+ const bind = meshes[0]!.data.inverseBindMatrices!;
+ expect(bind[0]).toBe(1);
+ expect(bind[16 + 12]).toBe(0);
+ });
+
+ it('imports static, and says so, when nothing binds the joints', async () => {
+ for (const opts of [{ skinOnNode: false }, { weights: false }]) {
+ const { meshes, warnings } = await importGltfMeshes(skinnedGltf(opts), 'rig');
+ expect(meshes[0]!.data.channels.some((c) => c.semantic === MeshChannel.Joints)).toBe(false);
+ expect(meshes[0]!.skinJoints).toBeUndefined();
+ expect(warnings.some((w) => /JOINTS_0 without/.test(w))).toBe(true);
+ }
+ });
+
+ it('names the joint entities the prefab gives those nodes', async () => {
+ const { meshes, nodes } = await importGltfMeshes(skinnedGltf(), 'rig');
+ const prefab = assembleGltfPrefab('rig', meshes, { nodes });
+ const body = prefab.entities.find((e) => e.name === 'Body')!;
+ const skin = body.components.find((c) => c.type === 'MeshSkin');
+ expect(skin?.data).toEqual({ joints: ['n1', 'n2'] });
+ // Those ids are entities the same prefab carries — a joint list pointing
+ // outside it would resolve to nothing at instantiation.
+ const ids = prefab.entities.map((e) => e.prefabEntityId);
+ expect(ids).toEqual(expect.arrayContaining(['n1', 'n2']));
+ });
+});
+
describe('meshopt-compressed geometry', () => {
it('imports to the very same mesh the uncompressed file does', async () => {
// The claim is not what the codec does — it is that compression is invisible
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 2c4af884b..f27651f0e 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -74,6 +74,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
ShadowCaster2D: { category: 'graphics', summary: 'Marks a renderer as an occluder, so 2D lights cast shadows from its silhouette.', doc: 'graphics/lighting', anchor: 'casting-shadows', anchorZh: '投射阴影' },
PostProcessVolume: { category: 'graphics', summary: 'A stack of full-screen effects (bloom, vignette, colour grading) applied after the scene is drawn.', doc: 'graphics/post-processing', anchor: 'using-a-postprocessvolume', anchorZh: '使用-postprocessvolume' },
Mesh2D: { category: 'graphics', summary: 'Arbitrary 2D geometry — your own vertices, indices and material — drawn like any other renderer.', doc: 'graphics/drawing', anchor: 'custom-meshes-mesh2d', anchorZh: '自定义网格mesh2d' },
+ MeshSkin: { category: 'graphics', summary: 'The joint entities that deform a Mesh2D — an imported skin, in the order its bind matrices are in.', doc: 'assets/models', anchor: 'skinning', anchorZh: '蒙皮' },
Video: { category: 'graphics', summary: 'Plays a video stream onto a surface in the world or the UI.', doc: 'graphics/video', anchor: 'the-video-component', anchorZh: 'video-组件' },
// ── UI ─────────────────────────────────────────────────────────────────────
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 751dc70ca..034b2cbd6 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1360,6 +1360,18 @@
"color.a"
]
},
+ {
+ "name": "MeshSkin",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "joints",
+ "type": "Entity",
+ "default": "",
+ "doc": "Joint entities, in the order the mesh's bind matrices are in."
+ }
+ ]
+ },
{
"name": "MotorJoint",
"source": "ts",
diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.ts
index 74ef7b3e7..e6d78decf 100644
--- a/pipeline/src/assets/gltfImport.ts
+++ b/pipeline/src/assets/gltfImport.ts
@@ -28,6 +28,9 @@ export interface ImportedMesh {
triangleCount: number;
/** The primitive's baseColor, absent when it names no material. */
material?: ImportedMaterial;
+ /** Source node indices of the joints its `Joints` channel indexes, in order.
+ * Absent for geometry nothing skins. */
+ skinJoints?: number[];
}
/** Where a material's image comes from: a product this import writes, or a file already on disk. */
@@ -203,7 +206,7 @@ interface GltfJson {
name?: string; children?: number[]; mesh?: number; skin?: number;
matrix?: number[]; translation?: number[]; rotation?: number[]; scale?: number[];
}[];
- skins?: unknown[];
+ skins?: { name?: string; joints: number[]; inverseBindMatrices?: number; skeleton?: number }[];
animations?: {
name?: string;
channels: { sampler: number; target: { node?: number; path: string } }[];
@@ -769,6 +772,32 @@ export function nodeChildPaths(nodes: ImportedNode[]): Map<number, string> {
return paths;
}
+/**
+ * A skin's inverse bind matrices, one 4x4 per joint. The accessor is optional
+ * per spec and its absence means identity — a bind pose already at the origin,
+ * not a missing one.
+ */
+function bindMatrices(src: GltfBytes, skin: NonNullable<GltfJson['skins']>[number],
+ warnings: string[]): Float32Array {
+ const out = new Float32Array(skin.joints.length * 16);
+ if (skin.inverseBindMatrices === undefined) {
+ for (let j = 0; j < skin.joints.length; j++) {
+ for (let c = 0; c < 4; c++) out[j * 16 + c * 5] = 1;
+ }
+ return out;
+ }
+ const read = readAccessor(src, skin.inverseBindMatrices);
+ if (read.length < out.length) {
+ warnings.push(`a skin declares ${skin.joints.length} joints but carries`
+ + ` ${read.length / 16} bind matrices; the rest are identity`);
+ }
+ out.set(read.subarray(0, Math.min(read.length, out.length)));
+ for (let j = read.length / 16; j < skin.joints.length; j++) {
+ for (let c = 0; c < 4; c++) out[j * 16 + c * 5] = 1;
+ }
+ return out;
+}
+
/** glTF's sampler interpolation → the engine's, which spells the same curves. */
const INTERPOLATION: Record<string, string> = {
LINEAR: 'linear', STEP: 'step', CUBICSPLINE: 'hermite',
@@ -973,6 +1002,19 @@ export async function importGltfMeshes(
const meshIndexOf = new Map<string, number>();
const single = (json.meshes ?? []).reduce((n, m) => n + m.primitives.length, 0) === 1;
+ // Which skin deforms each mesh. A skin sits on the NODE, not the primitive,
+ // so the geometry learns its bind pose from whatever draws it — and a mesh
+ // drawn by two nodes under different skins can only carry one of them.
+ const meshSkin = new Map<number, number>();
+ for (const node of json.nodes ?? []) {
+ if (node.mesh === undefined || node.skin === undefined) continue;
+ const seen = meshSkin.get(node.mesh);
+ if (seen === undefined) meshSkin.set(node.mesh, node.skin);
+ else if (seen !== node.skin) {
+ warnings.push(`mesh ${node.mesh} is drawn under two skins; it is bound to the first`);
+ }
+ }
+
// ~800KB of decoder, loaded only for a file that carries Draco — the same
// lazy dynamic import the cook uses for its KTX2 encoder, and the reason the
// import is async in the first place.
@@ -1024,9 +1066,6 @@ export async function importGltfMeshes(
if (prim.targets?.length) {
warnings.push(`${label}: ${prim.targets.length} morph target(s) not imported`);
}
- if (prim.attributes.JOINTS_0 !== undefined) {
- warnings.push(`${label}: skinning is not imported — the mesh comes in static`);
- }
const posIndex = prim.attributes.POSITION;
if (posIndex === undefined) {
warnings.push(`${label}: no POSITION — skipped`);
@@ -1076,13 +1115,33 @@ export async function importGltfMeshes(
return;
}
+ // Both halves or neither: a joint index nothing weights moves the
+ // vertex by an arbitrary bone, and a weight indexing nothing has
+ // no bone to apply. A skin is what says which bind pose they mean.
+ const skinIndex = meshSkin.get(meshIndex);
+ const skin = skinIndex !== undefined ? json.skins?.[skinIndex] : undefined;
+ const joints = skin ? attribute('JOINTS_0', prim.attributes.JOINTS_0) : null;
+ const weights = skin ? attribute('WEIGHTS_0', prim.attributes.WEIGHTS_0) : null;
+ const skinned = !!(skin?.joints?.length && joints && weights);
+ if (prim.attributes.JOINTS_0 !== undefined && !skinned) {
+ warnings.push(`${label}: JOINTS_0 without ${!skin?.joints?.length
+ ? 'a skin naming joints on any node drawing it' : 'WEIGHTS_0'}`
+ + ' — imported static');
+ }
+
const { channels, vertexStride } = packChannels([
{ semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
{ semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
{ semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
...(normals ? [{ semantic: MeshChannel.Normal, components: 3,
type: MeshChannelType.Float32 }] : []),
+ ...(skinned ? [
+ { semantic: MeshChannel.Joints, components: 4, type: MeshChannelType.UInt16 },
+ { semantic: MeshChannel.Weights, components: 4, type: MeshChannelType.Float32 },
+ ] : []),
]);
+ const jointsChannel = skinned ? channels[channels.length - 2]! : null;
+ const weightsChannel = skinned ? channels[channels.length - 1]! : null;
const vertices = new Uint8Array(vertexCount * vertexStride);
const dv = new DataView(vertices.buffer);
@@ -1115,15 +1174,25 @@ export async function importGltfMeshes(
dv.setFloat32(at + channels[3].offset + c * 4, normals[i * 3 + c] ?? 0, true);
}
}
+ if (jointsChannel && weightsChannel) {
+ for (let c = 0; c < 4; c++) {
+ dv.setUint16(at + jointsChannel.offset + c * 2, joints![i * 4 + c] ?? 0, true);
+ dv.setFloat32(at + weightsChannel.offset + c * 4, weights![i * 4 + c] ?? 0, true);
+ }
+ }
}
meshIndexOf.set(`${meshIndex}_${primIndex}`, meshes.length);
meshes.push({
name: single ? stem : `${stem}_${meshIndex}_${primIndex}`,
- data: { channels, vertexStride, vertexCount, vertices, indices, aabbMin: min, aabbMax: max },
+ data: {
+ channels, vertexStride, vertexCount, vertices, indices, aabbMin: min, aabbMax: max,
+ ...(skinned ? { inverseBindMatrices: bindMatrices(src, skin!, warnings) } : {}),
+ },
vertexCount,
triangleCount: indices.length / 3,
...(prim.material !== undefined ? { material: materialFor(prim.material) } : {}),
+ ...(skinned ? { skinJoints: skin!.joints } : {}),
});
} catch (err) {
warnings.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);
@@ -1131,9 +1200,6 @@ export async function importGltfMeshes(
});
});
- // A rigged source arrives as still geometry; that is a property of the import
- // worth stating once for the file rather than per primitive.
- if (json.skins?.length) warnings.push(`${json.skins.length} skin(s) not imported`);
if (meshes.length === 0 && warnings.length === 0) {
warnings.push('no triangle geometry found');
}
@@ -1291,6 +1357,16 @@ function meshComponent(mesh: ImportedMesh, stem: string, refs: ProductRefs): Com
} };
}
+/**
+ * The joints that deform this mesh, named by the prefab entity each source node
+ * became — the same `n<index>` ids {@link assembleGltfPrefab} emits, so a
+ * re-import keeps pointing at the same entities.
+ */
+function skinComponent(mesh: ImportedMesh): ComponentData[] {
+ if (!mesh.skinJoints) return [];
+ return [{ type: 'MeshSkin', data: { joints: mesh.skinJoints.map(i => `n${i}`) } }];
+}
+
/** Only what differs from a Transform's defaults, so a diff shows the placement. */
function transformComponent(trs?: Trs, scale?: number): ComponentData {
const s = trs?.scale ?? [1, 1, 1];
@@ -1327,7 +1403,8 @@ export function assembleGltfPrefab(name: string, meshes: ImportedMesh[],
const drawn = node.meshes.map(i => meshes[i]).filter((m): m is ImportedMesh => !!m);
// One primitive rides the node itself; several cannot, since a Mesh2D
// draws one mesh — they become its children, at its own origin.
- const own = drawn.length === 1 && drawn[0] ? [meshComponent(drawn[0], name, refs)] : [];
+ const own = drawn.length === 1 && drawn[0]
+ ? [meshComponent(drawn[0], name, refs), ...skinComponent(drawn[0])] : [];
const self = entity(id, node.name, parent,
[transformComponent(node, rootScale), ...own]);
entities.push(self);
@@ -1336,7 +1413,8 @@ export function assembleGltfPrefab(name: string, meshes: ImportedMesh[],
const childId = `${id}_p${i}`;
self.children.push(childId);
entities.push(entity(childId, mesh.name, id,
- [transformComponent(), meshComponent(mesh, name, refs)]));
+ [transformComponent(), meshComponent(mesh, name, refs),
+ ...skinComponent(mesh)]));
});
}
for (const child of node.children) self.children.push(emitNode(child, id));
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 23b220e49..984d5fef9 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 58 beta · 1418 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"97f0a1d90b227b76"
+"9b942024c64872cd"
```
## ANCHOR_AXES — const @experimental
@@ -4279,7 +4279,7 @@ static prototype: Mesh2DPlugin
## MeshChannel — const @experimental
```
-{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; }
+{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; readonly Joints: 5; readonly Weights: 6; }
```
## MeshChannelDesc — interface @experimental
@@ -4292,7 +4292,7 @@ type: number
## MeshChannelType — const @experimental
```
-{ readonly Float32: 0; readonly UNorm8: 1; }
+{ readonly Float32: 0; readonly UNorm8: 1; readonly UInt16: 2; }
```
## MeshData — interface @experimental
@@ -4301,6 +4301,7 @@ aabbMax: [number, number, number]
aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
+inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index a7b0cdcba..7e87b7296 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 63 beta · 1437 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"97f0a1d90b227b76"
+"9b942024c64872cd"
```
## ANCHOR_AXES — const @experimental
@@ -4292,7 +4292,7 @@ static prototype: Mesh2DPlugin
## MeshChannel — const @experimental
```
-{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; }
+{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; readonly Joints: 5; readonly Weights: 6; }
```
## MeshChannelDesc — interface @experimental
@@ -4305,7 +4305,7 @@ type: number
## MeshChannelType — const @experimental
```
-{ readonly Float32: 0; readonly UNorm8: 1; }
+{ readonly Float32: 0; readonly UNorm8: 1; readonly UInt16: 2; }
```
## MeshData — interface @experimental
@@ -4314,6 +4314,7 @@ aabbMax: [number, number, number]
aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
+inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4d5cdc728..d1adef3da 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4274,7 +4274,7 @@ static prototype: Mesh2DPlugin
## MeshChannel — const @experimental
```
-{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; }
+{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; readonly Joints: 5; readonly Weights: 6; }
```
## MeshChannelDesc — interface @experimental
@@ -4287,7 +4287,7 @@ type: number
## MeshChannelType — const @experimental
```
-{ readonly Float32: 0; readonly UNorm8: 1; }
+{ readonly Float32: 0; readonly UNorm8: 1; readonly UInt16: 2; }
```
## MeshData — interface @experimental
@@ -4296,6 +4296,7 @@ aabbMax: [number, number, number]
aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
+inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d23a43cf5..1b5969dde 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4274,7 +4274,7 @@ static prototype: Mesh2DPlugin
## MeshChannel — const @experimental
```
-{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; }
+{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; readonly Joints: 5; readonly Weights: 6; }
```
## MeshChannelDesc — interface @experimental
@@ -4287,7 +4287,7 @@ type: number
## MeshChannelType — const @experimental
```
-{ readonly Float32: 0; readonly UNorm8: 1; }
+{ readonly Float32: 0; readonly UNorm8: 1; readonly UInt16: 2; }
```
## MeshData — interface @experimental
@@ -4296,6 +4296,7 @@ aabbMax: [number, number, number]
aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
+inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index dd15b8acb..e4a8b5025 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -25,6 +25,7 @@ addFlexContainer: (entity: Entity, component: FlexContainer) => void
addInteractable: (entity: Entity, component: Interactable) => void
addLight2D: (entity: Entity, component: Light2D) => void
addMesh2D: (entity: Entity, component: Mesh2D) => void
+addMeshSkin: (entity: Entity, component: MeshSkin) => void
addParent: (entity: Entity, component: Parent) => void
addParticleEmitter: (entity: Entity, component: ParticleEmitter) => void
addParticleForceField: (entity: Entity, component: ParticleForceField) => void
@@ -59,6 +60,7 @@ getFlexContainer: (entity: Entity) => FlexContainer
getInteractable: (entity: Entity) => Interactable
getLight2D: (entity: Entity) => Light2D
getMesh2D: (entity: Entity) => Mesh2D
+getMeshSkin: (entity: Entity) => MeshSkin
getParent: (entity: Entity) => Parent
getParticleEmitter: (entity: Entity) => ParticleEmitter
getParticleForceField: (entity: Entity) => ParticleForceField
@@ -89,6 +91,7 @@ hasFlexContainer: (entity: Entity) => boolean
hasInteractable: (entity: Entity) => boolean
hasLight2D: (entity: Entity) => boolean
hasMesh2D: (entity: Entity) => boolean
+hasMeshSkin: (entity: Entity) => boolean
hasParent: (entity: Entity) => boolean
hasParticleEmitter: (entity: Entity) => boolean
hasParticleForceField: (entity: Entity) => boolean
@@ -119,6 +122,7 @@ removeFlexContainer: (entity: Entity) => void
removeInteractable: (entity: Entity) => void
removeLight2D: (entity: Entity) => void
removeMesh2D: (entity: Entity) => void
+removeMeshSkin: (entity: Entity) => void
removeParent: (entity: Entity) => void
removeParticleEmitter: (entity: Entity) => void
removeParticleForceField: (entity: Entity) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 5c7919a57..4d93c0613 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4281,7 +4281,7 @@ static prototype: Mesh2DPlugin
## MeshChannel — const @experimental
```
-{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; }
+{ readonly Position: 0; readonly Color: 1; readonly TexCoord0: 2; readonly Normal: 3; readonly Tangent: 4; readonly Joints: 5; readonly Weights: 6; }
```
## MeshChannelDesc — interface @experimental
@@ -4294,7 +4294,7 @@ type: number
## MeshChannelType — const @experimental
```
-{ readonly Float32: 0; readonly UNorm8: 1; }
+{ readonly Float32: 0; readonly UNorm8: 1; readonly UInt16: 2; }
```
## MeshData — interface @experimental
@@ -4303,6 +4303,7 @@ aabbMax: [number, number, number]
aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
+inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
diff --git a/sdk/src/asset/meshFormat.ts b/sdk/src/asset/meshFormat.ts
index df7cd5e13..486467c59 100644
--- a/sdk/src/asset/meshFormat.ts
+++ b/sdk/src/asset/meshFormat.ts
@@ -12,9 +12,13 @@
/** Magic 'ESMH', little-endian. */
const MAGIC = 0x484d5345;
-const VERSION = 1;
-const HEADER_BYTES = 44;
+const VERSION = 2;
+/** v1 had no joint count; a file that predates skinning reads with the shorter one. */
+const HEADER_BYTES_V1 = 44;
+const HEADER_BYTES = 48;
const CHANNEL_BYTES = 8;
+/** One inverse bind matrix: 16 floats. */
+const MATRIX_BYTES = 64;
/**
* What a channel means. The value IS the shader attribute location, and the first
@@ -27,12 +31,18 @@ export const MeshChannel = {
TexCoord0: 2,
Normal: 3,
Tangent: 4,
+ /** Which joints move this vertex — indices into the mesh's own bind matrices. */
+ Joints: 5,
+ /** How much each of those four joints moves it. */
+ Weights: 6,
} as const;
/** How a channel's components are stored. Append only — serialized. */
export const MeshChannelType = {
Float32: 0,
UNorm8: 1,
+ /** Joint indices: glTF writes them as u8 or u16, and u16 loses neither. */
+ UInt16: 2,
} as const;
export interface MeshChannelDesc {
@@ -55,11 +65,20 @@ export interface MeshData {
indices: Uint32Array;
aabbMin: [number, number, number];
aabbMax: [number, number, number];
+ /**
+ * The bind pose, one 4x4 per joint, in the order the `Joints` channel indexes.
+ * It lives with the vertices because those indices point AT it — split apart,
+ * a file's indices would name something it does not carry. Absent for
+ * geometry that is not skinned.
+ */
+ inverseBindMatrices?: Float32Array;
}
/** Bytes one component of a channel type occupies. */
function componentBytes(type: number): number {
- return type === MeshChannelType.UNorm8 ? 1 : 4;
+ if (type === MeshChannelType.UNorm8) return 1;
+ if (type === MeshChannelType.UInt16) return 2;
+ return 4;
}
/**
@@ -84,8 +103,10 @@ export function packChannels(semantics: { semantic: number; components: number;
}
export function encodeMesh(data: MeshData): Uint8Array {
+ const jointCount = (data.inverseBindMatrices?.length ?? 0) / 16;
const size = HEADER_BYTES + data.channels.length * CHANNEL_BYTES
- + data.vertexCount * data.vertexStride + data.indices.length * 4;
+ + data.vertexCount * data.vertexStride + data.indices.length * 4
+ + jointCount * MATRIX_BYTES;
const out = new Uint8Array(size);
const view = new DataView(out.buffer);
@@ -99,6 +120,7 @@ export function encodeMesh(data: MeshData): Uint8Array {
view.setFloat32(20 + i * 4, data.aabbMin[i], true);
view.setFloat32(32 + i * 4, data.aabbMax[i], true);
}
+ view.setUint32(44, jointCount, true);
let at = HEADER_BYTES;
for (const c of data.channels) {
@@ -113,12 +135,20 @@ export function encodeMesh(data: MeshData): Uint8Array {
out.set(data.vertices.subarray(0, data.vertexCount * data.vertexStride), at);
at += data.vertexCount * data.vertexStride;
out.set(new Uint8Array(data.indices.buffer, data.indices.byteOffset, data.indices.length * 4), at);
+ at += data.indices.length * 4;
+ if (data.inverseBindMatrices) {
+ // Written through the DataView: the section's start is only 4-byte
+ // aligned, and a Float32Array view on it may not be constructible.
+ for (let i = 0; i < data.inverseBindMatrices.length; i++) {
+ view.setFloat32(at + i * 4, data.inverseBindMatrices[i]!, true);
+ }
+ }
return out;
}
export function decodeMesh(bytes: Uint8Array): MeshData {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- if (bytes.byteLength < HEADER_BYTES || view.getUint32(0, true) !== MAGIC) {
+ if (bytes.byteLength < HEADER_BYTES_V1 || view.getUint32(0, true) !== MAGIC) {
throw new Error('not an .esmesh file');
}
const version = view.getUint16(4, true);
@@ -138,8 +168,11 @@ export function decodeMesh(bytes: Uint8Array): MeshData {
const aabbMax: [number, number, number] = [
view.getFloat32(32, true), view.getFloat32(36, true), view.getFloat32(40, true)];
+ const headerBytes = version >= 2 ? HEADER_BYTES : HEADER_BYTES_V1;
+ const jointCount = version >= 2 ? view.getUint32(44, true) : 0;
+
const channels: MeshChannelDesc[] = [];
- let at = HEADER_BYTES;
+ let at = headerBytes;
for (let i = 0; i < channelCount; i++) {
channels.push({
semantic: view.getUint8(at),
@@ -151,7 +184,7 @@ export function decodeMesh(bytes: Uint8Array): MeshData {
}
const vertexBytes = vertexCount * vertexStride;
- const expected = at + vertexBytes + indexCount * 4;
+ const expected = at + vertexBytes + indexCount * 4 + jointCount * MATRIX_BYTES;
if (bytes.byteLength < expected) {
throw new Error(`.esmesh is truncated: ${bytes.byteLength} bytes, header describes ${expected}`);
}
@@ -162,7 +195,14 @@ export function decodeMesh(bytes: Uint8Array): MeshData {
const indexBase = at + vertexBytes;
for (let i = 0; i < indexCount; i++) indices[i] = view.getUint32(indexBase + i * 4, true);
- return { channels, vertexStride, vertexCount, vertices, indices, aabbMin, aabbMax };
+ const out: MeshData = { channels, vertexStride, vertexCount, vertices, indices, aabbMin, aabbMax };
+ if (jointCount > 0) {
+ const base = indexBase + indexCount * 4;
+ const matrices = new Float32Array(jointCount * 16);
+ for (let i = 0; i < matrices.length; i++) matrices[i] = view.getFloat32(base + i * 4, true);
+ out.inverseBindMatrices = matrices;
+ }
+ return out;
}
/** The channel table as the engine takes it: one 8-byte record per channel. */
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index a12be48a7..039324db7 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { Dimension, Padding } from '../wasm/wasm.generated';
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '97f0a1d90b227b76';
+export const ABI_LAYOUT_HASH = '9b942024c64872cd';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -356,6 +356,18 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
material: { advanced: true },
},
},
+ MeshSkin: {
+ defaults: {
+ joints: [],
+ },
+ assetFields: [],
+ entityFields: ['joints'],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ joints: { tooltip: "Joint entities, in the order the mesh's bind matrices are in." },
+ },
+ },
Parent: {
defaults: {
entity: 0,
@@ -1015,6 +1027,10 @@ export interface Mesh2DData {
mesh: number;
}
+export interface MeshSkinData {
+ joints: Entity[];
+}
+
/**
* The fields of the engine's `Parent` component, generated from
* the C++ struct so the two shapes cannot drift.
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index a48700b3c..e63a8ba9f 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -356,6 +356,10 @@ export interface Mesh2D {
mesh: number;
}
+export interface MeshSkin {
+ joints: VectorEntity;
+}
+
export interface Parent {
entity: number;
}
@@ -667,6 +671,10 @@ export interface Registry {
getMesh2D(entity: Entity): Mesh2D;
addMesh2D(entity: Entity, component: Mesh2D): void;
removeMesh2D(entity: Entity): void;
+ hasMeshSkin(entity: Entity): boolean;
+ getMeshSkin(entity: Entity): MeshSkin;
+ addMeshSkin(entity: Entity, component: MeshSkin): void;
+ removeMeshSkin(entity: Entity): void;
hasParent(entity: Entity): boolean;
getParent(entity: Entity): Parent;
addParent(entity: Entity, component: Parent): void;
@@ -765,6 +773,7 @@ export interface ESEngineModule {
Interactable: new () => Interactable;
Light2D: new () => Light2D;
Mesh2D: new () => Mesh2D;
+ MeshSkin: new () => MeshSkin;
Parent: new () => Parent;
ParticleEmitter: new () => ParticleEmitter;
ParticleForceField: new () => ParticleForceField;
diff --git a/sdk/tests/mesh-format-skin.test.ts b/sdk/tests/mesh-format-skin.test.ts
new file mode 100644
index 000000000..6d6691ca2
--- /dev/null
+++ b/sdk/tests/mesh-format-skin.test.ts
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The bind pose a skinned `.esmesh` carries, and the older files it must
+ * keep reading.
+ *
+ * The joint channel indexes the matrices in the same file, so the two travel
+ * together; what this pins is that they survive the round trip intact and that
+ * a mesh written before skinning existed still decodes.
+ */
+import { describe, it, expect } from 'vitest';
+import { encodeMesh, decodeMesh, packChannels, MeshChannel, MeshChannelType } from '../src/asset/meshFormat';
+
+/** Channels a skinned import writes, plus one vertex bound to joints 1 and 2. */
+function skinnedMesh(): Uint8Array {
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+ { semantic: MeshChannel.Joints, components: 4, type: MeshChannelType.UInt16 },
+ { semantic: MeshChannel.Weights, components: 4, type: MeshChannelType.Float32 },
+ ]);
+ const vertices = new Uint8Array(3 * vertexStride);
+ const dv = new DataView(vertices.buffer);
+ const joints = channels[3]!;
+ const weights = channels[4]!;
+ dv.setUint16(joints.offset, 1, true);
+ dv.setUint16(joints.offset + 2, 2, true);
+ dv.setFloat32(weights.offset, 0.25, true);
+ dv.setFloat32(weights.offset + 4, 0.75, true);
+
+ // Two joints, the second offset 5 along x — a bind pose that is not identity.
+ const bind = new Float32Array(32);
+ for (let j = 0; j < 2; j++) for (let c = 0; c < 4; c++) bind[j * 16 + c * 5] = 1;
+ bind[16 + 12] = 5;
+
+ return encodeMesh({
+ channels, vertexStride, vertexCount: 3, vertices,
+ indices: Uint32Array.from([0, 1, 2]),
+ aabbMin: [0, 0, 0], aabbMax: [1, 1, 0],
+ inverseBindMatrices: bind,
+ });
+}
+
+describe('.esmesh skinning', () => {
+ it('round-trips the joint channel and the bind pose', () => {
+ const mesh = decodeMesh(skinnedMesh());
+
+ const joints = mesh.channels.find((c) => c.semantic === MeshChannel.Joints);
+ expect(joints).toMatchObject({ components: 4, type: MeshChannelType.UInt16 });
+ // Two bytes per index, not four: a stride that assumed floats would put
+ // every later channel of every vertex at the wrong offset.
+ const weights = mesh.channels.find((c) => c.semantic === MeshChannel.Weights)!;
+ expect(weights.offset - joints!.offset).toBe(8);
+
+ const dv = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);
+ expect(dv.getUint16(joints!.offset, true)).toBe(1);
+ expect(dv.getUint16(joints!.offset + 2, true)).toBe(2);
+ expect(dv.getFloat32(weights.offset + 4, true)).toBeCloseTo(0.75, 6);
+
+ expect(mesh.inverseBindMatrices).toHaveLength(32);
+ expect(mesh.inverseBindMatrices![16 + 12]).toBe(5);
+ });
+
+ it('leaves geometry that is not skinned without a bind pose', () => {
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ ]);
+ const mesh = decodeMesh(encodeMesh({
+ channels, vertexStride, vertexCount: 3,
+ vertices: new Uint8Array(3 * vertexStride),
+ indices: Uint32Array.from([0, 1, 2]),
+ aabbMin: [0, 0, 0], aabbMax: [1, 1, 0],
+ }));
+ expect(mesh.inverseBindMatrices).toBeUndefined();
+ });
+
+ it('reads a file written before the bind pose section existed', () => {
+ // A v1 file byte for byte: the 44-byte header has no joint count, so the
+ // channel table starts four bytes earlier than it does today.
+ const stride = 12;
+ const header = new ArrayBuffer(44 + 8 + 3 * stride + 3 * 4);
+ const dv = new DataView(header);
+ dv.setUint32(0, 0x484d5345, true);
+ dv.setUint16(4, 1, true); // version 1
+ dv.setUint16(6, 1, true); // one channel
+ dv.setUint32(8, stride, true);
+ dv.setUint32(12, 3, true); // three vertices
+ dv.setUint32(16, 3, true); // three indices
+ dv.setFloat32(32, 1, true); // aabbMax.x
+ dv.setUint8(44, MeshChannel.Position);
+ dv.setUint8(45, 3);
+ dv.setUint8(46, MeshChannelType.Float32);
+ for (let i = 0; i < 3; i++) dv.setUint32(44 + 8 + 3 * stride + i * 4, i, true);
+
+ const mesh = decodeMesh(new Uint8Array(header));
+ expect(mesh.channels).toHaveLength(1);
+ expect(mesh.vertexCount).toBe(3);
+ expect([...mesh.indices]).toEqual([0, 1, 2]);
+ expect(mesh.inverseBindMatrices).toBeUndefined();
+ });
+});
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 8968e9836..b3d275893 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 09fe34b6f64d2a9f
+ * @schema_hash b194d72fddb41534
*/
-#define ES_EDITOR_API_SCHEMA_HASH "09fe34b6f64d2a9f"
+#define ES_EDITOR_API_SCHEMA_HASH "b194d72fddb41534"
#include <emscripten/bind.h>
#include <string>
@@ -69,6 +69,7 @@ std::vector<std::string> editor_getComponentNames() {
"Interactable",
"Light2D",
"Mesh2D",
+ "MeshSkin",
"Parent",
"ParticleEmitter",
"ParticleForceField",
@@ -261,6 +262,10 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"enabled","type":"bool","group":"Mesh2D"},
{"key":"mesh","type":"asset","group":"Mesh2D"}
])JSON";
+ } else if (name == "MeshSkin") {
+ return R"JSON([
+ {"key":"joints","type":"entity","group":"MeshSkin"}
+ ])JSON";
} else if (name == "Parent") {
return R"JSON([
{"key":"entity","type":"entity","group":"Parent"}
@@ -634,6 +639,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "Mesh2D") {
if (!reg.has<esengine::ecs::Mesh2D>(entity)) reg.emplace<esengine::ecs::Mesh2D>(entity);
return true;
+ } else if (name == "MeshSkin") {
+ if (!reg.has<esengine::ecs::MeshSkin>(entity)) reg.emplace<esengine::ecs::MeshSkin>(entity);
+ return true;
} else if (name == "Parent") {
return false;
} else if (name == "ParticleEmitter") {
@@ -722,6 +730,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::Light2D>(entity)) { reg.remove<esengine::ecs::Light2D>(entity); return true; }
} else if (name == "Mesh2D") {
if (reg.has<esengine::ecs::Mesh2D>(entity)) { reg.remove<esengine::ecs::Mesh2D>(entity); return true; }
+ } else if (name == "MeshSkin") {
+ if (reg.has<esengine::ecs::MeshSkin>(entity)) { reg.remove<esengine::ecs::MeshSkin>(entity); return true; }
} else if (name == "Parent") {
if (reg.has<esengine::ecs::Parent>(entity)) { esengine::ecs::setParent(reg, entity, INVALID_ENTITY); return true; }
} else if (name == "ParticleEmitter") {
@@ -777,6 +787,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "Interactable") return reg.has<esengine::ecs::Interactable>(entity);
if (name == "Light2D") return reg.has<esengine::ecs::Light2D>(entity);
if (name == "Mesh2D") return reg.has<esengine::ecs::Mesh2D>(entity);
+ if (name == "MeshSkin") return reg.has<esengine::ecs::MeshSkin>(entity);
if (name == "Parent") return reg.has<esengine::ecs::Parent>(entity);
if (name == "ParticleEmitter") return reg.has<esengine::ecs::ParticleEmitter>(entity);
if (name == "ParticleForceField") return reg.has<esengine::ecs::ParticleForceField>(entity);
@@ -816,6 +827,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::Interactable>(entity)) result.push_back("Interactable");
if (reg.has<esengine::ecs::Light2D>(entity)) result.push_back("Light2D");
if (reg.has<esengine::ecs::Mesh2D>(entity)) result.push_back("Mesh2D");
+ if (reg.has<esengine::ecs::MeshSkin>(entity)) result.push_back("MeshSkin");
if (reg.has<esengine::ecs::Parent>(entity)) result.push_back("Parent");
if (reg.has<esengine::ecs::ParticleEmitter>(entity)) result.push_back("ParticleEmitter");
if (reg.has<esengine::ecs::ParticleForceField>(entity)) result.push_back("ParticleForceField");
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index d51d17e05..40fd8a7c3 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -285,6 +285,16 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS
}
}
+ // The file's channel TYPE code (0 float, 1 unorm8, 2 uint16), in the asset
+ // layer's vocabulary — the boundary the format crosses as bytes.
+ auto channelType = [](u8 code) {
+ switch (code) {
+ case 1: return GfxDataType::UnsignedByte;
+ case 2: return GfxDataType::UnsignedShort;
+ default: return GfxDataType::Float;
+ }
+ };
+
GfxVertexAttribute channels[MAX_VERTEX_ATTRIBUTES];
if (channelCount > MAX_VERTEX_ATTRIBUTES) return 0;
for (u32 i = 0; i < channelCount; ++i) {
@@ -292,7 +302,7 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS
channels[i] = GfxVertexAttribute{
.location = c[0],
.components = c[1],
- .type = c[2] == 1 ? GfxDataType::UnsignedByte : GfxDataType::Float,
+ .type = channelType(c[2]),
.normalized = c[3] != 0,
.offset = static_cast<u32>(c[4]) | (static_cast<u32>(c[5]) << 8)
| (static_cast<u32>(c[6]) << 16) | (static_cast<u32>(c[7]) << 24),
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index c5c312ab7..54ef656ae 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -488,6 +488,28 @@ Mesh2DJS mesh2dToJS(const esengine::ecs::Mesh2D& c) {
return js;
}
+struct MeshSkinJS {
+ std::vector<u32> joints;
+};
+
+void meshskinApplyJS(esengine::ecs::MeshSkin& c, const MeshSkinJS& js) {
+ c.joints.reserve(js.joints.size());
+ for (auto v : js.joints) c.joints.push_back(Entity(v));
+}
+
+esengine::ecs::MeshSkin meshskinFromJS(const MeshSkinJS& js) {
+ esengine::ecs::MeshSkin c;
+ meshskinApplyJS(c, js);
+ return c;
+}
+
+MeshSkinJS meshskinToJS(const esengine::ecs::MeshSkin& c) {
+ MeshSkinJS js;
+ js.joints.reserve(c.joints.size());
+ for (auto e : c.joints) js.joints.push_back(static_cast<u32>(e));
+ return js;
+}
+
struct ParentJS {
u32 entity;
};
@@ -1233,6 +1255,9 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("enabled", &Mesh2DJS::enabled)
.field("mesh", &Mesh2DJS::mesh);
+ value_object<MeshSkinJS>("MeshSkin")
+ .field("joints", &MeshSkinJS::joints);
+
value_object<ParentJS>("Parent")
.field("entity", &ParentJS::entity);
@@ -1762,6 +1787,30 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::Mesh2D>(entity);
}))
+ // MeshSkin
+ .function("hasMeshSkin", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::MeshSkin>(static_cast<Entity>(e));
+ }))
+ .function("getMeshSkin", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshSkin>(entity)) return MeshSkinJS{};
+ return meshskinToJS(r.get<esengine::ecs::MeshSkin>(entity));
+ }))
+ .function("addMeshSkin", optional_override([](Registry& r, u32 e, const MeshSkinJS& js) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ if (auto* existing = r.tryGet<esengine::ecs::MeshSkin>(entity)) {
+ meshskinApplyJS(*existing, js);
+ return;
+ }
+ r.emplaceOrReplace<esengine::ecs::MeshSkin>(entity, meshskinFromJS(js));
+ }))
+ .function("removeMeshSkin", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshSkin>(entity)) return;
+ r.remove<esengine::ecs::MeshSkin>(entity);
+ }))
+
// Parent
.function("hasParent", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Parent>(static_cast<Entity>(e));
@@ -2196,6 +2245,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("Interactable")));
arr.set(i++, val(std::string("Light2D")));
arr.set(i++, val(std::string("Mesh2D")));
+ arr.set(i++, val(std::string("MeshSkin")));
arr.set(i++, val(std::string("Parent")));
arr.set(i++, val(std::string("ParticleEmitter")));
arr.set(i++, val(std::string("ParticleForceField")));
@@ -2527,7 +2577,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "97f0a1d90b227b76";
+static const char* kEsAbiLayoutHash = "9b942024c64872cd";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/ecs/components/Mesh2D.hpp b/src/esengine/ecs/components/Mesh2D.hpp
index cf2879e0c..be32a69d1 100644
--- a/src/esengine/ecs/components/Mesh2D.hpp
+++ b/src/esengine/ecs/components/Mesh2D.hpp
@@ -120,4 +120,25 @@ struct Mesh2D {
Mesh2D() = default;
};
+// =============================================================================
+// MeshSkin Component
+// =============================================================================
+
+/**
+ * @brief What deforms a @ref Mesh2D: the entities its Joints channel indexes.
+ *
+ * @details Its own component because Mesh2D says WHAT is drawn and this says
+ * what moves it; entry i drives joint i of the mesh's own bind
+ * matrices. A skinned mesh's own transform is ignored (glTF requires
+ * it) — the joints are placed in the world, so the vertices are too.
+ */
+ES_COMPONENT()
+struct MeshSkin {
+ /** @brief Joint entities, in the order the mesh's bind matrices are stored. */
+ ES_PROPERTY(entity_ref, tooltip="Joint entities, in the order the mesh's bind matrices are in.")
+ std::vector<Entity> joints;
+
+ MeshSkin() = default;
+};
+
} // namespace esengine::ecs
diff --git a/tools/check-component-fields.mjs b/tools/check-component-fields.mjs
index 5e4b3a21f..570e59a7b 100644
--- a/tools/check-component-fields.mjs
+++ b/tools/check-component-fields.mjs
@@ -27,7 +27,22 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
* says which, so the list reads as work rather than as permission. Empty is the
* intended state: a field that earns an entry here is work, not permission.
*/
-const DECLARED_GAPS = {};
+const DECLARED_GAPS = {
+ 'AudioSource.priority': 'nothing limits how many sources play at once, so there is'
+ + ' never a moment where one has to be dropped in favour of another',
+ 'CacheAsBitmap.enabled': 'the component is declared and nothing renders a subtree to a'
+ + ' texture to draw it as one quad — the four fields below are the same gap',
+ 'CacheAsBitmap.dirty': 'see CacheAsBitmap.enabled',
+ 'CacheAsBitmap.width': 'see CacheAsBitmap.enabled',
+ 'CacheAsBitmap.height': 'see CacheAsBitmap.enabled',
+ 'ParticleEmitter.material': 'only the mesh path resolves a material into a program'
+ + ' (MaterialStore::meshProgram); particles, spine and dragonbones draw with their'
+ + ' own built-in shader and never consult the table',
+ 'SpineAnimation.material': 'see ParticleEmitter.material',
+ 'DragonBonesAnimation.material': 'see ParticleEmitter.material',
+ 'MeshSkin.joints': 'the import writes the joint list, and the renderer does not yet'
+ + ' build a bone matrix from it (REARCH_3D D1)',
+};
const components = JSON.parse(
readFileSync(path.join(ROOT, 'docs', 'astro', 'src', 'data', 'components.generated.json'), 'utf8'),
@@ -35,12 +50,27 @@ const components = JSON.parse(
// Every source a field can be READ from. Generated files name every field by
// construction, so including them would make this gate vacuous.
-const files = execFileSync('git', ['ls-files', 'src', 'sdk/src', 'desktop/src', 'native', 'plugins'],
+//
+// `examples` is in the list because some fields exist to be read by a GAME:
+// Perception writes what it saw and the engine never looks at it again, so
+// judging that one by engine sources alone would call an output a dead knob.
+const files = execFileSync('git',
+ ['ls-files', 'src', 'sdk/src', 'desktop/src', 'native', 'plugins', 'examples'],
{ cwd: ROOT, encoding: 'utf8' }).split('\n').filter(Boolean);
-const blob = files
+const sources = files
.filter((f) => /\.(cpp|hpp|h|ts|tsx)$/.test(f) && !f.includes('generated'))
- .map((f) => readFileSync(path.join(ROOT, f), 'utf8'))
- .join('\n');
+ .map((f) => readFileSync(path.join(ROOT, f), 'utf8'));
+
+/**
+ * A reader is a file naming the FIELD and the COMPONENT it belongs to. One
+ * concatenated blob let anything anywhere vouch for a common key — the counter
+ * `'physics.joints'` read as a reader of `MeshSkin.joints`. Reaching a field
+ * means getting its component, so the name is in the same file by construction.
+ */
+function hasReader(component, key) {
+ const spelled = new RegExp(`[.>'"]${key}\\b`);
+ return sources.some((text) => text.includes(component) && spelled.test(text));
+}
const problems = [];
const unusedGaps = new Set(Object.keys(DECLARED_GAPS));
@@ -48,7 +78,7 @@ for (const component of components) {
for (const field of component.fields ?? []) {
const name = `${component.name}.${field.key}`;
// `.key`, `->key`, or the key quoted (a TS projection writes it by name).
- if (new RegExp(`[.>'"]${field.key}\\b`).test(blob)) {
+ if (hasReader(component.name, field.key)) {
if (DECLARED_GAPS[name]) {
problems.push(`${name} is listed as a gap but something reads it — drop the entry`);
unusedGaps.delete(name);