A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
perf(spine): two clip fast paths, and where they actually fire
esengineb60b5ebb8f1b
diff --git a/sdk/benchmarks/spine-clip-stages.bench.ts b/sdk/benchmarks/spine-clip-stages.bench.tsindex 06710f0e0..03118d900 100644--- a/sdk/benchmarks/spine-clip-stages.bench.ts+++ b/sdk/benchmarks/spine-clip-stages.bench.ts@@ -50,6 +50,26 @@* 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.+ *+ * Two fast paths then took the two ends of that table out. Bounds that+ * cannot meet the region: 1.604 -> 0.011 µs. A mesh wholly inside a+ * convex one: 2.032 -> 0.064. Every other row moved by under 1%, so the+ * tests they added cost the cases they do not answer nothing.+ *+ * Their hit rate on the shipped 3.8 corpus, over every animation of+ * every example that clips, is the reason they are worth the code —+ * and it is lopsided:+ *+ * spineboy portal 339 input triangles a frame, ALL rejected on+ * bounds — a whole body inside a region it is+ * entirely outside of, cut to produce nothing+ * coin 11 of 20 clipped emits rejected on bounds+ * tank none — genuinely crossing, and concave+ *+ * The fully-inside path never fires on any of them: the three assets+ * that clip either cross their region or are outside it. It stays for+ * the shape it is meant for — a mask that contains its content — but+ * nothing in this corpus is that shape, and that should be said.*/import { describe, bench, beforeAll } from 'vitest';import { existsSync, readFileSync } from 'node:fs';@@ -103,6 +123,7 @@ const COUNTERS = ['slots', 'regions', 'meshes', 'clipStarts', 'clippedEmits','vGenerated', 'vEmitted', 'iEmitted', 'emits','polygons', 'polygonVertices', 'polygonEdges', 'inTriangles', 'outTriangles',+ 'boundsRejects', 'insideAccepts',] as const;let raw: SpineWasmModule;diff --git a/sdk/tests/helpers/syntheticSpine.ts b/sdk/tests/helpers/syntheticSpine.tsindex a8923545c..042d73431 100644--- a/sdk/tests/helpers/syntheticSpine.ts+++ b/sdk/tests/helpers/syntheticSpine.ts@@ -22,7 +22,7 @@ export interface SyntheticSkeleton {}/** Where the clip polygon sits relative to the strip of quads. */-export type ClipRelation = 'inside' | 'outside' | 'one-crossing' | 'all-crossing';+export type ClipRelation = 'inside' | 'outside' | 'one-crossing' | 'all-crossing' | 'notched';export interface SyntheticOptions {/** Quads in the row; the mesh has twice this many triangles. */@@ -74,6 +74,11 @@ function polygon(vertexCount: number, radius: number, concave: boolean): number[function clipShape(options: SyntheticOptions): number[] {const { relation } = options;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.+ if (relation === 'inside') {+ return polygon(options.polygonVertices, STRIP_WIDTH * 1.5, options.concave ?? false);+ }// 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)@@ -92,6 +97,15 @@ function clipShape(options: SyntheticOptions): number[] {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];+ case 'notched':+ // Concave, but only clear of the strip: a rectangle with a bite out+ // of its top edge at x 600..1000, where the strip ends at 400. So+ // nothing of the strip is outside the region, and it is still cut.+ return [+ -halfW * 4, -halfH * 8, halfW * 4, -halfH * 8, halfW * 4, halfH * 8,+ halfW * 2.5, halfH * 8, halfW * 2.5, halfH * 4, halfW * 1.5, halfH * 4,+ halfW * 1.5, halfH * 8, -halfW * 4, halfH * 8,+ ];}}diff --git a/sdk/tests/spine-clip-parity.test.ts b/sdk/tests/spine-clip-parity.test.tsnew file mode 100644index 000000000..1496d4c4e--- /dev/null+++ b/sdk/tests/spine-clip-parity.test.ts@@ -0,0 +1,130 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spine-clip-parity.test.ts+ * @brief The clip fast paths draw what the cut drew.+ *+ * @details They are only allowed to be faster. One of them deliberately changes+ * the BUFFER — a mesh wholly inside a convex region keeps its own+ * shared vertices instead of the clipper's per-triangle rebuild — so+ * bytes are the wrong witness and triangles are the right one: every+ * triangle, in order, as the three (x, y, u, v, rgba) it draws.+ *+ * The digests below were recorded from a build that had neither fast+ * path, so what they witness is not this build agreeing with itself.+ * `SPINE_CLIP_PARITY_REPORT=1` prints them, and `SPINE_WASM_OVERRIDE`+ * points the run at another module — which is how they were taken.+ */+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 OVERRIDE = process.env.SPINE_WASM_OVERRIDE;+const SPINE38_JS = OVERRIDE ? `${OVERRIDE}.js` : resolve(WASM_DIR, 'spine38.js');+const SPINE38_WASM = OVERRIDE ? `${OVERRIDE}.wasm` : resolve(WASM_DIR, 'spine38.wasm');+const FIXTURES = resolve(__dirname, '../benchmarks/fixtures/spine');+const HAS_WASM = existsSync(SPINE38_WASM);+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' },+ // 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' },+];++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(test: (typeof CASES)[number]): number {+ const real = test.skel !== undefined;+ const skelData = real+ ? new Uint8Array(readFileSync(resolve(FIXTURES, test.skel!)))+ : new TextEncoder().encode(syntheticSkeleton(test.options!).json);+ const atlas = real+ ? readFileSync(resolve(FIXTURES, test.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);+ });+ 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 instanceId = api.createInstance(handle);+ if (real) {+ const [first] = JSON.parse(api.getAnimations(instanceId)) as string[];+ const animation = test.animation ?? first;+ if (!api.playAnimation(instanceId, animation, true, 0)) throw new Error(`no "${animation}"`);+ }+ api.update(instanceId, real ? 0.3 : 0);+ return instanceId;+}++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;+}++/** Every triangle a frame draws, expanded to the vertices it draws them with. */+function soup(instanceId: number): string {+ 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');+}++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);+ });+});diff --git a/sdk/tests/spine-clip-stages.test.ts b/sdk/tests/spine-clip-stages.test.tsindex ce62d3c5e..1b418173e 100644--- a/sdk/tests/spine-clip-stages.test.ts+++ b/sdk/tests/spine-clip-stages.test.ts@@ -22,6 +22,7 @@ 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);/** The thirteen counters `spine_probe_counts` writes, in order. */@@ -29,6 +30,7 @@ const COUNTERS = ['slots', 'regionAttachments', 'meshAttachments', 'clipStarts', 'clippedEmits','verticesGenerated', 'verticesEmitted', 'indicesEmitted', 'emits','clipPolygons', 'clipPolygonVertices', 'clipPolygonEdges', 'clipInputTriangles', 'clipOutputTriangles',+ 'clipBoundsRejects', 'clipInsideAccepts',] as const;type Counts = Record<(typeof COUNTERS)[number], number>;const STAGE_EMIT = 5;@@ -80,30 +82,12 @@ function countsOf(instanceId: number): Counts {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' }));+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'one-crossing' }));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@@ -131,6 +115,7 @@ describe.skipIf(!HAS_WASM)('the synthetic clip fixtures are what they claim', ()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);+ expect(concave.clipPolygonEdges).toBeGreaterThan(convex.clipPolygonEdges);});it('the clipper stops growing its own scratch once a shape has run', () => {@@ -148,3 +133,81 @@ describe.skipIf(!HAS_WASM)('the synthetic clip fixtures are what they claim', ()expect(storage(), 'the clipper grew its scratch again on a steady shape').toEqual(warm);});});++describe.skipIf(!HAS_WASM)('the clip fast paths answer without cutting', () => {+ it('a region the strip is not in is rejected on bounds alone', () => {+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'outside' }));+ expect(c.clipBoundsRejects).toBe(1);+ expect(c.clipInputTriangles, 'the clipper ran on geometry that cannot survive').toBe(0);+ expect(c.emits, 'geometry that clipped away still reached the sink').toBe(0);+ });++ it('a strip wholly inside a convex region keeps its own topology', () => {+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'inside' }));+ expect(c.clipInsideAccepts).toBe(1);+ expect(c.clipInputTriangles, 'the clipper ran on geometry it cannot change').toBe(0);+ // The whole point of the second path: the clipper rebuilds every triangle+ // from its own three vertices, and a mesh that shared them stops sharing.+ // 34 vertices went in and 34 come out, not 96.+ expect(c.verticesEmitted).toBe(c.verticesGenerated);+ expect(c.indicesEmitted).toBe(QUADS * 2 * 3);+ });++ it('a strip wholly inside a CONCAVE region is still cut', () => {+ // Three vertices inside a concave polygon do not put the triangle inside+ // it, so this path is convex-only on purpose; nothing being removed is+ // what says the fixture really is within the region.+ const c = countsOf(instanceOf({+ quads: QUADS, relation: 'inside', polygonVertices: 16, concave: true,+ }));+ expect(c.clipPolygons, 'the fixture is not concave any more').toBeGreaterThan(1);+ expect(c.clipInsideAccepts, 'a concave region took the convex fast path').toBe(0);+ expect(c.clipOutputTriangles, 'the fixture is not wholly inside after all')+ .toBe(c.clipInputTriangles);+ expect(c.verticesEmitted, 'the slow path kept the sharing it cannot keep')+ .toBe(c.clipOutputTriangles * 3);+ });++ it('a concave region cuts geometry that is entirely within it', () => {+ // The strip spans x -400..400, the notch is at x 600..1000: nothing of+ // the strip is outside the region, and it is still cut, because the+ // pieces it decomposes into have boundaries the strip crosses.+ const c = countsOf(instanceOf({ quads: QUADS, relation: 'notched' }));+ expect(c.clipPolygons, 'the notch did not make it concave').toBeGreaterThan(1);+ expect(c.clipBoundsRejects).toBe(0);+ expect(c.clipInsideAccepts, 'a concave region took the convex fast path').toBe(0);+ expect(c.clipInputTriangles).toBe(QUADS * 2);+ expect(c.clipOutputTriangles).toBeGreaterThan(c.clipInputTriangles);+ });++ it('a shipped asset spends a frame cutting geometry that cannot survive', () => {+ // spineboy's portal animation opens a clip region its whole body is+ // outside of: 339 triangles a frame, cut to produce nothing. The bounds+ // test earns its place on a shipped asset, not only an authored one.+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, 'spineboy-38/spineboy-pro.skel')));+ const atlasText = readFileSync(resolve(FIXTURES, 'spineboy-38/spineboy.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, 2048, 2048);+ const instanceId = api.createInstance(handle);+ expect(api.playAnimation(instanceId, 'portal', true, 0)).toBeTruthy();+ api.update(instanceId, 0.3);++ const c = countsOf(instanceId);+ expect(c.clipStarts).toBe(1);+ expect(c.clipBoundsRejects, 'nothing was rejected on bounds').toBeGreaterThan(10);+ expect(c.clipInputTriangles, 'the cut still ran on geometry that cannot survive').toBe(0);+ });++ it('a region that is met, not missed, still goes through the cut', () => {+ for (const relation of ['one-crossing', 'all-crossing'] as const) {+ const c = countsOf(instanceOf({ quads: QUADS, relation }));+ expect(c.clipBoundsRejects, `${relation} was rejected on bounds`).toBe(0);+ expect(c.clipInsideAccepts, `${relation} was accepted as inside`).toBe(0);+ expect(c.clipInputTriangles, `${relation} skipped the cut`).toBe(QUADS * 2);+ }+ });+});diff --git a/sdk/tests/spine-extract-stages.test.ts b/sdk/tests/spine-extract-stages.test.tsindex 1deb57f90..712f71bea 100644--- a/sdk/tests/spine-extract-stages.test.ts+++ b/sdk/tests/spine-extract-stages.test.ts@@ -42,7 +42,7 @@ const COUNTERS = ['slots', 'regionAttachments', 'meshAttachments', 'clipStarts', 'clippedEmits','verticesGenerated', 'verticesEmitted', 'indicesEmitted', 'emits','clipPolygons', 'clipPolygonVertices', 'clipPolygonEdges',- 'clipInputTriangles', 'clipOutputTriangles',+ 'clipInputTriangles', 'clipOutputTriangles', 'clipBoundsRejects', 'clipInsideAccepts',] as const;type Counts = Record<(typeof COUNTERS)[number], number>;diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hppindex 4360ba6d7..0d4d0abb0 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 fourteen counters of the last probe run, into as many u32 slots.+// The sixteen 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.diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cppindex 21e189eea..fc057ebb4 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 fourteen u32 slots. */+/** The counts of the last {@link spine_probe_extract}, into sixteen u32 slots. */EMSCRIPTEN_KEEPALIVEvoid spine_probe_counts(std::uint32_t* out) {if (!out) return;@@ -307,6 +307,8 @@ void spine_probe_counts(std::uint32_t* out) {out[11] = g_probeCounts.clipPolygonEdges;out[12] = g_probeCounts.clipInputTriangles;out[13] = g_probeCounts.clipOutputTriangles;+ out[14] = g_probeCounts.clipBoundsRejects;+ out[15] = g_probeCounts.clipInsideAccepts;}/** BENCHMARK ONLY — the clipper's own scratch, into six u32 slots. Zero where adiff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hppindex a5d7eaa0d..d8e05df5b 100644--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp@@ -250,6 +250,10 @@ struct ProbeCounts {std::uint32_t clipPolygonEdges;std::uint32_t clipInputTriangles;std::uint32_t clipOutputTriangles;+ /// Attachments the two fast paths answered without cutting anything: one+ /// whose bounds miss the region entirely, one wholly inside a convex one.+ std::uint32_t clipBoundsRejects;+ std::uint32_t clipInsideAccepts;};/** BENCHMARK ONLY — the clipper's own scratch arrays, so a second storagediff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cppindex cf24a2091..88e0b707f 100644--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp@@ -629,6 +629,78 @@ bool setSkeletonColor(Instance* instance, float r, float g, float b, float a) {namespace {+/**+ * What the open clip region is, for the two questions that can be answered+ * without cutting: where it is, and whether it is a single convex piece.+ *+ * Captured at clipStart because `clipEnd` clears the polygon it is read from.+ */+struct ClipRegion {+ float minX, minY, maxX, maxY;+ /// The decomposition came back as one piece, so "every vertex is inside it"+ /// means the whole triangle is. A concave region decomposes into several and+ /// a triangle can span two of them while being inside neither.+ bool convex;+};+ClipRegion g_clipRegion{};++void captureClipRegion() {+ const spFloatArray* polygon = g_clipper->clippingPolygon;+ g_clipRegion = ClipRegion{};+ if (!polygon || polygon->size < 2) return;+ g_clipRegion.minX = g_clipRegion.maxX = polygon->items[0];+ g_clipRegion.minY = g_clipRegion.maxY = polygon->items[1];+ for (int i = 2; i < polygon->size; i += 2) {+ const float x = polygon->items[i];+ const float y = polygon->items[i + 1];+ g_clipRegion.minX = x < g_clipRegion.minX ? x : g_clipRegion.minX;+ g_clipRegion.maxX = x > g_clipRegion.maxX ? x : g_clipRegion.maxX;+ g_clipRegion.minY = y < g_clipRegion.minY ? y : g_clipRegion.minY;+ g_clipRegion.maxY = y > g_clipRegion.maxY ? y : g_clipRegion.maxY;+ }+ g_clipRegion.convex = g_clipper->clippingPolygons+ && g_clipper->clippingPolygons->size == 1;+}++/// Bounds that cannot meet the region's: nothing of this attachment survives.+bool outsideClipBounds(const float* positions, int vertexCount) {+ float minX = positions[0], maxX = positions[0];+ float minY = positions[1], maxY = positions[1];+ for (int i = 2; i < vertexCount * 2; i += 2) {+ const float x = positions[i];+ const float y = positions[i + 1];+ minX = x < minX ? x : minX;+ maxX = x > maxX ? x : maxX;+ minY = y < minY ? y : minY;+ maxY = y > maxY ? y : maxY;+ }+ return maxX < g_clipRegion.minX || minX > g_clipRegion.maxX+ || maxY < g_clipRegion.minY || minY > g_clipRegion.maxY;+}++/**+ * Every vertex strictly inside the single convex piece, by the SAME predicate+ * the clipper uses, so a vertex on an edge falls through to the cut. One piece+ * is a cost requirement, not a correctness one: a decomposed region's pieces+ * have boundaries geometry crosses, so this test would run and fail.+ */+bool insideConvexClip(const float* positions, int vertexCount) {+ if (!g_clipRegion.convex) return false;+ const spFloatArray* polygon = g_clipper->clippingPolygons->items[0];+ const float* edges = polygon->items;+ for (int e = 0; e <= polygon->size - 4; e += 2) {+ const float deltaX = edges[e] - edges[e + 2];+ const float deltaY = edges[e + 1] - edges[e + 3];+ const float edgeX2 = edges[e + 2], edgeY2 = edges[e + 3];+ for (int i = 0; i < vertexCount * 2; i += 2) {+ if (deltaX * (positions[i + 1] - edgeY2) - deltaY * (positions[i] - edgeX2) <= 0) {+ return false;+ }+ }+ }+ return true;+}+/*** 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@@ -648,17 +720,28 @@ void emit(TriangleSink& sink, bool clipping,int outTriangleCount = triangleCount;if (STAGE >= STAGE_CLIP && clipping && spSkeletonClipping_isClipping(g_clipper)) {- spSkeletonClipping_clipTriangles(g_clipper, positions, vertexCount * 2,- triangles, triangleCount, uvs, 2);- outPositions = g_clipper->clippedVertices->items;- outVertices = g_clipper->clippedVertices->size / 2;- outUVs = g_clipper->clippedUVs->items;- outTriangles = g_clipper->clippedTriangles->items;- outTriangleCount = g_clipper->clippedTriangles->size;- if constexpr (COUNT) {- counts->clippedEmits++;- counts->clipInputTriangles += static_cast<std::uint32_t>(triangleCount / 3);- counts->clipOutputTriangles += static_cast<std::uint32_t>(outTriangleCount / 3);+ // Neither changes what is drawn. The first answers "nothing of this+ // survives" without cutting; the second answers "all of it does", and+ // keeps the attachment's own topology instead of a per-triangle rebuild.+ if (outsideClipBounds(positions, vertexCount)) {+ if constexpr (COUNT) counts->clipBoundsRejects++;+ return;+ }+ if (insideConvexClip(positions, vertexCount)) {+ if constexpr (COUNT) counts->clipInsideAccepts++;+ } else {+ spSkeletonClipping_clipTriangles(g_clipper, positions, vertexCount * 2,+ triangles, triangleCount, uvs, 2);+ outPositions = g_clipper->clippedVertices->items;+ outVertices = g_clipper->clippedVertices->size / 2;+ outUVs = g_clipper->clippedUVs->items;+ outTriangles = g_clipper->clippedTriangles->items;+ outTriangleCount = g_clipper->clippedTriangles->size;+ if constexpr (COUNT) {+ counts->clippedEmits++;+ counts->clipInputTriangles += static_cast<std::uint32_t>(triangleCount / 3);+ counts->clipOutputTriangles += static_cast<std::uint32_t>(outTriangleCount / 3);+ }}}@@ -703,6 +786,7 @@ void renderImpl(Instance* instance, TriangleSink& sink, bool clipping, ProbeCounif (clipping && STAGE >= STAGE_CLIP_START) {auto* clip = reinterpret_cast<spClippingAttachment*>(attachment);const int pieces = spSkeletonClipping_clipStart(g_clipper, slot, clip);+ captureClipRegion();if constexpr (COUNT) {counts->clipPolygons += static_cast<std::uint32_t>(pieces);counts->clipPolygonVertices +=