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/rigqa.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * 拆件质检(纯计算,不碰文件系统、不联网)。
3
+ *
4
+ * 为什么需要它:拆件是整条链路里**唯一花钱、又最难验证**的一步。它出问题的方式
5
+ * 全都不是"报错",而是"看起来生成了 16 个部件"——
6
+ *
7
+ * · 同一个部位被画进多个网格格子(实测:4 段"大腿→膝盖"、4 只鞋袜脚、3 条整袖);
8
+ * · 网格位置决定部件名,模型却按自己的理解画(实测:第 2 格叫"胯部"画的是裙子、
9
+ * 第 9 格叫"脖子"画的是大腿)。名字错了,靠名字推出来的骨架从第一根骨头起就是错的;
10
+ * · 部件是重新绘制的,与参考图像素不像,模板匹配只能挑一个"不那么错"的位置,
11
+ * 相似度 0.08~0.5 却仍然报"已定位"。
12
+ *
13
+ * 这三种在插件里一路绿灯,要等用户看见"头长在脚上"才发现。所以在这里把它们变成
14
+ * **明确的、可读的结论**:重复件点名、拆件可信度打分、并给出三条具体建议。
15
+ *
16
+ * 判定分两级,与 `rigvalidate.ts` 一致:error = 这批拆件不可信(该重跑或该改语义),
17
+ * warning = 能跑但值得看一眼。
18
+ */
19
+ /** 轮廓比较用的归一化网格边长。64 足够区分"大腿"和"鞋",又不至于被抗锯齿噪声影响。 */
20
+ const PROFILE_SIZE = 64;
21
+ /** 内容包围盒的宽高比差异超过这个比例就不算同一块(避免把"细长腿"和"方裙子"判成一对)。 */
22
+ const ASPECT_TOLERANCE = 0.18;
23
+ /** 轮廓 IoU 超过它 = 疑似同一部位画了多遍。实测重复件能到 0.9+,正常不同部件 < 0.6。 */
24
+ export const DUPLICATE_IOU = 0.86;
25
+ /**
26
+ * 把部件压成一张**归一化轮廓位图**:裁到内容包围盒 → 缩放到 64×64 → 取 alpha 二值。
27
+ *
28
+ * 只比轮廓不比颜色:这次踩的坑里,重复件是"同一部位重画一遍",颜色深浅会有出入,
29
+ * 但形状几乎一致。比颜色会把它们判成不同件,反而漏掉。
30
+ */
31
+ export function partProfile(part, bounds, mirror = false) {
32
+ const box = bounds ?? contentBounds(part.rgba);
33
+ if (box === undefined || box.width <= 0 || box.height <= 0)
34
+ return undefined;
35
+ const profile = new Uint8Array(PROFILE_SIZE * PROFILE_SIZE);
36
+ for (let y = 0; y < PROFILE_SIZE; y++) {
37
+ for (let x = 0; x < PROFILE_SIZE; x++) {
38
+ // 最近邻采样:轮廓是二值的,插值只会糊掉边界。
39
+ const sx = box.x + Math.min(box.width - 1, Math.floor(((x + 0.5) * box.width) / PROFILE_SIZE));
40
+ const sy = box.y + Math.min(box.height - 1, Math.floor(((y + 0.5) * box.height) / PROFILE_SIZE));
41
+ const alpha = part.rgba.data[(sy * part.rgba.width + sx) * 4 + 3];
42
+ // `mirror` 时水平翻转:用来判「左右件」还是「同一块重画」,见 `findDuplicateParts`。
43
+ const target = mirror ? y * PROFILE_SIZE + (PROFILE_SIZE - 1 - x) : y * PROFILE_SIZE + x;
44
+ profile[target] = alpha > 128 ? 1 : 0;
45
+ }
46
+ }
47
+ return profile;
48
+ }
49
+ /** 内容(非透明)包围盒。 */
50
+ export function contentBounds(src, threshold = 8) {
51
+ let minX = src.width;
52
+ let minY = src.height;
53
+ let maxX = -1;
54
+ let maxY = -1;
55
+ for (let y = 0; y < src.height; y++) {
56
+ for (let x = 0; x < src.width; x++) {
57
+ if (src.data[(y * src.width + x) * 4 + 3] <= threshold)
58
+ continue;
59
+ if (x < minX)
60
+ minX = x;
61
+ if (y < minY)
62
+ minY = y;
63
+ if (x > maxX)
64
+ maxX = x;
65
+ if (y > maxY)
66
+ maxY = y;
67
+ }
68
+ }
69
+ if (maxX < 0)
70
+ return undefined;
71
+ return { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 };
72
+ }
73
+ /** 两张轮廓位图的交并比。 */
74
+ export function profileOverlap(a, b) {
75
+ let intersection = 0;
76
+ let union = 0;
77
+ for (let i = 0; i < a.length; i++) {
78
+ const x = a[i];
79
+ const y = b[i];
80
+ if (x === 1 || y === 1)
81
+ union++;
82
+ if (x === 1 && y === 1)
83
+ intersection++;
84
+ }
85
+ return union === 0 ? 0 : intersection / union;
86
+ }
87
+ /**
88
+ * 找出"同一部位画了多遍"的部件组。
89
+ *
90
+ * 用并查集把两两判定连成组:实测里 4 段大腿的相似度是链式的(相邻两块最像、
91
+ * 首尾略差),两两阈值判定会把它切成 2+2,而用户看到的是"一块部位出现了 4 次"。
92
+ */
93
+ export function findDuplicateParts(parts) {
94
+ const visible = parts.filter((part) => part.hidden !== true);
95
+ const records = visible.map((part) => {
96
+ const bounds = contentBounds(part.rgba);
97
+ return {
98
+ name: part.name,
99
+ bounds,
100
+ profile: partProfile(part, bounds),
101
+ mirrored: partProfile(part, bounds, true),
102
+ aspect: bounds === undefined ? 1 : bounds.width / bounds.height
103
+ };
104
+ });
105
+ const usable = records.filter((record) => record.profile !== undefined && record.bounds !== undefined);
106
+ const parent = new Map();
107
+ const find = (name) => {
108
+ let root = name;
109
+ while (parent.get(root) !== undefined && parent.get(root) !== root)
110
+ root = parent.get(root);
111
+ return root;
112
+ };
113
+ const union = (a, b) => {
114
+ const ra = find(a);
115
+ const rb = find(b);
116
+ if (ra !== rb)
117
+ parent.set(rb, ra);
118
+ };
119
+ for (const record of usable)
120
+ parent.set(record.name, record.name);
121
+ const pairwise = [];
122
+ for (let i = 0; i < usable.length; i++) {
123
+ for (let j = i + 1; j < usable.length; j++) {
124
+ const a = usable[i];
125
+ const b = usable[j];
126
+ // 宽高比差太多就不可能同源,先过掉——省下大量无关比较,也避免把
127
+ // 「细长腿」和「方头」在高 IoU 下误判成一类(归一化会抹掉长宽差异)。
128
+ const ratio = a.aspect / b.aspect;
129
+ if (ratio < 1 - ASPECT_TOLERANCE || ratio > 1 + ASPECT_TOLERANCE)
130
+ continue;
131
+ const score = profileOverlap(a.profile, b.profile);
132
+ const mirrored = profileOverlap(a.profile, b.mirrored);
133
+ // **只并同向的**。左右件(互为镜像)的同向重合实测只有 0.66~0.76,
134
+ // 天然进不了这个阈值;万一某块形状本身接近对称,两个值会一起高,
135
+ // 那就按 `symmetric` 降级成提示,不让人直接删。
136
+ if (score < DUPLICATE_IOU)
137
+ continue;
138
+ union(a.name, b.name);
139
+ pairwise.push({ a: a.name, b: b.name, score, mirrored });
140
+ }
141
+ }
142
+ const groups = new Map();
143
+ for (const record of usable) {
144
+ const root = find(record.name);
145
+ const list = groups.get(root) ?? [];
146
+ list.push(record.name);
147
+ groups.set(root, list);
148
+ }
149
+ const out = [];
150
+ for (const names of groups.values()) {
151
+ if (names.length < 2)
152
+ continue;
153
+ const related = pairwise.filter((pair) => names.includes(pair.a) && names.includes(pair.b));
154
+ const first = usable.find((record) => record.name === names[0]);
155
+ const minOverlap = Math.min(...related.map((pair) => pair.score));
156
+ const mirroredOverlap = Math.max(...related.map((pair) => pair.mirrored));
157
+ out.push({
158
+ parts: names.slice().sort(),
159
+ minOverlap: Number(minOverlap.toFixed(3)),
160
+ mirroredOverlap: Number(mirroredOverlap.toFixed(3)),
161
+ // 镜像重合也逼近同向重合 = 这块形状本身接近对称,单看轮廓分不出
162
+ // 「同一块重画」和「左右各一」。
163
+ symmetric: mirroredOverlap >= minOverlap - 0.05,
164
+ width: first.bounds?.width ?? 0,
165
+ height: first.bounds?.height ?? 0
166
+ });
167
+ }
168
+ out.sort((a, b) => b.parts.length - a.parts.length || a.parts[0].localeCompare(b.parts[0]));
169
+ return out;
170
+ }
171
+ /** 低于这个相似度就是"低置信度硬凑"(正常匹配应 > 0.6)。 */
172
+ export const LOW_SCORE = 0.5;
173
+ /** 低于这个相似度基本等于随机(实测错误位置常落在 0.08~0.3)。 */
174
+ export const GARBAGE_SCORE = 0.3;
175
+ /**
176
+ * 综合体检。三件事各自独立判:
177
+ * 1. 重复件(几何,需要像素);
178
+ * 2. 装配相似度(需要装配结果);
179
+ * 3. 部件数是否明显多于参考图可见部位数(需要 `expectedParts`)。
180
+ *
181
+ * 分数只用来给一个粗略的"要不要信这批拆件"的直觉,**判据永远是 issues**。
182
+ */
183
+ export function assessParts(options) {
184
+ const issues = [];
185
+ const parts = (options.parts ?? []).filter((part) => part.hidden !== true);
186
+ const duplicates = options.duplicates ?? (parts.length > 0 ? findDuplicateParts(parts) : []);
187
+ const partCount = parts.length > 0 ? parts.length : (options.partCount ?? 0);
188
+ if (duplicates.length > 0) {
189
+ const confirmed = duplicates.filter((group) => !group.symmetric);
190
+ const uncertain = duplicates.filter((group) => group.symmetric);
191
+ if (confirmed.length > 0) {
192
+ const total = confirmed.reduce((sum, group) => sum + group.parts.length, 0);
193
+ issues.push({
194
+ level: "error",
195
+ code: "duplicate-parts",
196
+ parts: confirmed.flatMap((group) => group.parts),
197
+ message: `有 ${confirmed.length} 组部件**朝向相同、轮廓几乎重合**(共 ${total} 块),基本可以确定是同一个部位被画了多遍:` +
198
+ confirmed.map((group) => `${group.parts.join(" / ")}(同向重合 ${group.minOverlap},镜像只有 ${group.mirroredOverlap})`).join(";") +
199
+ "。拆件模型在多个网格格子里重复画了同一块内容,多出来的部件会被硬塞进不相干的骨骼位。",
200
+ suggestion: "每组保留 1 块、隐藏其余(卡片上有「隐藏」)。注意判据:**同向**重合才是重复;" +
201
+ "如果两块互为镜像(同向 0.66~0.76、镜像 0.93+),那是左右各一,两块都要留"
202
+ });
203
+ }
204
+ if (uncertain.length > 0) {
205
+ issues.push({
206
+ level: "warning",
207
+ code: "duplicate-uncertain",
208
+ parts: uncertain.flatMap((group) => group.parts),
209
+ message: `有 ${uncertain.length} 组部件轮廓高度重合、但**互为镜像的程度也一样高**(形状本身接近对称),` +
210
+ `无法从轮廓判断是「同一块重画」还是「左右各一」:` +
211
+ uncertain.map((group) => `${group.parts.join(" / ")}(同向 ${group.minOverlap} / 镜像 ${group.mirroredOverlap})`).join(";"),
212
+ suggestion: "用 read_image 看一眼这几块的方向,再决定留几块——判错了会缺一整条肢体"
213
+ });
214
+ }
215
+ }
216
+ const matches = (options.matches ?? []).filter((item) => item.matched !== false && typeof item.score === "number");
217
+ if (matches.length > 0) {
218
+ const scores = matches.map((item) => item.score);
219
+ const mean = scores.reduce((sum, value) => sum + value, 0) / scores.length;
220
+ const low = matches.filter((item) => item.score < LOW_SCORE);
221
+ const garbage = matches.filter((item) => item.score < GARBAGE_SCORE);
222
+ if (mean < LOW_SCORE) {
223
+ issues.push({
224
+ level: "error",
225
+ code: "layout-low-confidence",
226
+ parts: low.map((item) => item.name),
227
+ message: `装配平均相似度只有 ${mean.toFixed(3)}(正常应 > ${LOW_SCORE}),${low.length}/${matches.length} 个部件低于阈值` +
228
+ (garbage.length > 0 ? `,其中 ${garbage.length} 个低于 ${GARBAGE_SCORE}(基本等于随机)` : "") +
229
+ "。这通常意味着拆件图里的部件与参考图**长得不像**(部件是重新绘制的服装裁片,或角色被换过)," +
230
+ "自动定位的结果不可信——「已定位 N/M」这个数字本身不会告诉你这件事。",
231
+ suggestion: "用 read_image 看参考图与 parts-montage.png,判断每块部件在参考图的哪个位置,用 " +
232
+ "`setRigLayoutHints` 写下大致像素框再重跑 `runRigLayout`;被遮挡、参考图里没有对应像素的部位(例如裙下的整段大腿)直接给最终位置,不要指望模板匹配"
233
+ });
234
+ }
235
+ else if (low.length > 0) {
236
+ issues.push({
237
+ level: "warning",
238
+ code: "layout-some-low",
239
+ parts: low.map((item) => item.name),
240
+ message: `有 ${low.length}/${matches.length} 个部件相似度低于 ${LOW_SCORE}(平均 ${mean.toFixed(3)}),这几件建议人工核对:${low.map((item) => item.name).join("、")}`,
241
+ suggestion: "在装配台上拖动核对,或对有疑问的那几件用 `setRigLayoutHints` 给区域框后单件重跑 `runRigLayout({names:[…]})`"
242
+ });
243
+ }
244
+ }
245
+ if (typeof options.expectedParts === "number" && options.expectedParts > 0 && partCount > options.expectedParts) {
246
+ issues.push({
247
+ level: "error",
248
+ code: "too-many-parts",
249
+ parts: [],
250
+ message: `拆出 ${partCount} 个部件,但参考图里大致只能看到 ${options.expectedParts} 个独立部位——` +
251
+ "多出来的部分多半是重复件,或者把同一个部位切成了几块。",
252
+ suggestion: "对照 parts-montage.png 逐块确认,隐藏重复件;或在拆件提示词里把每个网格格子该画什么写清楚"
253
+ });
254
+ }
255
+ const errors = issues.filter((issue) => issue.level === "error");
256
+ // 分数:重复件与"部件数偏多"是硬伤,各自压掉一截;相似度按均值线性给分。
257
+ let score = 1;
258
+ score -= Math.min(0.5, duplicates.filter((group) => !group.symmetric).length * 0.2 + duplicates.filter((group) => group.symmetric).length * 0.05);
259
+ if (errors.some((issue) => issue.code === "too-many-parts"))
260
+ score -= 0.25;
261
+ if (matches.length > 0) {
262
+ const mean = matches.reduce((sum, item) => sum + item.score, 0) / matches.length;
263
+ score = Math.min(score, Math.max(0, (mean - GARBAGE_SCORE) / (1 - GARBAGE_SCORE)));
264
+ }
265
+ score = Number(Math.max(0, Math.min(1, score)).toFixed(2));
266
+ const summary = errors.length === 0
267
+ ? `拆件质检通过(可信度 ${Math.round(score * 100)}%)` +
268
+ (issues.length > 0 ? `,另有 ${issues.length} 条提示` : "")
269
+ : `拆件质检不通过(可信度 ${Math.round(score * 100)}%):${errors.map((issue) => issue.code).join("、")}`;
270
+ return { ok: errors.length === 0, score, issues, duplicates, checked: partCount, summary };
271
+ }