rcompiler 2.1.0 → 2.2.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/CHANGELOG.md +11 -0
- package/README.md +15 -2
- package/docs/CONFIG.md +1 -1
- package/docs/NATIVE.md +110 -0
- package/exts/args.js +142 -0
- package/exts/fs.js +317 -0
- package/exts/io.js +396 -0
- package/exts/path.js +208 -0
- package/exts/process.js +416 -0
- package/package.json +1 -1
- package/src/analysis.js +8 -0
- package/src/assets.js +2 -2
- package/src/cli.js +2 -0
- package/src/emit.js +3 -3
- package/src/preludes.js +845 -122
- package/src/rcompiler.js +328 -60
- package/src/standard.js +176 -76
- package/src/web.js +0 -10
- /package/exts/{rcrcHelper.js → rcompilerExt.js} +0 -0
package/src/standard.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
const pkg = require('../package.json');
|
|
8
8
|
|
|
9
9
|
function registerStandard(ctx) {
|
|
10
|
-
const { S, T, C, Tools, emit, getvar, getlist, kwParse, compile_chain, registerScript, multi, isStageMode, frameWaitStmt, spawnScript, runtimeNumStr } = ctx;
|
|
10
|
+
const { S, T, C, Tools, emit, getvar, getlist, kwParse, compile_chain, registerScript, multi, isStageMode, frameWaitStmt, spawnScript, runtimeNumStr, stageIdxExpr } = ctx;
|
|
11
11
|
const compiles = S.compiles;
|
|
12
12
|
const inputs = S.inputscompiles;
|
|
13
13
|
|
|
@@ -49,6 +49,12 @@ function registerStandard(ctx) {
|
|
|
49
49
|
RT([
|
|
50
50
|
'fn rcompiler_js_number(s: &str) -> Option<f64> {',
|
|
51
51
|
'let t = s.trim();',
|
|
52
|
+
// 布尔字面量按 Scratch 变量语义数值化:真实 VM 把布尔报告器原值(JS boolean)存入
|
|
53
|
+
// 变量,随后 `变量 = 1` 经 Cast.toNumber(true)=1 成立;我们以 "true"/"false" 字符串
|
|
54
|
+
// 承载该状态,这里统一映射,保证 `set flag to <…=…>` 后 `flag = 1` 的比较成立。
|
|
55
|
+
// (偏差:字面量字符串 "true" 参与算术也会得到 1——真实 VM 为 NaN→0;极罕见)
|
|
56
|
+
'if t.eq_ignore_ascii_case("true") { return Some(1.0); }',
|
|
57
|
+
'if t.eq_ignore_ascii_case("false") { return Some(0.0); }',
|
|
52
58
|
'if t.is_empty() { return None; }',
|
|
53
59
|
'let (sign, body) = match t.strip_prefix(\'-\') { Some(b) => (-1.0f64, b), None => (1.0f64, t.strip_prefix(\'+\').unwrap_or(t)) };',
|
|
54
60
|
// 快路径:纯十进制(数字/./e/E)免分配直 parse——模拟器热路径的字符串全是
|
|
@@ -160,6 +166,27 @@ function registerStandard(ctx) {
|
|
|
160
166
|
if (ctx.inWarp && ctx.inWarp()) return '';
|
|
161
167
|
return multi() ? 'rcompiler_loop_yield().await;\n' : 'rcompiler_loop_yield();\n';
|
|
162
168
|
};
|
|
169
|
+
// 死循环哨兵(诊断;生成期 RCOMPILER_GEN_SPINGUARD=1 时启用):
|
|
170
|
+
// warp 循环无 await——真死循环会 100% CPU 且无法从外部探针观察。启用后每个
|
|
171
|
+
// 循环带计数上限(RCOMPILER_SPIN_LIMIT,默认 5e8 次迭代),超限打印位置并
|
|
172
|
+
// 以退出码 70 结束,把"哪个循环在转"直接暴露出来。
|
|
173
|
+
const SPIN_ON = process.env.RCOMPILER_GEN_SPINGUARD === '1';
|
|
174
|
+
const SPIN_LIMIT = Number(process.env.RCOMPILER_SPIN_LIMIT || 500000000);
|
|
175
|
+
const spinPre = (tag) => {
|
|
176
|
+
if (!SPIN_ON) return '';
|
|
177
|
+
ctx.sping = (ctx.sping || 0) + 1;
|
|
178
|
+
return `let mut __spg${ctx.sping} = 0u64;\n`;
|
|
179
|
+
};
|
|
180
|
+
const spinCheck = (tag) => {
|
|
181
|
+
if (!SPIN_ON) return '';
|
|
182
|
+
const n = ctx.sping;
|
|
183
|
+
return `__spg${n} += 1; if __spg${n} > ${SPIN_LIMIT} { eprintln!("rcompiler spin guard: loop#${n} ${tag}"); self.rcompiler_spin_report(); std::process::exit(70); }\n`;
|
|
184
|
+
};
|
|
185
|
+
const spinTag = (kind) => {
|
|
186
|
+
const cp = S.customproc;
|
|
187
|
+
const procName = cp ? (cp.proccode || cp.defName || cp.name || JSON.stringify(Object.keys(cp)).slice(0, 40)) : 'hat';
|
|
188
|
+
return `${kind} ti=${S.targetID} proc=${procName}`;
|
|
189
|
+
};
|
|
163
190
|
RT([
|
|
164
191
|
'fn scratch_mod(a: f64, b: f64) -> f64 {',
|
|
165
192
|
'if b == 0.0 { return 0.0; }',
|
|
@@ -301,7 +328,9 @@ function registerStandard(ctx) {
|
|
|
301
328
|
inputs['operator_and'] = (a) => new T.Bool(`(${C.SafeBool(a.OPERAND1)} && ${C.SafeBool(a.OPERAND2)})`);
|
|
302
329
|
inputs['operator_or'] = (a) => new T.Bool(`(${C.SafeBool(a.OPERAND1)} || ${C.SafeBool(a.OPERAND2)})`);
|
|
303
330
|
inputs['operator_not'] = (a) => new T.Bool(`(!(${C.SafeBool(a.OPERAND)}))`);
|
|
304
|
-
|
|
331
|
+
// format! 对 &str/&String/String 一律成立;旧模板 expr.to_owned() 在操作数已是
|
|
332
|
+
// &String(列表项读取)时会得到 &String+&String,Rust 无该 Add 实现
|
|
333
|
+
inputs['operator_join'] = (a) => new T.Stri(`format!("{}{}",${stuOf(a.STRING1)},${stuOf(a.STRING2)})`);
|
|
305
334
|
inputs['operator_letter_of'] = (a) => new T.Stri(`get_char_at(${stuOf(a.STRING)},${numOf(a.LETTER)})`);
|
|
306
335
|
inputs['operator_length'] = (a) => new T.Num(`((${stuOf(a.STRING)}).chars().count() as f64)`);
|
|
307
336
|
inputs['operator_contains'] = (a) => new T.Bool(`scratch_contains(&${stuOf(a.STRING1)},&${stuOf(a.STRING2)})`);
|
|
@@ -318,6 +347,10 @@ function registerStandard(ctx) {
|
|
|
318
347
|
case 'sin': return new T.Num(`(((${x}).to_radians()).sin())`);
|
|
319
348
|
case 'cos': return new T.Num(`(((${x}).to_radians()).cos())`);
|
|
320
349
|
case 'tan': return new T.Num(`(((${x}).to_radians()).tan())`);
|
|
350
|
+
// 反三角返回角度制;越界 |x|>1 时 f64::asin/acos 返回 NaN,与 JS Math.asin/acos 一致
|
|
351
|
+
case 'atan': return new T.Num(`((${x}).atan().to_degrees())`);
|
|
352
|
+
case 'asin': return new T.Num(`((${x}).asin().to_degrees())`);
|
|
353
|
+
case 'acos': return new T.Num(`((${x}).acos().to_degrees())`);
|
|
321
354
|
case 'ln': return new T.Num(`if (${x}) > 0.0 { (${x}).ln() } else { 0.0 }`);
|
|
322
355
|
case 'log': return new T.Num(`if (${x}) > 0.0 { (${x}).log10() } else { 0.0 }`);
|
|
323
356
|
case 'e ^': return new T.Num(`((${x}).exp())`);
|
|
@@ -369,6 +402,9 @@ function registerStandard(ctx) {
|
|
|
369
402
|
};
|
|
370
403
|
compiles['data_showvariable'] = (a) => `// showvariable ${a.scope.block.fields.VARIABLE[0]}\n`;
|
|
371
404
|
compiles['data_hidevariable'] = (a) => `// hidevariable ${a.scope.block.fields.VARIABLE[0]}\n`;
|
|
405
|
+
// 列表监视器显隐:与变量监视器同策略(静态监视器表不含运行时显隐,留注释追踪)
|
|
406
|
+
compiles['data_showlist'] = (a) => `// showlist ${a.scope.block.fields.LIST[0]}\n`;
|
|
407
|
+
compiles['data_hidelist'] = (a) => `// hidelist ${a.scope.block.fields.LIST[0]}\n`;
|
|
372
408
|
|
|
373
409
|
// ================= 数据:列表 =================
|
|
374
410
|
// 列表元素类型:declared==='f64' → Vec<f64>(固定类型优化:零字符串转换);
|
|
@@ -501,19 +537,21 @@ function registerStandard(ctx) {
|
|
|
501
537
|
};
|
|
502
538
|
compiles['event_whenbroadcastreceived'] = async (a) => {
|
|
503
539
|
const bname = a.scope.block.fields.BROADCAST_OPTION[0];
|
|
504
|
-
|
|
505
|
-
|
|
540
|
+
// 函数名与注册已在 phase 3a 预分配(帽编译序无关化,保证 event_broadcast 总能查到
|
|
541
|
+
// 接收者——帽的 sb3 遍历序可能晚于发送方编译序);此处仅编译帽体并发射函数
|
|
542
|
+
const fname = S.broadcastFnByBlock.get(a.scope.block) || (S.bccount++, S.fnName('bc_' + S.bccount));
|
|
506
543
|
const body = await compile_chain(a.scope.block.next, a.scope.target);
|
|
507
544
|
registerScript(fname, body, 'broadcast', { broadcast: String(bname) });
|
|
508
|
-
if (!S.broadcastScripts.has(String(bname)))
|
|
509
|
-
|
|
510
|
-
|
|
545
|
+
if (!S.broadcastScripts.has(String(bname))) {
|
|
546
|
+
S.broadcastScripts.set(String(bname), [fname]);
|
|
547
|
+
S.broadcastFnTi.set(fname, S.targetID);
|
|
548
|
+
}
|
|
511
549
|
return '';
|
|
512
550
|
};
|
|
513
|
-
const spawnTracked = (ti, inner) => `{ let __s = self.clone(); let __h = tokio::spawn(${spawnScript(`
|
|
551
|
+
const spawnTracked = (ti, inner) => `{ let __s = self.clone(); let __h = tokio::spawn(${spawnScript(`__s.${inner}`)}); rcompiler_track_task(${ti}, &__h); }`;
|
|
514
552
|
// 广播分发:原型实例 + 全部存活克隆实例(对照 startHats 遍历全部 targets/clones)
|
|
515
553
|
const spawnClonesOf = (ti, f) => isStageMode()
|
|
516
|
-
? `for __ci in self.stage.clone_indices(${ti}) { if let Some(__cs) = rcompiler_clone_get(__ci) { let __h = tokio::spawn(${spawnScript(`
|
|
554
|
+
? `for __ci in self.stage.clone_indices(${ti}) { if let Some(__cs) = rcompiler_clone_get(__ci) { let __h = tokio::spawn(${spawnScript(`__cs.${f}().await;`)}); rcompiler_track_task(${ti}, &__h); } }\n`
|
|
517
555
|
: '';
|
|
518
556
|
compiles['event_broadcast'] = (a) => {
|
|
519
557
|
if (!multi()) return '';
|
|
@@ -528,12 +566,12 @@ function registerStandard(ctx) {
|
|
|
528
566
|
const list = S.broadcastScripts.get(bname);
|
|
529
567
|
if (!list) return '';
|
|
530
568
|
let out = `let mut __bhs: Vec<tokio::task::JoinHandle<()>> = vec![`;
|
|
531
|
-
out += list.map(f => `{ let __s = self.clone(); let __h = tokio::spawn(${spawnScript(`
|
|
569
|
+
out += list.map(f => `{ let __s = self.clone(); let __h = tokio::spawn(${spawnScript(`__s.${f}().await;`)}); rcompiler_track_task(${S.broadcastFnTi.get(f) ?? 0}, &__h); __h }`).join(', ');
|
|
532
570
|
out += '];\n';
|
|
533
571
|
if (isStageMode()) {
|
|
534
572
|
for (const f of list) {
|
|
535
573
|
const ti = S.broadcastFnTi.get(f) ?? 0;
|
|
536
|
-
out += `for __ci in self.stage.clone_indices(${ti}) { if let Some(__cs) = rcompiler_clone_get(__ci) { __bhs.push(tokio::spawn(${spawnScript(`
|
|
574
|
+
out += `for __ci in self.stage.clone_indices(${ti}) { if let Some(__cs) = rcompiler_clone_get(__ci) { __bhs.push(tokio::spawn(${spawnScript(`__cs.${f}().await;`)})); } }\n`;
|
|
537
575
|
}
|
|
538
576
|
}
|
|
539
577
|
out += 'for __h in __bhs { let _ = __h.await; }\n';
|
|
@@ -654,7 +692,7 @@ function registerStandard(ctx) {
|
|
|
654
692
|
const n = S.repeatcount;
|
|
655
693
|
return `{\nlet __rn${n} = (${a.TIMES.Usize()});\nfor __rep${n} in 0..__rn${n} {\n${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n}\n`;
|
|
656
694
|
};
|
|
657
|
-
compiles['control_forever'] = (a) =>
|
|
695
|
+
compiles['control_forever'] = (a) => { const t = 'forever'; return `${spinPre(t)}loop {\n${spinCheck(t)}${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n`; };
|
|
658
696
|
// if/if_else:条件先求值到局部——条件中的列表锁(MutexGuard 临时值)会存活
|
|
659
697
|
// 到整个 if 语句结束(Rust 临时值规则),体内再次锁同一列表会同线程死锁
|
|
660
698
|
compiles['control_if'] = (a) => {
|
|
@@ -681,8 +719,8 @@ function registerStandard(ctx) {
|
|
|
681
719
|
};
|
|
682
720
|
// repeat_until/while/wait_until:条件每轮先求值到局部再判断——
|
|
683
721
|
// 条件中的列表锁(MutexGuard 临时值)在循环体 await 前释放(future Send 要求)
|
|
684
|
-
compiles['control_repeat_until'] = (a) =>
|
|
685
|
-
compiles['control_while'] = (a) => `loop {\
|
|
722
|
+
compiles['control_repeat_until'] = (a) => { const t = spinTag('until'); return `${spinPre(t)}loop {\n${spinCheck(t)}let __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\n${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n`; };
|
|
723
|
+
compiles['control_while'] = (a) => { const t = `while@#${(ctx.sping || 0) + 1}`; return `${spinPre(t)}loop {\n${spinCheck(t)}let __cu = (${C.SafeBool(a.CONDITION)});\nif !__cu { break; }\n${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n`; };
|
|
686
724
|
compiles['control_all_at_once'] = (a) => C.Safe(a.SUBSTACK);
|
|
687
725
|
compiles['control_for_each'] = (a) => {
|
|
688
726
|
ctx.markWrite();
|
|
@@ -755,22 +793,28 @@ function registerStandard(ctx) {
|
|
|
755
793
|
}
|
|
756
794
|
const fns = S.clonesByTarget.get(ti) || [];
|
|
757
795
|
emit.needsCloneDefault = true;
|
|
796
|
+
// 克隆父索引:上下文感知(普通脚本=编译期 ti;克隆=self.sprite_index;
|
|
797
|
+
// 广播=rcompiler_self_idx(ti))。恒用 self.sprite_index 会让原型实例
|
|
798
|
+
// (sprite_index=usize::MAX)落到 add_sprite_clone 的"最后一角色"错父——
|
|
799
|
+
// 克隆继承错造型/位置(Scratch 3 Emulator 的主题检测克隆即因此判 light)
|
|
800
|
+
const parentExpr = stageIdxExpr ? stageIdxExpr() : String(S.targetID);
|
|
758
801
|
let out = '';
|
|
759
802
|
for (const f of fns) {
|
|
760
803
|
// 克隆上限 300(对照 clonesAvailable;需舞台模块的克隆注册表);
|
|
761
804
|
// 克隆任务登记供 stop all 终止
|
|
762
805
|
out += isStageMode() ? `if self.stage.can_clone() {\n` : '{\n';
|
|
763
806
|
out += `let mut __c = self.clone_default();\n`;
|
|
764
|
-
if (isStageMode()) out += `__c.rcompiler_clone_init(
|
|
765
|
-
out += `let __c = std::sync::Arc::new(__c); let __s = __c.clone(); let __h = tokio::spawn(${spawnScript(`
|
|
807
|
+
if (isStageMode()) out += `__c.rcompiler_clone_init(${parentExpr});\n`;
|
|
808
|
+
out += `let __c = std::sync::Arc::new(__c); let __s = __c.clone(); let __h = tokio::spawn(${spawnScript(`__s.${f}().await;`)}); rcompiler_track_task(${ti}, &__h); }\n`;
|
|
766
809
|
}
|
|
767
810
|
return out;
|
|
768
811
|
};
|
|
769
812
|
// 删除克隆(对照 control_delete_this_clone → disposeTarget)
|
|
770
|
-
//
|
|
813
|
+
// 裸调用经 injectStageIdx 按上下文补 idx(普通脚本=角色 idx;克隆=self.sprite_index;
|
|
814
|
+
// 广播=rcompiler_self_idx)。运行时对原型实例安全无操作(is_clone 守卫)
|
|
771
815
|
compiles['control_delete_this_clone'] = (a) =>
|
|
772
816
|
(isStageMode() && multi())
|
|
773
|
-
? `self.s_delete_clone(
|
|
817
|
+
? `self.s_delete_clone();\nreturn;\n`
|
|
774
818
|
: 'return;\n';
|
|
775
819
|
|
|
776
820
|
// ================= 侦测 =================
|
|
@@ -814,7 +858,8 @@ function registerStandard(ctx) {
|
|
|
814
858
|
return new T.Num('sensing_dayssince2000()');
|
|
815
859
|
};
|
|
816
860
|
inputs['sensing_current'] = (a) => {
|
|
817
|
-
|
|
861
|
+
// sb3 存储的菜单值恒为大写(YEAR/MONTH/…/DAYOFWEEK);统一小写化后查表
|
|
862
|
+
const menu = String(a.scope.block.fields.CURRENTMENU[0]).toLowerCase();
|
|
818
863
|
if (web) {
|
|
819
864
|
RT([
|
|
820
865
|
'fn rcompiler_current(menu: &str) -> f64 {',
|
|
@@ -833,9 +878,13 @@ function registerStandard(ctx) {
|
|
|
833
878
|
return new T.Num(`rcompiler_current(${sl(menu)})`);
|
|
834
879
|
}
|
|
835
880
|
DEP('chrono = "0.4"'); USE('use chrono::Local;');
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
881
|
+
// year/month/day 属 Datelike,hour/minute/second 属 Timelike;
|
|
882
|
+
// 星期天数经 weekday().num_days_from_sunday()(Weekday 方法,Datelike 无此方法)
|
|
883
|
+
USE('use chrono::{Datelike, Timelike};');
|
|
884
|
+
// 值为完整字段/方法链表达式(不含外层括号)
|
|
885
|
+
const f = { 'year': 'year()', 'month': 'month()', 'date': 'day()', 'dayofweek': 'weekday().num_days_from_sunday()', 'hour': 'hour()', 'minute': 'minute()', 'second': 'second()' }[menu];
|
|
886
|
+
if (f == null) return new T.Num('0.0'); // 未知菜单:对照 VM 返回 0(web 路径 match 兜底一致)
|
|
887
|
+
return new T.Num(`(Local::now().${f} as f64)`);
|
|
839
888
|
};
|
|
840
889
|
inputs['sensing_answer'] = (a) => {
|
|
841
890
|
// 舞台模式:回答是全局运行时状态(对照 scratch3_sensing._answer),所有角色共享
|
|
@@ -883,11 +932,16 @@ function registerStandard(ctx) {
|
|
|
883
932
|
};
|
|
884
933
|
inputs['sensing_loudness'] = () => new T.Num('-1.0'); // 无麦克风
|
|
885
934
|
inputs['sensing_username'] = () => new T.Str('""');
|
|
935
|
+
// online?:对照 rCodenow fork isOnline——浏览器读 navigator.onLine,非浏览器环境恒 true;
|
|
936
|
+
// 原生可执行/WASM 均按非浏览器路径(WASM 无 DOM 时 VM 同样走该回退)
|
|
937
|
+
inputs['sensing_online'] = () => new T.Bool('true');
|
|
886
938
|
compiles['sensing_setdragmode'] = () => '';
|
|
887
939
|
inputs['sensing_keypressed'] = (a) => {
|
|
888
|
-
const key = a.scope.block.fields.KEY_OPTION[0];
|
|
889
940
|
if (!isStageMode()) { warnOnce('sensing_keypressed 控制台模式返回 false(键盘检测需 crossterm 轮询或舞台模块)'); return new T.Bool('false'); }
|
|
890
|
-
|
|
941
|
+
// KEY_OPTION 通常存于阴影菜单块(fields 仅帽块 event_whenkeypressed 直接携带)
|
|
942
|
+
const key = menuInput(a, 'KEY_OPTION', 'KEY_OPTION');
|
|
943
|
+
if (key == null) return new T.Bool('false');
|
|
944
|
+
return new T.Bool(`self.stage.key_down(${key})`);
|
|
891
945
|
};
|
|
892
946
|
inputs['sensing_mousedown'] = () => {
|
|
893
947
|
if (!isStageMode()) return new T.Bool('false');
|
|
@@ -902,6 +956,7 @@ function registerStandard(ctx) {
|
|
|
902
956
|
return new T.Num(`self.s_distance_to(${menu})`);
|
|
903
957
|
};
|
|
904
958
|
// 菜单输入统一读取:字段 / 被遮挡的菜单影子 / 动态表达式
|
|
959
|
+
// 阴影块 id 可能在 inp[2]([3, block, shadow])或 inp[1]([1, shadow],Scratch 原生未改菜单)
|
|
905
960
|
const menuInput = (a, key, fieldKey) => {
|
|
906
961
|
if (a.scope.block.fields[fieldKey]) return sl(a.scope.block.fields[fieldKey][0]);
|
|
907
962
|
if (a[key] && a[key].type !== 'Block' && typeof a[key].Stu === 'function') {
|
|
@@ -909,9 +964,13 @@ function registerStandard(ctx) {
|
|
|
909
964
|
return isStrLit(expr) ? expr : `&(${expr})`;
|
|
910
965
|
}
|
|
911
966
|
const inp = a.scope.block.inputs[key];
|
|
912
|
-
if (Array.isArray(inp)
|
|
913
|
-
const
|
|
914
|
-
|
|
967
|
+
if (Array.isArray(inp)) {
|
|
968
|
+
const sid = typeof inp[2] === 'string' ? inp[2]
|
|
969
|
+
: (inp[0] === 1 && typeof inp[1] === 'string' ? inp[1] : null);
|
|
970
|
+
if (sid != null) {
|
|
971
|
+
const sh = a.scope.target.blocks[sid];
|
|
972
|
+
if (sh && sh.fields && sh.fields[fieldKey]) return sl(sh.fields[fieldKey][0]);
|
|
973
|
+
}
|
|
915
974
|
}
|
|
916
975
|
return null;
|
|
917
976
|
};
|
|
@@ -921,8 +980,30 @@ function registerStandard(ctx) {
|
|
|
921
980
|
if (menu == null) return new T.Bool('false');
|
|
922
981
|
return new T.Bool(`self.s_touching(${menu})`);
|
|
923
982
|
};
|
|
924
|
-
|
|
925
|
-
|
|
983
|
+
// 像素级颜色查询(对照 scratch-render isTouchingColor):
|
|
984
|
+
// 遮罩=查询 sprite 自身渲染,场景=渲染线程最近一帧合成(无头模式每 tick 刷新)。
|
|
985
|
+
// idx 由 injectStageIdx 自动注入
|
|
986
|
+
inputs['sensing_touchingcolor'] = (a) => {
|
|
987
|
+
if (!isStageMode()) return new T.Bool('false');
|
|
988
|
+
const c = stuOf(a.COLOR);
|
|
989
|
+
return new T.Bool(`self.s_touching_color(${isStrLit(c) ? c : `&(${c})`}, None)`);
|
|
990
|
+
};
|
|
991
|
+
inputs['sensing_coloristouchingcolor'] = (a) => {
|
|
992
|
+
if (!isStageMode()) return new T.Bool('false');
|
|
993
|
+
const c1 = stuOf(a.COLOR);
|
|
994
|
+
const c2 = stuOf(a.COLOR2);
|
|
995
|
+
const arg = (expr) => isStrLit(expr) ? expr : `&(${expr})`;
|
|
996
|
+
return new T.Bool(`self.s_touching_color(${arg(c2)}, Some(${arg(c1)}))`);
|
|
997
|
+
};
|
|
998
|
+
// sensing_of:读取其他角色/舞台的属性(对照 rCodenow fork getAttributeOf:
|
|
999
|
+
// ①标准属性 ②属性名=目标(或全局)变量名 → 变量值 ③未知 → 0)
|
|
1000
|
+
inputs['sensing_of'] = (a) => {
|
|
1001
|
+
if (!isStageMode()) return new T.Str('String::new()');
|
|
1002
|
+
const obj = menuInput(a, 'OBJECT', 'OBJECT');
|
|
1003
|
+
const propField = a.scope.block.fields.PROPERTY;
|
|
1004
|
+
if (obj == null || !propField) return new T.Str('String::new()');
|
|
1005
|
+
return new T.Str(`self.s_of(${obj}, ${sl(String(propField[0]))})`);
|
|
1006
|
+
};
|
|
926
1007
|
|
|
927
1008
|
// ================= 外观(控制台回退)=================
|
|
928
1009
|
compiles['looks_say'] = (a) => {
|
|
@@ -957,42 +1038,16 @@ function registerStandard(ctx) {
|
|
|
957
1038
|
compiles['looks_switchcostumeto'] = (a) => {
|
|
958
1039
|
if (!isStageMode()) { warnOnce('looks_switchcostumeto 需要舞台模块,已跳过'); return ''; }
|
|
959
1040
|
// 造型输入三种形态:菜单字段 / 菜单影子(可被表达式遮挡)/ 动态表达式。
|
|
960
|
-
// 数字或数字字符串按序号(round+wrap,对照 _setCostume),其余按名称——运行时 s_switch_costume
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
expr = sl(a.scope.block.fields.COSTUME[0]);
|
|
964
|
-
} else if (a.COSTUME && a.COSTUME.type !== 'Block' && typeof a.COSTUME.Stu === 'function') {
|
|
965
|
-
expr = stuOf(a.COSTUME);
|
|
966
|
-
} else {
|
|
967
|
-
// 遮挡块是菜单本身(无法求值)→ 取影子里保存的造型名
|
|
968
|
-
const inp = a.scope.block.inputs.COSTUME;
|
|
969
|
-
let cname = '';
|
|
970
|
-
if (Array.isArray(inp) && typeof inp[2] === 'string') {
|
|
971
|
-
const sh = a.scope.target.blocks[inp[2]];
|
|
972
|
-
if (sh && sh.fields && sh.fields.COSTUME) cname = String(sh.fields.COSTUME[0]);
|
|
973
|
-
}
|
|
974
|
-
expr = sl(cname);
|
|
975
|
-
}
|
|
976
|
-
// 动态表达式可能是 String 值(&str 形参需借用)
|
|
977
|
-
if (!isStrLit(expr)) expr = `&(${expr})`;
|
|
1041
|
+
// 数字或数字字符串按序号(round+wrap,对照 _setCostume),其余按名称——运行时 s_switch_costume 解析。
|
|
1042
|
+
// 影子 id 有两种位置:inp[2](被遮挡形态)/ inp[1](纯影子形态,sb3 无遮挡层时)——menuInput 统一处理
|
|
1043
|
+
const expr = menuInput(a, 'COSTUME', 'COSTUME') || sl('');
|
|
978
1044
|
return `self.s_switch_costume(${expr});\n`;
|
|
979
1045
|
};
|
|
980
1046
|
compiles['looks_nextcostume'] = () => isStageMode() ? 'self.s_next_costume();\n' : (warnOnce('looks_nextcostume 需要舞台模块,已跳过'), '');
|
|
981
1047
|
compiles['looks_switchbackdropto'] = (a) => {
|
|
982
1048
|
if (!isStageMode()) { warnOnce('looks_switchbackdropto 需要舞台模块,已跳过'); return ''; }
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
else if (a.BACKDROP && a.BACKDROP.type !== 'Block' && typeof a.BACKDROP.Stu === 'function') expr = stuOf(a.BACKDROP);
|
|
986
|
-
else {
|
|
987
|
-
const inp = a.scope.block.inputs.BACKDROP;
|
|
988
|
-
let bname = '';
|
|
989
|
-
if (Array.isArray(inp) && typeof inp[2] === 'string') {
|
|
990
|
-
const sh = a.scope.target.blocks[inp[2]];
|
|
991
|
-
if (sh && sh.fields && sh.fields.BACKDROP) bname = String(sh.fields.BACKDROP[0]);
|
|
992
|
-
}
|
|
993
|
-
expr = sl(bname);
|
|
994
|
-
}
|
|
995
|
-
if (!isStrLit(expr)) expr = `&(${expr})`;
|
|
1049
|
+
// 同造型:菜单影子 id 双位置(inp[2]/inp[1])由 menuInput 统一处理
|
|
1050
|
+
const expr = menuInput(a, 'BACKDROP', 'BACKDROP') || sl('');
|
|
996
1051
|
return `self.s_switch_backdrop(${expr});\n`;
|
|
997
1052
|
};
|
|
998
1053
|
compiles['looks_nextbackdrop'] = () => isStageMode() ? 'self.s_next_backdrop();\n' : (warnOnce('looks_nextbackdrop 需要舞台模块,已跳过'), '');
|
|
@@ -1020,6 +1075,11 @@ function registerStandard(ctx) {
|
|
|
1020
1075
|
return fb === 'front' ? 'self.s_goto_front();\n' : 'self.s_goto_back();\n';
|
|
1021
1076
|
};
|
|
1022
1077
|
compiles['looks_gobacknlayers'] = (a) => isStageMode() ? `self.s_go_back_layers(${a.NUM.Usize()});\n` : '';
|
|
1078
|
+
compiles['looks_goforwardbackwardlayers'] = (a) => {
|
|
1079
|
+
if (!isStageMode()) return '';
|
|
1080
|
+
const fb = a.scope.block.fields.FORWARD_BACKWARD[0];
|
|
1081
|
+
return fb === 'forward' ? `self.s_go_forward_layers(${a.NUM.Usize()});\n` : `self.s_go_back_layers(${a.NUM.Usize()});\n`;
|
|
1082
|
+
};
|
|
1023
1083
|
inputs['looks_costumenumbername'] = (a) => {
|
|
1024
1084
|
if (!isStageMode()) return new T.Num('0.0');
|
|
1025
1085
|
const nn = a.scope.block.fields.NUMBER_NAME[0];
|
|
@@ -1097,6 +1157,34 @@ function registerStandard(ctx) {
|
|
|
1097
1157
|
compiles['sound_seteffectto'] = () => '';
|
|
1098
1158
|
compiles['sound_cleareffects'] = () => '';
|
|
1099
1159
|
|
|
1160
|
+
// ================= music 扩展(节奏状态 + 演奏时长;音色合成暂缺)=================
|
|
1161
|
+
// 对照 scratch3_music:tempo 为角色自定义状态(默认 60 BPM);
|
|
1162
|
+
// playDrum/playNote/rest 阻塞脚本 beats*60/tempo 秒;音色/鼓声合成暂缺(仅时长语义)
|
|
1163
|
+
const musicTempoField = () => {
|
|
1164
|
+
if (multi()) emit.field('music_tempo', 'std::sync::Mutex<f64>', 'std::sync::Mutex::new(60.0)');
|
|
1165
|
+
else emit.field('music_tempo', 'f64', '60.0');
|
|
1166
|
+
};
|
|
1167
|
+
const musicTempoGet = () => multi() ? '*self.music_tempo.lock().unwrap()' : 'self.music_tempo';
|
|
1168
|
+
const musicTempoSet = (expr) => multi() ? `*self.music_tempo.lock().unwrap() = (${expr});\n` : `self.music_tempo = (${expr});\n`;
|
|
1169
|
+
const musicBeatsSecs = (beats) => `((${beats}) as f64) * 60.0 / (${musicTempoGet()}).max(1e-6)`;
|
|
1170
|
+
compiles['music_playDrumForBeats'] = (a) => {
|
|
1171
|
+
musicTempoField();
|
|
1172
|
+
return `{ let __msecs = ${musicBeatsSecs(a.BEATS.Num())};\n${sleepCall('__msecs.max(0.0)')}` + '}\n';
|
|
1173
|
+
};
|
|
1174
|
+
compiles['music_playNoteForBeats'] = (a) => {
|
|
1175
|
+
musicTempoField();
|
|
1176
|
+
warnOnce('music 音色合成暂缺:playNote 仅按节拍阻塞时长,不发声');
|
|
1177
|
+
return `{ let __msecs = ${musicBeatsSecs(a.BEATS.Num())};\n${sleepCall('__msecs.max(0.0)')}` + '}\n';
|
|
1178
|
+
};
|
|
1179
|
+
compiles['music_restForBeats'] = (a) => {
|
|
1180
|
+
musicTempoField();
|
|
1181
|
+
return `{ let __msecs = ${musicBeatsSecs(a.BEATS.Num())};\n${sleepCall('__msecs.max(0.0)')}` + '}\n';
|
|
1182
|
+
};
|
|
1183
|
+
compiles['music_setTempo'] = (a) => { musicTempoField(); return musicTempoSet(a.TEMPO.Num()); };
|
|
1184
|
+
compiles['music_changeTempo'] = (a) => { musicTempoField(); return musicTempoSet(`(${musicTempoGet()}) + (${a.TEMPO.Num()})`); };
|
|
1185
|
+
inputs['music_getTempo'] = (a) => { musicTempoField(); return new T.Num(musicTempoGet()); };
|
|
1186
|
+
compiles['music_setInstrument'] = () => ''; // 乐器仅影响音色,无合成器时为 no-op
|
|
1187
|
+
|
|
1100
1188
|
// ================= 画笔(需舞台)=================
|
|
1101
1189
|
compiles['pen_clear'] = () => isStageMode() ? 'self.stage.pen_clear();\n' : (warnOnce('pen_clear 需要舞台模块,已跳过'), '');
|
|
1102
1190
|
compiles['pen_penDown'] = () => isStageMode() ? 'self.s_pen_down();\n' : (warnOnce('画笔需舞台模块,已跳过'), '');
|
|
@@ -1114,7 +1202,9 @@ function registerStandard(ctx) {
|
|
|
1114
1202
|
const ref = inp[1];
|
|
1115
1203
|
if (Array.isArray(ref)) col = String(ref[1] == null ? '' : ref[1]);
|
|
1116
1204
|
else if (typeof ref === 'string') {
|
|
1117
|
-
|
|
1205
|
+
// 影子 id 双位置:inp[2](被遮挡)/ inp[1](纯影子,无遮挡层)
|
|
1206
|
+
const sid = typeof inp[2] === 'string' ? inp[2] : (typeof inp[1] === 'string' ? inp[1] : null);
|
|
1207
|
+
const sh = sid != null && a.scope.target.blocks[sid];
|
|
1118
1208
|
if (sh && sh.fields && sh.fields.COLOR) col = String(sh.fields.COLOR[0]);
|
|
1119
1209
|
}
|
|
1120
1210
|
}
|
|
@@ -1123,27 +1213,37 @@ function registerStandard(ctx) {
|
|
|
1123
1213
|
if (!isStrLit(expr)) expr = `&(${expr})`;
|
|
1124
1214
|
return `self.s_pen_set_color(${expr});\n`;
|
|
1125
1215
|
};
|
|
1126
|
-
compiles['pen_changePenColorBy'] = () =>
|
|
1127
|
-
// 画笔参数(对照 scratch-pen setPenColorParamTo):transparency → alpha;
|
|
1128
|
-
// color/saturation/brightness 涉及 HSV 变换,暂不支持(警告一次)
|
|
1129
|
-
compiles['pen_setPenColorParamTo'] = (a) => {
|
|
1216
|
+
compiles['pen_changePenColorBy'] = (a) => {
|
|
1130
1217
|
if (!isStageMode()) return '';
|
|
1218
|
+
return `self.s_pen_change_param("color", ${a.VALUE ? a.VALUE.Num() : '0.0'});\n`;
|
|
1219
|
+
};
|
|
1220
|
+
// 画笔参数(对照 scratch-pen setPenColorParamTo):color=色相(0..100 回绕)、
|
|
1221
|
+
// saturation/brightness/transparency 0..100 钳制;HSV 变换在运行时 s_pen_set_param
|
|
1222
|
+
// 参数名是编译期常量(决定运行时调用哪个参数分支),须取原始值而非 Rust 表达式:
|
|
1223
|
+
// 阴影 id 可能在 inp[2]([3, block, shadow])或 inp[1]([1, shadow],未改动的下拉菜单)
|
|
1224
|
+
const penParamMenu = (a) => {
|
|
1225
|
+
if (a.scope.block.fields.COLOR_PARAM) return String(a.scope.block.fields.COLOR_PARAM[0]);
|
|
1131
1226
|
const inp = a.scope.block.inputs.COLOR_PARAM;
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
const sid = inp[2] != null ? inp[2] : inp[1];
|
|
1136
|
-
if (typeof sid === 'string') {
|
|
1227
|
+
if (Array.isArray(inp)) {
|
|
1228
|
+
const sid = typeof inp[2] === 'string' ? inp[2] : (inp[0] === 1 && typeof inp[1] === 'string' ? inp[1] : null);
|
|
1229
|
+
if (sid != null) {
|
|
1137
1230
|
const sh = a.scope.target.blocks[sid];
|
|
1138
|
-
if (sh && sh.fields && sh.fields.colorParam)
|
|
1231
|
+
if (sh && sh.fields && sh.fields.colorParam) return String(sh.fields.colorParam[0]);
|
|
1139
1232
|
}
|
|
1140
1233
|
}
|
|
1234
|
+
return null;
|
|
1235
|
+
};
|
|
1236
|
+
compiles['pen_setPenColorParamTo'] = (a) => {
|
|
1237
|
+
if (!isStageMode()) return '';
|
|
1238
|
+
const param = penParamMenu(a);
|
|
1141
1239
|
if (param == null) { warnOnce('画笔参数菜单无法解析,已跳过'); return ''; }
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1240
|
+
return `self.s_pen_set_param(${sl(param)}, ${a.VALUE.Num()});\n`;
|
|
1241
|
+
};
|
|
1242
|
+
compiles['pen_changePenColorParamBy'] = (a) => {
|
|
1243
|
+
if (!isStageMode()) return '';
|
|
1244
|
+
const param = penParamMenu(a);
|
|
1245
|
+
if (param == null) { warnOnce('画笔参数菜单无法解析,已跳过'); return ''; }
|
|
1246
|
+
return `self.s_pen_change_param(${sl(param)}, ${a.VALUE.Num()});\n`;
|
|
1147
1247
|
};
|
|
1148
1248
|
compiles['pen_setPenSizeTo'] = (a) => isStageMode() ? `self.s_pen_set_size(${a.SIZE.Num()});\n` : '';
|
|
1149
1249
|
compiles['pen_changePenSizeBy'] = (a) => isStageMode() ? `self.s_pen_change_size(${a.SIZE.Num()});\n` : '';
|
package/src/web.js
CHANGED
|
@@ -73,14 +73,12 @@ pub async fn rcompiler_wait_tick() {
|
|
|
73
73
|
}).await;
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
// ---------------------------------------------------------------------------
|
|
77
76
|
// tokio 兼容层(仅 WASM)
|
|
78
77
|
//
|
|
79
78
|
// 生成器沿用 tokio::spawn / tokio::time::sleep / tokio::task::* 的调用形态;
|
|
80
79
|
// WASM 上不能使用 tokio(线程/时间驱动),这里提供同形 API:
|
|
81
80
|
// - spawn_local + futures::Abortable + oneshot,支持 abort / await / id
|
|
82
81
|
// - sleep 走 setTimeout,yield_now 走 0ms timer
|
|
83
|
-
// ---------------------------------------------------------------------------
|
|
84
82
|
pub mod tokio {
|
|
85
83
|
use std::future::Future;
|
|
86
84
|
use std::pin::Pin;
|
|
@@ -183,9 +181,7 @@ pub mod tokio {
|
|
|
183
181
|
}
|
|
184
182
|
}
|
|
185
183
|
|
|
186
|
-
// ---------------------------------------------------------------------------
|
|
187
184
|
// JS 宿主导入
|
|
188
|
-
// ---------------------------------------------------------------------------
|
|
189
185
|
#[wasm_bindgen]
|
|
190
186
|
extern "C" {
|
|
191
187
|
#[wasm_bindgen(js_name = rcompilerHostSndPlay)]
|
|
@@ -231,7 +227,6 @@ impl std::default::Default for SoundMixer { fn default() -> Self { Self::new() }
|
|
|
231
227
|
// ---------------------------------------------------------------------------
|
|
232
228
|
|
|
233
229
|
const WEB_STAGE = `
|
|
234
|
-
// ============ WASM 舞台状态(渲染交给 JS scratch-render) ============
|
|
235
230
|
pub const STAGE_W: f64 = __RCOMPILER_STAGE_W__;
|
|
236
231
|
pub const STAGE_H: f64 = __RCOMPILER_STAGE_H__;
|
|
237
232
|
pub const RCOMPILER_TPS: f64 = __RCOMPILER_TPS__;
|
|
@@ -873,7 +868,6 @@ pub fn rcompiler_web_ask_submit(id: u32, answer: &str) {
|
|
|
873
868
|
// ---------------------------------------------------------------------------
|
|
874
869
|
|
|
875
870
|
const WEB_WARP = `
|
|
876
|
-
// ============ WASM warp(单线程任务局部深度) ============
|
|
877
871
|
thread_local! {
|
|
878
872
|
static RCOMPILER_WARP_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
|
|
879
873
|
}
|
|
@@ -908,7 +902,6 @@ impl Drop for RcompilerWarpGuard {
|
|
|
908
902
|
`;
|
|
909
903
|
|
|
910
904
|
const WEB_CLOCK_MULTI = `
|
|
911
|
-
// ============ WASM 无舞台帧时钟 ============
|
|
912
905
|
pub fn rcompiler_start_clock(tps: f64) {
|
|
913
906
|
wasm_bindgen_futures::spawn_local(async move {
|
|
914
907
|
let tps = if tps > 0.0 { tps } else { 60.0 };
|
|
@@ -922,7 +915,6 @@ pub async fn frame_tick() { rcompiler_wait_tick().await; }
|
|
|
922
915
|
`;
|
|
923
916
|
|
|
924
917
|
const WEB_CLOCK_SINGLE = `
|
|
925
|
-
// ============ WASM 无舞台帧时钟(同步项目仍由 JS tick 驱动) ============
|
|
926
918
|
pub fn rcompiler_start_sync_clock(tps: f64) {
|
|
927
919
|
let tps = if tps > 0.0 { tps } else { 60.0 };
|
|
928
920
|
wasm_bindgen_futures::spawn_local(async move {
|
|
@@ -1050,7 +1042,6 @@ function build(profile, P) {
|
|
|
1050
1042
|
// WASM 任务注册表(tokio 兼容层的类型)
|
|
1051
1043
|
function makeTaskMultiWeb() {
|
|
1052
1044
|
return `
|
|
1053
|
-
// ============ WASM 脚本任务注册表 ============
|
|
1054
1045
|
pub struct rcompiler_TaskRef {
|
|
1055
1046
|
pub id: tokio::task::Id,
|
|
1056
1047
|
pub idx: usize,
|
|
@@ -1391,7 +1382,6 @@ function updateMonitors() {
|
|
|
1391
1382
|
}
|
|
1392
1383
|
}
|
|
1393
1384
|
|
|
1394
|
-
// ---- 询问(与 rCodenow 相同的舞台底部输入框;z-index 高于监视器)----
|
|
1395
1385
|
function ensureAsk() {
|
|
1396
1386
|
if (askEls) return askEls;
|
|
1397
1387
|
const wrap = document.createElement('div');
|
|
File without changes
|