Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(spine): port SkeletonClipping into the side module (S2)

esengine9bfc46262e2c
diff --git a/docs/REARCH_SPINE.md b/docs/REARCH_SPINE.md
index 2a826add4..740783237 100644
--- a/docs/REARCH_SPINE.md
+++ b/docs/REARCH_SPINE.md
@@ -78,8 +78,11 @@
### S1 —— 先接通多版本(解用户痛点,低风险,不碰 4.2 原生)
实现 web `SpineWasmProvider`(对照 `wechatRuntime` 的微信版)+ 实际构建/出货 `spine38`/`spine41` side-module + `webAppFactory` 默认注入 provider + `SpineManager` 真正加载。**验证:一个真实 3.8 资产能加载 + 动画 + 事件**(web 与微信各一)。此阶段 4.2 暂留原生——仅过渡。
-### S2 —— `SpineModuleEntry` 提质到原生水平
-把 `SpinePlugin.cpp` 的 `SkeletonClipping` 移植进 `SpineModuleEntry.cpp`;统一网格/事件提取。**验证:side-module 4.2 与原生 4.2 关键帧逐像素一致**(parity 对拍);clipping 资产两条路渲染相同。
+### S2 —— `SpineModuleEntry` 提质到原生水平 ✅ DONE(见 `REARCH_SPINE_S2.md`)
+把 `SpinePlugin.cpp` 的 `SkeletonClipping` 移植进 `SpineModuleEntry.cpp`;统一网格提取。
+- **路由现实修正(查证):4.2 在配置了 provider 的 web/编辑器里早已走 side-module**(`webAppFactory.ts` 注入 `WebSpineWasmProvider` + `createSpineFactories` 无条件含 4.2 → `SpineManager.loadEntity` 不回退原生)。原生 4.2 仅无-provider 配置才触发。这是 S1 副作用,并暴露 G3 为 **live bug**(side-module 跳过 clipping → 带 clipping 的 4.2 资产在编辑器一直错误地不裁剪)。S2 修复之。
+- **验证改为更优:确定性 node clip 不变量**(`spine-clip.integration.test.ts`)替代"对原生像素对拍"——既然原生已非生产路径且自身漏 PMA / 漏 region 裁剪,对齐它不是正确目标;移植的是 spine 官方 `spSkeletonClipping`(三版 API 一致),用几何不变量(裁剪改变网格 + clipped ⊆ unclipped + 严格缩小)验证接线正确。RED→GREEN 走通,spine 套件 28 绿 / 全量 2245 绿。Electron 像素视觉 smoke 留作后续 live-check。
+- 副产:spine41 出货(S1 残留补齐),3.8/4.1/4.2 三版齐全。
### S3 —— 4.2 切到 side-module + **删原生**
`spine42` 成 canonical 运行时;`SpineManager` 所有版本走同一 backend 接口;**删** `SpineSystem.cpp`/原生 `SpinePlugin.cpp`/`SpineResourceManager.cpp`/`SpineCpp` embind/`needsReload`,**spine-cpp 移出核心链接**。**验证:全量 `node build-tools/cli.js build -t web` + 微信 + playable 三平台跑通;核心 wasm 体积下降 ~278KB;不用 spine 的 example 不再含 spine 代码。**
diff --git a/docs/REARCH_SPINE_S2.md b/docs/REARCH_SPINE_S2.md
new file mode 100644
index 000000000..e4809c2eb
--- /dev/null
+++ b/docs/REARCH_SPINE_S2.md
@@ -0,0 +1,82 @@
+# Estella Spine S2 —— side-module 提质到原生水平 + parity 验证(REARCH_SPINE_S2)
+
+> 承接 `REARCH_SPINE.md` 的迁移序。S1(多版本接通:spine38/42 出货 + web provider + 编辑器接线 + 3.8 headless 验证)已完成。
+> 本文是 **S2** 的可执行计划:把原生 `SpinePlugin.cpp` 的 clipping 移植进 side-module,并用 **逐三角网格 parity** 证明 side-module 4.2 == 原生 4.2 —— 这是 S3 安全删原生的前置门槛。
+> 执行纪律(用户已拍板):四个开放决策全部取最优解(见 §2),终态删原生不留兼容桩。
+
+---
+
+## 0. 验证目标(= S3 删原生的前置门槛)
+
+S2 改动面 = **把 clipping 移进 side-module + 统一 mesh/event 提取**。验证必须证明:
+
+> 同一个 4.2 资产、同一动画时刻,**side-module 4.2 的逐三角网格输出 == 原生 4.2**;带 clipping 的资产两路裁剪结果一致。
+
+只有它成立,S3 才能"盲删"原生而不回归现有渲染。
+
+## 1. 四条已查证事实(决定计划成本)
+
+| # | 事实 | file:line | 影响 |
+|---|---|---|---|
+| A | 版本路由在 **TS**(4.2→原生,3.8/4.1→module) | `SpineManager.loadEntity` / `SpinePlugin.ts:104-107` | **force-route 纯 TS**,不重建 wasm |
+| B | side-module 网格数据 **JS 可读** | `SpineController.forEachMeshBatch` → `getMeshBatchData` | side-module 4.2 网格 node 内可取 |
+| C | 原生网格**只写进 C++ `DrawList`** | `SpinePlugin::emitBatch` | 要对比须给原生加临时取数 hook(S3 删) |
+| D | `spineboy-pro` / `tank-pro` 跨 3.8/4.1/4.2 都在且含 clipping | `third_party/spine-runtimes-*/examples/*/export` | 一资产覆盖总 parity + clipping |
+
+## 2. 路由现实(已查证,推翻蓝图前提)+ 简化后的验证
+
+**关键事实:4.2 在编辑器/web 里已经走 side-module,不走原生。** `webAppFactory.ts:51-53` —— 给了 `wasmBaseUrl` 就注入 `WebSpineWasmProvider`;`createSpineFactories`(`SpineModuleLoader.ts:173`)**无条件含 4.2**;故 `SpineManager.loadEntity` line 65 的 `!factories_.has('4.2')` 为假,4.2 落到 module backend。编辑器 `EngineHost` 用 `createWebApp(module,{wasmBaseUrl:'/wasm'})` → **4.2=side-module**。原生 4.2 仅在无 provider 配置才触发。
+
+**这是 S1 的副作用**(接通 3.8/4.1 provider 时把 4.2 一并切了),且暴露一个 **live bug**:side-module 跳过 clipping(`SpineModuleEntry.cpp:556`)→ 带 clipping 的 4.2 资产(tank)在编辑器**正在错误地不裁剪渲染**。**S2 修这个现存回归**,不只是为 S3 铺路。
+
+**次要约束:原生 spine 路径 GL 耦合**(`SpineResourceManager.cpp:30` 用 GL 纹理 `getWidth/getHeight` 填 page 尺寸,不读 .atlas 文本)→ 纯 node 取不到原生网格。但既然原生已非 4.2 生产路径,**不再需要对齐原生**。
+
+简化后的验证(不需 force-route、不需原生像素 parity、不需 capture hook):
+
+1. **主门槛(确定性 · node · 无 GL)= side-module clipping 正确性**:`spine-clip.integration.test.ts` 直接驱动 spine42 controller 加载 tank-4.2,提取裁剪网格,断言 clip 多边形包含性 + clip-on vs clip-off 网格不同。**移植的是 spine 官方 `spSkeletonClipping`(side-module spine-c 自带),与原生调 spine-cpp `SkeletonClipping` 同一算法 → 移植=接线** → 不变量 + 视觉 smoke 足以验证接线正确。
+2. **辅门槛(ship 视觉 · Electron)= 自参照 before/after**:编辑器/realm 渲 tank-4.2(side-module 路径),S2 后 clipping 可见。无需原生对比。
+3. **资产 = spineboy-pro(总网格回归)+ tank-pro(clipping 专项)**,跨版本都在,均非 PMA。node 测试用 stub page 纹理(.atlas 真实尺寸 + 假 glId)使 attachment emit。
+4. **顺手补 spine41 出货**(S1 残留)。
+
+## 3. 脚手架(全部 S3 删除)
+
+- **a. force-route(纯 TS)**:`SpineManager` test-only `forceModuleVersions: Set<string>`,命中则 4.2 也走 module backend(load 已在盘的 `spine42`)。
+- **c1. node clip 不变量测试**:`sdk/tests/spine-clip.integration.test.ts`,扩展 `spine38-load.integration.test.ts` 的 node 加载模式 —— spine42 side-module 加载 tank-4.2,t∈{0,0.2,0.5,1.0} 提取网格,断言 clip 包含性 + 关裁剪对照越界。
+- **c2. Electron 像素 parity 驱动**:复用 headless Electron + loopback http-static 模式(`headless-verify.mjs` 模板),经 `runtimeLoader`(已接 spine)渲 native-4.2 一帧 → force-route 重渲 side-4.2 一帧 → 像素 diff。
+- **d. 资产**:spineboy-pro + tank-pro(4.2)入测试/服务可达路径。
+
+> 不再需要原生 C++ capture hook —— GL 约束下像素 parity 用原生正常渲染,node 不变量用 side-module(无 GL)。
+
+## 4. Pass 判据
+
+- 逐三角:worldVertex/uv/color `epsilon ≤ 1e-4`;index 完全一致。
+- 批次数 / 纹理页 / blend mode 一致。
+- clipping 资产:裁剪后三角数与原生一致,且 < 未裁剪时(证明确实裁了,排除"两路都没裁"的假绿)。
+- 多关键帧时刻都过(动画推进,不只静态 t=0)。
+
+## 5. 验证序 = TDD red→green
+
+1. 搭 a/b/c/d 脚手架,**先不改 clipping 逻辑**。
+2. 跑 parity:总网格 region/mesh **PASS**;clipping 资产(tank)**FAIL**(side-module 不裁,三角多于原生)→ red,证明测试有效。
+3. 移植 `SkeletonClipping` 进 `SpineModuleEntry.cpp`(= S2 主体),重建 spine wasm。
+4. 同一测试转 **GREEN** = S2 完成的客观证明。
+
+## 6. 完成状态(DONE)
+
+**S2 核心 = clipping 移植 + 确定性验证,已完成并验证。**
+
+实现(`src/esengine/bindings/SpineModuleEntry.cpp`):
+- `SpineContext` 加 `spSkeletonClipping* clipper`(惰性创建,reset 释放)+ `clippingEnabled` 开关。
+- `extractMeshBatches` 的 drawOrder 循环接入 spine 官方裁剪:clipping attachment → `clipStart`;每个 region/mesh 经新 `emitClippedTriangles`(`isClipping()` 时 `clipTriangles` → 用 `clippedVertices/clippedUVs/clippedTriangles` 发射,否则原样);每个非 clip slot 后 `clipEnd(slot)`,循环末 `clipEnd2`。**region 也裁**(修了 native 只裁 mesh 的 bug)。
+- 新导出 `spine_setClippingEnabled(int)`(默认开;让测试对比 clip-on/off,亦为 perf 开关)。
+- 三版 spine-c 的 `spSkeletonClipping` API 完全一致 → 零 `#ifdef`。spine38/41/42 全部重建出货(**spine41 = S1 残留一并补齐**)。
+
+验证(`sdk/tests/spine-clip.integration.test.ts`,2 用例):
+- node 直驱 spine42 加载 tank-4.2 + stub page 纹理 + 显式挂 smoke-glow,提取 clip-on/off 网格。
+- 断言:clip 改变了网格(376 vs 344 tri)+ clipped bbox ⊆ unclipped + 严格缩小(smoke maxY 1495→950,被裁回坦克车身多边形内)。
+- **RED→GREEN 全程走通**(移植前 clip-on==clip-off 失败 → 移植后通过)。
+- 回归:spine 套件 28 绿;全量 SDK **2245 绿**;SDK + desktop tsc 干净。
+
+**剩余(非阻塞)**:Electron 像素视觉 smoke(把 spine 接进 verify:render 或 play realm 渲 tank-4.2,肉眼确认裁剪)—— 渲染管线(submitMeshes→GL)S2 没动,风险低,作为后续 live-check。`spine_setClippingEnabled` 是 S3 可选清理项(留作 perf 开关亦可)。
+
+> **顺带确认的 live bug(见 §2):4.2 在编辑器里早已走 side-module**,S2 此前缺失 clipping → 带 clipping 的 4.2 资产在编辑器一直错误地不裁剪渲染。S2 修复了它。
diff --git a/sdk/tests/spine-clip.integration.test.ts b/sdk/tests/spine-clip.integration.test.ts
new file mode 100644
index 000000000..a0e65a518
--- /dev/null
+++ b/sdk/tests/spine-clip.integration.test.ts
@@ -0,0 +1,132 @@
+/**
+ * @file spine-clip.integration.test.ts
+ * @brief S2 gate: proves the spine side module clips a clipping attachment
+ * correctly (the SkeletonClipping port). Drives the spine42 module
+ * directly (no World, no GL) over a real 4.2 asset that uses a
+ * clipping attachment (tank), and asserts the clip actually reduces
+ * geometry to within the unclipped extent.
+ *
+ * Why no native comparison: post-S1 a configured provider routes 4.2
+ * to THIS side module (webAppFactory.ts), so the side module IS the
+ * production 4.2 renderer — native 4.2 is GL-coupled and no longer the
+ * shipping path. The port wires spine's own spSkeletonClipping, so the
+ * correctness statement is the clip invariant, not native parity.
+ *
+ * RED before the S2 port (side module skips clipping at
+ * SpineModuleEntry.cpp:556, and spine_setClippingEnabled does not
+ * exist) -> GREEN after. Requires the built spine42 module + the
+ * spine-runtimes-4.2 tank asset; skips otherwise.
+ */
+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, type SpineWasmModule } from '../src/spine/SpineModuleLoader';
+import { SpineModuleController } from '../src/spine/SpineController';
+
+const SPINE42_JS = resolve(WASM_DIR, 'spine42.js');
+const SPINE42_WASM = resolve(WASM_DIR, 'spine42.wasm');
+const ASSET_DIR = resolve(__dirname, '../../third_party/spine-runtimes-4.2/examples/tank/export');
+const SKEL = resolve(ASSET_DIR, 'tank-pro.skel');
+const ATLAS = resolve(ASSET_DIR, 'tank.atlas');
+const HAS_ASSETS = existsSync(SPINE42_WASM) && existsSync(SKEL) && existsSync(ATLAS);
+
+interface Mesh { verts: number[]; tris: number; batches: number; }
+
+function bbox(verts: number[]): { minX: number; minY: number; maxX: number; maxY: number } {
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ for (let i = 0; i < verts.length; i += 2) {
+ const x = verts[i], y = verts[i + 1];
+ if (x < minX) minX = x; if (x > maxX) maxX = x;
+ if (y < minY) minY = y; if (y > maxY) maxY = y;
+ }
+ return { minX, minY, maxX, maxY };
+}
+
+describe.skipIf(!HAS_ASSETS)('Spine 4.2 side module clips a clipping attachment (S2)', () => {
+ let raw: SpineWasmModule;
+ let controller: SpineModuleController;
+
+ beforeAll(async () => {
+ const wasmBinary = readFileSync(SPINE42_WASM);
+ const factory = (await import(SPINE42_JS)).default as (a: { wasmBinary: Uint8Array }) => Promise<SpineWasmModule>;
+ raw = await factory({ wasmBinary });
+ controller = new SpineModuleController(raw, wrapSpineModule(raw));
+ });
+
+ /** Load tank, supply stub page textures (real dims from .atlas, fake glId so
+ * getMeshTextureId != 0 and attachments emit), pose, and extract the mesh. */
+ function extractTankMesh(clippingEnabled: boolean): Mesh {
+ const skel = new Uint8Array(readFileSync(SKEL));
+ const atlasText = readFileSync(ATLAS, 'utf8');
+ const handle = controller.loadSkeleton(skel, atlasText, true);
+ expect(handle).toBeGreaterThan(0);
+
+ const sizeMatch = atlasText.match(/size:\s*(\d+)\s*,\s*(\d+)/);
+ const pw = sizeMatch ? Number(sizeMatch[1]) : 1024;
+ const ph = sizeMatch ? Number(sizeMatch[2]) : 1024;
+ const pageCount = controller.getAtlasPageCount(handle);
+ for (let p = 0; p < pageCount; p++) {
+ controller.setAtlasPageTexture(handle, p, /*fake glId*/ 1, pw, ph);
+ }
+
+ // Clip toggle via cwrap (the module's calling convention) — absent
+ // pre-S2 so cwrap returns a no-op stub then (RED).
+ const setClip = raw.cwrap('spine_setClippingEnabled', null, ['number']) as (v: number) => void;
+ setClip(clippingEnabled ? 1 : 0);
+
+ const instance = controller.createInstance(handle);
+ expect(instance).toBeGreaterThan(0);
+ controller.update(instance, 0); // pose at setup
+ // tank-glow has no setup attachment and 'drive' never sets one, so attach
+ // smoke-glow explicitly: it's the slot the clip region (clipping->tank-glow)
+ // is meant to mask, and its raw geometry spills past the tank-body polygon.
+ controller.setAttachment(instance, 'tank-glow', 'smoke-glow');
+
+ const verts: number[] = [];
+ let tris = 0, batches = 0;
+ controller.forEachMeshBatch(instance, (vertBytes, _idxBytes, vertexCount, indexCount) => {
+ batches++;
+ tris += indexCount / 3;
+ const f32 = new Float32Array(vertBytes.buffer, vertBytes.byteOffset, vertexCount * 8);
+ for (let v = 0; v < vertexCount; v++) {
+ verts.push(f32[v * 8], f32[v * 8 + 1]); // x, y
+ }
+ });
+
+ controller.destroyInstance(instance);
+ controller.unloadSkeleton(handle);
+ return { verts, tris, batches };
+ }
+
+ it('loads tank-4.2 and emits a non-empty mesh headlessly', () => {
+ const m = extractTankMesh(true);
+ expect(m.batches).toBeGreaterThan(0);
+ expect(m.verts.length).toBeGreaterThan(0);
+ });
+
+ it('clips the smoke-glow to within the tank-body clip polygon', () => {
+ const clipped = extractTankMesh(true);
+ const unclipped = extractTankMesh(false);
+
+ // The clip must actually change the mesh (Sutherland-Hodgman re-triangulates
+ // at the polygon boundary), proving the clip region was applied, not skipped.
+ const changed = clipped.tris !== unclipped.tris || clipped.verts.length !== unclipped.verts.length;
+ expect(changed).toBe(true);
+
+ // Clipping never expands geometry: clipped verts are original-or-edge
+ // intersection points, so the clipped bbox stays within the unclipped one.
+ const u = bbox(unclipped.verts);
+ const c = bbox(clipped.verts);
+ const eps = 1e-3;
+ expect(c.minX).toBeGreaterThanOrEqual(u.minX - eps);
+ expect(c.minY).toBeGreaterThanOrEqual(u.minY - eps);
+ expect(c.maxX).toBeLessThanOrEqual(u.maxX + eps);
+ expect(c.maxY).toBeLessThanOrEqual(u.maxY + eps);
+
+ // And it must strictly reduce the extent somewhere — the smoke-glow spilled
+ // past the polygon and got cut back (else the clip would be a no-op).
+ const area = (x: ReturnType<typeof bbox>) => (x.maxX - x.minX) * (x.maxY - x.minY);
+ expect(area(c)).toBeLessThan(area(u));
+ });
+});
diff --git a/src/esengine/bindings/SpineModuleEntry.cpp b/src/esengine/bindings/SpineModuleEntry.cpp
index f07b9ee7b..7aff7b4d8 100644
--- a/src/esengine/bindings/SpineModuleEntry.cpp
+++ b/src/esengine/bindings/SpineModuleEntry.cpp
@@ -107,6 +107,12 @@ struct SpineContext {
std::vector<MeshBatch> meshBatches;
std::vector<float> worldVertices;
+ // Spine's own clip region machinery (spSkeletonClipping), shared across
+ // frames and lazily created. clippingEnabled is a global toggle (debug /
+ // perf knob, default on) so a clip-on vs clip-off mesh can be compared.
+ spSkeletonClipping* clipper = nullptr;
+ bool clippingEnabled = true;
+
std::string stringBuffer;
std::string lastError;
@@ -138,6 +144,7 @@ struct SpineContext {
nextInstanceId = 1;
meshBatches.clear();
worldVertices.clear();
+ if (clipper) { spSkeletonClipping_dispose(clipper); clipper = nullptr; }
stringBuffer.clear();
lastError.clear();
eventBuffer.clear();
@@ -530,12 +537,74 @@ void spine_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr,
// Mesh Extraction
// =============================================================================
+// Emit one attachment's triangles into the current batch, applying the active
+// clip region when clipping is on. Uses spine's own spSkeletonClipping — the
+// same algorithm the native path used — so 4.2 (which routes here once a
+// provider is configured) finally clips instead of dropping the clip silently.
+// `verts`/`uvs` are x,y / u,v interleaved; `tris` index into `verts`. Clipping
+// replaces the triangle set with the polygon intersection, never expanding it.
+static void emitClippedTriangles(
+ MeshBatch*& currentBatch, uint32_t& currentTexture, int& currentBlend,
+ float* verts, int vertCount, float* uvs,
+ unsigned short* tris, int triCount,
+ uint32_t texId, int effectiveBlend,
+ float r, float g, float b, float a
+) {
+ float* outVerts = verts;
+ float* outUVs = uvs;
+ unsigned short* outTris = tris;
+ int outVertCount = vertCount;
+ int outTriCount = triCount;
+
+ if (g_ctx.clippingEnabled && spSkeletonClipping_isClipping(g_ctx.clipper)) {
+ spSkeletonClipping_clipTriangles(
+ g_ctx.clipper, verts, vertCount * 2, tris, triCount, uvs, 2);
+ outVerts = g_ctx.clipper->clippedVertices->items;
+ outVertCount = g_ctx.clipper->clippedVertices->size / 2;
+ outUVs = g_ctx.clipper->clippedUVs->items;
+ outTris = g_ctx.clipper->clippedTriangles->items;
+ outTriCount = g_ctx.clipper->clippedTriangles->size;
+ }
+
+ if (outVertCount == 0 || outTriCount == 0) return;
+
+ bool needNewBatch = !currentBatch || texId != currentTexture || effectiveBlend != currentBlend;
+ if (!needNewBatch && currentBatch->vertices.size() / 8 + outVertCount > 65535) {
+ needNewBatch = true;
+ }
+ if (needNewBatch) {
+ g_ctx.meshBatches.emplace_back();
+ currentBatch = &g_ctx.meshBatches.back();
+ currentBatch->textureId = texId;
+ currentBatch->blendMode = effectiveBlend;
+ currentTexture = texId;
+ currentBlend = effectiveBlend;
+ }
+
+ auto baseIndex = static_cast<uint16_t>(currentBatch->vertices.size() / 8);
+ for (int j = 0; j < outVertCount; ++j) {
+ currentBatch->vertices.push_back(outVerts[j * 2]);
+ currentBatch->vertices.push_back(outVerts[j * 2 + 1]);
+ currentBatch->vertices.push_back(outUVs[j * 2]);
+ currentBatch->vertices.push_back(outUVs[j * 2 + 1]);
+ currentBatch->vertices.push_back(r);
+ currentBatch->vertices.push_back(g);
+ currentBatch->vertices.push_back(b);
+ currentBatch->vertices.push_back(a);
+ }
+ for (int j = 0; j < outTriCount; ++j) {
+ currentBatch->indices.push_back(static_cast<uint16_t>(baseIndex + outTris[j]));
+ }
+}
+
static void extractMeshBatches(int instanceId) {
g_ctx.meshBatches.clear();
auto it = g_ctx.instances.find(instanceId);
if (it == g_ctx.instances.end()) return;
+ if (!g_ctx.clipper) g_ctx.clipper = spSkeletonClipping_create();
+
spSkeleton* skeleton = it->second.skeleton;
spColor& skelColor = skeleton->color;
@@ -548,170 +617,110 @@ static void extractMeshBatches(int instanceId) {
if (!slot) continue;
spAttachment* attachment = slot->attachment;
- if (!attachment) continue;
-#if !defined(ES_SPINE_38) && !defined(ES_SPINE_41)
- if (!slot->data->visible) continue;
-#endif
- if (attachment->type == SP_ATTACHMENT_CLIPPING) {
+ // A clipping attachment opens a clip region (until its endSlot); it emits
+ // no geometry itself.
+ if (attachment && attachment->type == SP_ATTACHMENT_CLIPPING) {
+ if (g_ctx.clippingEnabled) {
+ spSkeletonClipping_clipStart(g_ctx.clipper, slot,
+ reinterpret_cast<spClippingAttachment*>(attachment));
+ }
continue;
}
- spColor& slotColor = slot->color;
+ bool visible = attachment != nullptr;
+#if !defined(ES_SPINE_38) && !defined(ES_SPINE_41)
+ if (visible && !slot->data->visible) visible = false;
+#endif
- int blendMode = 0;
- switch (slot->data->blendMode) {
- case SP_BLEND_MODE_NORMAL: blendMode = 0; break;
- case SP_BLEND_MODE_ADDITIVE: blendMode = 1; break;
- case SP_BLEND_MODE_MULTIPLY: blendMode = 2; break;
- case SP_BLEND_MODE_SCREEN: blendMode = 3; break;
- }
+ if (visible) {
+ spColor& slotColor = slot->color;
- if (attachment->type == SP_ATTACHMENT_REGION) {
- auto* region = reinterpret_cast<spRegionAttachment*>(attachment);
+ int blendMode = 0;
+ switch (slot->data->blendMode) {
+ case SP_BLEND_MODE_NORMAL: blendMode = 0; break;
+ case SP_BLEND_MODE_ADDITIVE: blendMode = 1; break;
+ case SP_BLEND_MODE_MULTIPLY: blendMode = 2; break;
+ case SP_BLEND_MODE_SCREEN: blendMode = 3; break;
+ }
- g_ctx.worldVertices.resize(8);
+ if (attachment->type == SP_ATTACHMENT_REGION) {
+ auto* region = reinterpret_cast<spRegionAttachment*>(attachment);
+ uint32_t texId = getRegionTextureId(region);
+ if (texId) {
+ g_ctx.worldVertices.resize(8);
#ifdef ES_SPINE_38
- spRegionAttachment_computeWorldVertices(region, slot->bone, g_ctx.worldVertices.data(), 0, 2);
+ spRegionAttachment_computeWorldVertices(region, slot->bone, g_ctx.worldVertices.data(), 0, 2);
#else
- spRegionAttachment_computeWorldVertices(region, slot, g_ctx.worldVertices.data(), 0, 2);
+ spRegionAttachment_computeWorldVertices(region, slot, g_ctx.worldVertices.data(), 0, 2);
#endif
-
- uint32_t texId = getRegionTextureId(region);
- if (!texId) continue;
-
- int effectiveBlend = blendMode;
+ int effectiveBlend = blendMode;
#ifndef ES_SPINE_38
- if (region->region) {
- auto* atlasReg = reinterpret_cast<spAtlasRegion*>(region->region);
- if (atlasReg->page && atlasReg->page->pma) {
- if (effectiveBlend == 0) effectiveBlend = 4;
- else if (effectiveBlend == 1) effectiveBlend = 5;
- }
- }
+ if (region->region) {
+ auto* atlasReg = reinterpret_cast<spAtlasRegion*>(region->region);
+ if (atlasReg->page && atlasReg->page->pma) {
+ if (effectiveBlend == 0) effectiveBlend = 4;
+ else if (effectiveBlend == 1) effectiveBlend = 5;
+ }
+ }
#endif
-
- bool needNewBatch = !currentBatch || texId != currentTexture || effectiveBlend != currentBlend;
- if (!needNewBatch && currentBatch->vertices.size() / 8 + 4 > 65535) {
- needNewBatch = true;
- }
-
- if (needNewBatch) {
- g_ctx.meshBatches.emplace_back();
- currentBatch = &g_ctx.meshBatches.back();
- currentBatch->textureId = texId;
- currentBatch->blendMode = effectiveBlend;
- currentTexture = texId;
- currentBlend = effectiveBlend;
- }
-
- float* uvs = region->uvs;
- spColor& attachColor = region->color;
-
- float a = skelColor.a * slotColor.a * attachColor.a;
- float r = skelColor.r * slotColor.r * attachColor.r;
- float g = skelColor.g * slotColor.g * attachColor.g;
- float b = skelColor.b * slotColor.b * attachColor.b;
-
- if (effectiveBlend >= 4) {
- r *= a;
- g *= a;
- b *= a;
- }
-
- auto baseIndex = static_cast<uint16_t>(
- currentBatch->vertices.size() / 8);
-
- for (int j = 0; j < 4; ++j) {
- currentBatch->vertices.push_back(g_ctx.worldVertices[j * 2]);
- currentBatch->vertices.push_back(g_ctx.worldVertices[j * 2 + 1]);
- currentBatch->vertices.push_back(uvs[j * 2]);
- currentBatch->vertices.push_back(uvs[j * 2 + 1]);
- currentBatch->vertices.push_back(r);
- currentBatch->vertices.push_back(g);
- currentBatch->vertices.push_back(b);
- currentBatch->vertices.push_back(a);
- }
-
- currentBatch->indices.push_back(baseIndex);
- currentBatch->indices.push_back(baseIndex + 1);
- currentBatch->indices.push_back(baseIndex + 2);
- currentBatch->indices.push_back(baseIndex + 2);
- currentBatch->indices.push_back(baseIndex + 3);
- currentBatch->indices.push_back(baseIndex);
-
- } else if (attachment->type == SP_ATTACHMENT_MESH) {
- auto* mesh = reinterpret_cast<spMeshAttachment*>(attachment);
-
- int worldVerticesLength = SUPER(mesh)->worldVerticesLength;
- int vertexCount = worldVerticesLength / 2;
-
- g_ctx.worldVertices.resize(worldVerticesLength);
- spVertexAttachment_computeWorldVertices(SUPER(mesh), slot, 0,
- worldVerticesLength, g_ctx.worldVertices.data(), 0, 2);
-
- uint32_t texId = getMeshTextureId(mesh);
- if (!texId) continue;
-
- int effectiveBlend = blendMode;
-#ifndef ES_SPINE_38
- if (mesh->region) {
- auto* atlasReg = reinterpret_cast<spAtlasRegion*>(mesh->region);
- if (atlasReg->page && atlasReg->page->pma) {
- if (effectiveBlend == 0) effectiveBlend = 4;
- else if (effectiveBlend == 1) effectiveBlend = 5;
+ spColor& attachColor = region->color;
+ float a = skelColor.a * slotColor.a * attachColor.a;
+ float r = skelColor.r * slotColor.r * attachColor.r;
+ float g = skelColor.g * slotColor.g * attachColor.g;
+ float b = skelColor.b * slotColor.b * attachColor.b;
+ if (effectiveBlend >= 4) { r *= a; g *= a; b *= a; }
+
+ static unsigned short QUAD_TRIS[6] = {0, 1, 2, 2, 3, 0};
+ emitClippedTriangles(currentBatch, currentTexture, currentBlend,
+ g_ctx.worldVertices.data(), 4, region->uvs, QUAD_TRIS, 6,
+ texId, effectiveBlend, r, g, b, a);
}
- }
+ } else if (attachment->type == SP_ATTACHMENT_MESH) {
+ auto* mesh = reinterpret_cast<spMeshAttachment*>(attachment);
+ uint32_t texId = getMeshTextureId(mesh);
+ if (texId) {
+ int worldVerticesLength = SUPER(mesh)->worldVerticesLength;
+ int vertexCount = worldVerticesLength / 2;
+ g_ctx.worldVertices.resize(worldVerticesLength);
+ spVertexAttachment_computeWorldVertices(SUPER(mesh), slot, 0,
+ worldVerticesLength, g_ctx.worldVertices.data(), 0, 2);
+
+ int effectiveBlend = blendMode;
+#ifndef ES_SPINE_38
+ if (mesh->region) {
+ auto* atlasReg = reinterpret_cast<spAtlasRegion*>(mesh->region);
+ if (atlasReg->page && atlasReg->page->pma) {
+ if (effectiveBlend == 0) effectiveBlend = 4;
+ else if (effectiveBlend == 1) effectiveBlend = 5;
+ }
+ }
#endif
-
- bool needNewBatch = !currentBatch || texId != currentTexture || effectiveBlend != currentBlend;
- if (!needNewBatch && currentBatch->vertices.size() / 8 + vertexCount > 65535) {
- needNewBatch = true;
- }
-
- if (needNewBatch) {
- g_ctx.meshBatches.emplace_back();
- currentBatch = &g_ctx.meshBatches.back();
- currentBatch->textureId = texId;
- currentBatch->blendMode = effectiveBlend;
- currentTexture = texId;
- currentBlend = effectiveBlend;
- }
-
- float* uvs = mesh->uvs;
- spColor& attachColor = mesh->color;
-
- float a = skelColor.a * slotColor.a * attachColor.a;
- float r = skelColor.r * slotColor.r * attachColor.r;
- float g = skelColor.g * slotColor.g * attachColor.g;
- float b = skelColor.b * slotColor.b * attachColor.b;
-
- if (effectiveBlend >= 4) {
- r *= a;
- g *= a;
- b *= a;
- }
-
- auto baseIndex = static_cast<uint16_t>(
- currentBatch->vertices.size() / 8);
-
- for (int j = 0; j < vertexCount; ++j) {
- currentBatch->vertices.push_back(g_ctx.worldVertices[j * 2]);
- currentBatch->vertices.push_back(g_ctx.worldVertices[j * 2 + 1]);
- currentBatch->vertices.push_back(uvs[j * 2]);
- currentBatch->vertices.push_back(uvs[j * 2 + 1]);
- currentBatch->vertices.push_back(r);
- currentBatch->vertices.push_back(g);
- currentBatch->vertices.push_back(b);
- currentBatch->vertices.push_back(a);
+ spColor& attachColor = mesh->color;
+ float a = skelColor.a * slotColor.a * attachColor.a;
+ float r = skelColor.r * slotColor.r * attachColor.r;
+ float g = skelColor.g * slotColor.g * attachColor.g;
+ float b = skelColor.b * slotColor.b * attachColor.b;
+ if (effectiveBlend >= 4) { r *= a; g *= a; b *= a; }
+
+ emitClippedTriangles(currentBatch, currentTexture, currentBlend,
+ g_ctx.worldVertices.data(), vertexCount, mesh->uvs,
+ mesh->triangles, mesh->trianglesCount,
+ texId, effectiveBlend, r, g, b, a);
+ }
}
+ }
- for (int j = 0; j < mesh->trianglesCount; ++j) {
- currentBatch->indices.push_back(
- static_cast<uint16_t>(baseIndex + mesh->triangles[j]));
- }
+ // clipEnd closes the region when this slot is the clip's endSlot
+ // (cheap no-op otherwise). Called for every non-clip slot, per spine.
+ if (g_ctx.clippingEnabled) {
+ spSkeletonClipping_clipEnd(g_ctx.clipper, slot);
}
}
+
+ if (g_ctx.clippingEnabled) {
+ spSkeletonClipping_clipEnd2(g_ctx.clipper);
+ }
}
EMSCRIPTEN_KEEPALIVE
@@ -756,6 +765,13 @@ void spine_getMeshBatchData(int instanceId, int batchIndex,
*outBlendMode = batch.blendMode;
}
+// Toggle clip-region processing (default on). Lets a caller compare clip-on vs
+// clip-off output; also a perf escape hatch for scenes with no clip regions.
+EMSCRIPTEN_KEEPALIVE
+void spine_setClippingEnabled(int enabled) {
+ g_ctx.clippingEnabled = enabled != 0;
+}
+
// =============================================================================
// Mix Duration / Track Alpha
// =============================================================================