modelstage 0.10.1 → 0.11.2

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.
@@ -106,6 +106,74 @@
106
106
  * completeImageSize:number,mipCount:number,stream:{offset:number,size:number,path:string}|null,
107
107
  * inline:Uint8Array|null, raw:object}>}
108
108
  */
109
+ /**
110
+ * 主图解码后的 alpha 通道里是否含**真实透明像素**。
111
+ *
112
+ * 为什么不看纹理格式:格式"带 alpha"不等于内容真有 alpha。实测有包主图是 RGBA32,
113
+ * 但 alpha 整幅都是 255 —— 透明度被美工单独画在 `_AlphaTex` 的灰度里。
114
+ * 只按格式跳过合成,这类包就会整幅不透明、该透明处显示成黑块。
115
+ * 提前返回:遇到第一个非 255 就判定有效,正常带 alpha 的图不必扫完。
116
+ */
117
+ function alphaIsEffective(rgba) {
118
+ if (!rgba || !rgba.length) return false;
119
+ for (let i = 3; i < rgba.length; i += 4) if (rgba[i] !== 255) return true;
120
+ return false;
121
+ }
122
+
123
+ /**
124
+ * 从 Material 的 `m_SavedProperties.m_TexEnvs` 建立 `_MainTex pathID → _AlphaTex pathID`。
125
+ *
126
+ * 为什么用引用而不是贴图名:同名资源在包里可以有多份且内容不同(实测 `char_x` 与
127
+ * `char_x[alpha]` 各 2 份、md5 各异)—— 名字无法唯一标识,靠名字必然配错套。
128
+ * 权威依据只能是 Material 里的 PPtr pathID;该口径与 Python worker 完全一致,
129
+ * 否则前后端对同一个包会给出不同结论。
130
+ *
131
+ * 多个 Material 时只取**同时含 `_MainTex` 与 `_AlphaTex`** 的;同一 `_MainTex`
132
+ * 被多个 Material 引用时保留先遇到的(顺序稳定)。
133
+ */
134
+ function collectAlphaPairs(sf) {
135
+ const pairs = new Map();
136
+ for (const obj of NS.serialized.byClass(sf, 21)) { // 21 = Material
137
+ let tree;
138
+ try { tree = NS.typetree.readObject(sf, obj); } catch { continue; }
139
+ const texenvs = ((tree.m_SavedProperties || {}).m_TexEnvs) || [];
140
+ const found = new Map();
141
+ for (const entry of texenvs) {
142
+ const key = entry && (entry.first !== undefined ? entry.first : entry[0]);
143
+ const value = entry && (entry.second !== undefined ? entry.second : entry[1]);
144
+ const keyText = (key && typeof key === 'object')
145
+ ? String(key.text !== undefined ? key.text : (key.m_String !== undefined ? key.m_String : ''))
146
+ : String(key === undefined || key === null ? '' : key);
147
+ const tex = value && value.m_Texture;
148
+ const pathId = tex && (tex.m_PathID !== undefined ? tex.m_PathID : tex.pathID);
149
+ if (keyText && pathId !== undefined && pathId !== null) found.set(keyText, String(pathId));
150
+ }
151
+ const mainId = found.get('_MainTex');
152
+ const alphaId = found.get('_AlphaTex');
153
+ if (mainId && alphaId && !pairs.has(mainId)) pairs.set(mainId, alphaId);
154
+ }
155
+ return pairs;
156
+ }
157
+
158
+ /**
159
+ * 把 `_AlphaTex` 的灰度值写进主图 RGBA 的 alpha 通道。
160
+ * 尺寸不一致时用**最近邻**(不引入插值模糊,遮罩边缘该硬就硬)。
161
+ * @returns {{rgba: Uint8Array, scaled: boolean}}
162
+ */
163
+ function applyAlphaMask(rgba, width, height, maskRgba, maskWidth, maskHeight) {
164
+ const out = new Uint8Array(rgba);
165
+ const scaled = maskWidth !== width || maskHeight !== height;
166
+ for (let y = 0; y < height; y += 1) {
167
+ const sy = scaled ? Math.min(maskHeight - 1, Math.floor(y * maskHeight / height)) : y;
168
+ for (let x = 0; x < width; x += 1) {
169
+ const sx = scaled ? Math.min(maskWidth - 1, Math.floor(x * maskWidth / width)) : x;
170
+ // 灰度遮罩三通道相同,取 R 当 alpha
171
+ out[(y * width + x) * 4 + 3] = maskRgba[(sy * maskWidth + sx) * 4];
172
+ }
173
+ }
174
+ return { rgba: out, scaled };
175
+ }
176
+
109
177
  function findTextures(sf) {
110
178
  if (!NS.typetree) throw NS.errors.fail('ULB_ERR_EXTRACT', '缺少 lib/typetree.js,无法读取 Texture2D 字段');
111
179
  // 字段名在类型树里可能是带空格的可读名(如 "image data"),也可能是 m_ 前缀名;
@@ -237,6 +305,7 @@
237
305
 
238
306
  NS.extract = {
239
307
  findMoc3, findTextAssets, findTextures, findNativeCubismFiles,
308
+ collectAlphaPairs, applyAlphaMask, alphaIsEffective,
240
309
  extractAll, textureCompressedBytes, indexOfMagic, decodeUtf8, moc3NameCandidates,
241
310
  };
242
311
  }
@@ -2,8 +2,9 @@
2
2
  // plugins/unity-live2d-bundle/lib/texdecode.js —— 纹理格式分发
3
3
  //
4
4
  // 职责:读 Texture2D 的 m_TextureFormat,分发给对应解码器,返回 RGBA 字节。
5
- // · 已实现:ETC2_RGBA8(47) / ETC2_RGB(45) / ETC1_RGB4(34) / 未压缩 RGBA32/RGB24/Alpha8 等直通格式
6
- // · 未实现:ASTC / PVRTC / BCn 等 —— **抛可读错误**并把格式名与格式号带上,
5
+ // · 已实现:ASTC 全系列(48~59,解码器在 lib/astc.js) / ETC2_RGBA8(47) / ETC2_RGBA1(46)
6
+ // / ETC2_RGB(45) / ETC1_RGB4(34) / DXT1/3/4/5(10/12/26/27) / 未压缩 RGBA32/RGB24/Alpha8 等直通格式
7
+ // · 未实现:PVRTC / BC6H / BC7 等 —— **抛可读错误**并把格式名与格式号带上,
7
8
  // 绝不返回空白图或猜出来的图(否则上层会把"解码失败"当成"资源损坏")。
8
9
  //
9
10
  // 纹理尺寸与数据量的自检:按格式的块大小算出期望数据量,与给的字节数比对;
@@ -27,8 +28,24 @@
27
28
  7: { name: 'RGB565', block: 2, size: 1 },
28
29
  34: { name: 'ETC_RGB4', compress: 'etc1', block: 8, size: 4 },
29
30
  45: { name: 'ETC2_RGB', compress: 'etc2', block: 8, size: 4 },
31
+ 46: { name: 'ETC2_RGBA1', compress: 'etc2a1', block: 16, size: 4 },
30
32
  47: { name: 'ETC2_RGBA8', compress: 'etc2a8', block: 16, size: 4 },
31
- 48: { name: 'ETC2_RGBA1', compress: 'etc2a1', block: 16, size: 4 },
33
+ // 48~59 是 ASTC 系列(UnityPy/enums/TextureFormat.py;并被真实包的 m_CompleteImageSize
34
+ // 反推验证:440x440/87616 只有 6x6 唯一解、1024x1024/672400 只有 5x5)。
35
+ // **48 不是 ETC2_RGBA1**(那个是 46)。块边长各不相同,必须逐条写 bw/bh,
36
+ // 否则 expectedSize 会按 4x4 算错长度,把"格式未支持"错报成"数据不足"。
37
+ 48: { name: 'ASTC_RGB_4x4', block: 16, size: 4, bw: 4, bh: 4 },
38
+ 49: { name: 'ASTC_RGB_5x5', block: 16, size: 4, bw: 5, bh: 5 },
39
+ 50: { name: 'ASTC_RGB_6x6', block: 16, size: 4, bw: 6, bh: 6 },
40
+ 51: { name: 'ASTC_RGB_8x8', block: 16, size: 4, bw: 8, bh: 8 },
41
+ 52: { name: 'ASTC_RGB_10x10', block: 16, size: 4, bw: 10, bh: 10 },
42
+ 53: { name: 'ASTC_RGB_12x12', block: 16, size: 4, bw: 12, bh: 12 },
43
+ 54: { name: 'ASTC_RGBA_4x4', block: 16, size: 4, bw: 4, bh: 4 },
44
+ 55: { name: 'ASTC_RGBA_5x5', block: 16, size: 4, bw: 5, bh: 5 },
45
+ 56: { name: 'ASTC_RGBA_6x6', block: 16, size: 4, bw: 6, bh: 6 },
46
+ 57: { name: 'ASTC_RGBA_8x8', block: 16, size: 4, bw: 8, bh: 8 },
47
+ 58: { name: 'ASTC_RGBA_10x10', block: 16, size: 4, bw: 10, bh: 10 },
48
+ 59: { name: 'ASTC_RGBA_12x12', block: 16, size: 4, bw: 12, bh: 12 },
32
49
  // BC/DXT 家族(PC/主机资源包常用;块式压缩,解码实现见 lib/dxt.js)
33
50
  10: { name: 'DXT1', compress: 'bc1', block: 8, size: 4 },
34
51
  12: { name: 'DXT5', compress: 'bc3', block: 16, size: 4 },
@@ -46,8 +63,10 @@
46
63
  const f = FORMATS[fmt];
47
64
  if (!f) return null;
48
65
  if (f.size === 1) return width * height * f.block;
49
- const bw = Math.ceil(width / 4);
50
- const bh = Math.ceil(height / 4);
66
+ // 块边长按格式取(缺省 4):ETC/BC 全是 4x4 走缺省,ASTC 是 4~12 各不相同。
67
+ // 写死 4 会让 ASTC 算出偏大的期望长度 ⇒ 抛 TEX_DATA_SHORT,把"格式未支持"藏成"数据不足"。
68
+ const bw = Math.ceil(width / (f.bw || 4));
69
+ const bh = Math.ceil(height / (f.bh || 4));
51
70
  return bw * bh * f.block;
52
71
  }
53
72
 
@@ -128,19 +147,42 @@
128
147
  * 调用方**不得依赖**返回的 rgba 与入参共享底层 buffer(有的格式共享、有的不共享,
129
148
  * 原地修改它可能改到源数据、也可能改不到)。
130
149
  */
150
+ /**
151
+ * 生成"某个 ASTC 格式号"的解码器入口。
152
+ *
153
+ * 为什么要工厂而不是十二条手写箭头函数:块边长(4x4 ~ 12x12)只有 FORMATS 一处真相,
154
+ * 手抄一份数字到 DECODERS 就多了一处会漂移的副本 —— FORMATS 改了而这里没改时,
155
+ * 解码器会按错的块尺寸切块,表现为"图能出但整片错位",比直接报错难查得多。
156
+ */
157
+ const astcDecoder = (fmt) => (d, w, h) => {
158
+ const entry = FORMATS[fmt];
159
+ // astc.js 由文件清单在 texdecode.js 之前注入;缺了要说清是"没加载"而不是"格式不支持"
160
+ if (!NS.astc || typeof NS.astc.decodeAstc !== 'function') {
161
+ throw NS.errors.fail('ULB_ERR_TEX_DECODE',
162
+ `ASTC 解码器未加载(lib/astc.js 未按序注入?),无法解码 ${entry.name}(${fmt})`);
163
+ }
164
+ return NS.astc.decodeAstc(d, w, h, entry.bw, entry.bh);
165
+ };
166
+
131
167
  const DECODERS = {
132
168
  // 压缩格式:解码器自身产出 RGBA
133
169
  34: (d, w, h) => NS.etc2.decodeEtc1Rgb(d, w, h),
134
170
  45: (d, w, h) => NS.etc2.decodeEtc2Rgb(d, w, h),
135
171
  47: (d, w, h) => NS.etc2.decodeEtc2Rgba8(d, w, h),
136
- // 48 ETC2_RGBA1:ETC2 RGB 块(8 字节)+ 1bit alpha 平面(8 字节)。块布局与位序见
137
- // lib/etc2.js 的 decodeEtc2Rgba1 注释。此格式长期"格式表里有、解码器没登记",
138
- // 导致该格式的包整包报 ULB_ERR_TEX_DECODE(现场:蔚蓝档案部分 spinebackground 包)。
139
- 48: (d, w, h) => NS.etc2.decodeEtc2Rgba1(d, w, h),
172
+ // 46 ETC2_RGBA1:ETC2 RGB 块(8 字节)+ 1bit alpha 平面(8 字节)。块布局与位序见
173
+ // lib/etc2.js 的 decodeEtc2Rgba1 注释。
174
+ // 注意编号:ETC2_RGBA1 是 **46**,不是 48(48 是 ASTC_RGB_4x4,见 FORMATS 注释)。
175
+ 46: (d, w, h) => NS.etc2.decodeEtc2Rgba1(d, w, h),
140
176
  10: (d, w, h) => NS.dxt.decodeBc1(d, w, h),
141
177
  12: (d, w, h) => NS.dxt.decodeBc3(d, w, h),
142
178
  26: (d, w, h) => NS.dxt.decodeBc4(d, w, h),
143
179
  27: (d, w, h) => NS.dxt.decodeBc5(d, w, h),
180
+ // ASTC 全系列(48~53 无 alpha 变体 / 54~59 带 alpha 变体):同一个解码器,只有块边长不同。
181
+ // 块边长从 FORMATS 的 bw/bh 取(见 astcDecoder 的注释),这里只登记"哪个格式号归 ASTC"。
182
+ 48: astcDecoder(48), 49: astcDecoder(49), 50: astcDecoder(50),
183
+ 51: astcDecoder(51), 52: astcDecoder(52), 53: astcDecoder(53),
184
+ 54: astcDecoder(54), 55: astcDecoder(55), 56: astcDecoder(56),
185
+ 57: astcDecoder(57), 58: astcDecoder(58), 59: astcDecoder(59),
144
186
  // 未压缩格式:切片后按通道展开
145
187
  4: (d, w, h, need) => d.slice(0, need),
146
188
  5: (d, w, h, need) => argbToRgba(d.slice(0, need)),
@@ -159,12 +201,15 @@
159
201
  function decode(meta, data, opts) {
160
202
  const fmt = meta.format;
161
203
  const f = FORMATS[fmt];
162
- if (!f) throw NS.errors.fail('ULB_ERR_TEX_FORMAT_UNSUPPORTED', `暂不支持纹理格式 ${fmt}(${meta.name || ''})——已支持:ETC2_RGBA8(47)、ETC2_RGBA1(48)、ETC2_RGB(45)、ETC_RGB4(34)、DXT1(10)、DXT5(12)、BC4(26)、BC5(27)、RGBA32(4)、ARGB32(5)、RGB24(3)、Alpha8(1)、RGB565(7);暂未实现:ASTC(50 系列)、PVRTC(30/31)、BC6H(24)、BC7(25)`);
204
+ if (!f) throw NS.errors.fail('ULB_ERR_TEX_FORMAT_UNSUPPORTED', `暂不支持纹理格式 ${fmt}(${meta.name || ''})——已支持:ETC2_RGBA8(47)、ETC2_RGBA1(46)、ETC2_RGB(45)、ETC_RGB4(34)、DXT1(10)、DXT5(12)、BC4(26)、BC5(27)、ASTC 全系列(48~59)、RGBA32(4)、ARGB32(5)、RGB24(3)、Alpha8(1)、RGB565(7);未实现:PVRTC(30~33)、BC6H(24)、BC7(25)`);
205
+ // 解码器检查放在长度检查**之前**:表里有、但没登记解码器(PVRTC / BC6H / BC7 这类)
206
+ // 属于"格式未支持",不是"数据不足"。顺序反了会用尺寸错误掩盖真实原因。
207
+ const decoder = DECODERS[fmt];
208
+ if (!decoder) {
209
+ throw NS.errors.fail('ULB_ERR_TEX_FORMAT_UNSUPPORTED', `纹理格式 ${f.name}(${fmt})尚未实现解码器——当前未接入的格式只有 PVRTC / BC6H / BC7`);
210
+ }
163
211
  const need = expectedSize(fmt, meta.width, meta.height);
164
212
  if (data.length < need) throw NS.errors.fail('ULB_ERR_TEX_DATA_SHORT', `纹理 ${meta.name || ''}(${f.name} ${meta.width}x${meta.height})数据不足:需要 ${need} 字节,实际 ${data.length}`);
165
- // 表里有格式、但没有登记解码器(如 ASTC 50 系列)⇒ 继续走这条兜底
166
- const decoder = DECODERS[fmt];
167
- if (!decoder) throw NS.errors.fail('ULB_ERR_TEX_DECODE', `纹理格式 ${f.name} 的分发分支缺失`);
168
213
  const rgba = decoder(data, meta.width, meta.height, need);
169
214
  // 统一翻转:原实现用 finish() 包住每个 return,等价于在这里一次做完
170
215
  return !opts || opts.flipY !== false ? flipY(rgba, meta.width, meta.height) : rgba;
@@ -174,8 +219,8 @@
174
219
  * 某个 Unity TextureFormat 能否**真正解码**。
175
220
  *
176
221
  * 为什么需要它:FORMATS 是"格式字典"(名称 / 尺寸 / block 布局),**不代表能解码** ——
177
- * 例如 ASTC(50 系列) 在 FORMATS 里可能有条目、但 DECODERS 没登记,decode() 会抛
178
- * ULB_ERR_TEX_DECODE。若外部(预检 / 面板提示)拿 `!!FORMATS[fmt]` 当"支持",
222
+ * 例如 PVRTC 可能在 FORMATS 里有条目、但 DECODERS 没登记,decode() 会抛
223
+ * ULB_ERR_TEX_FORMAT_UNSUPPORTED。若外部(预检 / 面板提示)拿 `!!FORMATS[fmt]` 当"支持",
179
224
  * 就会先报"支持"、真正解包时才炸 —— 同一件事两套判据。
180
225
  * ⇒ 能力判定只认这张表:**这是"能不能解码"的唯一真相**。
181
226
  *
@@ -69,6 +69,7 @@
69
69
  "lib/extract.js",
70
70
  "lib/etc2.js",
71
71
  "lib/dxt.js",
72
+ "lib/astc.js",
72
73
  "lib/texdecode.js",
73
74
  "lib/bundle-probe.js",
74
75
  "lib/png.js",
@@ -76,17 +76,51 @@ export function listProviderPlugins() {
76
76
  }
77
77
 
78
78
  /**
79
- * provider 集合的指纹段(写进解包缓存键,插件升级/增减时缓存自然失效)。
79
+ * 插件的**源码指纹**:`files[]` 里每个随包脚本的 size + mtime 摘要。
80
80
  *
81
- * 单插件时返回该插件 id —— 与历史硬编码值**逐字相同**,所以现有缓存不会因为这次通用化失效;
82
- * 多插件时才拼成 `a@1+b@2`(顺序无关,排序后拼)。
81
+ * 为什么需要它:providerFingerprint 原先只含 `id@version`,而 version 是插件作者
82
+ * 手写的声明值 —— 改了插件代码但没升版本时,解包缓存键不变,产物永远命中旧缓存。
83
+ * 这会造成"代码明明修好了、页面还是旧结果",而且排查时看不到线索:缓存命中本身
84
+ * 是正常路径,日志里只有一句 hit。
85
+ * 把脚本 stat 计入后,"代码变了"本身就成为失效条件,不依赖作者记得升版本。
86
+ *
87
+ * exec 运行时(如 Python worker)的 `files` 通常为空,此时退到 `entry` —— 那才是
88
+ * 真正会被执行的入口脚本;不把它算进去等于漏掉整个插件。
89
+ */
90
+ function pluginSourceStamp(meta) {
91
+ const list = Array.isArray(meta.files) && meta.files.length
92
+ ? meta.files
93
+ : (meta.entry ? [meta.entry] : []);
94
+ const parts = [];
95
+ for (const rel of list) {
96
+ // 两种形态并存:`files[]` 来自插件清单,**已带插件 id 前缀**(`<id>/lib/x.js`);
97
+ // `entry` 是裸文件名(`worker.py`)。混用拼接必然 ENOENT,所以两种都试。
98
+ const withId = path.join(PLUGINS_DIR, meta.id, rel);
99
+ const bare = path.join(PLUGINS_DIR, rel);
100
+ let st = null;
101
+ try { st = fs.statSync(withId); } catch { try { st = fs.statSync(bare); } catch { st = null; } }
102
+ if (!st) continue; // 缺文件交给装载阶段报错;这里只负责算指纹
103
+ parts.push(`${rel}:${st.size}:${Math.round(st.mtimeMs)}`);
104
+ }
105
+ return parts.join(',');
106
+ }
107
+
108
+ /**
109
+ * provider 集合的指纹段(写进解包缓存键:插件增减、升级、**源码变动**都会让它失效)。
110
+ *
111
+ * 形态 `<id>@<version>#<源码摘要>`;多插件时各自算出后排序拼接(顺序无关)。
83
112
  * @returns {string}
84
113
  */
85
114
  export function providerFingerprint() {
86
115
  const list = listProviderPlugins();
87
116
  if (!list.length) return 'none';
88
- if (list.length === 1) return list[0].id;
89
- return list.map((m) => `${m.id}@${m.version === null || m.version === undefined ? '0' : m.version}`).sort().join('+');
117
+ const seg = (m) => {
118
+ const v = m.version === null || m.version === undefined ? '0' : m.version;
119
+ const stamp = pluginSourceStamp(m);
120
+ return stamp ? `${m.id}@${v}#${stamp}` : `${m.id}@${v}`;
121
+ };
122
+ if (list.length === 1) return seg(list[0]);
123
+ return list.map(seg).sort().join('+');
90
124
  }
91
125
 
92
126
  /**
@@ -547,12 +547,30 @@ export function loadExecPlugin(meta, ctx) {
547
547
  }
548
548
  const list = Array.isArray(resp.files) ? resp.files : [];
549
549
  const out = {};
550
+ const usedNames = new Set();
550
551
  for (const f of list) {
551
552
  const name = String((f && (f.name || f.path)) || '');
552
553
  if (!name) continue;
553
554
  const tmp = f && f.tmpPath ? String(f.tmpPath) : '';
554
555
  if (!tmp) continue; // 没有 tmpPath 的条目拿不到字节,宁可少一个也不报假成功
555
- out[name] = lazyBytes(tmp, f.size);
556
+ // 兜底去重:容器里的 m_Name **不保证唯一**(实测单包有 2 份同名 .skel 与 2 份同名 .atlas)。
557
+ // 用普通对象按 name 赋值会让后一条覆盖前一条 —— 产物少文件,且下游按名字配对时
558
+ // 可能把两套不同的资源拼在一起。这是通用正确性问题,与具体资源格式无关。
559
+ //
560
+ // 唯一性**主要由上游 worker 负责**:它按 pathID 生成 `<stem>__<pathId><ext>`
561
+ // (顺序无关、可复现)。这里只防"上游没做或做漏"的意外重复,不承担唯一性职责;
562
+ // 真走到这个分支时加的是序号(仅兜底,不保证跨版本可复现)。
563
+ let unique = name;
564
+ if (usedNames.has(unique)) {
565
+ const dot = name.lastIndexOf('.');
566
+ const stem = dot > 0 ? name.slice(0, dot) : name;
567
+ const ext = dot > 0 ? name.slice(dot) : '';
568
+ let i = 2;
569
+ while (usedNames.has(`${stem}__${i}${ext}`)) i += 1;
570
+ unique = `${stem}__${i}${ext}`;
571
+ }
572
+ usedNames.add(unique);
573
+ out[unique] = lazyBytes(tmp, f.size);
556
574
  }
557
575
  return {
558
576
  prefix: resp.prefix,
@@ -761,6 +761,9 @@ async function materialize(file, opts = {}) {
761
761
  if (bundleCands.length) {
762
762
  let fellBack = '';
763
763
  let anyProbed = false; // 有没有任何一个 worker 真的判过"不认这个包"
764
+ // worker 的失败原因先存着,等主线程结果出来再决定发"已恢复"还是"真失败":
765
+ // 在中间态就报红会让用户以为坏了(画面其实可能马上正常)。
766
+ let pendingWorkerError = '';
764
767
  for (const cand of bundleCands) {
765
768
  // 有内联字节就直投;否则把 URL 交给 worker 自己拉(主线程零字节搬运)。
766
769
  // ?workerFetch=0 时故意先读一遍,用来量"改造前"那一段的耗时。
@@ -793,9 +796,16 @@ async function materialize(file, opts = {}) {
793
796
  // 交给下面的同步路径去给出正确的"没有插件能处理"错误,不该谎报成后台不可用
794
797
  if (!fellBack && !anyProbed) fellBack = '所有候选插件的 worker 都不可用';
795
798
  if (fellBack) {
796
- // 降级**不静默**:明确告诉用户"后台解包用不了,接下来会卡数秒"
797
- say.warn(`后台解包不可用(${fellBack})—— 回落主线程解包,期间界面会卡住数秒`);
798
- emit('unpack.worker-fallback', { rootId: file.rootId, rel: file.rel, error: fellBack });
799
+ // 降级**不静默**:告诉用户"后台解包用不了,接下来会卡数秒"。
800
+ // 但**不要把 worker 的原始异常原文塞进这句文案**:它通常只是"某个候选插件在这个包上失败"
801
+ // (例如 live2d 插件撞到包内同名贴图),紧接着主线程很可能解包成功。
802
+ // 把 `ULB_ERR_MODEL_BUILD: ...` 这类原文摆在状态栏,用户看到的是"功能坏了",
803
+ // 实际画面马上就出来了 —— 原文仍留在诊断事件的 detail 里,排查要看得到。
804
+ say.warn('后台解包不可用,回落主线程解包 —— 这次会慢几秒');
805
+ // worker 失败这件事**此刻还只是中间态**:下面主线程还会再试一次,很可能成功。
806
+ // 早先是在这里就 emit('unpack.worker-fallback', {error}),于是诊断面板先落一条带错误的事件,
807
+ // 哪怕随后主线程装好了也不会收回。现在先记住,等主线程结果出来再按「最终成败」发事件。
808
+ pendingWorkerError = fellBack;
799
809
  }
800
810
  }
801
811
  // 同步解压前让出一帧:DOM 改了但主线程随即冻住,浏览器不会给你渲染机会。
@@ -808,7 +818,22 @@ async function materialize(file, opts = {}) {
808
818
  const read = await ensureBytes();
809
819
  const got = await resolveViaProvider(file, read.bytes);
810
820
  if (mon.checkNow()) throw Object.assign(new Error(mon.reason()), { reason: 'memory-guard' });
811
- if (!got.ok) throw Object.assign(new Error(got.message || '本地解包失败'), { reason: got.reason, passthrough: got });
821
+ if (!got.ok) {
822
+ // 主线程也失败 ⇒ 这才是**真失败**:把前面 worker 的失败原因一并带上,便于定位
823
+ if (pendingWorkerError) {
824
+ emit('unpack.worker-fallback', {
825
+ rootId: file.rootId, rel: file.rel, error: pendingWorkerError, finalError: got.message || got.reason || null,
826
+ });
827
+ }
828
+ throw Object.assign(new Error(got.message || '本地解包失败'), { reason: got.reason, passthrough: got });
829
+ }
830
+ if (pendingWorkerError) {
831
+ // 回退成功:worker 那次失败只是中间态。发一条**不带 error 字段**的恢复事件,
832
+ // 面板据此显示成信息而不是红字;worker 的原始原因留在 workerError 里供排查。
833
+ emit('unpack.worker-recovered', {
834
+ rootId: file.rootId, rel: file.rel, workerError: pendingWorkerError, provider: got.provider,
835
+ });
836
+ }
812
837
  return { ...got.res, provider: got.provider, src: 'local' };
813
838
  };
814
839
 
package/src/web/main.js CHANGED
@@ -25,6 +25,7 @@ import { createSpineStage } from './spine/canvas.js';
25
25
  import { createStageSurface } from './render/surface.js';
26
26
  import { createSpineRenderer } from './render/spine.js';
27
27
  import { createLive2DRenderer } from './render/live2d.js';
28
+ import { createThreeRenderer } from './render/demo-3d.js';
28
29
  import { createLive2DStage } from './live2d/stage.js';
29
30
  import { attachStageInteraction } from './render/interaction.js';
30
31
  import { dom, setStage, stage, state } from './app/context.js';
@@ -147,9 +148,16 @@ function initRenderer() {
147
148
  const surface = createStageSurface({ log: (message, level) => stageStatus(message, level === 'error' ? 'error' : level === 'warn' ? 'warn' : 'info') });
148
149
  surface.register(createSpineRenderer({ stage, onMsaa: applyMsaa }));
149
150
  surface.register(createLive2DRenderer({ live2d: ensureLive2DStage() }));
151
+ // 三维预留面:**注册但不激活**。没有任何内容类型会产出 kind='three',
152
+ // 所以它不会改变用户可见的默认面;注册它的价值是让"新面插得进来"这件事
153
+ // 处于可运行状态(面元数据、注册校验、相机语义分派全链路都在位)。
154
+ surface.register(createThreeRenderer({
155
+ log: (message, level) => stageStatus(message, level === 'warn' ? 'warn' : 'info'),
156
+ }));
150
157
  // 就绪信号 renderer 阶段(契约 §三):两面都注册完 = 已实例化;
151
158
  // 能力声明可读 = settled;能拿到 activeRenderer 且可下发设置 = interactive
152
- markStage('renderer', 'mounted', { faces: 2 });
159
+ // faces 取实际注册数(不写死,加面时诊断字段自动跟上)
160
+ markStage('renderer', 'mounted', { faces: typeof surface.renderers === 'function' ? surface.renderers().length : null });
153
161
  const twoFrames = (fn) => requestAnimationFrame(() => requestAnimationFrame(fn));
154
162
  twoFrames(() => {
155
163
  const caps = (() => { try { return surface.capabilities ? surface.capabilities() : null; } catch { return null; } })();
@@ -291,6 +299,19 @@ function cameraProxy() {
291
299
  zoomStep: forward('zoomStep'),
292
300
  zoomTo: forward('zoomTo'),
293
301
  panBy: forward('panBy'),
302
+ // 3D 面的相机用 orbitBy 表达"拖动 = 绕轨道转";2D 面没有这个方法,
303
+ // 转发后取到 null,交互层据此判定该面不支持轨道语义(而不是猜一个近似动作)。
304
+ orbitBy: forward('orbitBy'),
305
+ /**
306
+ * 当前相机是否真的提供 orbitBy。
307
+ * 为什么要单独一个探针:门面是固定形状的代理,2D 相机上也存在 `orbitBy` 这个键
308
+ * (转发后返回 null)。交互层若只看"有没有这个函数",在 2D 面上会误判成支持轨道,
309
+ * 把拖动变成静默无效。探针让"支不支持"由真实相机决定。
310
+ */
311
+ hasOrbit: () => {
312
+ const cam = pick();
313
+ return !!(cam && typeof cam.orbitBy === 'function');
314
+ },
294
315
  reset: forward('reset'),
295
316
  scale: forward('scale'),
296
317
  note: forward('note'),
@@ -302,6 +323,19 @@ function cameraProxy() {
302
323
  function interactionStage() {
303
324
  return {
304
325
  camera: cameraProxy(),
326
+ /**
327
+ * 当前渲染面声明的相机语义(`capabilities.camera`)。
328
+ *
329
+ * 交付给交互层的是**值**而不是能力表:交互层只需知道"这一面是平面还是绕轨道",
330
+ * 给它整份能力表会让它有机会去读与本层无关的字段。做成 getter 是因为切面后
331
+ * 语义会变,而交互层只在挂载时拿一次门面(每次调用现取才不会停在旧面上)。
332
+ */
333
+ get cameraCapability() {
334
+ const caps = state.surface && typeof state.surface.capabilities === 'function'
335
+ ? state.surface.capabilities()
336
+ : null;
337
+ return caps && typeof caps.camera === 'string' ? caps.camera : null;
338
+ },
305
339
  getView: (...args) => (stage && stage.getView ? stage.getView(...args) : null),
306
340
  setView: (...args) => (stage && stage.setView ? stage.setView(...args) : null),
307
341
  resetView: (...args) => (stage && stage.resetView ? stage.resetView(...args) : null),
@@ -318,7 +352,13 @@ function attachInteraction() {
318
352
  const target = (state.surface && state.surface.interactionTarget) || null;
319
353
  if (!target || !stage) return null;
320
354
  try {
321
- detachInteraction = attachStageInteraction({ canvas: target, stage: interactionStage() });
355
+ detachInteraction = attachStageInteraction({
356
+ canvas: target,
357
+ stage: interactionStage(),
358
+ // 交互层的告警要有出口:相机缺能力(例如 3D 面没实现 orbitBy)时,
359
+ // 只写相机内部日志会静默(相机 logger 未挂),用户只看到"拖不动"。
360
+ options: { log: (message, level) => stageStatus(message, level === 'info' ? 'info' : 'warn') },
361
+ });
322
362
  } catch (err) {
323
363
  state.stageError = formatError(err);
324
364
  }
@@ -34,12 +34,39 @@ export const LIVE2D_OVERRIDE = Object.freeze({});
34
34
  */
35
35
  export const SUBJECT_EXCLUDE = Object.freeze(['bg', 'back', 'background', 'effect', 'mask', 'scene', 'kazari']);
36
36
 
37
+ /**
38
+ * 三维(轨道相机)面的边界承载位:距离与俯仰。
39
+ *
40
+ * 本字段只是**结构就位**:当前没有任何实现消费它(没有 3D 渲染器),
41
+ * 目的是让 `limitsFor` 的形状在接入 3D 之前就稳定下来 —— 将来写轨道相机时
42
+ * 数值往这里填,不必回头改 `limitsFor` 的返回形状与所有调用点。
43
+ * 与契约里 `capabilities.camera = 'orbit-3d'` 是同一个语义键,两处必须一致。
44
+ */
45
+ export const ORBIT = Object.freeze({
46
+ /** 最近距离(推拉到最近处仍能看到主体) */
47
+ MIN_DISTANCE: 0.5,
48
+ /** 最远距离(再远就只剩一个小点,收益极低) */
49
+ MAX_DISTANCE: 12,
50
+ /** 最低俯仰角(弧度):约 8.6°,再低会看到地平面以下 */
51
+ MIN_POLAR: 0.15,
52
+ /** 最高俯仰角(弧度):约 83°,避免与极点重合导致万向锁抖动 */
53
+ MAX_POLAR: 1.45,
54
+ });
55
+
56
+ /**
57
+ * 面元数据表里 `cameraKind` 取这个值表示"该面用轨道相机"。
58
+ * 数值/形状由 ORBIT 承载;这里只是判定键。
59
+ */
60
+ export const ORBIT_CAMERA_KIND = 'orbit-3d';
61
+
37
62
  /**
38
63
  * 各面的相机覆盖值表(键 = 面元数据表的 cameraKind)。
39
64
  * 加新面时若要限制它的缩放范围,在这里加一个键 —— 不必改 limitsFor 的判断。
40
65
  */
41
66
  const CAMERA_OVERRIDES = Object.freeze({
42
67
  live2d: LIVE2D_OVERRIDE,
68
+ // 3D 面的缩放落在"距离"上,量级与 2D 的 userScale 不同,因此给一份独立覆盖值
69
+ [ORBIT_CAMERA_KIND]: Object.freeze({ MIN: ORBIT.MIN_DISTANCE, MAX: ORBIT.MAX_DISTANCE }),
43
70
  });
44
71
 
45
72
  /**
@@ -48,13 +75,24 @@ const CAMERA_OVERRIDES = Object.freeze({
48
75
  * 覆盖关系查 render/surfaces.js 的 cameraKind,不再写 `kind === 'live2d'`:
49
76
  * 未知 kind ⇒ 不叠加覆盖、直接用通用值。这里刻意**不抛错**:
50
77
  * 相机范围有通用兜底,不像画布/面模式那样写错就错乱,所以"查不到覆盖表键"等同于"这个面没有特殊限制"。
51
- * @param {'spine'|'live2d'} kind
52
- * @returns {{min: number, max: number}}
78
+ *
79
+ * 2D 面返回形状**只有 { min, max }**(一个字段都不多):交互/相机层按此读写缩放,
80
+ * 多给字段不会报错但会让"3D 结构已就位"这件事看不出边界;只有声明了轨道相机的面
81
+ * 才额外带 `orbit`(距离/俯仰),且该字段当前无人消费。
82
+ * @param {'spine'|'live2d'|'three'} kind
83
+ * @returns {{min: number, max: number, orbit?: {distance: {min: number, max: number}, polar: {min: number, max: number}}}}
53
84
  */
54
85
  export function limitsFor(kind) {
55
86
  const meta = byKind(kind);
56
87
  const override = meta ? (CAMERA_OVERRIDES[meta.cameraKind] || null) : null;
57
88
  const min = override && typeof override.MIN === 'number' ? override.MIN : CAMERA.MIN;
58
89
  const max = override && typeof override.MAX === 'number' ? override.MAX : CAMERA.MAX;
59
- return { min, max };
90
+ const limits = { min, max };
91
+ if (meta && meta.cameraKind === ORBIT_CAMERA_KIND) {
92
+ limits.orbit = {
93
+ distance: { min: ORBIT.MIN_DISTANCE, max: ORBIT.MAX_DISTANCE },
94
+ polar: { min: ORBIT.MIN_POLAR, max: ORBIT.MAX_POLAR },
95
+ };
96
+ }
97
+ return limits;
60
98
  }
@@ -0,0 +1,131 @@
1
+ // render/demo-3d.js —— 三维渲染面(id: 'three')的**占位实现**
2
+ //
3
+ // 这个文件不画 3D,也不引 three.js/glTF:它存在的唯一目的是证明
4
+ // 「契约里预留的三维位真的插得进来」—— 能注册、能被 activate、相机语义是 orbit-3d、
5
+ // 拖动会走轨道分支而不是平移。等真写 3D 渲染时,替换本文件的 mount/render 即可,
6
+ // 注册、面元数据、相机语义分派这些外围都已经就位。
7
+ //
8
+ // 为什么让相机走统一 createCamera:3D 面的边界值(距离/俯仰)已经在
9
+ // camera/constants.js 的 ORBIT 里备好,走同一条入口才能顺带验证那份结构的形状。
10
+ // 本面的缩放落在"距离"量级上,与 2D 的 userScale 不是一回事,覆盖值由
11
+ // cameraKind='orbit-3d' 单独给。
12
+
13
+ import { createCamera } from './camera/index.js';
14
+
15
+ /**
16
+ * 创建占位三维渲染器。
17
+ * @param {{log?: (message: string, level?: 'info'|'warn'|'error') => void}} [options]
18
+ */
19
+ export function createThreeRenderer({ log } = {}) {
20
+ const note = (message, level = 'info') => {
21
+ if (typeof log !== 'function') return;
22
+ try { log(message, level); } catch { /* 日志失败不影响渲染面 */ }
23
+ };
24
+
25
+ /** 轨道状态:占位实现只累计角度,不产生任何画面(真实现会把它换成相机的球坐标) */
26
+ const orbit = { yaw: 0, pitch: 0 };
27
+ /** 占位缩放:与 2D 的 userScale 同义(这里代表"距离") */
28
+ let distance = 1;
29
+ let mountedDocument = null;
30
+ let targetCanvas = null;
31
+ let offResize = null;
32
+
33
+ /**
34
+ * 把逻辑尺寸落到画布 backing store。
35
+ *
36
+ * 为什么占位面也要做这一步:像素尺寸由渲染器/引擎拥有(Surface 只给 geometry),
37
+ * 不做的话画布会停在浏览器默认的 300×150,看起来"这个面根本没接上"。
38
+ * 这里只改像素尺寸,CSS 尺寸仍由舞台的样式表决定。
39
+ */
40
+ function applyGeometry(handle) {
41
+ const size = handle && handle.size;
42
+ const dpr = handle && handle.dpr ? handle.dpr : 1;
43
+ if (!targetCanvas || !size) return null;
44
+ const width = Math.max(1, Math.round(size.width * dpr));
45
+ const height = Math.max(1, Math.round(size.height * dpr));
46
+ if (targetCanvas.width !== width) targetCanvas.width = width;
47
+ if (targetCanvas.height !== height) targetCanvas.height = height;
48
+ return { width, height, dpr };
49
+ }
50
+
51
+ const baseCamera = createCamera({
52
+ kind: 'three',
53
+ log: (message, level) => note(`[three] ${message}`, level),
54
+ backend: {
55
+ getScale: () => distance,
56
+ setScale: (value) => { distance = value; },
57
+ // 平移在轨道相机里没有对应动作:拖动语义由 orbitBy 承担,
58
+ // 这里保持空实现而不是转成平移,避免"位移看起来生效但视角没动"的假象。
59
+ pan: () => { note('pan 在轨道相机上不生效(拖动请走 orbitBy)', 'warn'); },
60
+ resetView: () => { orbit.yaw = 0; orbit.pitch = 0; distance = 1; },
61
+ },
62
+ });
63
+
64
+ const camera = {
65
+ ...baseCamera,
66
+ /**
67
+ * 拖动 → 绕轨道转(占位:只累计角度)。
68
+ * 屏幕像素按固定灵敏度换算成弧度,真实现应改为按视口高度换算。
69
+ */
70
+ orbitBy(dx, dy) {
71
+ const limits = baseCamera.info().limits;
72
+ const polar = limits && limits.orbit ? limits.orbit.polar : null;
73
+ orbit.yaw += Number(dx) || 0;
74
+ orbit.pitch += Number(dy) || 0;
75
+ if (polar) orbit.pitch = Math.min(polar.max, Math.max(polar.min, orbit.pitch));
76
+ note(`orbitBy(${Math.round(dx)}, ${Math.round(dy)}) → yaw=${orbit.yaw.toFixed(1)} pitch=${orbit.pitch.toFixed(3)}`);
77
+ return { ...orbit };
78
+ },
79
+ /** 只读轨道状态(验收/排查读它;真实现应返回相机姿态) */
80
+ orbitState: () => ({ ...orbit, distance }),
81
+ };
82
+
83
+ return {
84
+ id: 'three',
85
+ kind: 'three',
86
+ capabilities: {
87
+ // 占位面不声明任何设置项:没有实现却声明,面板就会给用户一个点了没反应的开关
88
+ settings: [],
89
+ debugDraw: [],
90
+ camera: 'orbit-3d',
91
+ },
92
+ camera,
93
+ /**
94
+ * 装载:占位实现只记录状态。
95
+ * 刻意沿用其它渲染器的入参形状(ready Document + Surface 句柄),
96
+ * 这样将来换真实现时调用方一行都不用改。
97
+ */
98
+ async mount(document, handle) {
99
+ mountedDocument = document || null;
100
+ targetCanvas = handle && handle.canvas ? handle.canvas : null;
101
+ const geometry = applyGeometry(handle);
102
+ // 尺寸变化订阅:与真渲染器同一条路径(Surface 是尺寸唯一来源,渲染器只消费)
103
+ offResize = handle && typeof handle.onResize === 'function'
104
+ ? handle.onResize(() => applyGeometry(handle))
105
+ : null;
106
+ note(`mount(占位)kind=${(document && document.kind) || '?'} canvas=${targetCanvas ? 'yes' : 'no'}`
107
+ + ` size=${geometry ? `${geometry.width}x${geometry.height}` : 'n/a'}`);
108
+ return { kind: 'three', stub: true, camera: camera.info(), geometry };
109
+ },
110
+ unmount() {
111
+ if (typeof offResize === 'function') { try { offResize(); } catch { /* 退订失败不影响卸载 */ } }
112
+ offResize = null;
113
+ targetCanvas = null;
114
+ mountedDocument = null;
115
+ note('unmount(占位)');
116
+ },
117
+ dispose() {
118
+ if (typeof offResize === 'function') { try { offResize(); } catch { /* 同上 */ } }
119
+ offResize = null;
120
+ targetCanvas = null;
121
+ mountedDocument = null;
122
+ orbit.yaw = 0;
123
+ orbit.pitch = 0;
124
+ distance = 1;
125
+ note('dispose(占位)');
126
+ },
127
+ isActive: () => mountedDocument !== null,
128
+ };
129
+ }
130
+
131
+ export default createThreeRenderer;