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/assets.js ADDED
@@ -0,0 +1,335 @@
1
+ // rCompiler V2 — 资产提取与常量生成
2
+ // 造型:png/jpg 直拷;svg 经 @resvg/resvg-js 渲染为 png(记录尺寸与旋转中心)
3
+ // 音频:wav 直拷;mp3/ogg/aif 等经 ffmpeg 转 16-bit PCM 22050Hz 单声道 WAV
4
+ // 产出:rmake/assets/*,并生成 include_bytes! 常量(CostumeInfo / RCOMPILER_SOUNDS)
5
+
6
+ 'use strict';
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const JSZip = require('jszip');
10
+
11
+ const PLACEHOLDER_PNG = Buffer.from(
12
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/x8AAwMB/6X0mQAAAABJRU5ErkJggg==', 'base64');
13
+
14
+ // 解析 SVG 的 viewBox / width / height(与 SkSVGDOM 的几何语义一致)。
15
+ // Scratch 编辑器导出的 SVG 恒有规范 viewBox;返回 {x,y,w,h},解析失败回退 0
16
+ function parseSvgMeta(svgText) {
17
+ const t = String(svgText);
18
+ const vb = t.match(/viewBox\s*=\s*["']([^"']+)["']/i);
19
+ if (vb) {
20
+ const p = vb[1].trim().split(/[\s,]+/).map(Number);
21
+ if (p.length === 4 && p.every(n => Number.isFinite(n))) {
22
+ return { x: p[0], y: p[1], w: p[2], h: p[3] };
23
+ }
24
+ }
25
+ const w = t.match(/\bwidth\s*=\s*["']\s*([\d.]+)/i);
26
+ const h = t.match(/\bheight\s*=\s*["']\s*([\d.]+)/i);
27
+ return { x: 0, y: 0, w: Number(w && w[1]) || 0, h: Number(h && h[1]) || 0 };
28
+ }
29
+
30
+ // 位图尺寸(编译期解析,供 WASM 清单/围栏/碰撞使用;native 仍可运行时解码)
31
+ function imageSize(buf) {
32
+ try {
33
+ if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504E47) {
34
+ return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
35
+ }
36
+ if (buf.length >= 4 && buf[0] === 0xFF && buf[1] === 0xD8) {
37
+ let i = 2;
38
+ while (i + 9 < buf.length) {
39
+ if (buf[i] !== 0xFF) { i++; continue; }
40
+ const m = buf[i + 1];
41
+ i += 2;
42
+ if (m === 0xD8 || m === 0xD9) continue;
43
+ const len = buf.readUInt16BE(i);
44
+ if ((m >= 0xC0 && m <= 0xC3) || (m >= 0xC5 && m <= 0xC7) ||
45
+ (m >= 0xC9 && m <= 0xCB) || (m >= 0xCD && m <= 0xCF)) {
46
+ return { w: buf.readUInt16BE(i + 5), h: buf.readUInt16BE(i + 3) };
47
+ }
48
+ i += len;
49
+ }
50
+ }
51
+ } catch (_) { /* 非法/未知图片:保持 0,由运行时处理 */ }
52
+ return { w: 0, h: 0 };
53
+ }
54
+
55
+ async function extractAssets(zipBuffer, outDir, profile, modFiles, encryptBuf) {
56
+ const result = { costumeFiles: new Map(), soundFiles: new Map() };
57
+ const writeAsset = (file, buf) => fs.writeFileSync(file, encryptBuf ? encryptBuf(buf) : buf);
58
+ let zip = null;
59
+ if (zipBuffer) {
60
+ try {
61
+ zip = new JSZip();
62
+ await zip.loadAsync(zipBuffer);
63
+ } catch (e) { zip = null; }
64
+ }
65
+ try {
66
+ const assetsDir = path.join(outDir, 'assets');
67
+ if (!fs.existsSync(assetsDir)) fs.mkdirSync(assetsDir, { recursive: true });
68
+
69
+ // 资产查找:主工程 zip → 模组包(mods.js 收集的 md5ext → bytes)
70
+ const lookup = async (file) => {
71
+ if (zip) {
72
+ const f = zip.file(file);
73
+ if (f) return f;
74
+ }
75
+ if (modFiles && modFiles.has(file)) return { buffer: modFiles.get(file) };
76
+ return null;
77
+ };
78
+
79
+ for (const c of profile.assets.costumes) {
80
+ const f = await lookup(c.file);
81
+ if (!f) {
82
+ // 压缩包缺少该资产:仍注册占位图,保持造型序号与名称对应
83
+ const outFile = `costume_${c.target}_${c.index}.png`;
84
+ writeAsset(path.join(assetsDir, outFile), PLACEHOLDER_PNG);
85
+ result.costumeFiles.set(`${c.target}:${c.index}`, {
86
+ file: outFile, name: c.name, svg: false, w: 0, h: 0,
87
+ rcx: c.rotationCenterX, rcy: c.rotationCenterY,
88
+ vbx: 0, vby: 0, bmr: c.bitmapResolution || 1, target: c.target
89
+ });
90
+ continue;
91
+ }
92
+ const buf = f.buffer ? f.buffer : await f.async('nodebuffer');
93
+ if (c.bitmap) {
94
+ // 位图:字节直拷,w/h=0 交由 Rust 端解码填充(除以 bitmapResolution)
95
+ const outFile = `costume_${c.target}_${c.index}.png`;
96
+ writeAsset(path.join(assetsDir, outFile), buf);
97
+ const dim = imageSize(buf);
98
+ const bmr = c.bitmapResolution || 1;
99
+ result.costumeFiles.set(`${c.target}:${c.index}`, {
100
+ // w/h 以舞台单位保存(原生 Skin 直接使用);清单再乘回 bmr 给 scratch-render
101
+ file: outFile, name: c.name, svg: false,
102
+ w: dim.w ? dim.w / bmr : 0, h: dim.h ? dim.h / bmr : 0,
103
+ rcx: c.rotationCenterX, rcy: c.rotationCenterY,
104
+ vbx: 0, vby: 0, bmr, target: c.target
105
+ });
106
+ } else {
107
+ // SVG:字节直嵌,运行时由 SkSVGDOM 矢量渲染
108
+ // (对照 scratch-render SVGSkin:size=viewBox 宽高,旋转中心补偿 viewBox 偏移)
109
+ const outFile = `costume_${c.target}_${c.index}.svg`;
110
+ writeAsset(path.join(assetsDir, outFile), buf);
111
+ const meta = parseSvgMeta(buf.toString('utf-8'));
112
+ result.costumeFiles.set(`${c.target}:${c.index}`, {
113
+ file: outFile, name: c.name, svg: true,
114
+ w: meta.w, h: meta.h, rcx: c.rotationCenterX, rcy: c.rotationCenterY,
115
+ vbx: meta.x, vby: meta.y, bmr: 1, target: c.target
116
+ });
117
+ }
118
+ }
119
+
120
+ for (const s of profile.assets.sounds) {
121
+ const f = await lookup(s.file);
122
+ if (!f) continue;
123
+ const buf = f.buffer ? f.buffer : await f.async('nodebuffer');
124
+ let outFile;
125
+ if (s.dataFormat === 'wav') {
126
+ outFile = `sound_${s.target}_${s.index}.wav`;
127
+ writeAsset(path.join(assetsDir, outFile), buf);
128
+ } else {
129
+ // ffmpeg 转码为 22050Hz 单声道 16-bit PCM WAV
130
+ outFile = `sound_${s.target}_${s.index}.wav`;
131
+ const tmpIn = path.join(assetsDir, `_tmp_${s.target}_${s.index}.${s.dataFormat || 'bin'}`);
132
+ fs.writeFileSync(tmpIn, buf);
133
+ const ok = await new Promise((resolve) => {
134
+ const { spawn } = require('child_process');
135
+ const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-i', tmpIn, '-ar', '22050', '-ac', '1', '-sample_fmt', 's16', path.join(assetsDir, outFile)]);
136
+ ff.on('close', (code) => resolve(code === 0));
137
+ ff.on('error', () => resolve(false));
138
+ });
139
+ fs.rmSync(tmpIn, { force: true });
140
+ if (!ok) {
141
+ console.warn(`\x1b[33m音频转码失败(${s.name}, ${s.dataFormat}):需要 ffmpeg\x1b[m`);
142
+ continue;
143
+ }
144
+ if (encryptBuf) {
145
+ const p = path.join(assetsDir, outFile);
146
+ writeAsset(p, fs.readFileSync(p));
147
+ }
148
+ }
149
+ result.soundFiles.set(`${s.target}:${s.index}`, { file: outFile, name: s.name });
150
+ }
151
+ } catch (e) {
152
+ console.warn('\x1b[33m资产提取失败\x1b[m', e.message);
153
+ }
154
+ return result;
155
+ }
156
+
157
+ // Rust f64 字面量:整数补 .0,小数原样(避免 "30.749.0" 这类非法字面量)
158
+ function f64lit(n) {
159
+ const x = Number(n) || 0;
160
+ return Number.isInteger(x) ? x.toFixed(1) : String(x);
161
+ }
162
+
163
+ // 将 PNG 原样塞进 ICO 目录(Windows Vista+ 支持 PNG 负载)。
164
+ // 仅接受 ≤256px 的 PNG;更大的图不生成 EXE 图标(运行时窗口图标仍照常)。
165
+ function pngToIco(png) {
166
+ if (png.length < 24 || png.readUInt32BE(0) !== 0x89504E47) return null;
167
+ const w = png.readUInt32BE(16);
168
+ const h = png.readUInt32BE(20);
169
+ if (w < 1 || h < 1 || w > 256 || h > 256) return null;
170
+ const dir = Buffer.alloc(22);
171
+ dir.writeUInt16LE(0, 0); // reserved
172
+ dir.writeUInt16LE(1, 2); // type: icon
173
+ dir.writeUInt16LE(1, 4); // count
174
+ dir[6] = w >= 256 ? 0 : w;
175
+ dir[7] = h >= 256 ? 0 : h;
176
+ dir[8] = 0; // color count
177
+ dir[9] = 0; // reserved
178
+ dir.writeUInt16LE(1, 10); // planes
179
+ dir.writeUInt16LE(32, 12); // bit count
180
+ dir.writeUInt32LE(png.length, 14); // bytes in resource
181
+ dir.writeUInt32LE(22, 18); // image offset
182
+ return Buffer.concat([dir, png]);
183
+ }
184
+
185
+ // 应用图标:面板存储 dataURL;写 app_icon.png(混淆时加密)+ Windows EXE 用 app_icon.ico
186
+ function writeAppIcon(profile, outDir, encryptBuf) {
187
+ if (!profile.hasStage || !profile.app || !profile.app.icon) return null;
188
+ const raw = String(profile.app.icon);
189
+ let png = null;
190
+ const m = /^data:image\/png;base64,([A-Za-z0-9+/=\s]+)$/i.exec(raw);
191
+ if (m) png = Buffer.from(m[1], 'base64');
192
+ else if (!/^data:/.test(raw) && fs.existsSync(raw)) png = fs.readFileSync(raw);
193
+ if (!png || png.length < 24 || png.readUInt32BE(0) !== 0x89504E47) {
194
+ console.warn('\x1b[33m应用图标解析失败:仅支持 PNG\x1b[m');
195
+ return null;
196
+ }
197
+ const dir = path.join(outDir, 'assets');
198
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
199
+ const file = path.join(dir, 'app_icon.png');
200
+ fs.writeFileSync(file, encryptBuf ? encryptBuf(png) : png);
201
+ const ico = pngToIco(png);
202
+ if (ico) fs.writeFileSync(path.join(dir, 'app_icon.ico'), ico);
203
+ else console.warn('\x1b[33m应用图标超过 256x256,已跳过 Windows EXE 图标(运行时窗口图标不受影响)\x1b[m');
204
+ return { ico: !!ico };
205
+ }
206
+
207
+ async function buildAssetConsts(profile, emit, opts) {
208
+ const outDir = (opts && opts.outDir) || process.cwd();
209
+ const encryptBuf = (opts && opts.encryptBuf) || null;
210
+ const web = profile.backend === 'web';
211
+ const strBytes = (opts && opts.strBytes)
212
+ || ((s) => `[${[...Buffer.from(String(s == null ? '' : s), 'utf8')].join(',')}]`);
213
+ const extracted = opts && opts.zipBuffer
214
+ ? await extractAssets(opts.zipBuffer, outDir, profile, opts.modFiles, encryptBuf)
215
+ : { costumeFiles: new Map(), soundFiles: new Map() };
216
+ // 应用图标(独立于 zip 资产;代码生成模式也要写盘)
217
+ // WASM 没有 Windows EXE 图标;网页图标由 index.html/favicon 处理
218
+ const icon = (profile.hasStage && !web) ? writeAppIcon(profile, outDir, encryptBuf) : null;
219
+ if (icon && icon.ico) emit.hasIcon = true;
220
+
221
+ if (profile.hasStage && !web) {
222
+ // skia-safe 启用 svg 模块(SkSVGDOM 真矢量渲染)。
223
+ // 预编译包按 feature 组合分发,各平台可用组合不同(缺组合将触发耗时源码编译):
224
+ // linux: gl+x11+svg → gl-svg-textlayout-x11 ✓
225
+ // macos/windows: gl+svg → gl-svg-textlayout ✓
226
+ emit.targetDep('target_os = "linux"', 'skia-safe = { version = "0.75", features = ["svg", "gl", "x11"] }');
227
+ emit.targetDep('target_os = "macos"', 'skia-safe = { version = "0.75", features = ["svg", "gl"] }');
228
+ emit.targetDep('target_os = "windows"', 'skia-safe = { version = "0.75", features = ["svg", "gl"] }');
229
+ emit.dep('winit = "0.29"');
230
+ emit.dep('softbuffer = "0.4"');
231
+ emit.dep('image = { version = "0.25", default-features = false, features = ["png"] }');
232
+ }
233
+ if (profile.hasSound && !web) {
234
+ emit.dep('rodio = { version = "0.17", default-features = false, features = ["wav"] }');
235
+ }
236
+
237
+ profile.costumeMeta = [];
238
+ profile.soundMeta = [];
239
+
240
+ if (profile.hasStage) {
241
+ const lines = ['// ---- 舞台造型常量 ----'];
242
+ const items = [];
243
+ for (const c of profile.assets.costumes) {
244
+ const info = extracted.costumeFiles.get(`${c.target}:${c.index}`);
245
+ if (!info) continue;
246
+ // Web:资产由 JS 宿主按 manifest 加载,wasm 只保留几何元数据,避免重复打包
247
+ lines.push(web
248
+ ? `const COSTUME_BYTES_${c.target}_${c.index}: &[u8] = &[];`
249
+ : `const COSTUME_BYTES_${c.target}_${c.index}: &[u8] = include_bytes!("../assets/${info.file}");`);
250
+ items.push(`CostumeInfo{ name: &${strBytes(info.name)}, bytes: COSTUME_BYTES_${c.target}_${c.index}, svg: ${info.svg ? 'true' : 'false'}, rcx: ${f64lit(info.rcx)}, rcy: ${f64lit(info.rcy)}, vbx: ${f64lit(info.vbx || 0)}, vby: ${f64lit(info.vby || 0)}, target: ${c.target}, w: ${f64lit(info.w)}, h: ${f64lit(info.h)}, bmr: ${f64lit(info.bmr || 1)} }`);
251
+ profile.costumeMeta.push(info);
252
+ }
253
+ items.push(web
254
+ ? `CostumeInfo{ name: &${strBytes('__white__')}, bytes: &[], svg: false, rcx: 0.0, rcy: 0.0, vbx: 0.0, vby: 0.0, target: -1, w: 480.0, h: 360.0, bmr: 1.0 }`
255
+ : `CostumeInfo{ name: &${strBytes('__white__')}, bytes: include_bytes!("../assets/placeholder.png"), svg: false, rcx: 0.0, rcy: 0.0, vbx: 0.0, vby: 0.0, target: -1, w: 480.0, h: 360.0, bmr: 1.0 }`);
256
+ // 占位图(白色 480x360 由 assets 目录预置)
257
+ const phDir = path.join(outDir, 'assets');
258
+ if (!fs.existsSync(phDir)) fs.mkdirSync(phDir, { recursive: true });
259
+ const phPng = path.join(phDir, 'placeholder.png');
260
+ // 每次生成都重写:混淆/正常模式共用一个输出目录时必须刷新编码方式
261
+ fs.writeFileSync(phPng, encryptBuf ? encryptBuf(PLACEHOLDER_PNG) : PLACEHOLDER_PNG);
262
+ lines.push(`pub const RCOMPILER_COSTUMES: &[CostumeInfo] = &[${items.join(',')}];`);
263
+ lines.push(`pub const RCOMPILER_TARGET_COUNT: usize = ${profile.targets.length};`);
264
+ lines.push(icon
265
+ ? `pub const RCOMPILER_ICON_PNG: Option<&'static [u8]> = Some(include_bytes!("../assets/app_icon.png"));`
266
+ : `pub const RCOMPILER_ICON_PNG: Option<&'static [u8]> = None;`);
267
+ emit.extra(lines.join('\n'));
268
+
269
+ if (web) {
270
+ // JS 宿主清单:scratch-render 需要原始 SVG/PNG/声音文件与 skin 元数据
271
+ const manifest = {
272
+ version: 1,
273
+ name: String((profile.app && profile.app.title) || (opts && opts.projectName) || 'rCompiler'),
274
+ stage: { width: profile.stageSize.width, height: profile.stageSize.height },
275
+ frame: profile.frame,
276
+ app: Object.assign({}, profile.app || {}, { icon: null }),
277
+ targets: profile.targets.map(t => ({
278
+ index: t.index, name: t.name, isStage: t.isStage,
279
+ x: t.x, y: t.y, direction: t.direction, size: t.size,
280
+ visible: t.visible, currentCostume: t.currentCostume
281
+ })),
282
+ costumes: [],
283
+ sounds: [],
284
+ monitors: (profile.monitorsActive || profile.monitors || []).map((m, i) => ({
285
+ index: i, opcode: m.opcode, mode: m.mode,
286
+ x: m.x, y: m.y, width: m.width, height: m.height,
287
+ sliderMin: m.sliderMin, sliderMax: m.sliderMax,
288
+ params: m.params
289
+ }))
290
+ };
291
+ for (const c of profile.assets.costumes) {
292
+ const info = extracted.costumeFiles.get(`${c.target}:${c.index}`);
293
+ if (!info) continue;
294
+ manifest.costumes.push({
295
+ globalIndex: manifest.costumes.length,
296
+ target: c.target, index: c.index, name: info.name,
297
+ file: '../assets/' + info.file, svg: !!info.svg,
298
+ // scratch-render 的位图 skin 使用原始像素尺寸/旋转中心,分辨率单独传
299
+ w: info.svg ? (info.w || 0) : ((info.w || 0) * (info.bmr || 1)),
300
+ h: info.svg ? (info.h || 0) : ((info.h || 0) * (info.bmr || 1)),
301
+ rcx: info.rcx || 0, rcy: info.rcy || 0,
302
+ vbx: info.vbx || 0, vby: info.vby || 0,
303
+ bmr: info.bmr || 1
304
+ });
305
+ }
306
+ for (const s of profile.assets.sounds) {
307
+ const info = extracted.soundFiles.get(`${s.target}:${s.index}`);
308
+ if (!info) continue;
309
+ manifest.sounds.push({
310
+ target: s.target, index: s.index, name: info.name,
311
+ file: '../assets/' + info.file
312
+ });
313
+ }
314
+ fs.writeFileSync(path.join(outDir, 'assets', 'rcompiler_manifest.json'), JSON.stringify(manifest, null, 2));
315
+ }
316
+ }
317
+
318
+ if (profile.hasSound) {
319
+ const lines = ['// ---- 声音常量 ----'];
320
+ const items = [];
321
+ for (const s of profile.assets.sounds) {
322
+ const info = extracted.soundFiles.get(`${s.target}:${s.index}`);
323
+ if (!info) continue;
324
+ lines.push(web
325
+ ? `const SOUND_BYTES_${s.target}_${s.index}: &[u8] = &[];`
326
+ : `const SOUND_BYTES_${s.target}_${s.index}: &[u8] = include_bytes!("../assets/${info.file}");`);
327
+ items.push(`(&${strBytes(info.name)}, SOUND_BYTES_${s.target}_${s.index})`);
328
+ profile.soundMeta.push(info);
329
+ }
330
+ lines.push(`pub const RCOMPILER_SOUNDS: &[(&[u8], &[u8])] = &[${items.join(',')}];`);
331
+ emit.extra(lines.join('\n'));
332
+ }
333
+ }
334
+
335
+ module.exports = { extractAssets, buildAssetConsts };