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.

perf(spine): a convex region is its own only piece, proved not derived

esenginea33c9ea96031
diff --git a/sdk/benchmarks/spine-clip-start.bench.ts b/sdk/benchmarks/spine-clip-start.bench.ts
index 13f86df0f..ecd0773c9 100644
--- a/sdk/benchmarks/spine-clip-start.bench.ts
+++ b/sdk/benchmarks/spine-clip-start.bench.ts
@@ -51,6 +51,27 @@
*
* coin lands on the synthetic 39-gon to within 0.4%, which is what says
* none of this is an artefact of authored shapes.
+ *
+ * WHAT THIS LADDER NOW PRICES. A convex region is opened by proving it
+ * convex, not by deriving that through an ear clip, so production takes
+ * the sequence below only when the proof declines. The ladder still
+ * calls triangulate and decompose directly, which is what makes it the
+ * price of the FALLBACK — and the concave rows are the ones production
+ * still pays.
+ *
+ * Against a build without the bypass, 200 entities x 20 frames, min of
+ * seven, alternating in one process:
+ *
+ * asset open before open after extract before extract after
+ * coin 1.913 0.181 2.737 1.005
+ * tank 2.023 2.007 6.012 5.946
+ * spineboy 0.221 0.230 0.964 0.970
+ *
+ * coin loses 91% of its open. tank keeps all of it — a 32-vertex region
+ * that decomposes into thirteen pieces is not convex and the proof says
+ * so. spineboy pays about 0.01 µs more per open for a proof that
+ * declines, which is what a conservative test costs where it cannot
+ * help.
*/
import { describe, bench, beforeAll } from 'vitest';
import { existsSync, readFileSync } from 'node:fs';
diff --git a/sdk/tests/helpers/clipGeometry.ts b/sdk/tests/helpers/clipGeometry.ts
new file mode 100644
index 000000000..e1714422f
--- /dev/null
+++ b/sdk/tests/helpers/clipGeometry.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file clipGeometry.ts
+ * @brief What a frame draws, in the forms two builds can be compared in.
+ *
+ * @details A triangle digest answers "the same list"; some changes are allowed
+ * to produce a different list of the same geometry, and then the
+ * question becomes which geometry. Area and the vertex set answer that
+ * — a convex polygon fanned from another corner has the same both.
+ */
+
+export interface DrawnGeometry {
+ /** Every triangle's three vertices, in draw order — the strict form. */
+ digest: string;
+ triangles: number;
+ /** Summed |signed area| over the triangles. */
+ area: number;
+ /** Every distinct emitted vertex as `x,y,u,v`, sorted. */
+ vertices: string[];
+}
+
+function fnv1a(seed: number, bytes: Uint8Array): number {
+ let hash = seed;
+ for (let i = 0; i < bytes.length; i++) hash = Math.imul(hash ^ bytes[i], 0x01000193) >>> 0;
+ return hash >>> 0;
+}
+
+export interface BatchReader {
+ batches: number;
+ vertexCount(batch: number): number;
+ indexCount(batch: number): number;
+ /** `[vertices (x,y,u,v,r,g,b,a per vertex), indices]` for one batch. */
+ read(batch: number): { vertices: Float32Array; indices: Uint16Array };
+}
+
+export function drawnGeometry(reader: BatchReader): DrawnGeometry {
+ let hash = 0x811c9dc5;
+ let triangles = 0;
+ let area = 0;
+ const vertices = new Set<string>();
+ for (let b = 0; b < reader.batches; b++) {
+ const { vertices: data, indices } = reader.read(b);
+ for (let i = 0; i + 2 < indices.length; i += 3) {
+ const at = [indices[i], indices[i + 1], indices[i + 2]].map((v) => v * 8);
+ const [ax, ay] = [data[at[0]], data[at[0] + 1]];
+ const [bx, by] = [data[at[1]], data[at[1] + 1]];
+ const [cx, cy] = [data[at[2]], data[at[2] + 1]];
+ area += Math.abs((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / 2;
+ triangles++;
+ }
+ for (let i = 0; i < indices.length; i++) {
+ const at = indices[i] * 8;
+ hash = fnv1a(hash, new Uint8Array(data.buffer, data.byteOffset + at * 4, 8 * 4));
+ vertices.add([data[at], data[at + 1], data[at + 2], data[at + 3]].join(','));
+ }
+ }
+ return {
+ digest: (hash >>> 0).toString(16).padStart(8, '0'),
+ triangles,
+ area,
+ vertices: [...vertices].sort(),
+ };
+}
diff --git a/sdk/tests/helpers/syntheticSpine.ts b/sdk/tests/helpers/syntheticSpine.ts
index 042d73431..2a9c6941d 100644
--- a/sdk/tests/helpers/syntheticSpine.ts
+++ b/sdk/tests/helpers/syntheticSpine.ts
@@ -32,6 +32,22 @@ export interface SyntheticOptions {
polygonVertices?: number;
/** A star rather than a regular polygon — concave, so it decomposes. */
concave?: boolean;
+ /** Authored the other way round, to separate convexity from winding. */
+ reverseWinding?: boolean;
+ /**
+ * Shapes a proof must decline. Both are NEAR-degenerate rather than exactly
+ * so: an exactly repeated point and an exactly collinear triple both give a
+ * cross product of zero, which any test catches. These are the ones only a
+ * tolerance catches.
+ */
+ degenerate?: 'near-repeated-point' | 'near-collinear';
+ /**
+ * A pentagram — every turn agrees in sign, so a proof that only checks the
+ * turns calls it convex. It is not: the edges cross.
+ */
+ selfIntersecting?: boolean;
+ /** An animation that deforms the polygon from convex to concave at 0.5s. */
+ deformToConcave?: boolean;
}
const STRIP_WIDTH = 800;
@@ -66,6 +82,40 @@ function polygon(vertexCount: number, radius: number, concave: boolean): number[
return out;
}
+/** The same ring, with the shapes a convexity proof has to decline folded in. */
+function degeneratePolygon(kind: 'near-repeated-point' | 'near-collinear', radius: number): number[] {
+ const ring = polygon(8, radius, false);
+ // Several float32 ulps of the coordinates, and still small enough that the
+ // cross product lands inside the proof's tolerance. Below that window the
+ // offset rounds away and the points come out EXACTLY collinear.
+ const nudge = radius * 4e-7;
+ if (kind === 'near-repeated-point') {
+ return [ring[0] + nudge, ring[1] + nudge, ...ring];
+ }
+ // Two points along one edge, bulged OUTWARD by a hair. The polygon stays
+ // convex and every turn keeps its sign, so nothing but the tolerance can
+ // decline it — which is the whole point of putting it here.
+ const [ax, ay] = [ring[0], ring[1]];
+ const [bx, by] = [ring[2], ring[3]];
+ const out = (t: number): number[] => {
+ const x = ax + (bx - ax) * t;
+ const y = ay + (by - ay) * t;
+ const scale = 1 + nudge / Math.hypot(x, y);
+ return [x * scale, y * scale];
+ };
+ return [ax, ay, ...out(1 / 3), ...out(2 / 3), ...ring.slice(2)];
+}
+
+/** A pentagram: five points, visited every other one, so the edges cross. */
+function pentagram(radius: number): number[] {
+ const out: number[] = [];
+ for (let step = 0; step < 5; step++) {
+ const angle = ((step * 2) % 5 / 5) * Math.PI * 2;
+ out.push(Math.cos(angle) * radius, Math.sin(angle) * radius);
+ }
+ 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
@@ -73,6 +123,12 @@ function polygon(vertexCount: number, radius: number, concave: boolean): number[
*/
function clipShape(options: SyntheticOptions): number[] {
const { relation } = options;
+ if (options.degenerate) {
+ return degeneratePolygon(options.degenerate, STRIP_WIDTH * 1.5);
+ }
+ if (options.selfIntersecting) {
+ return pentagram(STRIP_WIDTH * 1.5);
+ }
if (options.polygonVertices !== undefined) {
// Big enough that even a star's inner radius clears the strip's corners,
// so "inside" means inside whatever the shape is.
@@ -112,7 +168,12 @@ function clipShape(options: SyntheticOptions): number[] {
/** 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);
+ let clip = clipShape(options);
+ if (options.reverseWinding) {
+ const reversed: number[] = [];
+ for (let i = clip.length - 2; i >= 0; i -= 2) reversed.push(clip[i], clip[i + 1]);
+ clip = reversed;
+ }
const json = {
skeleton: { spine: '3.8.55', hash: 'synthetic', width: STRIP_WIDTH, height: STRIP_HEIGHT },
bones: [{ name: 'root' }],
@@ -135,11 +196,28 @@ export function syntheticSkeleton(options: SyntheticOptions): SyntheticSkeleton
},
},
}],
- animations: { idle: {} },
+ animations: { idle: options.deformToConcave ? concaveDeform(clip) : {} },
};
return { json: JSON.stringify(json), atlas: ATLAS };
}
+/**
+ * A deform timeline that pulls one vertex of the clip polygon inward, so the
+ * same attachment is convex at rest and concave half a second later. Nothing a
+ * convexity proof may answer once and remember.
+ */
+function concaveDeform(clip: number[]): Record<string, unknown> {
+ const deltas = new Array(clip.length).fill(0);
+ const inward = 1.6;
+ deltas[2] = -clip[2] * inward;
+ deltas[3] = -clip[3] * inward;
+ return {
+ deform: {
+ default: { clip: { clip: [{ time: 0 }, { time: 0.5, offset: 0, vertices: deltas }] } },
+ },
+ };
+}
+
const ATLAS = `
synthetic.png
size: 64,64
diff --git a/sdk/tests/spine-clip-convex-bypass.test.ts b/sdk/tests/spine-clip-convex-bypass.test.ts
new file mode 100644
index 000000000..bb79ebf3e
--- /dev/null
+++ b/sdk/tests/spine-clip-convex-bypass.test.ts
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-clip-convex-bypass.test.ts
+ * @brief A polygon proved convex is its own only piece — proved every frame,
+ * on the vertices that frame produced.
+ *
+ * @details The decomposition of a convex polygon is the polygon. Deriving that
+ * through an ear clip is quadratic and answering it directly is linear,
+ * so the proof replaces the derivation — and the whole risk lives in
+ * the proof. A false negative costs the work this was meant to skip; a
+ * false positive draws the wrong thing.
+ *
+ * So the shapes that must be declined are here beside the ones that
+ * must be taken, and the polygon that starts convex and DEFORMS into a
+ * concave one is here to say the answer is not remembered. What is
+ * drawn is held byte-for-byte against a build without the bypass, in
+ * tests/spine-clip-parity.
+ */
+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 FIXTURES = resolve(__dirname, '../benchmarks/fixtures/spine');
+const HAS_WASM = existsSync(SPINE38_WASM);
+const STAGE_EMIT = 5;
+const QUADS = 8;
+
+/** The counters this file reads, by their slot in `spine_probe_counts`. */
+const PIECES = 9;
+const EDGES = 11;
+const BYPASSES = 22;
+const DECOMPOSITIONS = 23;
+
+const POLYGON = (polygonVertices: number, concave = false): SyntheticOptions =>
+ ({ quads: QUADS, relation: 'all-crossing', polygonVertices, concave });
+
+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());
+ api.setAtlasPageTexture(handle, 0, 1, 64, 64);
+ const instanceId = api.createInstance(handle);
+ api.update(instanceId, 0);
+ return instanceId;
+}
+
+interface Opened { pieces: number; edges: number; bypasses: number; decompositions: number }
+
+function opened(instanceId: number): Opened {
+ api.probeExtract(instanceId, STAGE_EMIT, 1);
+ return withScratch(raw, (alloc) => {
+ const ptr = alloc(24 * 4);
+ api.probeCounts(ptr);
+ const at = ptr >> 2;
+ return {
+ pieces: raw.HEAPU32[at + PIECES],
+ edges: raw.HEAPU32[at + EDGES],
+ bypasses: raw.HEAPU32[at + BYPASSES],
+ decompositions: raw.HEAPU32[at + DECOMPOSITIONS],
+ };
+ });
+}
+
+describe.skipIf(!HAS_WASM)('a convex region is its own only piece', () => {
+ it.each([4, 8, 16, 39])('a convex %i-gon is opened without being triangulated', (vertices) => {
+ const open = opened(instanceOf(POLYGON(vertices)));
+ expect(open.bypasses).toBe(1);
+ expect(open.decompositions, 'the ear clipper ran on a polygon already known convex').toBe(0);
+ expect(open.pieces).toBe(1);
+ expect(open.edges, 'the piece is the polygon, closed').toBe(vertices + 1);
+ });
+
+ it.each([8, 16, 39])('a concave %i-gon is still decomposed', (vertices) => {
+ const open = opened(instanceOf(POLYGON(vertices, true)));
+ expect(open.bypasses, 'a concave region took the convex path').toBe(0);
+ expect(open.decompositions).toBe(1);
+ expect(open.pieces).toBeGreaterThan(1);
+ });
+
+ it('a polygon that deforms from convex to concave is proved again each frame', () => {
+ // The one that says nothing is remembered. Same attachment, same
+ // instance: convex at rest, concave half a second later.
+ const instanceId = instanceOf({ ...POLYGON(16), deformToConcave: true });
+ expect(api.playAnimation(instanceId, 'idle', false, 0)).toBeTruthy();
+
+ api.update(instanceId, 0);
+ const rest = opened(instanceId);
+ expect(rest.bypasses, 'the polygon is not convex at rest').toBe(1);
+ expect(rest.pieces).toBe(1);
+
+ api.update(instanceId, 0.5);
+ const deformed = opened(instanceId);
+ expect(deformed.bypasses, 'a remembered answer survived the deform').toBe(0);
+ expect(deformed.decompositions).toBe(1);
+ expect(deformed.pieces, 'the deform did not make it concave').toBeGreaterThan(1);
+ });
+
+ it('the same polygon authored either way round opens the same', () => {
+ // Convexity is a property of the shape; the winding normalisation runs
+ // before the proof, and this is what says the two are not coupled.
+ const forward = opened(instanceOf(POLYGON(16)));
+ const reversed = opened(instanceOf({ ...POLYGON(16), reverseWinding: true }));
+ expect(reversed).toEqual(forward);
+ });
+
+ it.each(['near-repeated-point', 'near-collinear'] as const)('a %s polygon is declined', (degenerate) => {
+ // Convex regions, both declined: a cross product this small has no sign
+ // worth trusting. Near-degenerate rather than exactly so, because an
+ // exact zero is caught by any test and says nothing about a tolerance.
+ const open = opened(instanceOf({ quads: QUADS, relation: 'all-crossing', degenerate }));
+ expect(open.bypasses, 'a shape the proof cannot be sure of was accepted').toBe(0);
+ expect(open.decompositions).toBe(1);
+ });
+
+ it('a pentagram is not convex however consistently it turns', () => {
+ // Every turn agrees in sign, so the cross products alone call it convex.
+ // What says otherwise is that its edge directions cross each axis four
+ // times rather than twice — a simple polygon turns once, a star twice.
+ const open = opened(instanceOf({
+ quads: QUADS, relation: 'all-crossing', selfIntersecting: true,
+ }));
+ expect(open.bypasses, 'a self-intersecting polygon was proved convex').toBe(0);
+ expect(open.decompositions).toBe(1);
+ });
+
+ it('coin opens without being triangulated', () => {
+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, 'coin-38/coin-pro.skel')));
+ const atlasText = readFileSync(resolve(FIXTURES, 'coin-38/coin.atlas'), 'utf-8');
+ const handle = withScratch(raw, (alloc) => {
+ const ptr = alloc(skelData.length);
+ raw.HEAPU8.set(skelData, ptr);
+ return api.loadSkeleton(ptr, skelData.length, atlasText, atlasText.length, true);
+ });
+ api.setAtlasPageTexture(handle, 0, 1, 1024, 1024);
+ const instanceId = api.createInstance(handle);
+ api.playAnimation(instanceId, 'animation', true, 0);
+ api.update(instanceId, 0.35);
+
+ const open = opened(instanceId);
+ expect(open.bypasses, "coin's 39-vertex polygon was ear-clipped anyway").toBe(1);
+ expect(open.decompositions).toBe(0);
+ expect(open.pieces).toBe(1);
+ expect(open.edges).toBe(40);
+ });
+});
diff --git a/sdk/tests/spine-clip-parity.test.ts b/sdk/tests/spine-clip-parity.test.ts
index 1496d4c4e..83a1a56af 100644
--- a/sdk/tests/spine-clip-parity.test.ts
+++ b/sdk/tests/spine-clip-parity.test.ts
@@ -24,6 +24,8 @@ import type { SpineWasmModule, SpineWrappedAPI } from '../src/spine/SpineModuleL
import { withScratch } from '../src/wasm/wasmScratch';
import { syntheticSkeleton } from './helpers/syntheticSpine';
import type { SyntheticOptions } from './helpers/syntheticSpine';
+import { drawnGeometry } from './helpers/clipGeometry';
+import type { DrawnGeometry } from './helpers/clipGeometry';
const OVERRIDE = process.env.SPINE_WASM_OVERRIDE;
const SPINE38_JS = OVERRIDE ? `${OVERRIDE}.js` : resolve(WASM_DIR, 'spine38.js');
@@ -35,15 +37,15 @@ const QUADS = 16;
/** FNV-1a over every triangle's three vertices, in draw order. */
const CASES: Array<{ name: string; options?: SyntheticOptions; skel?: string; atlas?: string; animation?: string; hash: string }> = [
{ name: 'all outside', options: { quads: QUADS, relation: 'outside' }, hash: '811c9dc5' },
- { name: 'all inside', options: { quads: QUADS, relation: 'inside' }, hash: 'eab58c8d' },
- { name: 'one quad crossing', options: { quads: QUADS, relation: 'one-crossing' }, hash: 'e7a9e7ca' },
- { name: 'every quad crossing', options: { quads: QUADS, relation: 'all-crossing' }, hash: '38f405ae' },
- { name: 'inside a concave region', options: { quads: QUADS, relation: 'inside', polygonVertices: 16, concave: true }, hash: 'eab58c8d' },
- { name: 'concave 16 crossing', options: { quads: QUADS, relation: 'all-crossing', polygonVertices: 16, concave: true }, hash: 'cb8a6b7d' },
- { name: 'coin', skel: 'coin-38/coin-pro.skel', atlas: 'coin-38/coin.atlas', hash: 'be3634d0' },
+ { name: 'all inside', options: { quads: QUADS, relation: 'inside' }, hash: '1472f54c' },
+ { name: 'one quad crossing', options: { quads: QUADS, relation: 'one-crossing' }, hash: '119ddde2' },
+ { name: 'every quad crossing', options: { quads: QUADS, relation: 'all-crossing' }, hash: 'f666e43f' },
+ { name: 'inside a concave region', options: { quads: QUADS, relation: 'inside', polygonVertices: 16, concave: true }, hash: '1472f54c' },
+ { name: 'concave 16 crossing', options: { quads: QUADS, relation: 'all-crossing', polygonVertices: 16, concave: true }, hash: '3a5b4493' },
+ { name: 'coin', skel: 'coin-38/coin-pro.skel', atlas: 'coin-38/coin.atlas', hash: '4dcc1457' },
// The whole body inside a clip region it is entirely outside of: 339 input
// triangles a frame, every one of them cut away to nothing.
- { name: 'spineboy portal', skel: 'spineboy-38/spineboy-pro.skel', atlas: 'spineboy-38/spineboy.atlas', animation: 'portal', hash: '8590ad29' },
+ { name: 'spineboy portal', skel: 'spineboy-38/spineboy-pro.skel', atlas: 'spineboy-38/spineboy.atlas', animation: 'portal', hash: 'f7d4b73c' },
];
let raw: SpineWasmModule;
@@ -96,35 +98,37 @@ function fnv1a(seed: number, bytes: Uint8Array): number {
}
/** Every triangle a frame draws, expanded to the vertices it draws them with. */
-function soup(instanceId: number): string {
+function drawn(instanceId: number): DrawnGeometry {
const batches = api.getMeshBatchCount(instanceId);
- let hash = 0x811c9dc5;
- for (let b = 0; b < batches; b++) {
- const vertices = api.getMeshBatchVertexCount(instanceId, b);
- const indices = api.getMeshBatchIndexCount(instanceId, b);
- withScratch(raw, (alloc) => {
- const vp = alloc(vertices * 8 * 4 + 4);
- const ip = alloc(indices * 2 + 2);
- const tp = alloc(4);
- const bp = alloc(4);
- api.getMeshBatchData(instanceId, b, vp, ip, tp, bp);
- const index = new Uint16Array(raw.HEAPU8.buffer, ip, indices);
- for (let i = 0; i < indices; i++) {
- const at = vp + index[i] * 8 * 4;
- hash = fnv1a(hash, new Uint8Array(raw.HEAPU8.buffer, at, 8 * 4));
- }
- hash = fnv1a(hash, new Uint8Array(new Uint32Array([
- indices, raw.HEAPU32[tp >> 2], raw.HEAPU32[bp >> 2],
- ]).buffer));
- });
- }
- return (hash >>> 0).toString(16).padStart(8, '0');
+ return drawnGeometry({
+ batches,
+ vertexCount: (b) => api.getMeshBatchVertexCount(instanceId, b),
+ indexCount: (b) => api.getMeshBatchIndexCount(instanceId, b),
+ read(b) {
+ const vertices = api.getMeshBatchVertexCount(instanceId, b);
+ const indices = api.getMeshBatchIndexCount(instanceId, b);
+ return withScratch(raw, (alloc) => {
+ const vp = alloc(vertices * 8 * 4 + 4);
+ const ip = alloc(indices * 2 + 2);
+ const tp = alloc(4);
+ const bp = alloc(4);
+ api.getMeshBatchData(instanceId, b, vp, ip, tp, bp);
+ return {
+ vertices: new Float32Array(raw.HEAPU8.buffer.slice(vp, vp + vertices * 8 * 4)),
+ indices: new Uint16Array(raw.HEAPU8.buffer.slice(ip, ip + indices * 2)),
+ };
+ });
+ },
+ });
}
describe.skipIf(!HAS_WASM)('the clip fast paths draw what the cut drew', () => {
it.each(CASES)('$name: the same triangles, in the same order', (test) => {
- const got = soup(instanceOf(test));
- if (process.env.SPINE_CLIP_PARITY_REPORT) console.log(`${test.name.padEnd(26)} ${got}`);
- expect(got, `${test.name}: the fast paths changed what is drawn`).toBe(test.hash);
+ const got = drawn(instanceOf(test));
+ if (process.env.SPINE_CLIP_PARITY_REPORT) {
+ console.log(`${test.name.padEnd(26)} ${got.digest} tri=${got.triangles} `
+ + `area=${got.area.toFixed(4)} verts=${got.vertices.length}`);
+ }
+ expect(got.digest, `${test.name}: the fast paths changed what is drawn`).toBe(test.hash);
});
});
diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hpp
index f4ad1df18..e9c092154 100644
--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp
+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp
@@ -86,7 +86,7 @@ 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 twenty-two counters of the last probe run, into as many u32 slots.
+// The twenty-four counters of the last probe run, into as many u32 slots.
void spine_probe_counts(uint32_t* out);
// BENCHMARK ONLY — open the first clip region to `stage` (es::spine::ClipStartStage).
diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
index dc0251213..9613fc0f7 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 twenty-two u32 slots. */
+/** The counts of the last {@link spine_probe_extract}, into twenty-four u32 slots. */
EMSCRIPTEN_KEEPALIVE
void spine_probe_counts(std::uint32_t* out) {
if (!out) return;
@@ -315,6 +315,8 @@ void spine_probe_counts(std::uint32_t* out) {
out[19] = g_probeCounts.clipEdgeWork;
out[20] = g_probeCounts.clipInputVertices;
out[21] = g_probeCounts.clipOutputVertices;
+ out[22] = g_probeCounts.clipConvexBypasses;
+ out[23] = g_probeCounts.clipDecompositions;
}
/** The last staged open's counts. Benchmark only; a frame never writes it. */
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
index 37c827cc3..96c8bb705 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
@@ -266,6 +266,11 @@ struct ProbeCounts {
std::uint32_t clipEdgeWork;
std::uint32_t clipInputVertices;
std::uint32_t clipOutputVertices;
+ /// Regions opened without triangulating, and regions that had to. A convex
+ /// polygon is its own only convex piece; proving that is linear, and
+ /// deriving it through an ear clip is quadratic.
+ std::uint32_t clipConvexBypasses;
+ std::uint32_t clipDecompositions;
};
/** BENCHMARK ONLY — the clipper's own scratch arrays, so a second storage
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
index fb570123b..f599e561d 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
@@ -709,6 +709,159 @@ bool insideConvexClip(const float* positions, int vertexCount) {
return true;
}
+namespace {
+
+/**
+ * spine's own `_makeClockwise`, which is static there, transcribed so the ladder
+ * below can stop before it. The full depth is held to the shipped clipStart's
+ * result, which is what says this stayed a transcription.
+ */
+void makeClockwise(spFloatArray* polygon) {
+ float* vertices = polygon->items;
+ const int length = polygon->size;
+ float area = vertices[length - 2] * vertices[1] - vertices[0] * vertices[length - 1];
+ for (int i = 0, n = length - 3; i < n; i += 2) {
+ const float p1x = vertices[i], p1y = vertices[i + 1];
+ const float p2x = vertices[i + 2], p2y = vertices[i + 3];
+ area += p1x * p2y - p2x * p1y;
+ }
+ if (area < 0) return;
+ for (int i = 0, lastX = length - 2, n = length >> 1; i < n; i += 2) {
+ const float x = vertices[i], y = vertices[i + 1];
+ const int other = lastX - i;
+ vertices[i] = vertices[other];
+ vertices[i + 1] = vertices[other + 1];
+ vertices[other] = x;
+ vertices[other + 1] = y;
+ }
+}
+
+/// The first clip region in draw order — the one every fixture here has one of.
+spSlot* firstClipSlot(spSkeleton* skeleton, spClippingAttachment** clip) {
+ for (int i = 0; i < skeleton->slotsCount; ++i) {
+ spSlot* slot = skeleton->drawOrder[i];
+ if (!slot || !slot->attachment) continue;
+ if (slot->attachment->type != SP_ATTACHMENT_CLIPPING) continue;
+ *clip = reinterpret_cast<spClippingAttachment*>(slot->attachment);
+ return slot;
+ }
+ return nullptr;
+}
+
+/// One convex piece this module owns, for the region that is its own only piece.
+spArrayFloatArray* g_convexPolygons = nullptr;
+
+/**
+ * Convex beyond doubt, on THIS frame's world vertices — a deformed polygon is a
+ * different shape every frame. Conservative: a false negative costs only the ear
+ * clip this skips, a false positive changes what is drawn, so a cross product
+ * with no trustworthy sign or directions that turn twice both decline.
+ */
+bool isDefinitelyConvex(const spFloatArray* polygon) {
+ const int count = polygon->size / 2;
+ if (count < 3) return false;
+ const float* v = polygon->items;
+
+ float minX = v[0], maxX = v[0], minY = v[1], maxY = v[1];
+ for (int i = 2; i < polygon->size; i += 2) {
+ minX = v[i] < minX ? v[i] : minX;
+ maxX = v[i] > maxX ? v[i] : maxX;
+ minY = v[i + 1] < minY ? v[i + 1] : minY;
+ maxY = v[i + 1] > maxY ? v[i + 1] : maxY;
+ }
+ const float span = (maxX - minX) > (maxY - minY) ? (maxX - minX) : (maxY - minY);
+ if (!(span > 0.0f)) return false;
+ const float crossEpsilon = span * span * 1e-7f;
+
+ int sign = 0;
+ int xTurns = 0;
+ int yTurns = 0;
+ float previousDx = 0.0f;
+ float previousDy = 0.0f;
+ for (int i = 0; i < count; ++i) {
+ const int a = i * 2;
+ const int b = ((i + 1) % count) * 2;
+ const int c = ((i + 2) % count) * 2;
+ const float dx = v[b] - v[a], dy = v[b + 1] - v[a + 1];
+ const float ex = v[c] - v[b], ey = v[c + 1] - v[b + 1];
+ const float cross = dx * ey - dy * ex;
+ if (cross > -crossEpsilon && cross < crossEpsilon) return false;
+ const int turn = cross > 0.0f ? 1 : -1;
+ if (sign == 0) sign = turn;
+ else if (turn != sign) return false;
+
+ // A simple convex polygon's edge directions cross each axis exactly
+ // twice; a star keeps a consistent turn but crosses them four times.
+ if (i > 0) {
+ if ((dx < 0.0f) != (previousDx < 0.0f)) ++xTurns;
+ if ((dy < 0.0f) != (previousDy < 0.0f)) ++yTurns;
+ }
+ previousDx = dx;
+ previousDy = dy;
+ }
+ if ((v[0] - v[(count - 1) * 2] < 0.0f) != (previousDx < 0.0f)) ++xTurns;
+ if ((v[1] - v[(count - 1) * 2 + 1] < 0.0f) != (previousDy < 0.0f)) ++yTurns;
+ return xTurns <= 2 && yTurns <= 2;
+}
+
+/**
+ * The polygon as the region's only piece, in the rotation the decomposition
+ * would have produced: the ear clipper takes vertex 0 first, so the fan begins
+ * at the LAST vertex. Starting elsewhere clips to the same area but fanned from
+ * another corner — this is what keeps the output identical, not equivalent.
+ */
+spArrayFloatArray* asSingleConvexPiece(spFloatArray* polygon) {
+ if (!g_convexPolygons) {
+ g_convexPolygons = spArrayFloatArray_create(1);
+ spArrayFloatArray_add(g_convexPolygons, spFloatArray_create(16));
+ }
+ spFloatArray* piece = g_convexPolygons->items[0];
+ spFloatArray_clear(piece);
+ const int last = polygon->size - 2;
+ spFloatArray_addAllValues(piece, polygon->items, last, 2);
+ spFloatArray_addAllValues(piece, polygon->items, 0, last);
+ spFloatArray_add(piece, piece->items[0]);
+ spFloatArray_add(piece, piece->items[1]);
+ g_convexPolygons->size = 1;
+ return g_convexPolygons;
+}
+
+/**
+ * spine's `clipStart`, with the proof in front of the derivation. Everything
+ * before the branch is what it does; the branch is that a polygon already known
+ * convex needs neither the ear clip nor the decomposition to say so.
+ */
+template <bool COUNT>
+int openClipRegion(spSlot* slot, spClippingAttachment* clip, ProbeCounts* counts) {
+ if (g_clipper->clipAttachment) return 0;
+ g_clipper->clipAttachment = clip;
+
+ const int length = clip->super.worldVerticesLength;
+ float* vertices = spFloatArray_setSize(g_clipper->clippingPolygon, length)->items;
+ spVertexAttachment_computeWorldVertices(&clip->super, slot, 0, length, vertices, 0, 2);
+ makeClockwise(g_clipper->clippingPolygon);
+
+ if (isDefinitelyConvex(g_clipper->clippingPolygon)) {
+ if constexpr (COUNT) counts->clipConvexBypasses++;
+ g_clipper->clippingPolygons = asSingleConvexPiece(g_clipper->clippingPolygon);
+ return 1;
+ }
+
+ if constexpr (COUNT) counts->clipDecompositions++;
+ g_clipper->clippingPolygons = spTriangulator_decompose(
+ g_clipper->triangulator, g_clipper->clippingPolygon,
+ spTriangulator_triangulate(g_clipper->triangulator, g_clipper->clippingPolygon));
+ for (int i = 0; i < g_clipper->clippingPolygons->size; ++i) {
+ spFloatArray* piece = g_clipper->clippingPolygons->items[i];
+ makeClockwise(piece);
+ spFloatArray_add(piece, piece->items[0]);
+ spFloatArray_add(piece, piece->items[1]);
+ }
+ return g_clipper->clippingPolygons->size;
+}
+
+} // namespace
+
/**
* Hand one attachment's triangles to the sink, clipped against the open clip
* region when there is one. Clipping replaces the triangle set with the polygon
@@ -806,7 +959,7 @@ void renderImpl(Instance* instance, TriangleSink& sink, bool clipping, ProbeCoun
if constexpr (COUNT) counts->clipStarts++;
if (clipping && STAGE >= STAGE_CLIP_START) {
auto* clip = reinterpret_cast<spClippingAttachment*>(attachment);
- const int pieces = spSkeletonClipping_clipStart(g_clipper, slot, clip);
+ const int pieces = openClipRegion<COUNT>(slot, clip, counts);
captureClipRegion();
if constexpr (COUNT) {
counts->clipPolygons += static_cast<std::uint32_t>(pieces);
@@ -927,46 +1080,6 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
renderImpl<STAGE_EMIT, false>(instance, sink, clipping, nullptr);
}
-namespace {
-
-/**
- * spine's own `_makeClockwise`, which is static there, transcribed so the ladder
- * below can stop before it. The full depth is held to the shipped clipStart's
- * result, which is what says this stayed a transcription.
- */
-void makeClockwise(spFloatArray* polygon) {
- float* vertices = polygon->items;
- const int length = polygon->size;
- float area = vertices[length - 2] * vertices[1] - vertices[0] * vertices[length - 1];
- for (int i = 0, n = length - 3; i < n; i += 2) {
- const float p1x = vertices[i], p1y = vertices[i + 1];
- const float p2x = vertices[i + 2], p2y = vertices[i + 3];
- area += p1x * p2y - p2x * p1y;
- }
- if (area < 0) return;
- for (int i = 0, lastX = length - 2, n = length >> 1; i < n; i += 2) {
- const float x = vertices[i], y = vertices[i + 1];
- const int other = lastX - i;
- vertices[i] = vertices[other];
- vertices[i + 1] = vertices[other + 1];
- vertices[other] = x;
- vertices[other + 1] = y;
- }
-}
-
-/// The first clip region in draw order — the one every fixture here has one of.
-spSlot* firstClipSlot(spSkeleton* skeleton, spClippingAttachment** clip) {
- for (int i = 0; i < skeleton->slotsCount; ++i) {
- spSlot* slot = skeleton->drawOrder[i];
- if (!slot || !slot->attachment) continue;
- if (slot->attachment->type != SP_ATTACHMENT_CLIPPING) continue;
- *clip = reinterpret_cast<spClippingAttachment*>(slot->attachment);
- return slot;
- }
- return nullptr;
-}
-
-} // namespace
namespace {
@@ -1023,6 +1136,7 @@ bool openToStage(Instance* instance, int stage, ClipStartCounts* counts) {
} // namespace
+
bool clipStartStage(Instance* instance, int stage, ClipStartCounts* counts) {
if (!instance || !counts) return false;
*counts = ClipStartCounts{};