rcompiler 0.0.0-stage → 2.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/src/emit.js ADDED
@@ -0,0 +1,353 @@
1
+ // rCompiler V2 — 阶段C:模块化运行时发射器
2
+ // 所有依赖/use/运行时函数/结构体字段/impl 函数经 Set 去重收集,
3
+ // emit() 依据 Profile 拼装最终 Rust 源与 Cargo.toml。
4
+
5
+ 'use strict';
6
+
7
+ class Emit {
8
+ constructor(profile) {
9
+ this.profile = profile;
10
+ this.target = profile.target || null;
11
+ this.deps = new Map(); // crate spec -> true (保序插入)
12
+ this.uses = new Set();
13
+ this.runtimes = new Set(); // 顶层自由函数
14
+ this.funcs = []; // impl Default 内函数(保序,不去重——同一函数不会注册两次)
15
+ this.funcSeen = new Set();
16
+ this.fields = []; // {name, type, init}
17
+ this.fieldSeen = new Set();
18
+ this.mainBody = []; // runflag 内附加语句(rcompiler_setmain 等)
19
+ this.scripts = []; // 入口脚本函数名 {name, kind}
20
+ this.projectpub = false;
21
+ this.selfmut = false; // single 模式需要 &mut self
22
+ this.needsCloneDefault = false;
23
+ this.extras = []; // 结构体之外的全局项(如 const COSTUMES)
24
+ this.tdeps = new Map(); // cfg 表达式 -> Map(spec -> true)(按平台条件依赖)
25
+ this.hasIcon = false; // 应用图标:Cargo 需要 build.rs(Windows EXE 图标)
26
+ this.cloneSharedFields = new Set(); // 克隆时保持 Arc 共享的字段(全局锁定变量/列表;私有一律深拷贝)
27
+ }
28
+
29
+ // ---------- 收集器(全部去重) ----------
30
+ dep(spec) { if (spec) this.deps.set(spec, true); }
31
+ targetDep(cfg, spec) {
32
+ if (!cfg || !spec) return;
33
+ if (!this.tdeps.has(cfg)) this.tdeps.set(cfg, new Map());
34
+ this.tdeps.get(cfg).set(spec, true);
35
+ }
36
+ use(line) { if (line) this.uses.add(line); }
37
+ runtime(code) { if (code) this.runtimes.add(code); }
38
+ func(code) {
39
+ if (!code) return;
40
+ if (this.funcSeen.has(code)) return;
41
+ this.funcSeen.add(code);
42
+ this.funcs.push(code);
43
+ }
44
+ field(name, type, init) {
45
+ const key = name;
46
+ if (this.fieldSeen.has(key)) return;
47
+ this.fieldSeen.add(key);
48
+ this.fields.push({ name, type, init });
49
+ }
50
+ hasField(name) { return this.fieldSeen.has(name); }
51
+ main(line) { if (line) this.mainBody.push(line); }
52
+ extra(code) { this.extras.push(code); }
53
+
54
+ // ---------- Cargo.toml ----------
55
+ cargo(name, ver) {
56
+ const web = this.profile.backend === 'web';
57
+ const lines = [
58
+ `# By rCompiler`,
59
+ '[package]',
60
+ `name = "${name}"`,
61
+ `version = "${ver}"`,
62
+ 'edition = "2021"',
63
+ ];
64
+ if (this.hasIcon && !web) lines.push('build = "build.rs"');
65
+ if (web) {
66
+ lines.push(
67
+ '',
68
+ '# WASM:wasm-bindgen 从 cdylib 生成 JS 胶水;输出 web/ 宿主所需的 wasm 模块',
69
+ '[lib]',
70
+ 'crate-type = ["cdylib"]',
71
+ 'path = "src/lib.rs"'
72
+ );
73
+ }
74
+ lines.push(
75
+ '',
76
+ '# 大型单文件项目下 rustc 的增量编译与调试信息内存开销极大,dev 档关闭',
77
+ '[profile.dev]',
78
+ 'debug = 0',
79
+ 'incremental = false'
80
+ );
81
+ // 运行/打包默认 release:与 JIT 过的 JS(TurboWarp 编译器)对比的前提是本机原生优化。
82
+ // panic 保持 unwind(stop 脚本/任务终止依赖栈回退语义);混淆模式在下方另行覆盖
83
+ if (this.profile.antiReverse !== 'obf') {
84
+ lines.push(
85
+ '',
86
+ '[profile.release]',
87
+ 'opt-level = 3',
88
+ 'lto = "thin"',
89
+ 'codegen-units = 1'
90
+ );
91
+ // WASM 浏览器不支持 unwind;panic=abort 同时减小体积
92
+ if (this.profile.backend === 'web') lines.push('panic = "abort"');
93
+ lines.push('');
94
+ } else {
95
+ lines.push('');
96
+ }
97
+ const deps = [...this.deps.keys()];
98
+ if (web) {
99
+ // WASM 运行时:只用浏览器可用的能力。舞台/声音的绘制与音频由 JS 宿主负责,
100
+ // 因此这里不引入 skia/winit/softbuffer/rodio。
101
+ deps.push(
102
+ 'wasm-bindgen = "0.2"',
103
+ 'wasm-bindgen-futures = "0.4"',
104
+ 'js-sys = "0.3"',
105
+ 'console_error_panic_hook = "0.1"',
106
+ 'gloo-timers = { version = "0.3", features = ["futures"] }',
107
+ 'futures = "0.3"'
108
+ );
109
+ }
110
+ if (deps.length > 0) {
111
+ lines.push('[dependencies]');
112
+ [...new Set(deps)].forEach(d => lines.push(d));
113
+ }
114
+ // 按平台条件依赖(如 skia-safe 的 svg 预编译组合各平台不同)
115
+ for (const [cfg, specs] of this.tdeps) {
116
+ if (specs.size === 0) continue;
117
+ lines.push('');
118
+ lines.push(`[target.'cfg(${cfg})'.dependencies]`);
119
+ [...specs.keys()].forEach(d => lines.push(d));
120
+ }
121
+ // Windows EXE 图标:ICONDIR + PNG 负载(assets/app_icon.ico 由 assets.js 生成)
122
+ if (this.hasIcon && !web) {
123
+ lines.push('', `[target.'cfg(windows)'.build-dependencies]`, 'winresource = "0.1"');
124
+ }
125
+ // 混淆模式:去符号 + 全量 LTO + 单编译单元 + panic=abort,压缩逆向空间
126
+ if (this.profile.antiReverse === 'obf') {
127
+ lines.push('', '[profile.release]', 'strip = true', 'lto = "fat"', 'codegen-units = 1', 'panic = "abort"');
128
+ }
129
+ return lines.join('\n') + '\n';
130
+ }
131
+
132
+ // ---------- Rust 源拼装 ----------
133
+ rust(fileName, preludes) {
134
+ const p = this.profile;
135
+ const stage = p.hasStage;
136
+ const out = [];
137
+ out.push(`// By rCompiler`);
138
+ out.push(`// profile: stage=${stage} sound=${p.hasSound} concurrency=${p.concurrency}`);
139
+
140
+ // 1. use 语句
141
+ const uses = [...this.uses].sort();
142
+ uses.forEach(u => out.push(u));
143
+
144
+ // 2. 顶层运行时辅助函数
145
+ if (this.runtimes.size > 0) {
146
+ out.push('');
147
+ [...this.runtimes].forEach(rt => out.push(rt));
148
+ }
149
+
150
+ // 3. 目标基础运行时(WASM 平台垫片等;native 为空)
151
+ if (preludes && preludes.base) { out.push(''); out.push(preludes.base); }
152
+
153
+ // 3.5 舞台/声音前置运行时
154
+ if (stage && preludes && preludes.stage) { out.push(''); out.push(preludes.stage); }
155
+ if (p.hasSound && preludes && preludes.sound) { out.push(''); out.push(preludes.sound); }
156
+
157
+ // 4. 额外全局项(Costume 常量等)
158
+ this.extras.forEach(e => out.push(e));
159
+
160
+ // 4.5 结构体之后的模块项(引用 Default 的静态注册表等)
161
+ (this.postStruct || []).forEach(e => out.push(e));
162
+
163
+ // 5. 结构体 Default
164
+ const pubk = this.projectpub ? 'pub ' : '';
165
+ out.push('');
166
+ out.push(`${pubk}struct Default{`);
167
+ out.push(this.fields.map(f => `${f.name}:${f.type}`).join(',\n'));
168
+ out.push('}');
169
+
170
+ // 6. impl Default
171
+ out.push('impl Default{');
172
+ out.push(`${pubk}fn new() -> Default{`);
173
+ out.push('Default{');
174
+ out.push(this.fields.map(f => `${f.name}:${f.init}`).join(',\n'));
175
+ out.push('}');
176
+ out.push('}');
177
+
178
+ // new_with_stage:舞台模式下 Default::new 需要 stage 句柄
179
+ if (stage && preludes && preludes.newWithStage) {
180
+ out.push(preludes.newWithStage);
181
+ }
182
+
183
+ this.funcs.forEach(f => out.push(f));
184
+
185
+ // 克隆支持:clone_default(全局锁字段共享 Arc,私有字段深拷贝)
186
+ if (this.needsCloneDefault) {
187
+ out.push(this.buildCloneDefault());
188
+ }
189
+
190
+ // 舞台桥接(Default 上的 s_* 方法,由 preludes 提供)
191
+ if (stage && preludes && preludes.defaultImpl) {
192
+ out.push(preludes.defaultImpl);
193
+ }
194
+ // 声音桥接
195
+ if (p.hasSound && preludes && preludes.soundImpl) {
196
+ out.push(preludes.soundImpl);
197
+ }
198
+
199
+ // 7. runflag(impl 内方法)+ main
200
+ out.push('');
201
+ out.push(this.buildRunflag());
202
+ out.push('}'); // impl Default 结束
203
+ out.push('');
204
+ out.push(this.buildMain());
205
+
206
+ return out.join('\n') + '\n';
207
+ }
208
+
209
+ buildCloneDefault() {
210
+ const lines = ['pub fn clone_default(&self) -> Default {', 'Default{'];
211
+ const parts = this.fields.map(f => {
212
+ if (f.name === 'stage') return `stage: std::sync::Arc::clone(&self.stage)`;
213
+ if (f.name === 'sprite_index') return `sprite_index: usize::MAX`;
214
+ if (f.type.startsWith('std::sync::Arc<RcompilerCell<')) {
215
+ // 全局锁定字段:Arc 共享(Scratch:克隆与原型共用全局变量);
216
+ // 私有锁定字段:深拷贝内层值(Scratch:克隆获得创建时刻的私有变量副本)
217
+ if (this.cloneSharedFields.has(f.name)) return `${f.name}: std::sync::Arc::clone(&self.${f.name})`;
218
+ return `${f.name}: std::sync::Arc::new(RcompilerCell { v: std::cell::RefCell::new(self.${f.name}.v.borrow().clone()) })`;
219
+ }
220
+ if (f.type.startsWith('std::sync::Arc<std::sync::Mutex<') && f.type.endsWith('>>')) {
221
+ return `${f.name}: std::sync::Arc::new(std::sync::Mutex::new(self.${f.name}.lock().unwrap().clone()))`;
222
+ }
223
+ if (f.type.startsWith('std::sync::Mutex<')) {
224
+ // Mutex<Instant>/Mutex<String> 等无 Clone 的字段:锁内取值重建(Mutex 本身不可克隆)
225
+ return `${f.name}: std::sync::Mutex::new(self.${f.name}.lock().unwrap().clone())`;
226
+ }
227
+ return `${f.name}: self.${f.name}.clone()`;
228
+ });
229
+ lines.push(parts.join(',\n'));
230
+ lines.push('}', '}');
231
+ return lines.join('\n');
232
+ }
233
+
234
+ buildRunflag() {
235
+ const p = this.profile;
236
+ const multi = p.concurrency === 'multi';
237
+ const scripts = this.scripts;
238
+ const body = this.mainBody.slice();
239
+ const pubk = this.projectpub ? 'pub ' : '';
240
+
241
+ // 舞台模式:runflag 拆成可重入的 rcompiler_spawn_all(顶栏绿旗/暂停/停止依赖),
242
+ // 初始启动由 rcompiler_stage_main 在事件循环外调用,不再阻塞等待全部脚本结束。
243
+ if (p.hasStage && multi) {
244
+ const lines = [`${pubk}fn rcompiler_spawn_all(self: std::sync::Arc<Self>) {`];
245
+ body.forEach(l => lines.push(l));
246
+ const gate = !!(p.frame && p.frame.gate);
247
+ scripts.forEach(s => {
248
+ const inner = `async move { __s.${s.name}().await; }`;
249
+ const ti = (s.ti == null || s.ti < 0) ? 0 : s.ti;
250
+ lines.push(`{ let __s = self.clone(); let __h = tokio::spawn(${gate ? `rcompiler_script(${inner})` : inner}); rcompiler_track_task(${ti}, &__h); }`);
251
+ });
252
+ lines.push('}');
253
+ lines.push(`${pubk}async fn runflag(self: std::sync::Arc<Self>) {`);
254
+ lines.push(' self.rcompiler_spawn_all();');
255
+ lines.push('}');
256
+ return lines.join('\n');
257
+ }
258
+
259
+ if (scripts.length === 0) {
260
+ // 无入口
261
+ if (multi) return `${pubk}async fn runflag(self: std::sync::Arc<Self>) {\n${body.join('\n')}\n}`;
262
+ const sig = this.selfmut ? '&mut self' : '&self';
263
+ return `${pubk}fn runflag(${sig}) {\n${body.join('\n')}\n}`;
264
+ }
265
+
266
+ if (multi) {
267
+ const lines = [`${pubk}async fn runflag(self: std::sync::Arc<Self>) {`];
268
+ body.forEach(l => lines.push(l));
269
+ const gate = !!(p.frame && p.frame.gate);
270
+ lines.push('let mut __handles: Vec<tokio::task::JoinHandle<()>> = Vec::new();');
271
+ scripts.forEach(s => {
272
+ const inner = `async move { __s.${s.name}().await; }`;
273
+ const ti = (s.ti == null || s.ti < 0) ? 0 : s.ti;
274
+ lines.push(`{ let __s = self.clone(); let __h = tokio::spawn(${gate ? `rcompiler_script(${inner})` : inner}); rcompiler_track_task(${ti}, &__h); __handles.push(__h); }`);
275
+ });
276
+ lines.push('for __h in __handles { let _ = __h.await; }');
277
+ lines.push('}');
278
+ return lines.join('\n');
279
+ }
280
+
281
+ const sig = this.selfmut ? '&mut self' : '&self';
282
+ const lines = [`${pubk}fn runflag(${sig}) {`];
283
+ body.forEach(l => lines.push(l));
284
+ scripts.forEach(s => lines.push(`self.${s.name}();`));
285
+ lines.push('}');
286
+ return lines.join('\n');
287
+ }
288
+
289
+ buildMain() {
290
+ const p = this.profile;
291
+ const multi = p.concurrency === 'multi';
292
+ const frameOn = !!(p.frame && p.frame.gate);
293
+ if (p.backend === 'web') {
294
+ // WASM 没有 process main:用 wasm-bindgen 的 start 入口。
295
+ // 舞台:由 web 运行时创建 StageShared,再由 JS 宿主按 TPS 调用 rcompiler_web_tick;
296
+ // 纯计算:单线程同步启动,或多任务 spawn_local 启动。
297
+ if (p.hasStage) {
298
+ return [
299
+ '#[wasm_bindgen(start)]',
300
+ 'pub fn rcompiler_web_start() {',
301
+ ' rcompiler_web_boot_stage(Default::new_with_stage);',
302
+ '}'
303
+ ].join('\n');
304
+ }
305
+ if (multi) {
306
+ return [
307
+ '#[wasm_bindgen(start)]',
308
+ 'pub fn rcompiler_web_start() {',
309
+ ' console_error_panic_hook::set_once();',
310
+ frameOn ? ' rcompiler_start_clock(RCOMPILER_TPS);' : '',
311
+ ' let init = std::sync::Arc::new(Default::new());',
312
+ ' wasm_bindgen_futures::spawn_local(async move { init.runflag().await; });',
313
+ '}'
314
+ ].join('\n');
315
+ }
316
+ return [
317
+ '#[wasm_bindgen(start)]',
318
+ 'pub fn rcompiler_web_start() {',
319
+ ' console_error_panic_hook::set_once();',
320
+ frameOn ? ' rcompiler_start_sync_clock(RCOMPILER_TPS);' : '',
321
+ ` let ${this.selfmut ? 'mut ' : ''}init = Default::new();`,
322
+ ' init.runflag();',
323
+ '}'
324
+ ].join('\n');
325
+ }
326
+ if (p.hasStage) {
327
+ // RCOMPILER_HEADLESS=1 运行时切换无头事件循环(无窗口跑逻辑+离屏导出);
328
+ // 混淆模式编译期移除该入口(与 RCOMPILER_STAGE_DUMP 同等待遇)
329
+ const headless = p.antiReverse === 'obf'
330
+ ? 'false'
331
+ : 'std::env::var("RCOMPILER_HEADLESS").as_deref() == Ok("1")';
332
+ return ['fn main() {',
333
+ ` if ${headless} { rcompiler_stage_headless(Default::new_with_stage); } else { rcompiler_stage_main(Default::new_with_stage); }`,
334
+ '}'].join('\n');
335
+ }
336
+ if (multi) {
337
+ const lines = ['#[tokio::main]', 'async fn main() {'];
338
+ if (frameOn) lines.push(' rcompiler_start_clock(RCOMPILER_TPS);');
339
+ lines.push(' let init = std::sync::Arc::new(Default::new());');
340
+ lines.push(' init.runflag().await;');
341
+ lines.push('}');
342
+ return lines.join('\n');
343
+ }
344
+ const lines = ['fn main() {'];
345
+ if (frameOn) lines.push(' rcompiler_start_sync_clock(RCOMPILER_TPS);');
346
+ lines.push(` let ${this.selfmut ? 'mut ' : ''}init = Default::new();`);
347
+ lines.push(' init.runflag();');
348
+ lines.push('}');
349
+ return lines.join('\n');
350
+ }
351
+ }
352
+
353
+ module.exports = { Emit };
package/src/mods.js ADDED
@@ -0,0 +1,146 @@
1
+ // rCompiler V2 — rCodenow 模组系统(模组/Mod)
2
+ // 兼容 rCodenow 的模组包格式:
3
+ // - 工程压缩包根目录携带 modconfigs.json(声明引用了哪些模组、哪些已启用)
4
+ // - 每个启用的模组以完整 sb3 形式内嵌于工程 zip 根(<模组名>-<id>.sb3)
5
+ // - 模组 targets 被展开为名为 `mods//<模组名>//<角色名>` 的普通角色参与编译,
6
+ // 但其绿旗/起动帽一律不执行(runtime._startupHatsRunOn)
7
+ // - 仍保持单 sb3 → 单 rs:模组展开发生在编译期,不产生额外源文件
8
+ //
9
+ // 替代旧版 rCompiler 的“引用/导出”系统(rcompiler_import / rcompiler_func / rcompiler_use 等)。
10
+
11
+ 'use strict';
12
+ const JSZip = require('jszip');
13
+
14
+ const MOD_SPRITE_PREFIX = 'mods//';
15
+
16
+ // modconfigs.json 结构:
17
+ // mods: [{ id, file, name?, version?, enabled?, blocks? }]
18
+ // enabled 缺省视为开启
19
+ async function loadMods(zipBuffer) {
20
+ const out = { mods: [], assetFiles: new Map() };
21
+ if (!zipBuffer) return out;
22
+ let zip;
23
+ try {
24
+ zip = new JSZip();
25
+ await zip.loadAsync(zipBuffer);
26
+ } catch (e) { return out; }
27
+ const cfgFile = zip.file('modconfigs.json');
28
+ if (!cfgFile) return out;
29
+ let cfg;
30
+ try { cfg = JSON.parse(await cfgFile.async('string')); } catch (e) {
31
+ console.warn('\x1b[33mmodconfigs.json 解析失败\x1b[m', e.message);
32
+ return out;
33
+ }
34
+ const list = Array.isArray(cfg.mods) ? cfg.mods : [];
35
+ for (const entry of list) {
36
+ if (!entry || entry.enabled === false || !entry.file) continue;
37
+ const pkg = zip.file(String(entry.file));
38
+ if (!pkg) { console.warn(`\x1b[33m模组包缺失\x1b[m: ${entry.file}`); continue; }
39
+ let modZip;
40
+ try {
41
+ modZip = new JSZip();
42
+ await modZip.loadAsync(await pkg.async('nodebuffer'));
43
+ } catch (e) { console.warn(`\x1b[33m模组包读取失败\x1b[m: ${entry.file} (${e.message})`); continue; }
44
+ const pjFile = modZip.file('project.json');
45
+ if (!pjFile) { console.warn(`\x1b[33m模组包缺少 project.json\x1b[m: ${entry.file}`); continue; }
46
+ let projectJson;
47
+ try { projectJson = JSON.parse(await pjFile.async('string')); } catch (e) { continue; }
48
+ if (!Array.isArray(projectJson.targets)) continue;
49
+ const name = String(entry.name || entry.id || entry.file);
50
+ out.mods.push({ id: entry.id || name, name, file: String(entry.file), projectJson });
51
+ // 收集模组资产(md5ext → bytes),供 assets.js 提取造型/声音
52
+ for (const t of projectJson.targets) {
53
+ for (const c of (t.costumes || [])) {
54
+ if (c.md5ext && !out.assetFiles.has(c.md5ext)) {
55
+ const f = modZip.file(c.md5ext);
56
+ if (f) out.assetFiles.set(c.md5ext, await f.async('nodebuffer'));
57
+ }
58
+ }
59
+ for (const s of (t.sounds || [])) {
60
+ if (s.md5ext && !out.assetFiles.has(s.md5ext)) {
61
+ const f = modZip.file(s.md5ext);
62
+ if (f) out.assetFiles.set(s.md5ext, await f.async('nodebuffer'));
63
+ }
64
+ }
65
+ }
66
+ }
67
+ return out;
68
+ }
69
+
70
+ // 模组角色名:mods//<模组名>//<角色名>(模组的舞台也变普通角色)
71
+ function modSpriteName(modName, targetName) {
72
+ return `${MOD_SPRITE_PREFIX}${modName}//${targetName || '角色'}`;
73
+ }
74
+
75
+ // 深拷贝并重写 id 前缀,防止与宿主工程的变量/列表/广播 id 冲突
76
+ // (对照 mods-expand.js 的 rcxm<N>- 前缀重写;这里只重写数据 id,
77
+ // 块 id 无需重写——编译器不跨 target 查找块)
78
+ function expandModTarget(target, modName, modIndex) {
79
+ const t = JSON.parse(JSON.stringify(target));
80
+ const pre = `m${modIndex}_`;
81
+ const idMap = new Map();
82
+ const mapId = (id) => {
83
+ if (typeof id !== 'string' || !id) return id;
84
+ if (!idMap.has(id)) idMap.set(id, pre + id);
85
+ return idMap.get(id);
86
+ };
87
+ const newVariables = {}, newLists = {}, newComments = {};
88
+ for (const k in (t.variables || {})) newVariables[mapId(k)] = t.variables[k];
89
+ for (const k in (t.lists || {})) newLists[mapId(k)] = t.lists[k];
90
+ for (const k in (t.comments || {})) newComments[mapId(k)] = t.comments[k];
91
+ t.variables = newVariables; t.lists = newLists; t.comments = newComments;
92
+ const visit = (v) => {
93
+ if (Array.isArray(v)) {
94
+ // [11|12|13, name, id] 原语数组
95
+ if (typeof v[0] === 'number' && (v[0] === 11 || v[0] === 12 || v[0] === 13) && v.length >= 3) {
96
+ return [v[0], v[1], mapId(String(v[2]))];
97
+ }
98
+ return v.map(visit);
99
+ }
100
+ if (v && typeof v === 'object') {
101
+ const r = {};
102
+ for (const k in v) r[k] = visit(v[k]);
103
+ return r;
104
+ }
105
+ return v;
106
+ };
107
+ for (const bid in (t.blocks || {})) {
108
+ const b = t.blocks[bid];
109
+ if (!b || typeof b !== 'object') continue;
110
+ // fields.VARIABLE / fields.LIST / fields.BROADCAST_OPTION = [name, id]
111
+ if (b.fields) {
112
+ for (const fk in b.fields) {
113
+ const f = b.fields[fk];
114
+ if (Array.isArray(f) && f.length === 2 && typeof f[1] === 'string' &&
115
+ ['VARIABLE', 'LIST', 'BROADCAST_OPTION'].includes(fk)) {
116
+ f[1] = mapId(f[1]);
117
+ }
118
+ }
119
+ }
120
+ if (b.inputs) visit(b.inputs);
121
+ }
122
+ t.name = modSpriteName(modName, t.name);
123
+ t.isRcModTarget = true; // 模组角色标记(对照 target.isRcModTarget)
124
+ if (t.isStage) { // 模组舞台降级为隐藏普通角色(mod-sprites.js)
125
+ t.isStage = false;
126
+ t.visible = false;
127
+ t.draggable = false;
128
+ }
129
+ return t;
130
+ }
131
+
132
+ // 读取模组并把启用的模组 targets 展开进 project.json(修改原对象)
133
+ // 返回 { mods, assetFiles } 供后续阶段(资产提取)使用
134
+ async function applyMods(projectJson, zipBuffer) {
135
+ const loaded = await loadMods(zipBuffer);
136
+ let mi = 0;
137
+ for (const mod of loaded.mods) {
138
+ for (const t of mod.projectJson.targets) {
139
+ (projectJson.targets = projectJson.targets || []).push(expandModTarget(t, mod.name, mi));
140
+ }
141
+ mi++;
142
+ }
143
+ return loaded;
144
+ }
145
+
146
+ module.exports = { loadMods, applyMods, modSpriteName, expandModTarget, MOD_SPRITE_PREFIX };