dsh-game-material-master 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/spine.js ADDED
@@ -0,0 +1,1392 @@
1
+ /**
2
+ * Spine 4.2 骨骼与动画(纯计算层,不碰文件系统)。
3
+ *
4
+ * 这一层是参考项目 [spine-animation-ai](https://github.com/GenielabsOpenSource/spine-animation-ai)
5
+ * 的 `build_spine_json.py` 与 `references/spine-json-spec.md` 的 TypeScript 移植,做了三件事:
6
+ *
7
+ * ① **从拆件结果自动推导骨骼层级**。参考项目要求调用方(Claude)手工给出
8
+ * bones / attachments,我们这里由「左侧拆件 + 右上装配定位」的结果直接算出来,
9
+ * 用户在界面上只做验收和微调。
10
+ * ② **生成 Spine 4.2 wire format**。参考项目花了很长篇幅讲清楚 3.8 时代的
11
+ * 简写(`angle` + 归一化 bezier)和 4.x 的区别,这里原样保留那套转换逻辑,
12
+ * 因为它正是「生成的 JSON 导进 Spine 后一动不动 / 第一帧就消失」的根因。
13
+ * ③ **动画预设**。idle / walk / run / wave / jump / attack 六个预设按 12 原则
14
+ * 编排(大骨骼幅度大、相关骨骼错开相位形成跟随),同样照搬参考项目。
15
+ *
16
+ * 坐标系约定(与参考项目示例 `examples/sombrero/skeleton.json` 一致):
17
+ * - Spine 是 Y 向上,图片是 Y 向下,因此 `worldY = canvasHeight - pixelY`。
18
+ * - 骨骼 x 以画布水平中心为 0,y 以画布底边为 0。
19
+ * - 骨骼的 `x` / `y` 是**相对父骨骼原点、并在父骨骼局部坐标系里**的位移
20
+ * (spine-core 的 `Bone.updateWorldTransform` 会先用父骨骼的旋转去转它)。
21
+ * - 挂点的 `x` / `y` 是**图片中心相对骨骼原点、在骨骼局部坐标系里**的位移,
22
+ * `rotation` 是挂点自身的局部旋转。见 `references/spine-json-spec.md` 与
23
+ * 参考项目 demo 渲染器的 `translate(att.x, att.y); drawImage(img, -w/2, -h/2)`。
24
+ */
25
+ import { createHash } from "node:crypto";
26
+ import { buildRigMesh, buildWaveDeform } from "./rigmesh.js";
27
+ import { pathSegmentLengths } from "./rigpath.js";
28
+ // ── 拆件槽位定义 ────────────────────────────────────────────────────────
29
+ /**
30
+ * 默认拆件网格:4 列 × 4 行 = 16 个标准人形部件,按阅读顺序排列。
31
+ *
32
+ * 之所以规定网格而不是「随便摊开」:生图模型只是把部件画出来,它不会告诉我们
33
+ * 哪一块是头。固定网格让「第几个格子 = 哪个部件」成为确定事实,
34
+ * 这样分割出来的每一块天然带语义名,骨骼层级和动画预设才能自动套上去。
35
+ */
36
+ export const RIG_GRID_COLUMNS = 4;
37
+ export const RIG_GRID_ROWS = 4;
38
+ const P_TOP = [0.5, 0];
39
+ const P_BOTTOM = [0.5, 1];
40
+ /** 逐个写清楚,是因为层级、锚点和中文名三者互相耦合,用表驱动最容易核对。 */
41
+ export const RIG_SLOTS = [
42
+ { name: "head", label: "头部", en: "head (face, hair and headwear)", parent: "neck", proximal: P_BOTTOM, distal: P_TOP },
43
+ { name: "neck", label: "脖子", en: "neck", parent: "torso", proximal: P_BOTTOM, distal: P_TOP },
44
+ { name: "torso", label: "躯干", en: "torso (chest and waist, with the upper garment)", parent: "hip", proximal: P_BOTTOM, distal: P_TOP },
45
+ { name: "hip", label: "胯部", en: "hip / pelvis (the pelvis area with whatever garment covers it)", parent: undefined, proximal: P_BOTTOM, distal: P_TOP },
46
+ { name: "left-upper-arm", label: "左上臂", en: "left upper arm (shoulder to elbow)", parent: "torso", proximal: P_TOP, distal: P_BOTTOM },
47
+ { name: "left-lower-arm", label: "左小臂", en: "left forearm (elbow to wrist)", parent: "left-upper-arm", proximal: P_TOP, distal: P_BOTTOM },
48
+ { name: "right-upper-arm", label: "右上臂", en: "right upper arm (shoulder to elbow)", parent: "torso", proximal: P_TOP, distal: P_BOTTOM },
49
+ { name: "right-lower-arm", label: "右小臂", en: "right forearm (elbow to wrist)", parent: "right-upper-arm", proximal: P_TOP, distal: P_BOTTOM },
50
+ { name: "left-hand", label: "左手", en: "left hand (open hand with fingers)", parent: "left-lower-arm", proximal: P_TOP, distal: P_BOTTOM },
51
+ { name: "right-hand", label: "右手", en: "right hand (open hand with fingers)", parent: "right-lower-arm", proximal: P_TOP, distal: P_BOTTOM },
52
+ { name: "left-upper-leg", label: "左大腿", en: "left thigh (hip to knee)", parent: "hip", proximal: P_TOP, distal: P_BOTTOM },
53
+ { name: "right-upper-leg", label: "右大腿", en: "right thigh (hip to knee)", parent: "hip", proximal: P_TOP, distal: P_BOTTOM },
54
+ { name: "left-lower-leg", label: "左小腿", en: "left lower leg (knee to ankle)", parent: "left-upper-leg", proximal: P_TOP, distal: P_BOTTOM },
55
+ { name: "right-lower-leg", label: "右小腿", en: "right lower leg (knee to ankle)", parent: "right-upper-leg", proximal: P_TOP, distal: P_BOTTOM },
56
+ { name: "left-foot", label: "左脚", en: "left foot and shoe", parent: "left-lower-leg", proximal: P_TOP, distal: P_BOTTOM },
57
+ { name: "right-foot", label: "右脚", en: "right foot and shoe", parent: "right-lower-leg", proximal: P_TOP, distal: P_BOTTOM }
58
+ ];
59
+ const SLOT_BY_NAME = new Map(RIG_SLOTS.map((slot) => [slot.name, slot]));
60
+ export function rigSlotOf(name) {
61
+ return SLOT_BY_NAME.get(name);
62
+ }
63
+ /**
64
+ * 人形默认绘制顺序(从最后面到最前面)。
65
+ *
66
+ * 为什么用固定层级而不是完全依赖遮挡投票:投票要在「已经摆好」的部件之间
67
+ * 比较像素,而自动装配本身有误差;摆错了再去投票,得到的是错的层级,接着又
68
+ * 用错的层级去纠正位置,误差会自己咬住自己。人形骨架的层叠关系是稳定的常识,
69
+ * 拿它当基准更可靠。遮挡投票的结果仍然算出来,作为**建议**暴露给界面。
70
+ */
71
+ export const DEFAULT_DRAW_ORDER = [
72
+ "left-upper-arm",
73
+ "right-upper-arm",
74
+ "left-lower-arm",
75
+ "right-lower-arm",
76
+ "left-hand",
77
+ "right-hand",
78
+ "left-upper-leg",
79
+ "right-upper-leg",
80
+ "left-lower-leg",
81
+ "right-lower-leg",
82
+ "left-foot",
83
+ "right-foot",
84
+ "hip",
85
+ "torso",
86
+ "neck",
87
+ "head"
88
+ ];
89
+ /** 语义排序值;表外的部件一律排在最后面(作为附加装饰画在最底层更安全)。 */
90
+ export function drawRankOf(name) {
91
+ const index = DEFAULT_DRAW_ORDER.indexOf(name);
92
+ return index === -1 ? -1 : index;
93
+ }
94
+ export function defaultPartNames() {
95
+ return RIG_SLOTS.map((slot) => slot.name);
96
+ }
97
+ export function partLabel(name) {
98
+ return SLOT_BY_NAME.get(name)?.label ?? name;
99
+ }
100
+ /**
101
+ * 任意部件名的语义父骨骼。
102
+ *
103
+ * 默认网格之外的部件(用户自己命名的「披风」「法杖」……)也要能挂进骨架:
104
+ * 先按关键词猜一个合理宿主,猜不到就挂到躯干上——总比散落一地强。
105
+ */
106
+ export function parentBoneOf(name) {
107
+ const known = SLOT_BY_NAME.get(name);
108
+ if (known !== undefined)
109
+ return known.parent;
110
+ const lower = name.toLowerCase();
111
+ const has = (...keys) => keys.some((key) => lower.includes(key));
112
+ const side = has("left", "左") ? "left" : has("right", "右") ? "right" : "";
113
+ if (has("hair", "hat", "cap", "helmet", "horn", "ear", "eye", "face", "发", "帽", "盔", "角"))
114
+ return "head";
115
+ if (has("beard", "scarf", "cape", "wing", "back", "披风", "翅膀", "背包"))
116
+ return "torso";
117
+ if (has("weapon", "sword", "blade", "shield", "staff", "gun", "刀", "剑", "盾", "杖"))
118
+ return side === "" ? "torso" : `${side}-hand`;
119
+ if (has("arm", "hand", "臂", "手"))
120
+ return side === "" ? "torso" : `${side}-upper-arm`;
121
+ if (has("leg", "foot", "feet", "thigh", "shin", "腿", "脚", "足"))
122
+ return side === "" ? "hip" : `${side}-upper-leg`;
123
+ if (has("tail", "skirt", "belt", "hip", "pelvis", "腰", "裙", "尾"))
124
+ return "hip";
125
+ return "torso";
126
+ }
127
+ /** 默认网格之外部件的锚点规则:整体朝上,绕包围盒底边中点旋转。 */
128
+ export function anchorsOf(name) {
129
+ const known = SLOT_BY_NAME.get(name);
130
+ if (known !== undefined)
131
+ return { proximal: known.proximal, distal: known.distal };
132
+ return { proximal: P_BOTTOM, distal: P_TOP };
133
+ }
134
+ export const RIG_ANIMATIONS = [
135
+ { id: "idle", label: "待机", duration: 1.6, loop: true, summary: "呼吸起伏 + 躯干/头部反向轻摆,首尾闭合可循环" },
136
+ { id: "walk", label: "行走", duration: 0.8, loop: true, summary: "手臂与腿反向摆动,胯部上下颠簸" },
137
+ { id: "run", label: "奔跑", duration: 0.5, loop: true, summary: "行走的夸张版 + 前倾 + 更大的弹跳" },
138
+ { id: "wave", label: "挥手", duration: 1.2, loop: true, summary: "抬起右臂,小臂来回摆动" },
139
+ { id: "jump", label: "跳跃", duration: 1.0, loop: true, summary: "下蹲蓄力 → 起跳 → 滞空 → 落地缓冲" },
140
+ { id: "attack", label: "攻击", duration: 0.6, loop: true, summary: "抬手蓄力 → 挥砍 → 收势跟随" }
141
+ ];
142
+ const ANIMATION_IDS = new Set(RIG_ANIMATIONS.map((item) => item.id));
143
+ const ANIMATION_BY_ID = new Map(RIG_ANIMATIONS.map((item) => [item.id, item]));
144
+ export function animationPresetOf(id) {
145
+ return ANIMATION_BY_ID.get(id);
146
+ }
147
+ export function isAnimationId(value) {
148
+ return typeof value === "string" && ANIMATION_IDS.has(value);
149
+ }
150
+ export function defaultAnimationIds() {
151
+ return ["idle", "walk", "run", "wave", "jump", "attack"];
152
+ }
153
+ /** 参数范围:挡住「amplitude 填 1000」这类会让插件生成一坨垃圾的输入。 */
154
+ export const ANIMATION_AMPLITUDE_RANGE = [0.1, 4];
155
+ export const ANIMATION_DURATION_RANGE = [0.1, 10];
156
+ /** 归一化一份动画参数:非法值丢弃、超范围夹紧、全默认的条目删掉。 */
157
+ export function normalizeAnimationSetting(value) {
158
+ const record = value !== null && typeof value === "object" ? value : {};
159
+ const out = {};
160
+ const duration = Number(record.duration);
161
+ if (Number.isFinite(duration) && duration > 0) {
162
+ out.duration = Number(Math.min(ANIMATION_DURATION_RANGE[1], Math.max(ANIMATION_DURATION_RANGE[0], duration)).toFixed(3));
163
+ }
164
+ const amplitude = Number(record.amplitude);
165
+ if (Number.isFinite(amplitude) && amplitude > 0) {
166
+ out.amplitude = Number(Math.min(ANIMATION_AMPLITUDE_RANGE[1], Math.max(ANIMATION_AMPLITUDE_RANGE[0], amplitude)).toFixed(3));
167
+ }
168
+ return Object.keys(out).length === 0 ? undefined : out;
169
+ }
170
+ /**
171
+ * 归一化**并按预设默认值剪枝**。
172
+ *
173
+ * 与骨骼偏移不同,动画参数的默认值不是 0:幅度默认 1、时长默认是该预设自己的
174
+ * `duration`。所以「改回默认」不能靠「值为零」判断,必须拿预设的原始值比。
175
+ * 剪掉之后,「这条参数有没有被人动过」就是一个存在性判断,而不是数值比较——
176
+ * 界面上的「—」与 JSON diff 都干净。
177
+ */
178
+ export function pruneAnimationSetting(id, value) {
179
+ const normalized = normalizeAnimationSetting(value);
180
+ if (normalized === undefined)
181
+ return undefined;
182
+ const preset = ANIMATION_BY_ID.get(id);
183
+ const out = {};
184
+ if (normalized.amplitude !== undefined && Math.abs(normalized.amplitude - 1) > 1e-6)
185
+ out.amplitude = normalized.amplitude;
186
+ if (normalized.duration !== undefined && preset !== undefined && Math.abs(normalized.duration - preset.duration) > 1e-3) {
187
+ out.duration = normalized.duration;
188
+ }
189
+ return Object.keys(out).length === 0 ? undefined : out;
190
+ }
191
+ export function normalizeAnimationSettings(value) {
192
+ if (value === null || typeof value !== "object")
193
+ return undefined;
194
+ const out = {};
195
+ for (const [id, setting] of Object.entries(value)) {
196
+ if (!ANIMATION_IDS.has(id))
197
+ continue;
198
+ const normalized = pruneAnimationSetting(id, setting);
199
+ if (normalized !== undefined)
200
+ out[id] = normalized;
201
+ }
202
+ return Object.keys(out).length === 0 ? undefined : out;
203
+ }
204
+ // 缓动曲线(归一化控制点,与参考项目一致)。
205
+ const EASE = [0.25, 0, 0.75, 1];
206
+ const EASE_IN = [0.42, 0, 1, 1];
207
+ const EASE_OUT = [0, 0, 0.58, 1];
208
+ const EASE_FAST = [0.4, 0, 0.2, 1];
209
+ function kf(time, angle, x, y, curve = EASE) {
210
+ const frame = { time: round(time, 4) };
211
+ if (angle !== undefined)
212
+ frame.angle = round(angle, 2);
213
+ if (x !== undefined)
214
+ frame.x = round(x, 2);
215
+ if (y !== undefined)
216
+ frame.y = round(y, 2);
217
+ if (curve)
218
+ frame.curve = curve;
219
+ return frame;
220
+ }
221
+ function round(value, digits) {
222
+ const factor = 10 ** digits;
223
+ return Math.round(value * factor) / factor;
224
+ }
225
+ /**
226
+ * 挂点:有网格就出 `mesh`,否则出 `region`。
227
+ *
228
+ * **网格顶点用「部件中心为原点」的坐标**,与 region attachment 的 `-w/2, -h/2` 同一套系——
229
+ * 这样运行时两种附件共用同一条变换链(骨骼世界矩阵 → 挂点 x/y/rotation → 顶点),
230
+ * 不必为 mesh 另写一套定位逻辑。`buildRigMesh` 那边用的是「左上角为原点」,
231
+ * 转换就发生在这里,且只发生一次。
232
+ *
233
+ * 暂时**不写 `weights`**:那是 LBS(多骨骼线性混合蒙皮),格式在两条导出路径里都绕
234
+ * (Spine 的加权顶点是 `[骨骼数, (索引, x, y, 权重)…]` 的交错数组),而它解决的问题是
235
+ * 「一块贴图被多根骨骼共同拉扯」——FFD 时间轴已经把「裙摆上缘不动、下缘甩出去」这件事
236
+ * 做到了,先把能验证的那条链路走通。`RigMesh` 已经产出权重,接进导出是独立的一步。
237
+ */
238
+ /** 每个变形循环采样几个关键帧。6 段对「裙摆左右摆」这种低频运动足够。 */
239
+ export const ANIMATION_DEFORM_SAMPLES = 6;
240
+ /** 取部件的网格(没有就返回 undefined)。网格是确定性重算的,不落盘。 */
241
+ function meshGridOf(spec, part) {
242
+ if (spec === undefined || part === undefined)
243
+ return undefined;
244
+ const width = Math.max(1, part.width);
245
+ const height = Math.max(1, part.height);
246
+ return {
247
+ mesh: buildRigMesh({ width, height, cols: spec.cols, rows: spec.rows, bones: [], x: part.x, y: part.y }),
248
+ width,
249
+ height
250
+ };
251
+ }
252
+ function meshAttachmentOf(name, part, attachment, spec, context) {
253
+ // 这里**不能**复用 `meshGridOf`:那个是给 deform 采样用的,骨骼列表是空的
254
+ // (采样只需要顶点坐标),拿它来算权重会得到一张空权重表,然后静默退回非加权格式
255
+ // ——表现是「权重算了但导出里没有」,不报错。顶点本身两者一致(权重不改变顶点)。
256
+ const grid = buildRigMesh({
257
+ width: Math.max(1, part.width),
258
+ height: Math.max(1, part.height),
259
+ cols: spec.cols,
260
+ rows: spec.rows,
261
+ bones: context.imageBones,
262
+ x: part.x,
263
+ y: part.y
264
+ });
265
+ if (grid === undefined)
266
+ return attachment;
267
+ const vertices = [];
268
+ for (let i = 0; i < grid.vertices.length; i += 2) {
269
+ vertices.push(round(grid.vertices[i] - part.width / 2, 3), round(grid.vertices[i + 1] - part.height / 2, 3));
270
+ }
271
+ const base = {
272
+ ...attachment,
273
+ type: "mesh",
274
+ // `path` 指向图集里的区域名:mesh 与 region 取的是同一张图,只是画法不同。
275
+ path: name,
276
+ uvs: grid.uvs,
277
+ triangles: grid.triangles,
278
+ // Spine 用它做编辑器里的凸包显示;给顶点数即可(规则网格的凸包就是外圈)。
279
+ hull: (grid.cols + 1) * 2 + (grid.rows - 1) * 2
280
+ };
281
+ // LBS 加权顶点(有影响骨骼时)。退回非加权格式是**必须**的:两种格式在运行时是
282
+ // 两条解析分支,混着写会让解析器读到错位的字节流(表现是网格扭曲成乱线,不报错)。
283
+ const weighted = buildWeightedVertices(grid, part, attachment, context);
284
+ return weighted === undefined ? { ...base, vertices } : { ...base, vertices: weighted };
285
+ }
286
+ /**
287
+ * 把「顶点 → 影响骨骼」写成 Spine 的**加权顶点流**。
288
+ *
289
+ * Spine 的格式是交错数组:`[骨骼数, (骨骼下标, x, y, 权重) × 骨骼数, 骨骼数, …]`,
290
+ * 其中 x/y 是顶点**相对该骨骼**的局部坐标(绑定姿势下)。
291
+ *
292
+ * 两处坐标系必须同时对上,这是最容易错的地方:
293
+ * - 自动权重是在**图像坐标**里算的(与部件同一套系,`buildRigMesh` 收的就是它);
294
+ * - 加权顶点要写到**骨骼局部**(Spine 世界坐标 + 骨骼旋转)。
295
+ * 中间的桥是附件变换:`顶点世界 = R(骨世界旋转)·(R(挂点旋转)·顶点 + 挂点偏移) + 骨原点`。
296
+ */
297
+ function buildWeightedVertices(mesh, part, attachment, context) {
298
+ const owned = context.worldOf(part.name);
299
+ if (owned === undefined)
300
+ return undefined;
301
+ if (context.imageBones.length === 0)
302
+ return undefined;
303
+ if (!mesh.weights.some((list) => list.length > 0))
304
+ return undefined;
305
+ const halfW = part.width / 2;
306
+ const halfH = part.height / 2;
307
+ const attRad = ((attachment.rotation ?? 0) * Math.PI) / 180;
308
+ const cosA = Math.cos(attRad);
309
+ const sinA = Math.sin(attRad);
310
+ const boneRad = (owned.rotation * Math.PI) / 180;
311
+ const cosB = Math.cos(boneRad);
312
+ const sinB = Math.sin(boneRad);
313
+ const out = [];
314
+ for (let i = 0; i < mesh.vertices.length / 2; i++) {
315
+ const localX = mesh.vertices[i * 2] - halfW;
316
+ const localY = mesh.vertices[i * 2 + 1] - halfH;
317
+ const attX = cosA * localX - sinA * localY + (attachment.x ?? 0);
318
+ const attY = sinA * localX + cosA * localY + (attachment.y ?? 0);
319
+ const worldX = cosB * attX - sinB * attY + owned.x;
320
+ const worldY = sinB * attX + cosB * attY + owned.y;
321
+ const usable = mesh.weights[i].filter((entry) => {
322
+ const boneName = mesh.bones[entry.bone];
323
+ return context.boneIndex.has(boneName) && context.worldOf(boneName) !== undefined;
324
+ });
325
+ if (usable.length === 0)
326
+ return undefined;
327
+ // 权重必须归一化:Spine 直接按权重线性混合顶点,和不等于 1 会让整块网格缩放。
328
+ const total = usable.reduce((sum, entry) => sum + entry.weight, 0);
329
+ if (total <= 1e-6)
330
+ return undefined;
331
+ out.push(usable.length);
332
+ for (const entry of usable) {
333
+ const boneName = mesh.bones[entry.bone];
334
+ const target = context.worldOf(boneName);
335
+ const rad = (target.rotation * Math.PI) / 180;
336
+ const dx = worldX - target.x;
337
+ const dy = worldY - target.y;
338
+ const c = Math.cos(-rad);
339
+ const s = Math.sin(-rad);
340
+ out.push(context.boneIndex.get(boneName), round(dx * c - dy * s, 3), round(dx * s + dy * c, 3),
341
+ // 6 位小数:权重是乘出来的,4 位在小权重上会直接归零。
342
+ Number((entry.weight / total).toFixed(6)));
343
+ }
344
+ }
345
+ return out;
346
+ }
347
+ /** 宽容取数:非数字/NaN 一律回落到 `fallback`(约束参数来自界面与对话,不能假设它干净)。 */
348
+ function num(value, fallback) {
349
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
350
+ }
351
+ ;
352
+ function has(bones, ...names) {
353
+ return names.some((name) => bones.has(name));
354
+ }
355
+ function genIdle(B) {
356
+ const bones = {};
357
+ const D = 1.6;
358
+ const sway = [
359
+ ["torso", 1.5, 0.5],
360
+ ["neck", 1.0, 0.55],
361
+ ["head", -2.0, 0.6]
362
+ ];
363
+ for (const [name, amp, phase] of sway) {
364
+ if (!B.has(name))
365
+ continue;
366
+ bones[name] = { rotate: [kf(0, 0, undefined, undefined, null), kf(D * phase, amp), kf(D, 0)] };
367
+ }
368
+ if (B.has("torso")) {
369
+ bones.torso = bones.torso ?? {};
370
+ bones.torso.translate = [kf(0, undefined, 0, 0, null), kf(D * 0.5, undefined, 0, 1.5), kf(D, undefined, 0, 0)];
371
+ }
372
+ for (const side of ["left", "right"]) {
373
+ const s = side === "left" ? 1 : -1;
374
+ const parts = [
375
+ [`${side}-upper-arm`, s * 1.5, 0.5],
376
+ [`${side}-lower-arm`, s * 1.0, 0.55]
377
+ ];
378
+ for (const [part, amp, phase] of parts) {
379
+ if (!B.has(part))
380
+ continue;
381
+ bones[part] = { rotate: [kf(0, 0, undefined, undefined, null), kf(D * phase, amp), kf(D, 0)] };
382
+ }
383
+ }
384
+ return bones;
385
+ }
386
+ function genWalk(B) {
387
+ const bones = {};
388
+ const D = 0.8;
389
+ const Q = D / 4;
390
+ const segments = (values) => values.map((value, index) => kf(index * Q, value, undefined, undefined, index === 0 ? null : EASE));
391
+ if (B.has("hip")) {
392
+ bones.hip = {
393
+ translate: [
394
+ kf(0, undefined, 0, 0, null),
395
+ kf(Q, undefined, 0, 3),
396
+ kf(Q * 2, undefined, 0, 0),
397
+ kf(Q * 3, undefined, 0, 3),
398
+ kf(D, undefined, 0, 0)
399
+ ],
400
+ rotate: segments([0, -2, 0, 2, 0])
401
+ };
402
+ }
403
+ if (B.has("torso"))
404
+ bones.torso = { rotate: segments([0, 3, 0, -3, 0]) };
405
+ if (B.has("head"))
406
+ bones.head = { rotate: segments([0, -1.5, 0, 1.5, 0]) };
407
+ for (const [side, shift] of [["left", 0], ["right", 0.5]]) {
408
+ const upper = `${side}-upper-leg`;
409
+ const lower = `${side}-lower-leg`;
410
+ if (B.has(upper)) {
411
+ const a = shift === 0 ? -25 : 25;
412
+ bones[upper] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, 0), kf(Q * 2, -a), kf(Q * 3, 0), kf(D, a)] };
413
+ }
414
+ if (B.has(lower)) {
415
+ const a = shift === 0 ? 5 : 35;
416
+ const b = shift === 0 ? 35 : 5;
417
+ bones[lower] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, 35), kf(Q * 2, b), kf(Q * 3, 5), kf(D, a)] };
418
+ }
419
+ }
420
+ for (const [side, shift] of [["left", 0.5], ["right", 0]]) {
421
+ const upper = `${side}-upper-arm`;
422
+ const lower = `${side}-lower-arm`;
423
+ if (B.has(upper)) {
424
+ const a = shift === 0 ? -20 : 20;
425
+ bones[upper] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, 0), kf(Q * 2, -a), kf(Q * 3, 0), kf(D, a)] };
426
+ }
427
+ if (B.has(lower)) {
428
+ const a = shift === 0 ? -10 : -30;
429
+ const b = shift === 0 ? -30 : -10;
430
+ bones[lower] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, -20), kf(Q * 2, b), kf(Q * 3, -20), kf(D, a)] };
431
+ }
432
+ }
433
+ return bones;
434
+ }
435
+ function genRun(B) {
436
+ const bones = {};
437
+ const D = 0.5;
438
+ const Q = D / 4;
439
+ if (B.has("hip")) {
440
+ bones.hip = {
441
+ translate: [
442
+ kf(0, undefined, 0, 0, null),
443
+ kf(Q, undefined, 0, 6),
444
+ kf(Q * 2, undefined, 0, -2),
445
+ kf(Q * 3, undefined, 0, 6),
446
+ kf(D, undefined, 0, 0)
447
+ ],
448
+ rotate: [kf(0, 0, undefined, undefined, null), kf(Q, -3), kf(Q * 2, 0), kf(Q * 3, 3), kf(D, 0)]
449
+ };
450
+ }
451
+ if (B.has("torso")) {
452
+ // 常驻前倾:起止值不再是 0,循环时依然首尾相接。
453
+ bones.torso = { rotate: [kf(0, 8, undefined, undefined, null), kf(Q, 12), kf(Q * 2, 8), kf(Q * 3, 12), kf(D, 8)] };
454
+ }
455
+ if (B.has("head")) {
456
+ bones.head = { rotate: [kf(0, -6, undefined, undefined, null), kf(Q, -8), kf(Q * 2, -6), kf(Q * 3, -8), kf(D, -6)] };
457
+ }
458
+ for (const [side, ph] of [["left", 0], ["right", 0.5]]) {
459
+ const upper = `${side}-upper-leg`;
460
+ const lower = `${side}-lower-leg`;
461
+ if (B.has(upper)) {
462
+ const a = ph === 0 ? -35 : 40;
463
+ bones[upper] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, 0), kf(Q * 2, -a), kf(Q * 3, 0), kf(D, a)] };
464
+ }
465
+ if (B.has(lower)) {
466
+ const a = ph === 0 ? 10 : 50;
467
+ const b = ph === 0 ? 50 : 10;
468
+ bones[lower] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, 50), kf(Q * 2, b), kf(Q * 3, 10), kf(D, a)] };
469
+ }
470
+ }
471
+ for (const [side, ph] of [["left", 0.5], ["right", 0]]) {
472
+ const upper = `${side}-upper-arm`;
473
+ const lower = `${side}-lower-arm`;
474
+ if (B.has(upper)) {
475
+ const a = ph === 0 ? -30 : 30;
476
+ bones[upper] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, 0), kf(Q * 2, -a), kf(Q * 3, 0), kf(D, a)] };
477
+ }
478
+ if (B.has(lower)) {
479
+ const a = ph === 0 ? -20 : -50;
480
+ const b = ph === 0 ? -50 : -20;
481
+ bones[lower] = { rotate: [kf(0, a, undefined, undefined, null), kf(Q, -35), kf(Q * 2, b), kf(Q * 3, -35), kf(D, a)] };
482
+ }
483
+ }
484
+ return bones;
485
+ }
486
+ function genWave(B) {
487
+ const bones = {};
488
+ const D = 1.2;
489
+ if (B.has("right-upper-arm")) {
490
+ bones["right-upper-arm"] = {
491
+ rotate: [kf(0, 0, undefined, undefined, null), kf(0.2, -130, undefined, undefined, EASE_OUT), kf(D - 0.2, -130, undefined, undefined, null), kf(D, 0, undefined, undefined, EASE_IN)]
492
+ };
493
+ }
494
+ if (B.has("right-lower-arm")) {
495
+ bones["right-lower-arm"] = {
496
+ rotate: [kf(0, 0, undefined, undefined, null), kf(0.2, -30, undefined, undefined, EASE_OUT), kf(0.4, 20), kf(0.6, -20), kf(0.8, 20), kf(1.0, -20), kf(D, 0, undefined, undefined, EASE_IN)]
497
+ };
498
+ }
499
+ if (B.has("torso")) {
500
+ bones.torso = { rotate: [kf(0, 0, undefined, undefined, null), kf(0.2, -3), kf(D - 0.2, -3, undefined, undefined, null), kf(D, 0)] };
501
+ }
502
+ if (B.has("head")) {
503
+ bones.head = { rotate: [kf(0, 0, undefined, undefined, null), kf(0.3, 5), kf(D - 0.2, 5, undefined, undefined, null), kf(D, 0)] };
504
+ }
505
+ return bones;
506
+ }
507
+ function genJump(B) {
508
+ const bones = {};
509
+ const D = 1.0;
510
+ if (B.has("hip")) {
511
+ bones.hip = {
512
+ translate: [
513
+ kf(0, undefined, 0, 0, null),
514
+ kf(0.15, undefined, 0, -20, EASE_IN),
515
+ kf(0.35, undefined, 0, 70, EASE_OUT),
516
+ kf(0.55, undefined, 0, 65, null),
517
+ kf(0.8, undefined, 0, -10, EASE_IN),
518
+ kf(D, undefined, 0, 0, EASE_OUT)
519
+ ]
520
+ };
521
+ }
522
+ if (B.has("torso")) {
523
+ bones.torso = {
524
+ rotate: [kf(0, 0, undefined, undefined, null), kf(0.15, 8, undefined, undefined, EASE_IN), kf(0.35, -5, undefined, undefined, EASE_OUT), kf(0.8, 5, undefined, undefined, EASE_IN), kf(D, 0, undefined, undefined, EASE_OUT)]
525
+ };
526
+ }
527
+ if (B.has("head")) {
528
+ bones.head = { rotate: [kf(0, 0, undefined, undefined, null), kf(0.15, 5), kf(0.35, -8), kf(0.8, 3), kf(D, 0)] };
529
+ }
530
+ for (const side of ["left", "right"]) {
531
+ const s = side === "left" ? 1 : -1;
532
+ const arm = `${side}-upper-arm`;
533
+ const upper = `${side}-upper-leg`;
534
+ const lower = `${side}-lower-leg`;
535
+ if (B.has(arm)) {
536
+ bones[arm] = {
537
+ rotate: [kf(0, 0, undefined, undefined, null), kf(0.15, s * 10), kf(0.35, s * -50, undefined, undefined, EASE_OUT), kf(0.8, s * 8, undefined, undefined, EASE_IN), kf(D, 0)]
538
+ };
539
+ }
540
+ if (B.has(upper)) {
541
+ bones[upper] = { rotate: [kf(0, 0, undefined, undefined, null), kf(0.15, 20), kf(0.35, -15), kf(0.55, 10), kf(0.8, 15), kf(D, 0)] };
542
+ }
543
+ if (B.has(lower)) {
544
+ bones[lower] = { rotate: [kf(0, 0, undefined, undefined, null), kf(0.15, -30), kf(0.35, 10), kf(0.55, -15), kf(0.8, -20), kf(D, 0)] };
545
+ }
546
+ }
547
+ return bones;
548
+ }
549
+ function genAttack(B) {
550
+ const bones = {};
551
+ const D = 0.6;
552
+ if (B.has("right-upper-arm")) {
553
+ bones["right-upper-arm"] = {
554
+ rotate: [kf(0, 0, undefined, undefined, null), kf(0.1, 40, undefined, undefined, EASE_IN), kf(0.25, -80, undefined, undefined, EASE_FAST), kf(0.4, -60, undefined, undefined, null), kf(D, 0, undefined, undefined, EASE_OUT)]
555
+ };
556
+ }
557
+ if (B.has("right-lower-arm")) {
558
+ bones["right-lower-arm"] = {
559
+ rotate: [kf(0, 0, undefined, undefined, null), kf(0.1, -40, undefined, undefined, EASE_IN), kf(0.25, 10, undefined, undefined, EASE_FAST), kf(0.4, -5, undefined, undefined, null), kf(D, 0, undefined, undefined, EASE_OUT)]
560
+ };
561
+ }
562
+ if (B.has("torso")) {
563
+ bones.torso = {
564
+ rotate: [kf(0, 0, undefined, undefined, null), kf(0.1, -8, undefined, undefined, EASE_IN), kf(0.25, 12, undefined, undefined, EASE_FAST), kf(0.4, 5, undefined, undefined, null), kf(D, 0, undefined, undefined, EASE_OUT)]
565
+ };
566
+ }
567
+ if (B.has("hip")) {
568
+ bones.hip = {
569
+ translate: [kf(0, undefined, 0, 0, null), kf(0.1, undefined, -5, -5, EASE_IN), kf(0.25, undefined, 10, 2, EASE_FAST), kf(D, undefined, 0, 0, EASE_OUT)]
570
+ };
571
+ }
572
+ return bones;
573
+ }
574
+ const PRESETS = {
575
+ idle: genIdle,
576
+ walk: genWalk,
577
+ run: genRun,
578
+ wave: genWave,
579
+ jump: genJump,
580
+ attack: genAttack
581
+ };
582
+ // ── Spine 4.2 wire format 转换 ──────────────────────────────────────────
583
+ /**
584
+ * 时间轴类型 → 它驱动的属性名与默认值。
585
+ * 属性个数决定 bezier 要写 4 个数(单属性)还是 8 个(双属性)。
586
+ */
587
+ const TIMELINE_PROPERTIES = {
588
+ rotate: [["value", 0]],
589
+ translate: [["x", 0], ["y", 0]],
590
+ scale: [["x", 1], ["y", 1]],
591
+ shear: [["x", 0], ["y", 0]]
592
+ };
593
+ /**
594
+ * 一条时间轴驱动几个属性。
595
+ *
596
+ * 这个数字直接决定 bezier 控制点该写 4 个还是 8 个——写错了运行时就会越界读
597
+ * `undefined`,NaN 顺着骨骼变换扩散,整只骨架渲染一帧后消失(见 `convertTimeline`
598
+ * 的注释)。所以它必须能被导出前的校验器读到,而不是只活在 `spine.ts` 里。
599
+ */
600
+ export function timelinePropertyCount(kind) {
601
+ return TIMELINE_PROPERTIES[kind]?.length ?? 0;
602
+ }
603
+ /**
604
+ * 把一条时间轴就地改写成 Spine 4.2 wire format。三个坑(照搬参考项目的注释):
605
+ *
606
+ * 1. 旋转值写在 `value` 下,不是 `angle`——4.x 运行时遇到 `angle` 会当成 0,骨骼不动。
607
+ * 2. bezier 是**每个被动画属性一份**,不是每个关键帧一份。`rotate` 一份 4 个数,
608
+ * `translate` 两份共 8 个;只给 4 个,运行时读过数组末尾得到 undefined,
609
+ * NaN 顺着骨骼变换扩散,骨架渲染一帧后整体消失。
610
+ * 3. 控制点是**绝对量**(和 time / value 同单位),不是 0~1 的归一化比例。
611
+ * 归一化会让手柄落到自己所在区间之外,插值变成突跳而不是缓动。
612
+ *
613
+ * 另外:某个关键帧的 curve 描述的是**从它开始**的那一段,所以归一化 curve 要
614
+ * 整体前移一帧——生成器把它挂在第 i 帧上,实际描述的是 i-1 → i。
615
+ */
616
+ function convertTimeline(kind, frames) {
617
+ const properties = TIMELINE_PROPERTIES[kind];
618
+ if (properties === undefined || frames.length < 2)
619
+ return;
620
+ if (kind === "rotate") {
621
+ for (const frame of frames) {
622
+ if (frame.angle !== undefined) {
623
+ frame.value = frame.angle;
624
+ delete frame.angle;
625
+ }
626
+ }
627
+ }
628
+ const authored = frames.map((frame) => {
629
+ const curve = frame.curve ?? null;
630
+ delete frame.curve;
631
+ return curve;
632
+ });
633
+ for (let i = 0; i < frames.length - 1; i++) {
634
+ const curve = authored[i + 1];
635
+ if (curve === null || curve === undefined)
636
+ continue;
637
+ if (curve === "stepped") {
638
+ frames[i].curve = "stepped";
639
+ continue;
640
+ }
641
+ if (!Array.isArray(curve) || curve.length < 4)
642
+ continue;
643
+ const [cx1, cy1, cx2, cy2] = curve;
644
+ const time1 = frames[i].time;
645
+ const time2 = frames[i + 1].time;
646
+ const span = time2 - time1;
647
+ const absolute = [];
648
+ for (const [name, fallback] of properties) {
649
+ const value1 = frames[i][name] ?? fallback;
650
+ const value2 = frames[i + 1][name] ?? fallback;
651
+ const delta = value2 - value1;
652
+ absolute.push(round(time1 + span * cx1, 6), round(value1 + delta * cy1, 6), round(time1 + span * cx2, 6), round(value1 + delta * cy2, 6));
653
+ }
654
+ frames[i].curve = absolute;
655
+ }
656
+ }
657
+ function toSpine42(animations) {
658
+ for (const animation of Object.values(animations)) {
659
+ const bones = animation?.bones;
660
+ if (bones === null || typeof bones !== "object")
661
+ continue;
662
+ for (const timelines of Object.values(bones)) {
663
+ for (const [kind, frames] of Object.entries(timelines)) {
664
+ if (Array.isArray(frames))
665
+ convertTimeline(kind, frames);
666
+ }
667
+ }
668
+ }
669
+ }
670
+ /**
671
+ * 把参数作用在**简写**上(`toSpine42` 之前)。
672
+ *
673
+ * 顺序很关键:简写的 curve 是归一化控制点,时间与数值一起缩放之后,由
674
+ * `convertTimeline` 绝对化出来的控制点仍落在正确的段内。若反过来先绝对化再缩放,
675
+ * 控制点会跑到所属区间之外,运动就变成突跳。
676
+ */
677
+ function applyAnimationSetting(bones, preset, setting) {
678
+ if (setting === undefined)
679
+ return;
680
+ const amplitude = setting.amplitude ?? 1;
681
+ const scale = setting.duration !== undefined && preset.duration > 0 ? setting.duration / preset.duration : 1;
682
+ if (amplitude === 1 && scale === 1)
683
+ return;
684
+ for (const timelines of Object.values(bones)) {
685
+ for (const [kind, frames] of Object.entries(timelines)) {
686
+ if (!Array.isArray(frames))
687
+ continue;
688
+ for (const frame of frames) {
689
+ if (typeof frame.time === "number")
690
+ frame.time = round(frame.time * scale, 4);
691
+ if (kind === "rotate" && typeof frame.angle === "number")
692
+ frame.angle = round(frame.angle * amplitude, 2);
693
+ if (kind === "translate") {
694
+ if (typeof frame.x === "number")
695
+ frame.x = round(frame.x * amplitude, 2);
696
+ if (typeof frame.y === "number")
697
+ frame.y = round(frame.y * amplitude, 2);
698
+ }
699
+ if (kind === "scale") {
700
+ // 缩放是**相对 1** 的量:0.9 的挤压在 amplitude=2 时应该变成 0.8。
701
+ if (typeof frame.x === "number")
702
+ frame.x = round(1 + (frame.x - 1) * amplitude, 4);
703
+ if (typeof frame.y === "number")
704
+ frame.y = round(1 + (frame.y - 1) * amplitude, 4);
705
+ }
706
+ }
707
+ }
708
+ }
709
+ }
710
+ /**
711
+ * 生成全部预设动画的**简写**形式。
712
+ *
713
+ * 简写 = `{time: 秒, angle/x/y, curve: 0~1 归一化控制点 | "stepped" | null}`。
714
+ * 它是两条导出路径(Spine 4.2 / DragonBones 5.5)**共同的输入**:Spine 的
715
+ * `curve` 是绝对量、DragonBones 的是 0~1 归一化,两者必须各自编码一次——
716
+ * 早先只有 `buildAnimations` 一条路(末尾顺手 `toSpine42` 就地改写),
717
+ * 拿它去喂 DragonBones 就会把绝对量当成归一化值写出去。
718
+ */
719
+ export function buildAnimationShorthands(boneNames, ids, settings = {}) {
720
+ const set = new Set(boneNames);
721
+ const animations = {};
722
+ for (const id of ids) {
723
+ const generator = PRESETS[id];
724
+ const preset = ANIMATION_BY_ID.get(id);
725
+ if (generator === undefined || preset === undefined)
726
+ continue;
727
+ const setting = settings[id];
728
+ const bones = generator(set);
729
+ if (Object.keys(bones).length === 0)
730
+ continue;
731
+ applyAnimationSetting(bones, preset, setting);
732
+ animations[id] = { bones };
733
+ }
734
+ return animations;
735
+ }
736
+ /** 生成全部预设动画(Spine 4.2 wire format)。传入的 `boneNames` 决定哪些骨骼会被写到。 */
737
+ export function buildAnimations(boneNames, ids, settings = {}) {
738
+ const animations = buildAnimationShorthands(boneNames, ids, settings);
739
+ toSpine42(animations);
740
+ return animations;
741
+ }
742
+ /** 实际生效的时长(预设时长被参数覆盖时以参数为准)。 */
743
+ export function animationDurationOf(id, settings = {}) {
744
+ const preset = ANIMATION_BY_ID.get(id);
745
+ return settings[id]?.duration ?? preset?.duration ?? 0;
746
+ }
747
+ /**
748
+ * 从预设**实例化**一份可编辑的动画。
749
+ *
750
+ * 时间轴编辑器第一次碰到某台动画时用它当初始值——「编辑」这个动作的本质是
751
+ * 「把参数化的预设固化成一份显式的关键帧数据,从此以数据为准」。参数
752
+ * (`animationSettings` 的时长 / 幅度)在这里已经被烘进关键帧,之后再改参数
753
+ * 不会影响这份数据,这是刻意的:否则「手调过的帧」会被下一次调参悄悄改掉。
754
+ */
755
+ export function instantiateAnimation(id, boneNames, settings = {}) {
756
+ const preset = ANIMATION_BY_ID.get(id);
757
+ if (preset === undefined)
758
+ return undefined;
759
+ const shorthand = buildAnimationShorthands(boneNames, [id], settings)[id];
760
+ if (shorthand === undefined)
761
+ return undefined;
762
+ // 末帧永远不带 curve:Spine 的 curve 描述的是「以本帧为起点」的下一段,末帧没有下一段,
763
+ // 写了也永远不会被读到(方案附录 A 第 4 条)。预设生成器给每帧都挂了默认缓动,
764
+ // 这里清掉——编辑器里的数据不该有「永远不会生效的字段」,用户会以为自己改到了什么。
765
+ for (const kinds of Object.values(shorthand.bones)) {
766
+ for (const frames of Object.values(kinds)) {
767
+ if (Array.isArray(frames) && frames.length > 0)
768
+ frames[frames.length - 1].curve = null;
769
+ }
770
+ }
771
+ return {
772
+ duration: animationDurationOf(id, settings),
773
+ loop: preset.loop,
774
+ bones: shorthand.bones,
775
+ source: "preset"
776
+ };
777
+ }
778
+ /** 一条时间轴在简写里驱动哪些字段(用于校验与界面)。 */
779
+ export function timelineValueKeys(kind) {
780
+ return (TIMELINE_PROPERTIES[kind] ?? []).map(([name]) => name);
781
+ }
782
+ /** 简写时间轴里的「旋转」字段名是 `angle`(`toSpine42` 之后才改名 `value`)。 */
783
+ export function keyframeValueKeys(kind) {
784
+ if (kind === "rotate")
785
+ return ["angle"];
786
+ return timelineValueKeys(kind);
787
+ }
788
+ /** 沿父级往上取链上的骨骼名,**从根到末端**。末端骨自己也算。 */
789
+ export function ikChainOf(boneParent, bone, chain) {
790
+ const out = [bone];
791
+ let cursor = boneParent.get(bone);
792
+ for (let i = 0; i < chain && cursor !== undefined; i++) {
793
+ out.unshift(cursor);
794
+ cursor = boneParent.get(cursor);
795
+ }
796
+ return out;
797
+ }
798
+ /** 图片像素坐标 → Spine 世界坐标(Y 翻转、水平以画布中心为 0)。 */
799
+ function toWorld(px, py, canvasWidth, canvasHeight) {
800
+ return { x: px - canvasWidth / 2, y: canvasHeight - py };
801
+ }
802
+ function deg(rad) {
803
+ return (rad * 180) / Math.PI;
804
+ }
805
+ function normalizeAngle(value) {
806
+ let angle = value % 360;
807
+ if (angle > 180)
808
+ angle -= 360;
809
+ if (angle <= -180)
810
+ angle += 360;
811
+ return round(angle, 4);
812
+ }
813
+ /**
814
+ * 核心:把「每个部件的像素框 + 层级」变成一份可动画的骨架。
815
+ *
816
+ * 对每个部件:
817
+ * 1. 取近端/远端锚点,得到世界坐标下的骨骼原点与朝向(Spine 的 0° 指向 +Y,
818
+ * 所以朝向向量 (dx,dy) 对应 `atan2(-dx, dy)`)。
819
+ * 2. 骨骼 x/y 换算到**父骨骼的局部坐标系**里(spine-core 会先转父骨骼再平移)。
820
+ * 3. 挂点用「图片中心 − 骨骼原点」再逆旋转到骨骼局部系,并用 `rotation`
821
+ * 补偿骨骼朝向——这样**初始姿态和装配结果逐像素一致**,而动画一开始,
822
+ * 部件就绕着正确的那节骨头转。
823
+ */
824
+ export function buildSkeleton(options) {
825
+ const warnings = [];
826
+ const visible = options.parts.filter((part) => part.hidden !== true);
827
+ const byName = new Map(visible.map((part) => [part.name, part]));
828
+ // 只需要「这个部件在哪个骨骼上」——骨骼名与部件名一一对应,少一层心智负担。
829
+ const boneNames = new Set(visible.map((part) => part.name));
830
+ boneNames.add("root");
831
+ /**
832
+ * 只解析「语义 → 关键词」这一层父级,**不管成环**。成环在下面的拓扑排序里统一断。
833
+ *
834
+ * 为什么要拆开:早先 `resolveParent(name, seen)` 把「按名字找父级」和
835
+ * 「按当前祖先栈断环」揉在一个函数里,然后被**调用了两次**——拓扑排序时传的是
836
+ * 祖先栈,写骨骼字段时传的是空集。两次结果可以不同,于是「排序用的父级」和
837
+ * 「写进产物的父级」对不上,真的产出了 `hip ← torso` 且 `torso ← hip` 的**互环**
838
+ * (Spine 里没人发现,是 DragonBones 那边的拓扑序校验拦下来的)。
839
+ */
840
+ const rawParentOf = (name) => {
841
+ // ① 语义层显式指定的父级优先。它可能指向一个被隐藏/未生成的部件——
842
+ // 那种情况下不能让骨架断链,所以继续走 ②。
843
+ const explicit = byName.get(name)?.parent;
844
+ if (explicit !== undefined && explicit !== name && boneNames.has(explicit))
845
+ return explicit;
846
+ // ② 按名字关键词沿语义链往上找第一个真实存在的骨骼。
847
+ // 加 guard 是因为 `parentBoneOf` 的关键词规则本身可能成环
848
+ // (例如某个名字同时命中两组关键词),无界循环会让整个推导卡死。
849
+ const guard = new Set();
850
+ let cursor = parentBoneOf(name);
851
+ while (cursor !== undefined && !guard.has(cursor)) {
852
+ guard.add(cursor);
853
+ if (cursor !== name && boneNames.has(cursor))
854
+ return cursor;
855
+ const next = parentBoneOf(cursor);
856
+ if (next === cursor)
857
+ break;
858
+ cursor = next;
859
+ }
860
+ return undefined;
861
+ };
862
+ /**
863
+ * 兜底宿主:优先躯干,其次胯部。
864
+ *
865
+ * **只服务默认网格之外的部件**。已知槽位走到这里只有一个可能——它的
866
+ * `parent` 就是 `undefined`,也就是 `hip`(胯部)本身:它是身体根,
867
+ * 兜底把它挂到躯干上会立刻造出 `hip ↔ torso` 的互环
868
+ * (躯干的父级按名字规则正是胯部)。这个互环在 v1 一直存在,
869
+ * 只是因为两边都没做拓扑序校验而没人发现。
870
+ */
871
+ const fallbackHostOf = (name) => {
872
+ if (name === "root")
873
+ return undefined;
874
+ if (SLOT_BY_NAME.has(name))
875
+ return undefined;
876
+ if (byName.has("torso"))
877
+ return "torso";
878
+ if (byName.has("hip"))
879
+ return "hip";
880
+ return undefined;
881
+ };
882
+ // 拓扑排序:父骨骼永远排在子骨骼前面。
883
+ //
884
+ // 父级**只解析一次**并存进 `resolvedParent`,排序与骨骼字段共用同一份——
885
+ // 这样「排序里的父子关系」与「产物里的父子关系」不可能再分叉。
886
+ const resolvedParent = new Map();
887
+ const ordered = [];
888
+ const visited = new Set();
889
+ const visit = (name, stack) => {
890
+ if (visited.has(name) || stack.has(name))
891
+ return;
892
+ stack.add(name);
893
+ if (name !== "root") {
894
+ let parent = rawParentOf(name);
895
+ // 语义链可能绕回自己(例如「胯部」的父级按语义也算胯部),必须在这里断开,
896
+ // 否则骨骼表里会出现自环,渲染时无限递归。
897
+ if (parent === name)
898
+ parent = undefined;
899
+ if (parent !== undefined && stack.has(parent)) {
900
+ warnings.push(`骨骼 ${name} 的父级 ${parent} 与祖先成环,这条边已断开`);
901
+ parent = undefined;
902
+ }
903
+ if (parent === undefined)
904
+ parent = fallbackHostOf(name);
905
+ // 兜底宿主自己也可能正在栈上(torso 与 hip 互相指认时就是这么来的)——
906
+ // 早先这里没有第二道检查,于是「挂到 torso」把刚断开的环**又接了回来**。
907
+ if (parent !== undefined && stack.has(parent)) {
908
+ warnings.push(`骨骼 ${name} 的兜底宿主 ${parent} 也在环上,改挂到 root`);
909
+ parent = undefined;
910
+ }
911
+ resolvedParent.set(name, parent);
912
+ if (parent !== undefined)
913
+ visit(parent, stack);
914
+ }
915
+ else {
916
+ resolvedParent.set("root", undefined);
917
+ }
918
+ stack.delete(name);
919
+ visited.add(name);
920
+ ordered.push(name);
921
+ };
922
+ for (const name of visible.map((part) => part.name))
923
+ visit(name, new Set());
924
+ const world = new Map();
925
+ world.set("root", { x: 0, y: 0, rotation: 0 });
926
+ const bones = [{ name: "root", x: 0, y: 0, rotation: 0, length: 0 }];
927
+ const attachments = {};
928
+ const slots = [];
929
+ const sorted = [...visible].sort((a, b) => a.z - b.z);
930
+ /**
931
+ * 每个部件的近端锚点世界坐标(骨骼原点)。
932
+ *
933
+ * 预先算一遍,是因为**骨骼方向要指向子部件的近端**——那需要父骨骼在处理时就能
934
+ * 拿到子部件的近端坐标,而拓扑序里子部件排在后面。
935
+ */
936
+ const proxWorldOf = new Map();
937
+ for (const name of ordered) {
938
+ if (name === "root")
939
+ continue;
940
+ const part = byName.get(name);
941
+ if (part === undefined)
942
+ continue;
943
+ const anchors = anchorsOf(name);
944
+ const proximal = part.proximal ?? anchors.proximal;
945
+ proxWorldOf.set(name, toWorld(part.x + proximal[0] * part.width, part.y + proximal[1] * part.height, options.canvasWidth, options.canvasHeight));
946
+ }
947
+ /**
948
+ * 父 → 子。
949
+ *
950
+ * 用来把骨骼**末端指到子骨骼的起点**上。这是「骨骼首尾相接」的来源:
951
+ * 早先每根骨的方向都取「自己部件的近端 → 远端」(固定的上中 → 下中),于是
952
+ * 斜着摆的部件(举起的手臂)会解出两条**互相错开**的骨骼——实测上臂到前臂的
953
+ * 骨骼原点只差 41.5px,而上臂骨骼长 85px。视觉上拼图是对的,但动画时部件
954
+ * 绕的旋转中心不在关节上。
955
+ */
956
+ const childrenOf = new Map();
957
+ for (const [child, parent] of resolvedParent) {
958
+ if (parent === undefined || child === "root")
959
+ continue;
960
+ const list = childrenOf.get(parent) ?? [];
961
+ list.push(child);
962
+ childrenOf.set(parent, list);
963
+ }
964
+ for (const list of childrenOf.values())
965
+ list.sort();
966
+ for (const name of ordered) {
967
+ if (name === "root")
968
+ continue;
969
+ const part = byName.get(name);
970
+ if (part === undefined)
971
+ continue;
972
+ // 锚点:语义层给了就用它(人在界面上拖过、或 AI 判断过),没给才回落到
973
+ // 角色的默认锚点。这是「初始姿态逐像素还原」的前提下唯一允许改动的输入。
974
+ const fallbackAnchors = anchorsOf(name);
975
+ const proximal = part.proximal ?? fallbackAnchors.proximal;
976
+ const distal = part.distal ?? fallbackAnchors.distal;
977
+ const proxPx = part.x + proximal[0] * part.width;
978
+ const proxPy = part.y + proximal[1] * part.height;
979
+ const distPx = part.x + distal[0] * part.width;
980
+ const distPy = part.y + distal[1] * part.height;
981
+ const centerPx = part.x + part.width / 2;
982
+ const centerPy = part.y + part.height / 2;
983
+ const prox = toWorld(proxPx, proxPy, options.canvasWidth, options.canvasHeight);
984
+ const ownDist = toWorld(distPx, distPy, options.canvasWidth, options.canvasHeight);
985
+ const center = toWorld(centerPx, centerPy, options.canvasWidth, options.canvasHeight);
986
+ // 骨骼末端优先指到**子部件的近端**——「首尾相接」就是这么来的。
987
+ // 没有子部件(叶子骨,例如头、手、脚)才退回自己部件的远端。
988
+ //
989
+ // 只影响朝向与长度:位置(`prox`)与挂点都照旧,所以初始姿态一格不动。
990
+ const childName = (childrenOf.get(name) ?? [])[0];
991
+ const childProx = childName === undefined ? undefined : proxWorldOf.get(childName);
992
+ const dist = childProx !== undefined && Math.hypot(childProx.x - prox.x, childProx.y - prox.y) >= 1 ? childProx : ownDist;
993
+ const dirX = dist.x - prox.x;
994
+ const dirY = dist.y - prox.y;
995
+ const length = Math.hypot(dirX, dirY) || Math.max(1, Math.max(part.width, part.height));
996
+ const worldRot = deg(Math.atan2(-dirX, dirY));
997
+ const parentName = resolvedParent.get(name);
998
+ const parentWorld = world.get(parentName ?? "root") ?? world.get("root");
999
+ // 位移先逆旋转到父骨骼局部系,再作为骨骼 x/y。
1000
+ const deltaX = prox.x - parentWorld.x;
1001
+ const deltaY = prox.y - parentWorld.y;
1002
+ const pRad = (parentWorld.rotation * Math.PI) / 180;
1003
+ const cosP = Math.cos(-pRad);
1004
+ const sinP = Math.sin(-pRad);
1005
+ const localX = deltaX * cosP - deltaY * sinP;
1006
+ const localY = deltaX * sinP + deltaY * cosP;
1007
+ // ── 三通道:local = origin ⊕ offset(动画由时间轴另行叠加)──────────
1008
+ //
1009
+ // 注意 `world` 里存的仍然是 **origin**(不含 offset):
1010
+ // 子骨骼的局部坐标要相对父骨骼的**绑定姿势**去算,这样运行时父骨骼一旦带上
1011
+ // offset,子骨骼会跟着一起动(转躯干时头/手臂跟着转)——这才是「手工调骨骼」
1012
+ // 期望的手感。若把 offset 也并进 world,子骨骼会被抵消掉、不跟随。
1013
+ const originRotation = normalizeAngle(worldRot - (parentName === undefined ? 0 : parentWorld.rotation));
1014
+ const boneOffset = part.offset ?? {};
1015
+ bones.push({
1016
+ name,
1017
+ parent: parentName,
1018
+ x: round(localX + (boneOffset.x ?? 0), 4),
1019
+ y: round(localY + (boneOffset.y ?? 0), 4),
1020
+ rotation: normalizeAngle(originRotation + (boneOffset.rotation ?? 0)),
1021
+ length: round(length, 4)
1022
+ });
1023
+ world.set(name, { x: prox.x, y: prox.y, rotation: worldRot });
1024
+ // 挂点:图片中心相对骨骼原点,逆旋转到骨骼局部系。
1025
+ const offX = center.x - prox.x;
1026
+ const offY = center.y - prox.y;
1027
+ const bRad = (worldRot * Math.PI) / 180;
1028
+ const cosB = Math.cos(-bRad);
1029
+ const sinB = Math.sin(-bRad);
1030
+ attachments[name] = {
1031
+ [name]: {
1032
+ x: round(offX * cosB - offY * sinB, 4),
1033
+ y: round(offX * sinB + offY * cosB, 4),
1034
+ // 挂点自身旋转 = 抵消骨骼朝向(让初始姿态正立)+ 手动装配里拧的角度。
1035
+ rotation: normalizeAngle(-worldRot + (part.rotation ?? 0)),
1036
+ width: round(part.width, 4),
1037
+ height: round(part.height, 4)
1038
+ }
1039
+ };
1040
+ slots.push({ name, bone: name, attachment: name });
1041
+ }
1042
+ // slots 的顺序即绘制顺序:越靠前画得越早(越靠后)。按 z 升序排。
1043
+ slots.sort((a, b) => {
1044
+ const za = visible.find((part) => part.name === a.name)?.z ?? 0;
1045
+ const zb = visible.find((part) => part.name === b.name)?.z ?? 0;
1046
+ return za - zb;
1047
+ });
1048
+ const orderedBoneNames = bones.map((bone) => bone.name);
1049
+ const settings = options.animationSettings ?? {};
1050
+ // 简写留一份给 DragonBones:它的 curve 是 0~1 归一化,而 `toSpine42` 会就地把
1051
+ // curve 绝对化,走过一遍就拿不回来了。
1052
+ const animationsRaw = buildAnimationShorthands(orderedBoneNames, options.animationIds, settings);
1053
+ // 手工/AI 编辑过的动画在这里**顶掉**预设实例(而不是在转换之后再塞进去)。
1054
+ //
1055
+ // 早先的写法是先 `buildAnimations`(内部已 `toSpine42`)再赋值 customAnimations、
1056
+ // 最后又调一次 `toSpine42`——那一遍会把**已经绝对化**的预设 curve 当归一化值
1057
+ // 再绝对化一次(`time1 + span × 已绝对值`),运动直接算飞。合并必须发生在
1058
+ // 简写层,转换只做一次。
1059
+ if (options.customAnimations !== undefined) {
1060
+ for (const [key, value] of Object.entries(options.customAnimations)) {
1061
+ if (value === null || value === undefined)
1062
+ continue;
1063
+ animationsRaw[key] = value;
1064
+ }
1065
+ }
1066
+ const animations = JSON.parse(JSON.stringify(animationsRaw));
1067
+ toSpine42(animations);
1068
+ // ── FFD 变形时间轴(M5 的 L3)───────────────────────────────────────
1069
+ //
1070
+ // 把波形**采样**成有限个关键帧再导出:两条导出路径的 deform/ffd 都是关键帧列表,
1071
+ // 而波形是连续的。采样点数取 6(每周期 6 段),对「裙摆左右摆」这个低频运动足够,
1072
+ // 也不会让 JSON 膨胀——顶点数是 49,每帧 98 个数字,6 帧约 600 个。
1073
+ //
1074
+ // 采样时间对齐到**每个动画自己的时长**:这样每个动画的 deform 都首尾闭合,
1075
+ // 切成任何一台动画看,裙摆都不会在接缝处跳一下。
1076
+ for (const [id, animation] of Object.entries(animations)) {
1077
+ const duration = animationDurationOf(id, options.animationSettings ?? {});
1078
+ for (const [name, deform] of Object.entries(options.deforms ?? {})) {
1079
+ const grid = meshGridOf(options.meshes?.[name], byName.get(name));
1080
+ if (grid === undefined || deform === null || deform === undefined)
1081
+ continue;
1082
+ const frames = [];
1083
+ for (let i = 0; i <= ANIMATION_DEFORM_SAMPLES; i++) {
1084
+ const at = (i / ANIMATION_DEFORM_SAMPLES) * duration;
1085
+ const { offsets } = buildWaveDeform({
1086
+ mesh: grid.mesh,
1087
+ width: grid.width,
1088
+ height: grid.height,
1089
+ phase: at / Math.max(0.01, deform.duration),
1090
+ amplitude: deform.amplitude,
1091
+ cycles: deform.cycles,
1092
+ direction: deform.direction,
1093
+ anchor: deform.anchor
1094
+ });
1095
+ frames.push({ time: round(at, 4), offset: 0, vertices: offsets });
1096
+ }
1097
+ animation.deform = animation.deform ?? {};
1098
+ animation.deform[name] = { default: frames };
1099
+ }
1100
+ }
1101
+ if (Object.keys(animations).length === 0) {
1102
+ warnings.push("没有生成任何动画:所选预设依赖的骨骼名在本次拆件里都不存在");
1103
+ }
1104
+ const hash = createHash("md5")
1105
+ .update(JSON.stringify({ w: options.canvasWidth, h: options.canvasHeight, parts: visible.map((p) => [p.name, p.x, p.y, p.width, p.height]) }))
1106
+ .digest("hex")
1107
+ .slice(0, 20);
1108
+ // ── IK 约束 ──────────────────────────────────────────────────────────
1109
+ //
1110
+ // 目标骨不在骨架里就补一根:它只是一个**可拖的点**,不带贴图、不参与绘制。
1111
+ // 位置取链末端当前的世界坐标,于是「刚加上约束时姿态不变」——用户看到的是
1112
+ // 一个可以直接拖的目标点,而不是先跳一下。
1113
+ const ik = [];
1114
+ const boneParent = new Map(bones.map((bone) => [bone.name, bone.parent]));
1115
+ for (const constraint of options.constraints ?? []) {
1116
+ if (constraint === null || typeof constraint !== "object")
1117
+ continue;
1118
+ if (constraint.type !== undefined && constraint.type !== "ik")
1119
+ continue;
1120
+ const chainLength = Math.max(1, Math.min(8, Math.round(num(constraint.chain, 1))));
1121
+ const chain = ikChainOf(boneParent, constraint.bone, chainLength);
1122
+ if (chain.length < 2) {
1123
+ warnings.push(`IK「${constraint.name}」的链端骨骼不存在或没有父级:${constraint.bone}`);
1124
+ continue;
1125
+ }
1126
+ if (chain[chain.length - 1] !== constraint.bone) {
1127
+ warnings.push(`IK「${constraint.name}」的链端骨骼不是 ${constraint.bone}`);
1128
+ continue;
1129
+ }
1130
+ // 链上每根骨都必须有长度,否则余弦定理无从下手(长度 0 的骨在几何上是退化的)。
1131
+ const lengths = chain.map((name) => bones.find((bone) => bone.name === name)?.length ?? 0);
1132
+ if (lengths.some((value) => value <= 0.01)) {
1133
+ warnings.push(`IK「${constraint.name}」的链上有长度为 0 的骨骼(${chain.filter((name, index) => lengths[index] <= 0.01).join("、")}),已跳过`);
1134
+ continue;
1135
+ }
1136
+ const targetName = typeof constraint.target === "string" && constraint.target !== "" ? constraint.target : `${constraint.name}-target`;
1137
+ if (!boneNames.has(targetName)) {
1138
+ // 目标点落在链末端的**骨尖**上(原点沿自身朝向再走一个 length,和预览器的画法一致):
1139
+ // 加上约束的那一刻姿态不变,用户看到的是一个可以直接拖的点,而不是先跳一下。
1140
+ const tip = bones.find((bone) => bone.name === constraint.bone);
1141
+ const origin = world.get(constraint.bone) ?? { x: tip.x, y: tip.y, rotation: 0 };
1142
+ const dirRad = (origin.rotation * Math.PI) / 180;
1143
+ const tipWorldX = origin.x - Math.sin(dirRad) * tip.length;
1144
+ const tipWorldY = origin.y + Math.cos(dirRad) * tip.length;
1145
+ bones.splice(bones.findIndex((bone) => bone.name === constraint.bone) + 1, 0, { name: targetName, x: round(tipWorldX, 4), y: round(tipWorldY, 4), rotation: 0, length: 0 });
1146
+ boneNames.add(targetName);
1147
+ boneParent.set(targetName, undefined);
1148
+ }
1149
+ ik.push({
1150
+ name: constraint.name,
1151
+ // Spine 4.2:`bones` 是链上的骨骼,**包含末端**、顺序从根到末端
1152
+ // (官方示例 `["front-upper-arm","front-lower-arm"]`)。
1153
+ // DragonBones 那边要的是「末端骨 + chain 长度」,导出时从这份反推。
1154
+ bones: chain,
1155
+ target: targetName,
1156
+ mix: Math.max(0, Math.min(1, num(constraint.weight, 1))),
1157
+ bendPositive: constraint.bendPositive !== false,
1158
+ compress: false,
1159
+ stretch: false,
1160
+ uniform: false,
1161
+ // 我们自己的字段:DragonBones 导出要用,Spine 侧会忽略。
1162
+ chain: chainLength,
1163
+ order: ik.length
1164
+ });
1165
+ }
1166
+ // ── Path 约束 ────────────────────────────────────────────────────────
1167
+ //
1168
+ // Spine 的 path 约束要求目标是一个**带 PathAttachment 的槽位**,所以这里顺手建一个
1169
+ // 无贴图的槽挂在 `root` 上:路径是全局的(当前设计里它不跟随骨骼)。
1170
+ // 槽位没有贴图,渲染器取不到 image 就会跳过,不影响绘制顺序。
1171
+ const pathConstraints = [];
1172
+ for (const [name, entry] of Object.entries(options.paths ?? {})) {
1173
+ const chain = (entry.bones ?? []).filter((bone) => boneNames.has(bone));
1174
+ if (chain.length === 0) {
1175
+ warnings.push(`Path「${name}」没有可用的骨骼链,已跳过`);
1176
+ continue;
1177
+ }
1178
+ if (entry.points.length < 4) {
1179
+ warnings.push(`Path「${name}」点数不足,已跳过`);
1180
+ continue;
1181
+ }
1182
+ const spec = { points: entry.points, closed: entry.closed === true };
1183
+ const lengths = pathSegmentLengths(spec);
1184
+ // 路径点转成**骨骼世界坐标**:槽挂在 root(世界原点),所以 attachment 的顶点
1185
+ // 直接用世界坐标即可,不必再相对某根骨骼做一次逆变换。
1186
+ const vertices = [];
1187
+ for (let i = 0; i + 1 < entry.points.length; i += 2) {
1188
+ const world = toWorld(entry.points[i], entry.points[i + 1], options.canvasWidth, options.canvasHeight);
1189
+ vertices.push(round(world.x, 3), round(world.y, 3));
1190
+ }
1191
+ const slotName = `path:${name}`;
1192
+ slots.push({ name: slotName, bone: "root", attachment: name });
1193
+ attachments[slotName] = {
1194
+ [name]: {
1195
+ type: "path",
1196
+ vertices,
1197
+ lengths,
1198
+ closed: spec.closed === true,
1199
+ // 恒定速度:让沿路径的采样按**弧长**而不是按段索引走,与预览器的算法一致。
1200
+ constantSpeed: true
1201
+ }
1202
+ };
1203
+ pathConstraints.push({
1204
+ name,
1205
+ order: pathConstraints.length,
1206
+ bones: chain,
1207
+ target: "root",
1208
+ // spacing > 0 是「固定间距」,否则「均匀铺满整条路径」。
1209
+ positionMode: entry.spacing > 0 ? "fixed" : "percent",
1210
+ spacingMode: "length",
1211
+ rotateMode: "tangent",
1212
+ rotation: 0,
1213
+ translateMix: Math.max(0, Math.min(1, num(entry.translateMix, 1))),
1214
+ rotateMix: Math.max(0, Math.min(1, num(entry.rotateMix, 1)))
1215
+ });
1216
+ }
1217
+ // ── 蒙皮网格附件(L1 / LBS)──────────────────────────────────────────
1218
+ //
1219
+ // **必须排在 IK 与 Path 之后**:那两处都会往 `bones` 里插骨骼(IK 会补一根目标骨),
1220
+ // 而加权顶点写的是**骨骼在最终骨骼表里的下标**。早于它们生成的话,插进来的骨骼会把
1221
+ // 后面所有下标整体推后一位,运行时就会读到错的骨骼——实测 `skel.bones[idx]` 直接
1222
+ // 越界成 undefined(表现是网格扭曲,而且不报错)。
1223
+ const boneIndex = new Map(bones.map((bone, index) => [bone.name, index]));
1224
+ const fromWorld = (wx, wy) => ({
1225
+ x: wx + options.canvasWidth / 2,
1226
+ y: options.canvasHeight - wy
1227
+ });
1228
+ for (const [meshName, spec] of Object.entries(options.meshes ?? {})) {
1229
+ const part = byName.get(meshName);
1230
+ const region = attachments[meshName]?.[meshName];
1231
+ if (part === undefined || region === undefined)
1232
+ continue;
1233
+ // 自动权重在**图像坐标**里算(与部件同一套系),所以骨骼位置也换算回去。
1234
+ //
1235
+ // 候选骨骼**限制在语义相关的那些**(自己 + 往上的父级链 + 直接子级),不能是全体。
1236
+ // 纯几何距离会把裙子绑到手臂上——实测 hip 的网格选了 `right-lower-arm` /
1237
+ // `right-hand` / `right-upper-arm`,因为裙子**上缘**到垂下的手臂比到腿还近
1238
+ // (腰部到手臂 ~82px,到小腿 ~278px)。距离不懂拓扑,语义得由调用方给。
1239
+ const related = new Set([meshName]);
1240
+ let cursor = resolvedParent.get(meshName);
1241
+ for (let depth = 0; depth < 3 && cursor !== undefined; depth++) {
1242
+ related.add(cursor);
1243
+ cursor = resolvedParent.get(cursor);
1244
+ }
1245
+ for (const child of childrenOf.get(meshName) ?? [])
1246
+ related.add(child);
1247
+ const imageBones = [...world.entries()]
1248
+ .filter(([name]) => name !== meshName && related.has(name) && boneNames.has(name))
1249
+ .map(([name, point]) => {
1250
+ const image = fromWorld(point.x, point.y);
1251
+ return { name, x: image.x, y: image.y };
1252
+ });
1253
+ attachments[meshName] = {
1254
+ [meshName]: meshAttachmentOf(meshName, part, region, spec, {
1255
+ imageBones,
1256
+ worldOf: (name) => world.get(name),
1257
+ boneIndex
1258
+ })
1259
+ };
1260
+ }
1261
+ const spine = {
1262
+ skeleton: {
1263
+ hash,
1264
+ spine: "4.2.0",
1265
+ x: -Math.round(options.canvasWidth / 2),
1266
+ y: 0,
1267
+ width: Math.round(options.canvasWidth),
1268
+ height: Math.round(options.canvasHeight),
1269
+ images: "./images/"
1270
+ },
1271
+ bones,
1272
+ slots,
1273
+ ik: ik.length === 0 ? undefined : ik,
1274
+ path: pathConstraints.length === 0 ? undefined : pathConstraints,
1275
+ skins: [{ name: "default", attachments }],
1276
+ animations
1277
+ };
1278
+ return { spine, bones, warnings, animationsRaw };
1279
+ }
1280
+ function nextPow2(value) {
1281
+ let v = Math.max(1, Math.ceil(value)) - 1;
1282
+ v |= v >> 1;
1283
+ v |= v >> 2;
1284
+ v |= v >> 4;
1285
+ v |= v >> 8;
1286
+ v |= v >> 16;
1287
+ return Math.max(v + 1, 1);
1288
+ }
1289
+ /**
1290
+ * 行式装箱(参考项目 `make_atlas.py` 的同款策略)。
1291
+ *
1292
+ * 这里不追求最优 packing:部件数量在十几个量级,行式装箱已经足够紧凑,
1293
+ * 而且**结果可复现**——同样的输入永远得到同样的 atlas 坐标,
1294
+ * 用户重跑不会因为坐标漂移而误以为「产物变了」。
1295
+ *
1296
+ * 相对参考项目修掉两个缺陷:
1297
+ * ① **超宽件**:它的换行判断只在 `rx + w + padding > atlasW` 时换行,
1298
+ * 却从不检查「一件本身就比页宽还宽」,于是 `paste` 静默裁掉超出部分,
1299
+ * `.atlas` 里仍写完整 `size` → 引擎里画出错位图。
1300
+ * 这里把页宽的初值取成 `max(面积估算, 最宽件 + 2×padding)`。
1301
+ * ② **无分页**:装不下时按 `maxSize` 开新页,而不是无限长高或静默裁切。
1302
+ */
1303
+ export function packAtlas(sizes, options = {}) {
1304
+ const padding = Math.max(0, Math.round(options.padding ?? 2));
1305
+ const maxSize = Math.max(16, Math.round(options.maxSize ?? 4096));
1306
+ const baseName = options.pageName ?? "skeleton.png";
1307
+ /** 首页用原名;第二页起在扩展名前插序号。 */
1308
+ const pageNameOf = (index) => {
1309
+ if (index === 0)
1310
+ return baseName;
1311
+ const dot = baseName.lastIndexOf(".");
1312
+ return dot === -1 ? `${baseName}${index + 1}` : `${baseName.slice(0, dot)}${index + 1}${baseName.slice(dot)}`;
1313
+ };
1314
+ if (sizes.length === 0)
1315
+ return { pages: [] };
1316
+ const totalArea = sizes.reduce((sum, item) => sum + item.width * item.height, 0);
1317
+ const widest = Math.max(...sizes.map((item) => item.width + padding * 2));
1318
+ let pageWidth = nextPow2(Math.max(Math.sqrt(totalArea) * 1.3, widest));
1319
+ // 页宽被 maxSize 夹住时,比 maxSize 还宽的件就真的放不下了——这一条由
1320
+ // `validateAtlas` 报出来,这里不静默裁切。
1321
+ if (pageWidth > maxSize)
1322
+ pageWidth = maxSize;
1323
+ const sorted = [...sizes].sort((a, b) => b.height - a.height || a.name.localeCompare(b.name));
1324
+ const pages = [];
1325
+ let current = {
1326
+ width: pageWidth,
1327
+ height: 0,
1328
+ placements: [],
1329
+ cursorX: padding,
1330
+ cursorY: padding,
1331
+ rowHeight: 0,
1332
+ maxWidth: 0
1333
+ };
1334
+ const flush = () => {
1335
+ if (current.placements.length === 0)
1336
+ return;
1337
+ pages.push({
1338
+ name: pageNameOf(pages.length),
1339
+ width: nextPow2(Math.min(Math.max(current.maxWidth, pageWidth), maxSize)),
1340
+ height: nextPow2(current.cursorY + current.rowHeight + padding),
1341
+ placements: current.placements
1342
+ });
1343
+ };
1344
+ for (const item of sorted) {
1345
+ if (current.cursorX + item.width + padding > pageWidth) {
1346
+ current.cursorX = padding;
1347
+ current.cursorY += current.rowHeight + padding;
1348
+ current.rowHeight = 0;
1349
+ }
1350
+ // 换行之后仍然超出本页高度上限 → 开新页。
1351
+ if (current.cursorY + item.height + padding > maxSize) {
1352
+ flush();
1353
+ current = { width: pageWidth, height: 0, placements: [], cursorX: padding, cursorY: padding, rowHeight: 0, maxWidth: 0 };
1354
+ }
1355
+ current.placements.push({
1356
+ name: item.name,
1357
+ x: current.cursorX,
1358
+ y: current.cursorY,
1359
+ width: item.width,
1360
+ height: item.height,
1361
+ origWidth: item.origWidth,
1362
+ origHeight: item.origHeight,
1363
+ offsetX: item.offsetX,
1364
+ offsetY: item.offsetY
1365
+ });
1366
+ current.maxWidth = Math.max(current.maxWidth, current.cursorX + item.width + padding);
1367
+ current.rowHeight = Math.max(current.rowHeight, item.height);
1368
+ current.cursorX += item.width + padding;
1369
+ }
1370
+ flush();
1371
+ return { pages };
1372
+ }
1373
+ /**
1374
+ * 生成 Spine `.atlas` 文本(与参考项目 `make_atlas.py` 输出格式一致)。
1375
+ *
1376
+ * 与参考项目的差别:`orig` / `offset` 写**真实值**。它恒写 `orig == size` 且
1377
+ * `offset: 0, 0`,等于永远不裁透明边、也永远不记录裁剪偏移;一旦源图有透明边,
1378
+ * 整张图(含空白)都会被塞进图集,白白撑大体积。
1379
+ */
1380
+ export function buildAtlasText(pages) {
1381
+ const lines = [];
1382
+ for (const page of pages) {
1383
+ lines.push(page.name, `size: ${page.width},${page.height}`, "format: RGBA8888", "filter: Linear,Linear", "repeat: none");
1384
+ for (const item of page.placements) {
1385
+ const origWidth = item.origWidth ?? item.width;
1386
+ const origHeight = item.origHeight ?? item.height;
1387
+ lines.push(item.name, " rotate: false", ` xy: ${item.x}, ${item.y}`, ` size: ${item.width}, ${item.height}`, ` orig: ${origWidth}, ${origHeight}`, ` offset: ${item.offsetX ?? 0}, ${item.offsetY ?? 0}`, " index: -1");
1388
+ }
1389
+ }
1390
+ return `${lines.join("\n")}\n`;
1391
+ }
1392
+ export const SPINE_VERSION = "4.2.0";