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.

test(spine): what clipping costs, against the geometry that decides it

esengine294c56ed5e1c
diff --git a/sdk/benchmarks/spine-clip-stages.bench.ts b/sdk/benchmarks/spine-clip-stages.bench.ts
new file mode 100644
index 000000000..06710f0e0
--- /dev/null
+++ b/sdk/benchmarks/spine-clip-stages.bench.ts
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-clip-stages.bench.ts
+ * @brief What clipping costs, against the geometry that decides it.
+ *
+ * @details coin says clip-heavy Spine is clipping-bound — 2.48 ms of its 2.53 —
+ * and nothing more, because its 39-vertex polygon, its clipped
+ * attachments and its triangle count all move together. So the fixtures
+ * here are authored: the same strip of quads every time, with only the
+ * clip polygon's SHAPE or its RELATION to the strip changing.
+ *
+ * Two depths bracket it. S_start opens the region — the polygon made
+ * clockwise and decomposed into convex pieces — and cuts nothing;
+ * S_clip cuts. Their difference is the cut, and S_start minus the
+ * depth below it is what a clip region costs before any triangle.
+ *
+ * Fixtures are asserted in tests/spine-clip-stages, which is what makes
+ * "few cross" and "all cross" mean anything. `SPINE_CLIP_REPORT=1`
+ * prints the counters each row was measured on.
+ *
+ * What it answered, µs per entity per frame (min of two runs):
+ *
+ * case edges inTri | open cut store | ns/(tri*edge)
+ * all outside 5 32 | 0.064 1.604 0.005 | 10.0
+ * all inside 5 32 | 0.068 2.032 0.065 | 12.7
+ * one quad crossing 5 32 | 0.067 1.706 0.100 | 10.7
+ * every quad cross 5 32 | 0.065 2.259 0.166 | 14.1
+ * convex 8 9 32 | 0.158 4.075 0.171 | 14.1
+ * convex 16 17 32 | 0.406 7.752 0.101 | 14.2
+ * concave 8 15 32 | 0.208 6.494 0.338 | 13.5
+ * concave 16 41 32 | 0.716 16.559 0.918 | 12.6
+ * coin 40 2 | 2.001 2.055 0.111 | 25.7
+ *
+ * Storing the result is never the term: 5% of a clip at worst, and the
+ * clipper's own scratch stops growing after one shape.
+ *
+ * Where the triangles fall barely is one either. Same triangles, same
+ * polygon: geometry that clips away to NOTHING costs 71% of geometry
+ * that is entirely cut. Being inside a clip region is the tax; crossing
+ * its boundary is a surcharge on top.
+ *
+ * The axis is the polygon's EDGES, because the cut runs one pass per
+ * edge per triangle: 14 ns x inputTriangles x edges holds within 10%
+ * from 5 edges to 41. Concave sits on the same line rather than a worse
+ * one — decomposition just multiplies the edges (an 8-point star
+ * becomes 3 pieces and 15 edges, a 16-point one 9 pieces and 41).
+ *
+ * Opening the region is a separate, super-linear term in the ORIGINAL
+ * vertex count: 0.065 / 0.158 / 0.406 / 2.001 µs at 4 / 8 / 16 / 39
+ * vertices. For coin that is HALF its clipping cost — to prepare a
+ * polygon that goes on to cut two triangles.
+ */
+import { describe, bench, beforeAll } from 'vitest';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { WASM_DIR } from '../tests/helpers/loadWasm';
+import { wrapSpineModule } from '../src/spine/SpineModuleLoader';
+import type { SpineWasmModule, SpineWrappedAPI } from '../src/spine/SpineModuleLoader';
+import { withScratch } from '../src/wasm/wasmScratch';
+import { syntheticSkeleton } from '../tests/helpers/syntheticSpine';
+import type { SyntheticOptions } from '../tests/helpers/syntheticSpine';
+
+const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');
+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');
+const HAS_WASM = existsSync(SPINE38_WASM);
+
+const ENTITIES = 200;
+const FRAMES = 20;
+const QUADS = 16;
+
+const STAGE_VERTICES = 2;
+const STAGE_CLIP_START = 3;
+const STAGE_CLIP = 4;
+const STAGE_EMIT = 5;
+
+/** Same strip, same 512 input triangles; only where the boundary falls moves. */
+const RELATIONS: Array<{ name: string; options: SyntheticOptions }> = [
+ { name: 'all inside', options: { quads: QUADS, relation: 'inside' } },
+ { name: 'all outside', options: { quads: QUADS, relation: 'outside' } },
+ { name: 'one quad crossing', options: { quads: QUADS, relation: 'one-crossing' } },
+ { name: 'every quad crossing', options: { quads: QUADS, relation: 'all-crossing' } },
+];
+
+/** Same relation, same triangles; only the polygon's own complexity moves. */
+const POLYGONS: Array<{ name: string; options: SyntheticOptions }> = [
+ { name: 'convex 4', options: { quads: QUADS, relation: 'all-crossing', polygonVertices: 4 } },
+ { name: 'convex 8', options: { quads: QUADS, relation: 'all-crossing', polygonVertices: 8 } },
+ { name: 'convex 16', options: { quads: QUADS, relation: 'all-crossing', polygonVertices: 16 } },
+ { name: 'concave 8', options: { quads: QUADS, relation: 'all-crossing', polygonVertices: 8, concave: true } },
+ { name: 'concave 16', options: { quads: QUADS, relation: 'all-crossing', polygonVertices: 16, concave: true } },
+];
+
+/** The shipped asset the model has to explain, in the same harness. */
+const REAL: Array<{ name: string; skel: string; atlas: string }> = [
+ { name: 'coin (39-vertex polygon)', skel: 'coin-38/coin-pro.skel', atlas: 'coin-38/coin.atlas' },
+];
+const FIXTURES = resolve(__dirname, 'fixtures/spine');
+
+const CASES = [...RELATIONS, ...POLYGONS,
+ ...REAL.filter((r) => existsSync(resolve(FIXTURES, r.skel))).map((r) => ({ name: r.name, real: r }))];
+const COUNTERS = [
+ 'slots', 'regions', 'meshes', 'clipStarts', 'clippedEmits',
+ 'vGenerated', 'vEmitted', 'iEmitted', 'emits',
+ 'polygons', 'polygonVertices', 'polygonEdges', 'inTriangles', 'outTriangles',
+] as const;
+
+let raw: SpineWasmModule;
+let api: SpineWrappedAPI;
+const instances = new Map<string, number[]>();
+
+beforeAll(async () => {
+ if (!HAS_WASM) return;
+ const factory = (await import(SPINE38_JS)).default as (opts: unknown) => Promise<SpineWasmModule>;
+ const bytes = readFileSync(SPINE38_WASM);
+ raw = await factory({
+ instantiateWasm(imports: WebAssembly.Imports, cb: (i: WebAssembly.Instance, m: WebAssembly.Module) => void) {
+ void WebAssembly.instantiate(bytes, imports).then((r) => cb(r.instance, r.module));
+ return {};
+ },
+ });
+ api = wrapSpineModule(raw);
+
+ for (const test of CASES) {
+ const real = 'real' in test ? test.real : null;
+ const skelData = real
+ ? new Uint8Array(readFileSync(resolve(FIXTURES, real.skel)))
+ : new TextEncoder().encode(syntheticSkeleton(test.options).json);
+ const atlas = real
+ ? readFileSync(resolve(FIXTURES, real.atlas), 'utf-8')
+ : syntheticSkeleton(test.options).atlas;
+ const handle = withScratch(raw, (alloc) => {
+ const ptr = alloc(skelData.length);
+ raw.HEAPU8.set(skelData, ptr);
+ return api.loadSkeleton(ptr, skelData.length, atlas, atlas.length, real !== null);
+ });
+ if (handle < 0) throw new Error(`${test.name}: ${api.getLastError()}`);
+ for (let i = 0, pages = api.getAtlasPageCount(handle); i < pages; i++) {
+ api.setAtlasPageTexture(handle, i, 1, 1024, 1024);
+ }
+ const ids: number[] = [];
+ for (let i = 0; i < ENTITIES; i++) {
+ const id = api.createInstance(handle);
+ if (real) {
+ const [first] = JSON.parse(api.getAnimations(id)) as string[];
+ if (!api.playAnimation(id, first, true, 0)) throw new Error(`${test.name}: no "${first}"`);
+ }
+ api.update(id, real ? 0.35 : 0);
+ ids.push(id);
+ }
+ instances.set(test.name, ids);
+ }
+
+ if (process.env.SPINE_CLIP_REPORT) report();
+});
+
+function countsOf(instanceId: number): Record<string, number> {
+ api.probeExtract(instanceId, STAGE_EMIT, 1);
+ return withScratch(raw, (alloc) => {
+ const ptr = alloc(COUNTERS.length * 4);
+ api.probeCounts(ptr);
+ const out: Record<string, number> = {};
+ COUNTERS.forEach((name, i) => { out[name] = raw.HEAPU32[(ptr >> 2) + i]; });
+ return out;
+ });
+}
+
+/** The geometry behind each row, so a millisecond can be read against it. */
+function report(): void {
+ const rows = CASES.map((test) => {
+ const c = countsOf(instances.get(test.name)![0]);
+ return {
+ case: test.name, polygons: c.polygons, polyVerts: c.polygonVertices,
+ edges: c.polygonEdges, inTri: c.inTriangles, outTri: c.outTriangles,
+ amplification: (c.outTriangles / Math.max(1, c.inTriangles)).toFixed(2),
+ outVerts: c.vEmitted,
+ };
+ });
+ const keys = Object.keys(rows[0]);
+ const width = (k: string) => Math.max(k.length, ...rows.map((r) => String((r as never)[k]).length));
+ const line = (cells: unknown[]) => cells.map((c, i) => String(c).padStart(width(keys[i]))).join(' ');
+ console.log(line(keys));
+ for (const row of rows) console.log(line(keys.map((k) => (row as never)[k])));
+ console.log('clipper scratch:', withScratch(raw, (alloc) => {
+ const ptr = alloc(6 * 4);
+ api.probeClipStorage(ptr);
+ return Array.from({ length: 6 }, (_, i) => raw.HEAPU32[(ptr >> 2) + i]).join(' ');
+ }));
+}
+
+function pass(name: string, stage: number): void {
+ const ids = instances.get(name)!;
+ for (let f = 0; f < FRAMES; f++) {
+ for (const id of ids) api.probeExtract(id, stage, 1);
+ }
+}
+
+describe.skipIf(!HAS_WASM)(`Spine clip stages: ${ENTITIES} entities x${FRAMES}`, () => {
+ for (const test of CASES) {
+ bench(`S2 vertices, no clip region — ${test.name}`, () => { pass(test.name, STAGE_VERTICES); });
+ bench(`S3 + open the region — ${test.name}`, () => { pass(test.name, STAGE_CLIP_START); });
+ bench(`S4 + cut the triangles — ${test.name}`, () => { pass(test.name, STAGE_CLIP); });
+ bench(`S5 + store the result — ${test.name}`, () => { pass(test.name, STAGE_EMIT); });
+ }
+});
diff --git a/sdk/benchmarks/spine-extract-stages.bench.ts b/sdk/benchmarks/spine-extract-stages.bench.ts
index 1e72b0234..09254bd0d 100644
--- a/sdk/benchmarks/spine-extract-stages.bench.ts
+++ b/sdk/benchmarks/spine-extract-stages.bench.ts
@@ -15,7 +15,7 @@
* has no stage check and no counter in it. Every depth costs exactly
* one crossing per instance, so the boundary cancels in the differences.
*
- * S4c minus S4 is the storage, and it was never the reallocation:
+ * S5c minus S5 is the storage, and it was never the reallocation:
* making the slots outlive the frame drove that to zero and moved this
* number by nothing. It was the per-element writing — eight pushes per
* vertex, three thousand per skeleton — and appending in blocks instead
@@ -87,7 +87,8 @@ describe.skipIf(!HAS_ASSETS)(`Spine extraction stages: ${ENTITIES} entities x${F
bench('S0 setup (the crossing and the instance lookup)', () => { pass(0, 0); });
bench('S1 + draw-order traversal', () => { pass(1, 0); });
bench('S2 + world vertices and tint', () => { pass(2, 0); });
- bench('S3 + clipping', () => { pass(3, 0); });
- bench('S4 + emit, counted and dropped', () => { pass(4, 0); });
- bench('S4c + emit into the frame\'s batch vectors', () => { pass(4, 1); });
+ bench('S3 + open the clip regions', () => { pass(3, 0); });
+ bench('S4 + cut the triangles', () => { pass(4, 0); });
+ bench('S5 + emit, counted and dropped', () => { pass(5, 0); });
+ bench('S5c + emit into the frame\'s batch vectors', () => { pass(5, 1); });
});
diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.ts
index 944ef7a4b..dcf5f8f1a 100644
--- a/sdk/src/spine/SpineModuleLoader.ts
+++ b/sdk/src/spine/SpineModuleLoader.ts
@@ -60,6 +60,7 @@ export interface SpineWasmModule {
_spine_setPathConstraintMix(instanceId: number, name: number, position: number, spacing: number, rotate: number, x: number, y: number): number;
_spine_probe_extract(instanceId: number, stage: number, useCollector: number): number;
_spine_probe_counts(out: number): void;
+ _spine_probe_clip_storage(out: number): void;
_spine_probe_storage(out: number): void;
_spine_probe_pose(instanceId: number, dt: number, stage: number): number;
_spine_probe_pose_counts(out: number): void;
@@ -129,6 +130,7 @@ export interface SpineWrappedAPI {
*/
probeExtract(instanceId: number, stage: number, useCollector: number): number;
probeCounts(out: number): void;
+ probeClipStorage(out: number): void;
probeStorage(out: number): void;
probePose(instanceId: number, dt: number, stage: number): number;
probePoseCounts(out: number): void;
@@ -183,6 +185,7 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {
probeExtract: cw('spine_probe_extract', 'number', ['number', 'number', 'number']) as SpineWrappedAPI['probeExtract'],
probeCounts: cw('spine_probe_counts', null, ['number']) as SpineWrappedAPI['probeCounts'],
+ probeClipStorage: cw('spine_probe_clip_storage', null, ['number']) as SpineWrappedAPI['probeClipStorage'],
probeStorage: cw('spine_probe_storage', null, ['number']) as SpineWrappedAPI['probeStorage'],
probePose: cw('spine_probe_pose', 'number', ['number', 'number', 'number']) as SpineWrappedAPI['probePose'],
probePoseCounts: cw('spine_probe_pose_counts', null, ['number']) as SpineWrappedAPI['probePoseCounts'],
diff --git a/sdk/tests/helpers/syntheticSpine.ts b/sdk/tests/helpers/syntheticSpine.ts
new file mode 100644
index 000000000..a8923545c
--- /dev/null
+++ b/sdk/tests/helpers/syntheticSpine.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file syntheticSpine.ts
+ * @brief Spine skeletons authored to hold one thing constant and vary another.
+ *
+ * @details Clipping cost cannot be read off shipped assets: coin's clip polygon
+ * has 39 vertices around 20 generated vertices, so every axis moves at
+ * once. These build a skeleton with a chosen number of input triangles
+ * and a chosen clip polygon, and place the two so that a KNOWN share of
+ * the triangles fall inside, outside, or across the boundary.
+ *
+ * The mesh is one row of quads, which is what makes the share
+ * controllable: a rectangle that spans the row but not its height
+ * crosses every quad, one that ends midway crosses one.
+ */
+
+/** A 3.8 skeleton and the atlas its attachments resolve against. */
+export interface SyntheticSkeleton {
+ json: string;
+ atlas: string;
+}
+
+/** Where the clip polygon sits relative to the strip of quads. */
+export type ClipRelation = 'inside' | 'outside' | 'one-crossing' | 'all-crossing';
+
+export interface SyntheticOptions {
+ /** Quads in the row; the mesh has twice this many triangles. */
+ quads: number;
+ relation: ClipRelation;
+ /** Vertices on the clip polygon. Ignored for the rectangle relations. */
+ polygonVertices?: number;
+ /** A star rather than a regular polygon — concave, so it decomposes. */
+ concave?: boolean;
+}
+
+const STRIP_WIDTH = 800;
+const STRIP_HEIGHT = 100;
+
+/** One row of quads spanning [-W/2, W/2] x [-H/2, H/2]. */
+function strip(quads: number): { vertices: number[]; uvs: number[]; triangles: number[]; hull: number } {
+ const vertices: number[] = [];
+ const uvs: number[] = [];
+ const triangles: number[] = [];
+ const step = STRIP_WIDTH / quads;
+ for (let i = 0; i <= quads; i++) {
+ const x = -STRIP_WIDTH / 2 + i * step;
+ vertices.push(x, -STRIP_HEIGHT / 2, x, STRIP_HEIGHT / 2);
+ uvs.push(i / quads, 1, i / quads, 0);
+ }
+ for (let i = 0; i < quads; i++) {
+ const a = i * 2;
+ triangles.push(a, a + 1, a + 3, a, a + 3, a + 2);
+ }
+ return { vertices, uvs, triangles, hull: (quads + 1) * 2 };
+}
+
+/** A closed polygon, counter-clockwise; a star alternates two radii. */
+function polygon(vertexCount: number, radius: number, concave: boolean): number[] {
+ const out: number[] = [];
+ for (let i = 0; i < vertexCount; i++) {
+ const angle = (i / vertexCount) * Math.PI * 2;
+ const r = concave && i % 2 === 1 ? radius * 0.4 : radius;
+ out.push(Math.cos(angle) * r, Math.sin(angle) * r);
+ }
+ return out;
+}
+
+/**
+ * The clip polygon for a relation. The rectangles are the point: they put a
+ * known number of quads across the boundary rather than however many a circle's
+ * circumference happens to touch.
+ */
+function clipShape(options: SyntheticOptions): number[] {
+ const { relation } = options;
+ if (options.polygonVertices !== undefined) {
+ // The polygon axis: same relation for every vertex count — a shape that
+ // covers the strip's width and cuts through its height.
+ return polygon(options.polygonVertices, STRIP_WIDTH, options.concave ?? false)
+ .map((v, i) => (i % 2 === 1 ? v * (STRIP_HEIGHT / 4 / STRIP_WIDTH) : v));
+ }
+ const halfW = STRIP_WIDTH / 2;
+ const halfH = STRIP_HEIGHT / 2;
+ switch (relation) {
+ case 'inside':
+ return [-halfW * 4, -halfH * 4, halfW * 4, -halfH * 4, halfW * 4, halfH * 4, -halfW * 4, halfH * 4];
+ case 'outside':
+ return [-halfW, halfH * 20, halfW, halfH * 20, halfW, halfH * 40, -halfW, halfH * 40];
+ case 'one-crossing':
+ // Ends inside the middle quad, and is tall enough to clear the strip.
+ return [-halfW * 4, -halfH * 4, 0.5, -halfH * 4, 0.5, halfH * 4, -halfW * 4, halfH * 4];
+ case 'all-crossing':
+ // Spans the whole row but only its middle band, so every quad is cut.
+ return [-halfW * 4, -halfH / 2, halfW * 4, -halfH / 2, halfW * 4, halfH / 2, -halfW * 4, halfH / 2];
+ }
+}
+
+/** A skeleton whose only slots are one clip region and one mesh inside it. */
+export function syntheticSkeleton(options: SyntheticOptions): SyntheticSkeleton {
+ const mesh = strip(options.quads);
+ const clip = clipShape(options);
+ const json = {
+ skeleton: { spine: '3.8.55', hash: 'synthetic', width: STRIP_WIDTH, height: STRIP_HEIGHT },
+ bones: [{ name: 'root' }],
+ slots: [
+ { name: 'clip', bone: 'root', attachment: 'clip' },
+ { name: 'mesh', bone: 'root', attachment: 'mesh' },
+ ],
+ skins: [{
+ name: 'default',
+ attachments: {
+ clip: {
+ clip: { type: 'clipping', end: 'mesh', vertexCount: clip.length / 2, vertices: clip },
+ },
+ mesh: {
+ mesh: {
+ type: 'mesh', path: 'white',
+ uvs: mesh.uvs, triangles: mesh.triangles, vertices: mesh.vertices,
+ hull: mesh.hull, width: STRIP_WIDTH, height: STRIP_HEIGHT,
+ },
+ },
+ },
+ }],
+ animations: { idle: {} },
+ };
+ return { json: JSON.stringify(json), atlas: ATLAS };
+}
+
+const ATLAS = `
+synthetic.png
+size: 64,64
+format: RGBA8888
+filter: Linear,Linear
+repeat: none
+white
+ rotate: false
+ xy: 0, 0
+ size: 64, 64
+ orig: 64, 64
+ offset: 0, 0
+ index: -1
+`;
diff --git a/sdk/tests/spine-clip-stages.test.ts b/sdk/tests/spine-clip-stages.test.ts
new file mode 100644
index 000000000..ce62d3c5e
--- /dev/null
+++ b/sdk/tests/spine-clip-stages.test.ts
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-clip-stages.test.ts
+ * @brief The synthetic clip fixtures are the geometry they claim to be.
+ *
+ * @details A cost model built on "few triangles cross" is worth nothing if the
+ * fixture that was supposed to make few triangles cross made all of
+ * them. Each relation is held here to what the clipper reports it did,
+ * and the counters that model is fitted from are held to the shapes
+ * they count.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { WASM_DIR } from './helpers/loadWasm';
+import { wrapSpineModule } from '../src/spine/SpineModuleLoader';
+import type { SpineWasmModule, SpineWrappedAPI } from '../src/spine/SpineModuleLoader';
+import { withScratch } from '../src/wasm/wasmScratch';
+import { syntheticSkeleton } from './helpers/syntheticSpine';
+import type { SyntheticOptions } from './helpers/syntheticSpine';
+
+const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');
+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');
+const HAS_WASM = existsSync(SPINE38_WASM);
+
+/** The thirteen counters `spine_probe_counts` writes, in order. */
+const COUNTERS = [
+ 'slots', 'regionAttachments', 'meshAttachments', 'clipStarts', 'clippedEmits',
+ 'verticesGenerated', 'verticesEmitted', 'indicesEmitted', 'emits',
+ 'clipPolygons', 'clipPolygonVertices', 'clipPolygonEdges', 'clipInputTriangles', 'clipOutputTriangles',
+] as const;
+type Counts = Record<(typeof COUNTERS)[number], number>;
+const STAGE_EMIT = 5;
+const QUADS = 16;
+
+let raw: SpineWasmModule;
+let api: SpineWrappedAPI;
+
+beforeAll(async () => {
+ if (!HAS_WASM) return;
+ const factory = (await import(SPINE38_JS)).default as (opts: unknown) => Promise<SpineWasmModule>;
+ const bytes = readFileSync(SPINE38_WASM);
+ raw = await factory({
+ instantiateWasm(imports: WebAssembly.Imports, cb: (i: WebAssembly.Instance, m: WebAssembly.Module) => void) {
+ void WebAssembly.instantiate(bytes, imports).then((r) => cb(r.instance, r.module));
+ return {};
+ },
+ });
+ api = wrapSpineModule(raw);
+});
+
+function instanceOf(options: SyntheticOptions): number {
+ const { json, atlas } = syntheticSkeleton(options);
+ const skelData = new TextEncoder().encode(json);
+ const handle = withScratch(raw, (alloc) => {
+ const ptr = alloc(skelData.length);
+ raw.HEAPU8.set(skelData, ptr);
+ return api.loadSkeleton(ptr, skelData.length, atlas, atlas.length, false);
+ });
+ if (handle < 0) throw new Error(api.getLastError());
+ for (let i = 0, pages = api.getAtlasPageCount(handle); i < pages; i++) {
+ api.setAtlasPageTexture(handle, i, 1, 64, 64);
+ }
+ const instanceId = api.createInstance(handle);
+ api.update(instanceId, 0);
+ return instanceId;
+}
+
+function countsOf(instanceId: number): Counts {
+ api.probeExtract(instanceId, STAGE_EMIT, 1);
+ return withScratch(raw, (alloc) => {
+ const ptr = alloc(COUNTERS.length * 4);
+ api.probeCounts(ptr);
+ const out = {} as Counts;
+ COUNTERS.forEach((name, i) => { out[name] = raw.HEAPU32[(ptr >> 2) + i]; });
+ return out;
+ });
+}
+
+describe.skipIf(!HAS_WASM)('the synthetic clip fixtures are what they claim', () => {
+ it('a strip of quads is the triangles it says it is', () => {
+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'inside' }));
+ expect(c.meshAttachments).toBe(1);
+ expect(c.clipStarts).toBe(1);
+ expect(c.clipInputTriangles, 'a quad is two triangles').toBe(QUADS * 2);
+ });
+
+ it('every quad inside the region survives whole', () => {
+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'inside' }));
+ expect(c.clipOutputTriangles, 'a triangle that crossed nothing was still cut')
+ .toBe(c.clipInputTriangles);
+ // But not untouched: the clipper rebuilds every triangle from its own
+ // three vertices, so a mesh that shared them does not any more. Being
+ // inside a clip region is not free — 34 vertices come back as 96.
+ expect(c.verticesEmitted).toBe(c.clipOutputTriangles * 3);
+ expect(c.verticesEmitted).toBeGreaterThan(c.verticesGenerated);
+ });
+
+ it('a region the strip is not in emits nothing at all', () => {
+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'outside' }));
+ expect(c.clipInputTriangles).toBe(QUADS * 2);
+ expect(c.clipOutputTriangles).toBe(0);
+ expect(c.emits, 'geometry that clipped away still reached the sink').toBe(0);
+ });
+
+ it('a boundary that ends inside one quad crosses only that one', () => {
+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'one-crossing' }));
+ // Half the strip survives whole; the quad the edge ends in comes back as
+ // a fan, so the total is a little over half the input.
+ expect(c.clipOutputTriangles).toBeGreaterThan(QUADS);
+ expect(c.clipOutputTriangles).toBeLessThan(QUADS * 2);
+ });
+
+ it('a band across the whole strip crosses every quad', () => {
+ const one = countsOf(instanceOf({ quads: QUADS, relation: 'one-crossing' }));
+ const all = countsOf(instanceOf({ quads: QUADS, relation: 'all-crossing' }));
+ expect(all.clipInputTriangles).toBe(one.clipInputTriangles);
+ // Every triangle is cut and re-triangulated, so this is the relation that
+ // amplifies: more output than went in, from the same input.
+ expect(all.clipOutputTriangles).toBeGreaterThan(all.clipInputTriangles);
+ expect(all.clipOutputTriangles).toBeGreaterThan(one.clipOutputTriangles);
+ });
+
+ it('a convex polygon is one piece and a concave one is several', () => {
+ const convex = countsOf(instanceOf({ quads: QUADS, relation: 'all-crossing', polygonVertices: 8 }));
+ const concave = countsOf(instanceOf({
+ quads: QUADS, relation: 'all-crossing', polygonVertices: 8, concave: true,
+ }));
+ expect(convex.clipPolygonVertices).toBe(8);
+ expect(concave.clipPolygonVertices).toBe(8);
+ expect(convex.clipPolygons, 'a convex polygon needed decomposing').toBe(1);
+ expect(concave.clipPolygons, 'a concave polygon came back as one piece').toBeGreaterThan(1);
+ });
+
+ it('the clipper stops growing its own scratch once a shape has run', () => {
+ const instanceId = instanceOf({ quads: QUADS, relation: 'all-crossing' });
+ const storage = () => withScratch(raw, (alloc) => {
+ const ptr = alloc(6 * 4);
+ api.probeClipStorage(ptr);
+ return Array.from({ length: 6 }, (_, i) => raw.HEAPU32[(ptr >> 2) + i]);
+ });
+ countsOf(instanceId);
+ const warm = storage();
+ expect(warm.some((c) => c > 0), 'the clipper reports no scratch at all').toBe(true);
+
+ for (let frame = 0; frame < 5; frame++) countsOf(instanceId);
+ expect(storage(), 'the clipper grew its scratch again on a steady shape').toEqual(warm);
+ });
+});
diff --git a/sdk/tests/spine-extract-stages.test.ts b/sdk/tests/spine-extract-stages.test.ts
index cfe92aa4a..1deb57f90 100644
--- a/sdk/tests/spine-extract-stages.test.ts
+++ b/sdk/tests/spine-extract-stages.test.ts
@@ -41,10 +41,12 @@ const HAS_ASSETS = existsSync(SPINE38_WASM)
const COUNTERS = [
'slots', 'regionAttachments', 'meshAttachments', 'clipStarts', 'clippedEmits',
'verticesGenerated', 'verticesEmitted', 'indicesEmitted', 'emits',
+ 'clipPolygons', 'clipPolygonVertices', 'clipPolygonEdges',
+ 'clipInputTriangles', 'clipOutputTriangles',
] as const;
type Counts = Record<(typeof COUNTERS)[number], number>;
-const STAGE_EMIT = 4;
+const STAGE_EMIT = 5;
let raw: SpineWasmModule;
let api: SpineWrappedAPI;
diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hpp
index f44288526..4360ba6d7 100644
--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp
+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp
@@ -86,9 +86,12 @@ size_t spine_eventBufferBytes();
// or counts and drops them: the one way to price the buffers apart from the work.
int spine_probe_extract(int instanceId, int stage, int useCollector);
-// The nine counters of the last probe run, into as many u32 slots.
+// The fourteen counters of the last probe run, into as many u32 slots.
void spine_probe_counts(uint32_t* out);
+// The clipper's own scratch capacities, into six u32 slots.
+void spine_probe_clip_storage(uint32_t* out);
+
// BENCHMARK ONLY — the pose run to `stage` (es::spine::PoseStage). This ADVANCES
// the instance: a caller measuring with it owns that instance's clock.
int spine_probe_pose(int instanceId, float dt, int stage);
diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
index 6a20ea644..21e189eea 100644
--- a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
+++ b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
@@ -289,7 +289,7 @@ int spine_probe_extract(int instanceId, int stage, int useCollector) {
stage, &g_probeCounts) ? 1 : 0;
}
-/** The counts of the last {@link spine_probe_extract}, into nine u32 slots. */
+/** The counts of the last {@link spine_probe_extract}, into fourteen u32 slots. */
EMSCRIPTEN_KEEPALIVE
void spine_probe_counts(std::uint32_t* out) {
if (!out) return;
@@ -302,6 +302,26 @@ void spine_probe_counts(std::uint32_t* out) {
out[6] = g_probeCounts.verticesEmitted;
out[7] = g_probeCounts.indicesEmitted;
out[8] = g_probeCounts.emits;
+ out[9] = g_probeCounts.clipPolygons;
+ out[10] = g_probeCounts.clipPolygonVertices;
+ out[11] = g_probeCounts.clipPolygonEdges;
+ out[12] = g_probeCounts.clipInputTriangles;
+ out[13] = g_probeCounts.clipOutputTriangles;
+}
+
+/** BENCHMARK ONLY — the clipper's own scratch, into six u32 slots. Zero where a
+ * backend keeps no clipper of its own. */
+EMSCRIPTEN_KEEPALIVE
+void spine_probe_clip_storage(std::uint32_t* out) {
+ if (!out) return;
+ es::spine::ClipStorage held{};
+ es::spine::clipStorage(&held);
+ out[0] = held.polygon;
+ out[1] = held.output;
+ out[2] = held.vertices;
+ out[3] = held.uvs;
+ out[4] = held.triangles;
+ out[5] = held.scratch;
}
/**
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
index 20a136e9b..a5d7eaa0d 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
@@ -220,11 +220,13 @@ void render(Instance* instance, TriangleSink& sink, bool clipping);
* stage costs is the difference between two runs — the only way to price a step
* of this walk without a clock inside it. */
enum RenderStage {
- STAGE_SETUP = 0, ///< The instance and the clipper; the loop does not run.
- STAGE_TRAVERSE = 1, ///< Walk the draw order, resolving what each slot holds.
- STAGE_VERTICES = 2, ///< …and compute world vertices and tint.
- STAGE_CLIP = 3, ///< …and clip them where a clip region is open.
- STAGE_EMIT = 4, ///< …and hand them to the sink. The full extraction.
+ STAGE_SETUP = 0, ///< The instance and the clipper; the loop does not run.
+ STAGE_TRAVERSE = 1, ///< Walk the draw order, resolving what each slot holds.
+ STAGE_VERTICES = 2, ///< …and compute world vertices and tint.
+ STAGE_CLIP_START = 3, ///< …and open each clip region: its polygon, made
+ ///< clockwise and decomposed into convex pieces.
+ STAGE_CLIP = 4, ///< …and cut the triangles against those pieces.
+ STAGE_EMIT = 5, ///< …and hand them to the sink. The full extraction.
};
/** What the walk did, so a time can be explained rather than only reported. */
@@ -238,8 +240,32 @@ struct ProbeCounts {
std::uint32_t verticesEmitted;
std::uint32_t indicesEmitted;
std::uint32_t emits;
+ /// Convex pieces the clip polygons decomposed into. One per clip region says
+ /// the polygon was convex; more is what a concave one costs before any
+ /// triangle is cut, and every piece re-runs the cut.
+ std::uint32_t clipPolygons;
+ std::uint32_t clipPolygonVertices;
+ /// Edges summed over those pieces — what a cut actually costs per triangle,
+ /// since the clip runs one pass per edge, per piece, per triangle.
+ std::uint32_t clipPolygonEdges;
+ std::uint32_t clipInputTriangles;
+ std::uint32_t clipOutputTriangles;
};
+/** BENCHMARK ONLY — the clipper's own scratch arrays, so a second storage
+ * problem inside it cannot hide behind the first one having been fixed. */
+struct ClipStorage {
+ std::uint32_t polygon;
+ std::uint32_t output;
+ std::uint32_t vertices;
+ std::uint32_t uvs;
+ std::uint32_t triangles;
+ std::uint32_t scratch;
+};
+
+/** False where a backend has no clipper of its own to report on. */
+bool clipStorage(ClipStorage* out);
+
/**
* BENCHMARK ONLY — the same walk as {@link render}, stopped at `stage`, so its
* cost can be decomposed without a clock inside the loop being decomposed.
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
index 70335a6d0..3286e59e0 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
@@ -557,6 +557,10 @@ bool poseStage(Instance*, float, int, PoseCounts*) {
return false;
}
+bool clipStorage(ClipStorage*) {
+ return false;
+}
+
int version() {
return ES_SPINE_VERSION;
}
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
index 0e36435b1..cf24a2091 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
@@ -655,7 +655,11 @@ void emit(TriangleSink& sink, bool clipping,
outUVs = g_clipper->clippedUVs->items;
outTriangles = g_clipper->clippedTriangles->items;
outTriangleCount = g_clipper->clippedTriangles->size;
- if constexpr (COUNT) counts->clippedEmits++;
+ if constexpr (COUNT) {
+ counts->clippedEmits++;
+ counts->clipInputTriangles += static_cast<std::uint32_t>(triangleCount / 3);
+ counts->clipOutputTriangles += static_cast<std::uint32_t>(outTriangleCount / 3);
+ }
}
if (outVertices == 0 || outTriangleCount == 0) return;
@@ -696,9 +700,18 @@ void renderImpl(Instance* instance, TriangleSink& sink, bool clipping, ProbeCoun
// draws nothing itself.
if (attachment && attachment->type == SP_ATTACHMENT_CLIPPING) {
if constexpr (COUNT) counts->clipStarts++;
- if (clipping && STAGE >= STAGE_CLIP) {
- spSkeletonClipping_clipStart(g_clipper, slot,
- reinterpret_cast<spClippingAttachment*>(attachment));
+ if (clipping && STAGE >= STAGE_CLIP_START) {
+ auto* clip = reinterpret_cast<spClippingAttachment*>(attachment);
+ const int pieces = spSkeletonClipping_clipStart(g_clipper, slot, clip);
+ if constexpr (COUNT) {
+ counts->clipPolygons += static_cast<std::uint32_t>(pieces);
+ counts->clipPolygonVertices +=
+ static_cast<std::uint32_t>(clip->super.worldVerticesLength / 2);
+ for (int p = 0; p < g_clipper->clippingPolygons->size; ++p) {
+ counts->clipPolygonEdges +=
+ static_cast<std::uint32_t>(g_clipper->clippingPolygons->items[p]->size / 2);
+ }
+ }
}
continue;
}
@@ -788,10 +801,21 @@ void renderImpl(Instance* instance, TriangleSink& sink, bool clipping, ProbeCoun
// Closes the region when this slot is the clip's end slot; a cheap no-op
// otherwise, which is why every non-clip slot passes through here.
- if (clipping && STAGE >= STAGE_CLIP) spSkeletonClipping_clipEnd(g_clipper, slot);
+ if (clipping && STAGE >= STAGE_CLIP_START) spSkeletonClipping_clipEnd(g_clipper, slot);
}
- if (clipping && STAGE >= STAGE_CLIP) spSkeletonClipping_clipEnd2(g_clipper);
+ if (clipping && STAGE >= STAGE_CLIP_START) spSkeletonClipping_clipEnd2(g_clipper);
+}
+
+bool clipStorage(ClipStorage* out) {
+ if (!out || !g_clipper) return false;
+ out->polygon = static_cast<std::uint32_t>(g_clipper->clippingPolygon->capacity);
+ out->output = static_cast<std::uint32_t>(g_clipper->clipOutput->capacity);
+ out->vertices = static_cast<std::uint32_t>(g_clipper->clippedVertices->capacity);
+ out->uvs = static_cast<std::uint32_t>(g_clipper->clippedUVs->capacity);
+ out->triangles = static_cast<std::uint32_t>(g_clipper->clippedTriangles->capacity);
+ out->scratch = static_cast<std::uint32_t>(g_clipper->scratch->capacity);
+ return true;
}
void render(Instance* instance, TriangleSink& sink, bool clipping) {
@@ -804,6 +828,7 @@ bool renderStage(Instance* instance, TriangleSink& sink, bool clipping,
case STAGE_SETUP: renderImpl<STAGE_SETUP, true>(instance, sink, clipping, counts); break;
case STAGE_TRAVERSE: renderImpl<STAGE_TRAVERSE, true>(instance, sink, clipping, counts); break;
case STAGE_VERTICES: renderImpl<STAGE_VERTICES, true>(instance, sink, clipping, counts); break;
+ case STAGE_CLIP_START: renderImpl<STAGE_CLIP_START, true>(instance, sink, clipping, counts); break;
case STAGE_CLIP: renderImpl<STAGE_CLIP, true>(instance, sink, clipping, counts); break;
case STAGE_EMIT: renderImpl<STAGE_EMIT, true>(instance, sink, clipping, counts); break;
default: return false;
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
index a47552b08..2db490887 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
@@ -538,6 +538,10 @@ bool poseStage(Instance*, float, int, PoseCounts*) {
return false;
}
+bool clipStorage(ClipStorage*) {
+ return false;
+}
+
int version() {
return ES_SPINE_VERSION;
}