rcompiler 0.0.0-stage → 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 +31 -0
- package/CONTRIBUTING.md +38 -0
- package/LICENSE +15 -0
- package/README.md +170 -2
- package/SECURITY.md +27 -0
- package/assets/placeholder.png +0 -0
- package/docs/ARCHITECTURE.md +74 -0
- package/docs/CLI.md +67 -0
- package/docs/COMPATIBILITY.md +29 -0
- package/docs/CONFIG.md +73 -0
- package/docs/DEBUGGING.md +46 -0
- package/docs/NATIVE.md +110 -0
- package/docs/ROADMAP.md +12 -0
- package/docs/TESTING.md +55 -0
- package/exts/args.js +142 -0
- package/exts/freya.js +430 -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/exts/rcompilerExt.js +1396 -0
- package/exts/vartypeany.js +131 -0
- package/package.json +50 -4
- package/src/analysis.js +571 -0
- package/src/assets.js +335 -0
- package/src/cli.js +359 -0
- package/src/emit.js +353 -0
- package/src/mods.js +146 -0
- package/src/preludes.js +4174 -0
- package/src/rcompiler.js +2785 -0
- package/src/standard.js +1452 -0
- package/src/targets.js +129 -0
- package/src/web.js +1593 -0
package/src/web.js
ADDED
|
@@ -0,0 +1,1593 @@
|
|
|
1
|
+
// rCompiler V2 — WASM/Web 后端
|
|
2
|
+
//
|
|
3
|
+
// 角色分工:
|
|
4
|
+
// - wasm:编译后的 Scratch 脚本 + target 状态 + 画笔命令队列 + 输入队列
|
|
5
|
+
// - JS :scratch-render(WebGL/SVG/位图/图层/特效/画笔/拾取)+ WebAudio + DOM
|
|
6
|
+
//
|
|
7
|
+
// rCompiler 替代 scratch-vm 的脚本/状态角色;scratch-render 只负责渲染。
|
|
8
|
+
// 这里不依赖 scratch-vm:JS 宿主把 wasm 导出的状态同步到 scratch-render 的
|
|
9
|
+
// Drawable/Skin 上,并把输入事件写回 wasm。
|
|
10
|
+
|
|
11
|
+
'use strict';
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const { spawnSync } = require('child_process');
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Rust:WASM 基础垫片
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
const WEB_BASE = `
|
|
21
|
+
use wasm_bindgen::prelude::*;
|
|
22
|
+
use std::future::Future;
|
|
23
|
+
use std::pin::Pin;
|
|
24
|
+
use std::task::{Context, Poll, Waker};
|
|
25
|
+
use std::time::Duration;
|
|
26
|
+
|
|
27
|
+
/// WASM 上的单调时钟(js Date.now,毫秒)。std::time::Instant 在
|
|
28
|
+
/// wasm32-unknown-unknown 上不可用,舞台/计时器统一走这里。
|
|
29
|
+
#[derive(Clone, Copy)]
|
|
30
|
+
pub struct RcompilerInstant(f64);
|
|
31
|
+
impl RcompilerInstant {
|
|
32
|
+
pub fn now() -> Self { Self(js_sys::Date::now()) }
|
|
33
|
+
pub fn elapsed(&self) -> Duration {
|
|
34
|
+
Duration::from_secs_f64(((js_sys::Date::now() - self.0).max(0.0)) / 1000.0)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
pub async fn rcompiler_sleep(secs: f64) {
|
|
39
|
+
let ms = (secs.max(0.0) * 1000.0).min(u32::MAX as f64) as u32;
|
|
40
|
+
gloo_timers::future::TimeoutFuture::new(ms).await;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/// 同步让出(画笔/队列自旋处使用;WASM 单线程下就是空操作)
|
|
44
|
+
pub fn rcompiler_yield_now() {}
|
|
45
|
+
|
|
46
|
+
/// 同步等待(仅用于无法 await 的单线程纯计算路径;会阻塞浏览器主线程)
|
|
47
|
+
pub fn rcompiler_sleep_sync(secs: f64) {
|
|
48
|
+
let ms = (secs.max(0.0) * 1000.0).min(60_000.0);
|
|
49
|
+
let t0 = js_sys::Date::now();
|
|
50
|
+
while js_sys::Date::now() - t0 < ms { std::hint::spin_loop(); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 逻辑 tick:JS 宿主按 TPS 调用 rcompiler_web_tick,frame_wait 等到下一 tick
|
|
54
|
+
static RCOMPILER_TICK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
55
|
+
static RCOMPILER_TICK_WAKERS: std::sync::Mutex<Vec<Waker>> = std::sync::Mutex::new(Vec::new());
|
|
56
|
+
|
|
57
|
+
pub fn rcompiler_notify_tick() {
|
|
58
|
+
RCOMPILER_TICK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
59
|
+
let wakers: Vec<Waker> = {
|
|
60
|
+
let mut w = RCOMPILER_TICK_WAKERS.lock().unwrap();
|
|
61
|
+
std::mem::take(&mut *w)
|
|
62
|
+
};
|
|
63
|
+
for w in wakers { w.wake(); }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
pub async fn rcompiler_wait_tick() {
|
|
67
|
+
let cur = RCOMPILER_TICK.load(std::sync::atomic::Ordering::Relaxed);
|
|
68
|
+
futures::future::poll_fn(|cx| {
|
|
69
|
+
if RCOMPILER_TICK.load(std::sync::atomic::Ordering::Relaxed) != cur { return Poll::Ready(()); }
|
|
70
|
+
let mut w = RCOMPILER_TICK_WAKERS.lock().unwrap();
|
|
71
|
+
if !w.iter().any(|x| x.will_wake(cx.waker())) { w.push(cx.waker().clone()); }
|
|
72
|
+
if RCOMPILER_TICK.load(std::sync::atomic::Ordering::Relaxed) != cur { Poll::Ready(()) } else { Poll::Pending }
|
|
73
|
+
}).await;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// tokio 兼容层(仅 WASM)
|
|
77
|
+
//
|
|
78
|
+
// 生成器沿用 tokio::spawn / tokio::time::sleep / tokio::task::* 的调用形态;
|
|
79
|
+
// WASM 上不能使用 tokio(线程/时间驱动),这里提供同形 API:
|
|
80
|
+
// - spawn_local + futures::Abortable + oneshot,支持 abort / await / id
|
|
81
|
+
// - sleep 走 setTimeout,yield_now 走 0ms timer
|
|
82
|
+
pub mod tokio {
|
|
83
|
+
use std::future::Future;
|
|
84
|
+
use std::pin::Pin;
|
|
85
|
+
use std::task::{Context, Poll};
|
|
86
|
+
|
|
87
|
+
pub mod task {
|
|
88
|
+
use super::*;
|
|
89
|
+
use std::cell::Cell;
|
|
90
|
+
|
|
91
|
+
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
92
|
+
pub struct Id(pub u64);
|
|
93
|
+
|
|
94
|
+
#[derive(Clone, Copy, Debug)]
|
|
95
|
+
pub struct JoinError;
|
|
96
|
+
|
|
97
|
+
thread_local! {
|
|
98
|
+
static CURRENT: Cell<Option<Id>> = const { Cell::new(None) };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
pub(crate) fn set_current(v: Option<Id>) -> Option<Id> {
|
|
102
|
+
CURRENT.with(|c| c.replace(v))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
pub fn try_id() -> Option<Id> { CURRENT.with(|c| c.get()) }
|
|
106
|
+
|
|
107
|
+
#[derive(Clone)]
|
|
108
|
+
pub struct AbortHandle { pub(crate) inner: futures::future::AbortHandle }
|
|
109
|
+
impl AbortHandle {
|
|
110
|
+
pub fn abort(&self) { self.inner.abort(); }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
pub struct JoinHandle<T> {
|
|
114
|
+
pub(crate) id: Id,
|
|
115
|
+
pub(crate) rx: futures::channel::oneshot::Receiver<Result<T, futures::future::Aborted>>,
|
|
116
|
+
pub(crate) abort: futures::future::AbortHandle,
|
|
117
|
+
}
|
|
118
|
+
impl<T> JoinHandle<T> {
|
|
119
|
+
pub fn id(&self) -> Id { self.id }
|
|
120
|
+
pub fn abort_handle(&self) -> AbortHandle { AbortHandle { inner: self.abort.clone() } }
|
|
121
|
+
}
|
|
122
|
+
impl<T> Future for JoinHandle<T> {
|
|
123
|
+
type Output = Result<T, JoinError>;
|
|
124
|
+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
125
|
+
let this = self.as_mut().get_mut();
|
|
126
|
+
match Pin::new(&mut this.rx).poll(cx) {
|
|
127
|
+
Poll::Ready(Ok(Ok(v))) => Poll::Ready(Ok(v)),
|
|
128
|
+
Poll::Ready(Ok(Err(_))) => Poll::Ready(Err(JoinError)),
|
|
129
|
+
Poll::Ready(Err(_)) => Poll::Ready(Err(JoinError)),
|
|
130
|
+
Poll::Pending => Poll::Pending,
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
pub async fn yield_now() {
|
|
136
|
+
gloo_timers::future::TimeoutFuture::new(0).await;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
pub mod time {
|
|
141
|
+
pub async fn sleep(d: std::time::Duration) {
|
|
142
|
+
let ms = d.as_millis().min(u32::MAX as u128) as u32;
|
|
143
|
+
gloo_timers::future::TimeoutFuture::new(ms).await;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
use std::cell::Cell;
|
|
148
|
+
thread_local! {
|
|
149
|
+
static NEXT_ID: Cell<u64> = const { Cell::new(1) };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
struct SetCurrent<F: Future> {
|
|
153
|
+
id: task::Id,
|
|
154
|
+
inner: Pin<Box<F>>,
|
|
155
|
+
}
|
|
156
|
+
impl<F: Future> Future for SetCurrent<F> {
|
|
157
|
+
type Output = F::Output;
|
|
158
|
+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<F::Output> {
|
|
159
|
+
let this = self.as_mut().get_mut();
|
|
160
|
+
let prev = task::set_current(Some(this.id));
|
|
161
|
+
let r = this.inner.as_mut().poll(cx);
|
|
162
|
+
task::set_current(prev);
|
|
163
|
+
r
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
pub fn spawn<F>(fut: F) -> task::JoinHandle<F::Output>
|
|
168
|
+
where F: Future + 'static, F::Output: 'static {
|
|
169
|
+
let id = NEXT_ID.with(|c| { let v = c.get(); c.set(v + 1); task::Id(v) });
|
|
170
|
+
let (abort, reg) = futures::future::AbortHandle::new_pair();
|
|
171
|
+
let (tx, rx) = futures::channel::oneshot::channel();
|
|
172
|
+
let inner = SetCurrent {
|
|
173
|
+
id,
|
|
174
|
+
inner: Box::pin(futures::future::Abortable::new(fut, reg)),
|
|
175
|
+
};
|
|
176
|
+
wasm_bindgen_futures::spawn_local(async move {
|
|
177
|
+
let r = inner.await;
|
|
178
|
+
let _ = tx.send(r);
|
|
179
|
+
});
|
|
180
|
+
task::JoinHandle { id, rx, abort }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// JS 宿主导入
|
|
185
|
+
#[wasm_bindgen]
|
|
186
|
+
extern "C" {
|
|
187
|
+
#[wasm_bindgen(js_name = rcompilerHostSndPlay)]
|
|
188
|
+
fn host_snd_play(name: &str) -> u32;
|
|
189
|
+
#[wasm_bindgen(js_name = rcompilerHostSndStop)]
|
|
190
|
+
fn host_snd_stop(id: u32);
|
|
191
|
+
#[wasm_bindgen(js_name = rcompilerHostSndStopAll)]
|
|
192
|
+
fn host_snd_stop_all();
|
|
193
|
+
#[wasm_bindgen(js_name = rcompilerHostSndVolume)]
|
|
194
|
+
fn host_snd_volume(v: f64);
|
|
195
|
+
#[wasm_bindgen(js_name = rcompilerHostSndGetVolume)]
|
|
196
|
+
fn host_snd_get_volume() -> f64;
|
|
197
|
+
#[wasm_bindgen(js_name = rcompilerHostSndPlaying)]
|
|
198
|
+
fn host_snd_playing(id: u32) -> bool;
|
|
199
|
+
/// 无舞台 Web 项目的询问回退(浏览器 prompt);舞台项目走 DOM 输入框 + ask 队列
|
|
200
|
+
#[wasm_bindgen(js_name = rcompilerHostAsk)]
|
|
201
|
+
fn host_ask(question: &str) -> String;
|
|
202
|
+
}
|
|
203
|
+
#[wasm_bindgen(js_name = rcompilerHostLog)]
|
|
204
|
+
fn host_log(s: &str);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// WASM 声音:实际播放/解码由 JS WebAudio 完成
|
|
208
|
+
#[derive(Clone)]
|
|
209
|
+
pub struct SoundMixer;
|
|
210
|
+
impl SoundMixer {
|
|
211
|
+
pub fn new() -> Self { SoundMixer }
|
|
212
|
+
pub fn play(&self, name: &str) -> Option<std::sync::Arc<Sink>> {
|
|
213
|
+
let id = host_snd_play(name);
|
|
214
|
+
if id == 0 { None } else { Some(std::sync::Arc::new(Sink { id })) }
|
|
215
|
+
}
|
|
216
|
+
pub fn stop_all(&self) { host_snd_stop_all(); }
|
|
217
|
+
pub fn set_volume(&self, v: f64) { host_snd_volume(v.clamp(0.0, 100.0)); }
|
|
218
|
+
pub fn volume(&self) -> f64 { host_snd_get_volume() }
|
|
219
|
+
}
|
|
220
|
+
pub struct Sink { id: u32 }
|
|
221
|
+
impl Sink { pub fn empty(&self) -> bool { !host_snd_playing(self.id) } }
|
|
222
|
+
impl std::default::Default for SoundMixer { fn default() -> Self { Self::new() } }
|
|
223
|
+
`;
|
|
224
|
+
|
|
225
|
+
// ---------------------------------------------------------------------------
|
|
226
|
+
// Rust:WASM 舞台状态 / 桥接
|
|
227
|
+
// ---------------------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
const WEB_STAGE = `
|
|
230
|
+
pub const STAGE_W: f64 = __RCOMPILER_STAGE_W__;
|
|
231
|
+
pub const STAGE_H: f64 = __RCOMPILER_STAGE_H__;
|
|
232
|
+
pub const RCOMPILER_TPS: f64 = __RCOMPILER_TPS__;
|
|
233
|
+
pub const RCOMPILER_RENDER_FPS: f64 = __RCOMPILER_RENDER_FPS__;
|
|
234
|
+
pub const RCOMPILER_FRAME_GATE: bool = __RCOMPILER_FRAME_GATE__;
|
|
235
|
+
pub const RCOMPILER_INTERP: bool = __RCOMPILER_INTERP__;
|
|
236
|
+
|
|
237
|
+
thread_local! {
|
|
238
|
+
static RCOMPILER_RAND_STATE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
|
239
|
+
}
|
|
240
|
+
pub fn rand_uniform() -> f64 {
|
|
241
|
+
RCOMPILER_RAND_STATE.with(|c| {
|
|
242
|
+
let mut s = c.get();
|
|
243
|
+
if s == 0 { s = (js_sys::Date::now() as u64) | 1; }
|
|
244
|
+
s ^= s >> 12; s ^= s << 25; s ^= s >> 27;
|
|
245
|
+
c.set(s);
|
|
246
|
+
(s.wrapping_mul(0x2545F4914F6CDD1D) >> 11) as f64 / (1u64 << 53) as f64
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
fn rcompiler_to_uint32(x: f64) -> u32 {
|
|
251
|
+
if x.is_nan() || x.is_infinite() { return 0; }
|
|
252
|
+
let m = x.trunc() % 4294967296.0;
|
|
253
|
+
if m < 0.0 { (m + 4294967296.0) as u32 } else { m as u32 }
|
|
254
|
+
}
|
|
255
|
+
pub fn pen_color_rgba(v: &str) -> [f32; 4] {
|
|
256
|
+
let f = |x: u32| x as f32 / 255.0;
|
|
257
|
+
if let Some(hex) = v.strip_prefix('#') {
|
|
258
|
+
let mut val: u32 = 0;
|
|
259
|
+
let mut digits = 0usize;
|
|
260
|
+
for c in hex.chars() {
|
|
261
|
+
match c.to_digit(16) { Some(d) => { val = val.wrapping_mul(16).wrapping_add(d); digits += 1; } None => break }
|
|
262
|
+
}
|
|
263
|
+
let len = hex.chars().count();
|
|
264
|
+
if digits == 0 || (len != 3 && len != 6) { return [0.0, 0.0, 0.0, 1.0]; }
|
|
265
|
+
if len == 3 {
|
|
266
|
+
let nib = |x: u32| (((x & 0xf) << 4) | (x & 0xf)) as f32 / 255.0;
|
|
267
|
+
[nib(val >> 8), nib(val >> 4), nib(val), 1.0]
|
|
268
|
+
} else {
|
|
269
|
+
[f((val >> 16) & 0xff), f((val >> 8) & 0xff), f(val & 0xff), 1.0]
|
|
270
|
+
}
|
|
271
|
+
} else {
|
|
272
|
+
let n = match rcompiler_js_number(v) { Some(x) => x, None => v.trim().parse::<f64>().unwrap_or(f64::NAN) };
|
|
273
|
+
let u = rcompiler_to_uint32(n);
|
|
274
|
+
let a = (u >> 24) & 0xff;
|
|
275
|
+
[f((u >> 16) & 0xff), f((u >> 8) & 0xff), f(u & 0xff), f(if a > 0 { a } else { 255 })]
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
#[derive(Clone)]
|
|
280
|
+
pub struct CostumeInfo {
|
|
281
|
+
pub name: &'static [u8],
|
|
282
|
+
pub bytes: &'static [u8],
|
|
283
|
+
pub svg: bool,
|
|
284
|
+
pub rcx: f64, pub rcy: f64,
|
|
285
|
+
pub vbx: f64, pub vby: f64,
|
|
286
|
+
pub target: i32,
|
|
287
|
+
pub w: f64, pub h: f64, pub bmr: f64,
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
pub struct Skin {
|
|
291
|
+
pub name: String,
|
|
292
|
+
pub target: i32,
|
|
293
|
+
pub w: f64, pub h: f64,
|
|
294
|
+
pub rcx: f64, pub rcy: f64,
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
#[derive(Clone)]
|
|
298
|
+
pub struct Sprite {
|
|
299
|
+
pub x: f64, pub y: f64, pub direction: f64,
|
|
300
|
+
pub costumes: Vec<usize>, pub costume_index: usize,
|
|
301
|
+
pub scale: f64, pub alpha: f64, pub visible: bool,
|
|
302
|
+
pub rotation_style: u8,
|
|
303
|
+
pub say: String, pub say_kind: u8,
|
|
304
|
+
pub say_usage: u64,
|
|
305
|
+
pub layer: i32,
|
|
306
|
+
pub is_clone: bool,
|
|
307
|
+
pub clone_of: usize,
|
|
308
|
+
pub dead: bool,
|
|
309
|
+
pub pen_down: bool, pub pen_color: [f32; 4], pub pen_size: f32,
|
|
310
|
+
}
|
|
311
|
+
impl std::default::Default for Sprite {
|
|
312
|
+
fn default() -> Self {
|
|
313
|
+
Sprite { x: 0.0, y: 0.0, direction: 90.0, costumes: vec![], costume_index: 0,
|
|
314
|
+
scale: 1.0, alpha: 1.0, visible: true, rotation_style: 0,
|
|
315
|
+
say: String::new(), say_kind: 0, say_usage: 0, layer: 0,
|
|
316
|
+
is_clone: false, clone_of: usize::MAX, dead: false,
|
|
317
|
+
pen_down: false, pen_color: [0.0, 0.0, 1.0, 1.0], pen_size: 1.0 }
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
#[derive(Clone, Copy)]
|
|
322
|
+
pub struct PenCmd {
|
|
323
|
+
pub kind: u8, // 0=line 1=stamp 2=clear
|
|
324
|
+
pub x0: f64, pub y0: f64, pub x1: f64, pub y1: f64,
|
|
325
|
+
pub color: [f32; 4], pub size: f32,
|
|
326
|
+
pub sprite: usize,
|
|
327
|
+
pub stamp: Option<StampState>,
|
|
328
|
+
}
|
|
329
|
+
#[derive(Clone, Copy)]
|
|
330
|
+
pub struct StampState {
|
|
331
|
+
pub x: f64, pub y: f64, pub direction: f64,
|
|
332
|
+
pub scale: f64, pub alpha: f64,
|
|
333
|
+
pub skin: usize, pub rotation_style: u8,
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
#[derive(Default)]
|
|
337
|
+
pub struct InputState {
|
|
338
|
+
pub keys_down: std::collections::HashSet<String>,
|
|
339
|
+
pub mouse_x: f64, pub mouse_y: f64, pub mouse_down: bool,
|
|
340
|
+
pub key_log: std::collections::VecDeque<(u64, String)>,
|
|
341
|
+
pub key_seq: u64,
|
|
342
|
+
pub click_log: std::collections::VecDeque<(u64, usize)>,
|
|
343
|
+
pub click_seq: u64,
|
|
344
|
+
pub backdrop_log: std::collections::VecDeque<(u64, String)>,
|
|
345
|
+
pub backdrop_seq: u64,
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
pub struct PenShared { pub queue: std::sync::Mutex<Vec<PenCmd>> }
|
|
349
|
+
|
|
350
|
+
pub struct StageShared {
|
|
351
|
+
pub sprites: std::sync::Mutex<Vec<std::sync::Arc<std::sync::Mutex<Sprite>>>>,
|
|
352
|
+
pub order: std::sync::Mutex<Vec<usize>>,
|
|
353
|
+
pub input: std::sync::Mutex<InputState>,
|
|
354
|
+
pub pen: PenShared,
|
|
355
|
+
pub skins: Vec<Skin>,
|
|
356
|
+
pub backdrops: Vec<usize>,
|
|
357
|
+
pub backdrop: std::sync::atomic::AtomicUsize,
|
|
358
|
+
pub monitor_rows: std::sync::Mutex<Vec<Vec<String>>>,
|
|
359
|
+
pub monitor_setq: std::sync::Mutex<Vec<(usize, f64)>>,
|
|
360
|
+
pub ask: std::sync::Mutex<AskState>,
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
fn sprite_quad_aabb(sp: &Sprite, skins: &[Skin]) -> (f64, f64, f64, f64) {
|
|
364
|
+
let ci = *sp.costumes.get(sp.costume_index).unwrap_or(&0);
|
|
365
|
+
let skin = &skins[ci.min(skins.len().saturating_sub(1))];
|
|
366
|
+
let (cw, ch) = (skin.w, skin.h);
|
|
367
|
+
let (rcx, rcy) = (skin.rcx, skin.rcy);
|
|
368
|
+
let (w, h) = (cw * sp.scale, ch * sp.scale);
|
|
369
|
+
let cx = sp.x + (cw / 2.0 - rcx) * sp.scale;
|
|
370
|
+
let cy = sp.y - (ch / 2.0 - rcy) * sp.scale;
|
|
371
|
+
(cx - w / 2.0, cy + h / 2.0, cx + w / 2.0, cy - h / 2.0)
|
|
372
|
+
}
|
|
373
|
+
fn s_is_named_or_clone_of(idx: usize, name: &str, stage: &StageShared) -> bool {
|
|
374
|
+
let sp_arc = stage.sprite(idx);
|
|
375
|
+
let sp = sp_arc.lock().unwrap();
|
|
376
|
+
if sp.clone_of == usize::MAX { rcompiler_target_name(idx) == name }
|
|
377
|
+
else { rcompiler_target_name(sp.clone_of) == name }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
impl StageShared {
|
|
381
|
+
pub fn detached() -> std::sync::Arc<StageShared> { Self::with_clock(0, 30.0) }
|
|
382
|
+
pub fn new(target_count: usize) -> std::sync::Arc<StageShared> { Self::with_clock(target_count, 30.0) }
|
|
383
|
+
pub fn with_clock(target_count: usize, _tps: f64) -> std::sync::Arc<StageShared> {
|
|
384
|
+
let mut sprites = Vec::new();
|
|
385
|
+
let mut order = Vec::new();
|
|
386
|
+
for i in 0..target_count {
|
|
387
|
+
let mut sp = Sprite::default();
|
|
388
|
+
if i == 0 { sp.visible = false; }
|
|
389
|
+
sprites.push(std::sync::Arc::new(std::sync::Mutex::new(sp)));
|
|
390
|
+
order.push(i);
|
|
391
|
+
}
|
|
392
|
+
let mut skins = Vec::new();
|
|
393
|
+
for ci in RCOMPILER_COSTUMES {
|
|
394
|
+
let bmr = if ci.bmr > 0.0 { ci.bmr } else { 1.0 };
|
|
395
|
+
let (w, h, rcx, rcy) = if ci.svg {
|
|
396
|
+
(ci.w, ci.h, ci.rcx - ci.vbx, ci.rcy - ci.vby)
|
|
397
|
+
} else {
|
|
398
|
+
(ci.w, ci.h, ci.rcx / bmr, ci.rcy / bmr)
|
|
399
|
+
};
|
|
400
|
+
skins.push(Skin { name: rcompiler_name(ci.name), target: ci.target, w, h, rcx, rcy });
|
|
401
|
+
}
|
|
402
|
+
let backdrops: Vec<usize> = skins.iter().enumerate()
|
|
403
|
+
.filter(|(_, s)| s.target == 0).map(|(i, _)| i).collect();
|
|
404
|
+
std::sync::Arc::new(StageShared {
|
|
405
|
+
sprites: std::sync::Mutex::new(sprites),
|
|
406
|
+
order: std::sync::Mutex::new(order),
|
|
407
|
+
input: std::sync::Mutex::new(InputState::default()),
|
|
408
|
+
pen: PenShared { queue: std::sync::Mutex::new(vec![]) },
|
|
409
|
+
skins, backdrops,
|
|
410
|
+
backdrop: std::sync::atomic::AtomicUsize::new(0),
|
|
411
|
+
monitor_rows: std::sync::Mutex::new(Vec::new()),
|
|
412
|
+
monitor_setq: std::sync::Mutex::new(Vec::new()),
|
|
413
|
+
ask: std::sync::Mutex::new(AskState::default()),
|
|
414
|
+
})
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
pub fn sprite(&self, idx: usize) -> std::sync::Arc<std::sync::Mutex<Sprite>> {
|
|
418
|
+
let vec = self.sprites.lock().unwrap();
|
|
419
|
+
let i = idx.min(vec.len().saturating_sub(1));
|
|
420
|
+
std::sync::Arc::clone(&vec[i])
|
|
421
|
+
}
|
|
422
|
+
pub fn sprite_count(&self) -> usize { self.sprites.lock().unwrap().len() }
|
|
423
|
+
pub fn is_dead(&self, idx: usize) -> bool {
|
|
424
|
+
if idx == usize::MAX || idx >= self.sprite_count() { return false; }
|
|
425
|
+
self.sprite(idx).lock().unwrap().dead
|
|
426
|
+
}
|
|
427
|
+
pub fn configure_sprite(&self, ti: usize, x: f64, y: f64, direction: f64, size: f64, visible: bool, layer: i32, current: usize) {
|
|
428
|
+
let vec = self.sprites.lock().unwrap();
|
|
429
|
+
if ti >= vec.len() { return; }
|
|
430
|
+
let mut sp = vec[ti].lock().unwrap();
|
|
431
|
+
sp.x = x; sp.y = y; sp.direction = direction;
|
|
432
|
+
sp.scale = (size / 100.0).max(0.001);
|
|
433
|
+
sp.visible = visible; sp.layer = layer;
|
|
434
|
+
sp.costumes = self.skins.iter().enumerate()
|
|
435
|
+
.filter(|(_, s)| s.target == ti as i32)
|
|
436
|
+
.map(|(i, _)| i).collect();
|
|
437
|
+
sp.costume_index = current.min(sp.costumes.len().saturating_sub(1));
|
|
438
|
+
}
|
|
439
|
+
fn live_clones(&self) -> usize {
|
|
440
|
+
self.sprites.lock().unwrap().iter()
|
|
441
|
+
.filter(|s| { let sp = s.lock().unwrap(); sp.is_clone && !sp.dead }).count()
|
|
442
|
+
}
|
|
443
|
+
pub fn can_clone(&self) -> bool { self.live_clones() < RCOMPILER_CLONE_LIMIT }
|
|
444
|
+
pub fn add_sprite_clone(&self, parent: usize) -> usize {
|
|
445
|
+
let idx;
|
|
446
|
+
{
|
|
447
|
+
let mut vec = self.sprites.lock().unwrap();
|
|
448
|
+
if vec.iter().filter(|s| { let sp = s.lock().unwrap(); sp.is_clone && !sp.dead }).count() >= RCOMPILER_CLONE_LIMIT {
|
|
449
|
+
return usize::MAX;
|
|
450
|
+
}
|
|
451
|
+
idx = vec.len();
|
|
452
|
+
let parent = parent.min(vec.len().saturating_sub(1));
|
|
453
|
+
let proto = vec[parent].lock().unwrap().clone();
|
|
454
|
+
vec.push(std::sync::Arc::new(std::sync::Mutex::new(Sprite {
|
|
455
|
+
say: String::new(), say_kind: 0, say_usage: 0,
|
|
456
|
+
is_clone: true, clone_of: parent, dead: false,
|
|
457
|
+
pen_down: proto.pen_down, pen_color: proto.pen_color, pen_size: proto.pen_size,
|
|
458
|
+
..proto
|
|
459
|
+
})));
|
|
460
|
+
}
|
|
461
|
+
let mut o = self.order.lock().unwrap();
|
|
462
|
+
let pos = o.iter().position(|&x| x == parent).unwrap_or(o.len());
|
|
463
|
+
let at = pos.min(o.len());
|
|
464
|
+
o.insert(at, idx);
|
|
465
|
+
idx
|
|
466
|
+
}
|
|
467
|
+
pub fn delete_clone(&self, idx: usize) {
|
|
468
|
+
if idx == usize::MAX || idx >= self.sprite_count() { return; }
|
|
469
|
+
{
|
|
470
|
+
let sp_arc = self.sprite(idx);
|
|
471
|
+
let mut sp = sp_arc.lock().unwrap();
|
|
472
|
+
if !sp.is_clone || sp.dead { return; }
|
|
473
|
+
sp.dead = true; sp.visible = false; sp.say.clear(); sp.say_kind = 0;
|
|
474
|
+
}
|
|
475
|
+
self.order.lock().unwrap().retain(|&x| x != idx);
|
|
476
|
+
}
|
|
477
|
+
pub fn stop_all_clones(&self) {
|
|
478
|
+
{
|
|
479
|
+
let vec = self.sprites.lock().unwrap();
|
|
480
|
+
for s in vec.iter() {
|
|
481
|
+
let mut sp = s.lock().unwrap();
|
|
482
|
+
if sp.is_clone { sp.dead = true; sp.visible = false; sp.say.clear(); }
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
let alive: Vec<usize> = {
|
|
486
|
+
let vec = self.sprites.lock().unwrap();
|
|
487
|
+
(0..vec.len()).filter(|&i| !vec[i].lock().unwrap().is_clone).collect()
|
|
488
|
+
};
|
|
489
|
+
self.order.lock().unwrap().retain(|x| alive.contains(x));
|
|
490
|
+
}
|
|
491
|
+
pub fn reset_visuals(&self) {
|
|
492
|
+
let vec = self.sprites.lock().unwrap();
|
|
493
|
+
for s in vec.iter() {
|
|
494
|
+
let mut sp = s.lock().unwrap();
|
|
495
|
+
sp.say.clear(); sp.say_kind = 0; sp.alpha = 1.0;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
pub fn touch_pen(&self, idx: usize, old_x: f64, old_y: f64) {
|
|
499
|
+
if idx == usize::MAX || idx >= self.sprite_count() { return; }
|
|
500
|
+
let sp_arc = self.sprite(idx);
|
|
501
|
+
let mut sp = sp_arc.lock().unwrap();
|
|
502
|
+
if sp.dead || !sp.pen_down { return; }
|
|
503
|
+
let cmd = PenCmd { kind: 0, x0: old_x, y0: old_y, x1: sp.x, y1: sp.y,
|
|
504
|
+
color: sp.pen_color, size: sp.pen_size, sprite: idx, stamp: None };
|
|
505
|
+
drop(sp);
|
|
506
|
+
loop {
|
|
507
|
+
match self.pen.queue.try_lock() {
|
|
508
|
+
Ok(mut q) => { q.push(cmd); break; }
|
|
509
|
+
Err(_) => rcompiler_yield_now(),
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
pub fn set_xy(&self, idx: usize, x: f64, y: f64) {
|
|
514
|
+
if idx == usize::MAX || idx >= self.sprite_count() { return; }
|
|
515
|
+
let sp_arc = self.sprite(idx);
|
|
516
|
+
let mut sp = sp_arc.lock().unwrap();
|
|
517
|
+
if sp.dead { return; }
|
|
518
|
+
const FENCE_WIDTH: f64 = 15.0;
|
|
519
|
+
let aabb = sprite_quad_aabb(&sp, &self.skins);
|
|
520
|
+
let (cx, cy) = (sp.x, sp.y);
|
|
521
|
+
let dx = x - cx; let dy = y - cy;
|
|
522
|
+
let inset = ((aabb.2 - aabb.0).min(aabb.1 - aabb.3) / 2.0).floor();
|
|
523
|
+
let sx = STAGE_W / 2.0 - FENCE_WIDTH.min(inset);
|
|
524
|
+
let mut fx = x;
|
|
525
|
+
if aabb.2 + dx < -sx { fx = (cx - (sx + aabb.2)).ceil(); }
|
|
526
|
+
else if aabb.0 + dx > sx { fx = (cx + (sx - aabb.0)).floor(); }
|
|
527
|
+
let sy = STAGE_H / 2.0 - FENCE_WIDTH.min(inset);
|
|
528
|
+
let mut fy = y;
|
|
529
|
+
if aabb.1 + dy < -sy { fy = (cy - (sy + aabb.1)).ceil(); }
|
|
530
|
+
else if aabb.3 + dy > sy { fy = (cy + (sy - aabb.3)).floor(); }
|
|
531
|
+
let (ox, oy) = (sp.x, sp.y);
|
|
532
|
+
sp.x = fx; sp.y = fy;
|
|
533
|
+
drop(sp);
|
|
534
|
+
self.touch_pen(idx, ox, oy);
|
|
535
|
+
}
|
|
536
|
+
pub fn get_xy(&self, idx: usize) -> (f64, f64) {
|
|
537
|
+
if idx >= self.sprite_count() { return (0.0, 0.0); }
|
|
538
|
+
let sp_arc = self.sprite(idx);
|
|
539
|
+
let sp = sp_arc.lock().unwrap();
|
|
540
|
+
(sp.x, sp.y)
|
|
541
|
+
}
|
|
542
|
+
pub fn key_seq(&self) -> u64 { self.input.lock().unwrap().key_seq }
|
|
543
|
+
pub fn next_key(&self, cursor: &mut u64, name: &str) -> bool {
|
|
544
|
+
let input = self.input.lock().unwrap();
|
|
545
|
+
let mut maxs = *cursor;
|
|
546
|
+
for &(s, ref k) in &input.key_log {
|
|
547
|
+
if s > *cursor {
|
|
548
|
+
maxs = s;
|
|
549
|
+
if name == "any" || *k == name { *cursor = s; return true; }
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
*cursor = maxs; false
|
|
553
|
+
}
|
|
554
|
+
pub fn key_down(&self, name: &str) -> bool { self.input.lock().unwrap().keys_down.contains(name) }
|
|
555
|
+
pub fn click_seq(&self) -> u64 { self.input.lock().unwrap().click_seq }
|
|
556
|
+
pub fn next_click(&self, cursor: &mut u64, idx: usize) -> bool {
|
|
557
|
+
let input = self.input.lock().unwrap();
|
|
558
|
+
let sprites = self.sprites.lock().unwrap();
|
|
559
|
+
let mut maxs = *cursor;
|
|
560
|
+
for &(s, hit) in &input.click_log {
|
|
561
|
+
if s > *cursor {
|
|
562
|
+
maxs = s;
|
|
563
|
+
let matches = if idx == usize::MAX { hit == usize::MAX }
|
|
564
|
+
else if hit == idx { true }
|
|
565
|
+
else if hit < sprites.len() {
|
|
566
|
+
let sp = sprites[hit].lock().unwrap();
|
|
567
|
+
sp.is_clone && sp.clone_of == idx
|
|
568
|
+
} else { false };
|
|
569
|
+
if matches { *cursor = s; return true; }
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
*cursor = maxs; false
|
|
573
|
+
}
|
|
574
|
+
pub fn backdrop_seq(&self) -> u64 { self.input.lock().unwrap().backdrop_seq }
|
|
575
|
+
pub fn clone_indices(&self, ti: usize) -> Vec<usize> {
|
|
576
|
+
let vec = self.sprites.lock().unwrap();
|
|
577
|
+
let mut out = Vec::new();
|
|
578
|
+
for (i, s) in vec.iter().enumerate() {
|
|
579
|
+
let sp = s.lock().unwrap();
|
|
580
|
+
if sp.is_clone && !sp.dead && sp.clone_of == ti { out.push(i); }
|
|
581
|
+
}
|
|
582
|
+
out
|
|
583
|
+
}
|
|
584
|
+
pub fn next_backdrop_switch(&self, cursor: &mut u64, name: &str) -> bool {
|
|
585
|
+
let input = self.input.lock().unwrap();
|
|
586
|
+
let mut maxs = *cursor;
|
|
587
|
+
for &(s, ref k) in &input.backdrop_log {
|
|
588
|
+
if s > *cursor {
|
|
589
|
+
maxs = s;
|
|
590
|
+
if k == name { *cursor = s; return true; }
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
*cursor = maxs; false
|
|
594
|
+
}
|
|
595
|
+
pub fn mouse_x(&self) -> f64 { self.input.lock().unwrap().mouse_x }
|
|
596
|
+
pub fn mouse_y(&self) -> f64 { self.input.lock().unwrap().mouse_y }
|
|
597
|
+
pub fn mouse_down(&self) -> bool { self.input.lock().unwrap().mouse_down }
|
|
598
|
+
pub fn pen_clear(&self) {
|
|
599
|
+
self.pen.queue.lock().unwrap().push(PenCmd { kind: 2, x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0, color: [0.0; 4], size: 0.0, sprite: 0, stamp: None });
|
|
600
|
+
}
|
|
601
|
+
pub fn pen_stamp(&self, idx: usize) {
|
|
602
|
+
let st = self.sprite_state(idx);
|
|
603
|
+
let stamp = StampState { x: st.x, y: st.y, direction: st.direction, scale: st.scale, alpha: st.alpha, skin: st.skin, rotation_style: st.rotation_style };
|
|
604
|
+
self.pen.queue.lock().unwrap().push(PenCmd { kind: 1, x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0, color: [0.0; 4], size: 0.0, sprite: idx, stamp: Some(stamp) });
|
|
605
|
+
}
|
|
606
|
+
pub fn sprite_state(&self, idx: usize) -> RenderState {
|
|
607
|
+
if idx >= self.sprite_count() { return RenderState::default(); }
|
|
608
|
+
let sp_arc = self.sprite(idx);
|
|
609
|
+
let sp = sp_arc.lock().unwrap();
|
|
610
|
+
RenderState { x: sp.x, y: sp.y, direction: sp.direction, scale: sp.scale, alpha: sp.alpha.clamp(0.0, 1.0),
|
|
611
|
+
visible: sp.visible, skin: *sp.costumes.get(sp.costume_index).unwrap_or(&0), layer: sp.layer,
|
|
612
|
+
rotation_style: sp.rotation_style }
|
|
613
|
+
}
|
|
614
|
+
pub fn hull_aabb(&self, idx: usize) -> (f64, f64, f64, f64) {
|
|
615
|
+
let sp_arc = self.sprite(idx);
|
|
616
|
+
let sp = sp_arc.lock().unwrap();
|
|
617
|
+
let ci = *sp.costumes.get(sp.costume_index).unwrap_or(&0);
|
|
618
|
+
let skin = &self.skins[ci.min(self.skins.len().saturating_sub(1))];
|
|
619
|
+
let (w, h) = (skin.w * sp.scale, skin.h * sp.scale);
|
|
620
|
+
let (rcx, rcy) = (skin.rcx * sp.scale, skin.rcy * sp.scale);
|
|
621
|
+
let corners = [(-rcx, rcy), (w - rcx, rcy), (-rcx, -(h - rcy)), (w - rcx, -(h - rcy))];
|
|
622
|
+
let (rad, flip_x) = match sp.rotation_style {
|
|
623
|
+
1 => (0.0f64, sp.direction < 0.0),
|
|
624
|
+
2 => (0.0f64, false),
|
|
625
|
+
_ => ((90.0 - sp.direction).to_radians(), false),
|
|
626
|
+
};
|
|
627
|
+
let (s, c) = rad.sin_cos();
|
|
628
|
+
let (mut l, mut t, mut r, mut b) = (f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
|
629
|
+
for &(lx, ly) in &corners {
|
|
630
|
+
let lx = if flip_x { -lx } else { lx };
|
|
631
|
+
let wx = lx * c - ly * s;
|
|
632
|
+
let wy = lx * s + ly * c;
|
|
633
|
+
l = l.min(wx); r = r.max(wx); b = b.min(wy); t = t.max(wy);
|
|
634
|
+
}
|
|
635
|
+
(sp.x + l, sp.y + t, sp.x + r, sp.y + b)
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
__RCOMPILER_ASK_RUNTIME__
|
|
640
|
+
|
|
641
|
+
/// WASM:询问状态变化无需唤醒事件循环(JS 每帧轮询 ask_view)
|
|
642
|
+
pub fn rcompiler_ask_wake_ui() {}
|
|
643
|
+
|
|
644
|
+
#[derive(Clone, Copy, Default)]
|
|
645
|
+
pub struct RenderState {
|
|
646
|
+
pub x: f64, pub y: f64, pub direction: f64,
|
|
647
|
+
pub scale: f64, pub alpha: f64,
|
|
648
|
+
pub visible: bool, pub skin: usize, pub layer: i32,
|
|
649
|
+
pub rotation_style: u8,
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
pub struct MonitorInfo {
|
|
653
|
+
pub kind: u8, pub label: &'static [u8],
|
|
654
|
+
pub x: f64, pub y: f64, pub width: f64, pub height: f64,
|
|
655
|
+
pub slider_min: f64, pub slider_max: f64, pub discrete: bool,
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
pub static RCOMPILER_MAIN: std::sync::OnceLock<std::sync::Arc<Default>> = std::sync::OnceLock::new();
|
|
659
|
+
pub static RCOMPILER_STAGE: std::sync::OnceLock<std::sync::Arc<StageShared>> = std::sync::OnceLock::new();
|
|
660
|
+
|
|
661
|
+
pub fn rcompiler_web_boot_stage(new_fn: fn(std::sync::Arc<StageShared>) -> Default) {
|
|
662
|
+
console_error_panic_hook::set_once();
|
|
663
|
+
let tps = if RCOMPILER_TPS > 0.0 { RCOMPILER_TPS } else { 30.0 };
|
|
664
|
+
let shared = StageShared::with_clock(RCOMPILER_TARGET_COUNT, tps);
|
|
665
|
+
let init = std::sync::Arc::new(new_fn(std::sync::Arc::clone(&shared)));
|
|
666
|
+
let _ = RCOMPILER_MAIN.set(std::sync::Arc::clone(&init));
|
|
667
|
+
let _ = RCOMPILER_STAGE.set(shared);
|
|
668
|
+
if RCOMPILER_AUTOPLAY { init.rcompiler_spawn_all(); }
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
fn rcompiler_json_array(v: &[String]) -> String {
|
|
672
|
+
// Rust Debug for Vec<String> 输出即为 JSON 兼容的字符串数组(含引号/转义)
|
|
673
|
+
format!("{:?}", v)
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
#[wasm_bindgen]
|
|
677
|
+
pub fn rcompiler_web_tick() { rcompiler_notify_tick(); }
|
|
678
|
+
|
|
679
|
+
#[wasm_bindgen]
|
|
680
|
+
pub fn rcompiler_web_stage_size() -> Vec<f64> { vec![STAGE_W, STAGE_H] }
|
|
681
|
+
|
|
682
|
+
#[wasm_bindgen]
|
|
683
|
+
pub fn rcompiler_web_sprite_count() -> u32 {
|
|
684
|
+
RCOMPILER_STAGE.get().map(|s| s.sprite_count() as u32).unwrap_or(0)
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
#[wasm_bindgen]
|
|
688
|
+
pub fn rcompiler_web_sprite_state(i: u32) -> Vec<f64> {
|
|
689
|
+
let i = i as usize;
|
|
690
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return vec![]; };
|
|
691
|
+
if i >= stage.sprite_count() { return vec![]; }
|
|
692
|
+
let st = stage.sprite_state(i);
|
|
693
|
+
vec![st.x, st.y, st.direction, st.scale, st.alpha,
|
|
694
|
+
if st.visible { 1.0 } else { 0.0 }, st.skin as f64,
|
|
695
|
+
st.rotation_style as f64, st.layer as f64]
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
#[wasm_bindgen]
|
|
699
|
+
pub fn rcompiler_web_sprite_extra(i: u32) -> Vec<f64> {
|
|
700
|
+
let i = i as usize;
|
|
701
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return vec![]; };
|
|
702
|
+
if i >= stage.sprite_count() { return vec![]; }
|
|
703
|
+
let sp_arc = stage.sprite(i);
|
|
704
|
+
let sp = sp_arc.lock().unwrap();
|
|
705
|
+
vec![sp.say_kind as f64, if sp.dead { 1.0 } else { 0.0 }, if sp.is_clone { 1.0 } else { 0.0 }, sp.clone_of as f64]
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
#[wasm_bindgen]
|
|
709
|
+
pub fn rcompiler_web_sprite_say(i: u32) -> String {
|
|
710
|
+
let i = i as usize;
|
|
711
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return String::new(); };
|
|
712
|
+
if i >= stage.sprite_count() { return String::new(); }
|
|
713
|
+
let sp_arc = stage.sprite(i);
|
|
714
|
+
let s = sp_arc.lock().unwrap().say.clone();
|
|
715
|
+
s
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
#[wasm_bindgen]
|
|
719
|
+
pub fn rcompiler_web_order() -> Vec<u32> {
|
|
720
|
+
RCOMPILER_STAGE.get()
|
|
721
|
+
.map(|s| s.order.lock().unwrap().iter().map(|&x| x as u32).collect())
|
|
722
|
+
.unwrap_or_default()
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
#[wasm_bindgen]
|
|
726
|
+
pub fn rcompiler_web_sprite_skin(i: u32) -> u32 {
|
|
727
|
+
let i = i as usize;
|
|
728
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return 0; };
|
|
729
|
+
if i >= stage.sprite_count() { return 0; }
|
|
730
|
+
stage.sprite_state(i).skin as u32
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
#[wasm_bindgen]
|
|
734
|
+
pub fn rcompiler_web_backdrop() -> u32 {
|
|
735
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return 0; };
|
|
736
|
+
let bd = stage.backdrop.load(std::sync::atomic::Ordering::Relaxed);
|
|
737
|
+
stage.backdrops.get(bd).copied().unwrap_or(0) as u32
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
#[wasm_bindgen]
|
|
741
|
+
pub fn rcompiler_web_pen_drain() -> Vec<f64> {
|
|
742
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return vec![]; };
|
|
743
|
+
let cmds: Vec<PenCmd> = { stage.pen.queue.lock().unwrap().drain(..).collect() };
|
|
744
|
+
let mut out = Vec::with_capacity(cmds.len() * 12);
|
|
745
|
+
for c in cmds {
|
|
746
|
+
out.push(c.kind as f64);
|
|
747
|
+
match c.kind {
|
|
748
|
+
2 => {}
|
|
749
|
+
0 => {
|
|
750
|
+
out.extend_from_slice(&[c.x0, c.y0, c.x1, c.y1,
|
|
751
|
+
c.color[0] as f64, c.color[1] as f64, c.color[2] as f64, c.color[3] as f64, c.size as f64]);
|
|
752
|
+
}
|
|
753
|
+
_ => {
|
|
754
|
+
if let Some(s) = c.stamp {
|
|
755
|
+
out.extend_from_slice(&[s.x, s.y, s.direction, s.scale, s.alpha,
|
|
756
|
+
s.skin as f64, s.rotation_style as f64]);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
out
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
#[wasm_bindgen]
|
|
765
|
+
pub fn rcompiler_web_key(name: &str, down: bool) {
|
|
766
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return; };
|
|
767
|
+
let mut input = stage.input.lock().unwrap();
|
|
768
|
+
if down {
|
|
769
|
+
input.keys_down.insert(name.to_string());
|
|
770
|
+
input.key_seq += 1;
|
|
771
|
+
let seq = input.key_seq;
|
|
772
|
+
input.key_log.push_back((seq, name.to_string()));
|
|
773
|
+
while input.key_log.len() > 1024 { input.key_log.pop_front(); }
|
|
774
|
+
} else {
|
|
775
|
+
input.keys_down.remove(name);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
#[wasm_bindgen]
|
|
780
|
+
pub fn rcompiler_web_mouse(x: f64, y: f64, down: bool) {
|
|
781
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return; };
|
|
782
|
+
let mut input = stage.input.lock().unwrap();
|
|
783
|
+
input.mouse_x = x; input.mouse_y = y; input.mouse_down = down;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
#[wasm_bindgen]
|
|
787
|
+
pub fn rcompiler_web_click(hit: i32) {
|
|
788
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return; };
|
|
789
|
+
let mut input = stage.input.lock().unwrap();
|
|
790
|
+
input.click_seq += 1;
|
|
791
|
+
let seq = input.click_seq;
|
|
792
|
+
input.click_log.push_back((seq, if hit < 0 { usize::MAX } else { hit as usize }));
|
|
793
|
+
while input.click_log.len() > 1024 { input.click_log.pop_front(); }
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
#[wasm_bindgen]
|
|
797
|
+
pub fn rcompiler_web_pause(paused: bool) {
|
|
798
|
+
RCOMPILER_PAUSED.store(paused, std::sync::atomic::Ordering::Relaxed);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
#[wasm_bindgen]
|
|
802
|
+
pub fn rcompiler_web_stop() {
|
|
803
|
+
if let Some(main) = RCOMPILER_MAIN.get() {
|
|
804
|
+
let m = std::sync::Arc::clone(main);
|
|
805
|
+
wasm_bindgen_futures::spawn_local(async move { m.rcompiler_stop_all().await; });
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
#[wasm_bindgen]
|
|
810
|
+
pub fn rcompiler_web_green_flag() {
|
|
811
|
+
RCOMPILER_PAUSED.store(false, std::sync::atomic::Ordering::Relaxed);
|
|
812
|
+
if let Some(main) = RCOMPILER_MAIN.get() {
|
|
813
|
+
let m = std::sync::Arc::clone(main);
|
|
814
|
+
m.stage.ask_cancel_all();
|
|
815
|
+
m.stage.ask_reset_answer();
|
|
816
|
+
m.stage.stop_all_clones();
|
|
817
|
+
m.stage.reset_visuals();
|
|
818
|
+
rcompiler_stop_tasks(None);
|
|
819
|
+
m.rcompiler_spawn_all();
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
#[wasm_bindgen]
|
|
824
|
+
pub fn rcompiler_web_monitor_rows() -> String {
|
|
825
|
+
let Some(main) = RCOMPILER_MAIN.get() else { return "[]".to_string(); };
|
|
826
|
+
let rows: Vec<String> = (0..RCOMPILER_MONITORS.len())
|
|
827
|
+
.map(|i| rcompiler_json_array(&main.rcompiler_monitor_get(i))).collect();
|
|
828
|
+
format!("[{}]", rows.join(","))
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
#[wasm_bindgen]
|
|
832
|
+
pub fn rcompiler_web_monitor_meta() -> String {
|
|
833
|
+
let mut parts: Vec<String> = Vec::new();
|
|
834
|
+
for m in RCOMPILER_MONITORS {
|
|
835
|
+
parts.push(format!(
|
|
836
|
+
r#"{{"kind":{},"label":{:?},"x":{},"y":{},"width":{},"height":{},"sliderMin":{},"sliderMax":{},"discrete":{}}}"#,
|
|
837
|
+
m.kind, rcompiler_name(m.label), m.x, m.y, m.width, m.height,
|
|
838
|
+
m.slider_min, m.slider_max, m.discrete
|
|
839
|
+
));
|
|
840
|
+
}
|
|
841
|
+
format!("[{}]", parts.join(","))
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
#[wasm_bindgen]
|
|
845
|
+
pub fn rcompiler_web_monitor_set(i: u32, v: f64) {
|
|
846
|
+
if let Some(main) = RCOMPILER_MAIN.get() { main.rcompiler_monitor_set(i as usize, v); }
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/// 询问视图:[id, label, use_bubble];无询问时为空数组
|
|
850
|
+
#[wasm_bindgen]
|
|
851
|
+
pub fn rcompiler_web_ask_view() -> Vec<String> {
|
|
852
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return vec![]; };
|
|
853
|
+
match stage.ask_view() {
|
|
854
|
+
Some((id, label, bubble)) => vec![id.to_string(), label, if bubble { "1".into() } else { "0".into() }],
|
|
855
|
+
None => vec![],
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
#[wasm_bindgen]
|
|
860
|
+
pub fn rcompiler_web_ask_submit(id: u32, answer: &str) {
|
|
861
|
+
let Some(stage) = RCOMPILER_STAGE.get() else { return; };
|
|
862
|
+
let _ = stage.ask_submit(id as u64, answer.to_string());
|
|
863
|
+
}
|
|
864
|
+
`;
|
|
865
|
+
|
|
866
|
+
// ---------------------------------------------------------------------------
|
|
867
|
+
// Rust:warp / 无舞台帧时钟 / 声音桥
|
|
868
|
+
// ---------------------------------------------------------------------------
|
|
869
|
+
|
|
870
|
+
const WEB_WARP = `
|
|
871
|
+
thread_local! {
|
|
872
|
+
static RCOMPILER_WARP_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
|
|
873
|
+
}
|
|
874
|
+
pub fn rcompiler_in_warp() -> bool { RCOMPILER_WARP_DEPTH.with(|c| c.get() > 0) }
|
|
875
|
+
pub struct RcompilerWarpGuard;
|
|
876
|
+
impl RcompilerWarpGuard {
|
|
877
|
+
pub fn enter() -> Self { RCOMPILER_WARP_DEPTH.with(|c| c.set(c.get() + 1)); RcompilerWarpGuard }
|
|
878
|
+
}
|
|
879
|
+
impl Drop for RcompilerWarpGuard {
|
|
880
|
+
fn drop(&mut self) { RCOMPILER_WARP_DEPTH.with(|c| c.set(c.get().saturating_sub(1))); }
|
|
881
|
+
}
|
|
882
|
+
pub fn rcompiler_script<F: std::future::Future<Output = ()> + 'static>(fut: F) -> impl std::future::Future<Output = ()> {
|
|
883
|
+
async move {
|
|
884
|
+
RCOMPILER_WARP_DEPTH.with(|c| c.set(0));
|
|
885
|
+
fut.await;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
`;
|
|
889
|
+
|
|
890
|
+
const WEB_WARP_SINGLE = `
|
|
891
|
+
thread_local! {
|
|
892
|
+
static RCOMPILER_WARP_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
|
|
893
|
+
}
|
|
894
|
+
pub fn rcompiler_in_warp() -> bool { RCOMPILER_WARP_DEPTH.with(|c| c.get() > 0) }
|
|
895
|
+
pub struct RcompilerWarpGuard;
|
|
896
|
+
impl RcompilerWarpGuard {
|
|
897
|
+
pub fn enter() -> Self { RCOMPILER_WARP_DEPTH.with(|c| c.set(c.get() + 1)); RcompilerWarpGuard }
|
|
898
|
+
}
|
|
899
|
+
impl Drop for RcompilerWarpGuard {
|
|
900
|
+
fn drop(&mut self) { RCOMPILER_WARP_DEPTH.with(|c| c.set(c.get().saturating_sub(1))); }
|
|
901
|
+
}
|
|
902
|
+
`;
|
|
903
|
+
|
|
904
|
+
const WEB_CLOCK_MULTI = `
|
|
905
|
+
pub fn rcompiler_start_clock(tps: f64) {
|
|
906
|
+
wasm_bindgen_futures::spawn_local(async move {
|
|
907
|
+
let tps = if tps > 0.0 { tps } else { 60.0 };
|
|
908
|
+
loop {
|
|
909
|
+
rcompiler_sleep(1.0 / tps).await;
|
|
910
|
+
rcompiler_notify_tick();
|
|
911
|
+
}
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
pub async fn frame_tick() { rcompiler_wait_tick().await; }
|
|
915
|
+
`;
|
|
916
|
+
|
|
917
|
+
const WEB_CLOCK_SINGLE = `
|
|
918
|
+
pub fn rcompiler_start_sync_clock(tps: f64) {
|
|
919
|
+
let tps = if tps > 0.0 { tps } else { 60.0 };
|
|
920
|
+
wasm_bindgen_futures::spawn_local(async move {
|
|
921
|
+
loop {
|
|
922
|
+
rcompiler_sleep(1.0 / tps).await;
|
|
923
|
+
rcompiler_notify_tick();
|
|
924
|
+
}
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
pub fn rcompiler_frame_wait() { /* 同步模式无异步等待;由 JS tick 推进 */ }
|
|
928
|
+
`;
|
|
929
|
+
|
|
930
|
+
const WEB_SOUND_BRIDGES = `
|
|
931
|
+
pub fn snd_play(&self, name: &str) -> Option<std::sync::Arc<Sink>> { self.audio.play(name) }
|
|
932
|
+
pub fn snd_stop_all(&self) { self.audio.stop_all(); }
|
|
933
|
+
pub fn snd_set_volume(&self, v: f64) { self.audio.set_volume(v); }
|
|
934
|
+
pub fn snd_change_volume(&self, d: f64) {
|
|
935
|
+
let v = self.audio.volume() + d;
|
|
936
|
+
self.audio.set_volume(v);
|
|
937
|
+
}
|
|
938
|
+
pub fn snd_volume(&self) -> f64 { self.audio.volume() }
|
|
939
|
+
`;
|
|
940
|
+
|
|
941
|
+
// ---------------------------------------------------------------------------
|
|
942
|
+
// 构建
|
|
943
|
+
// ---------------------------------------------------------------------------
|
|
944
|
+
|
|
945
|
+
function f64lit(n, dflt) {
|
|
946
|
+
const d = (dflt === undefined ? 0 : dflt);
|
|
947
|
+
const x = Number(n);
|
|
948
|
+
const v = Number.isFinite(x) ? x : d;
|
|
949
|
+
return Number.isInteger(v) ? v.toFixed(1) : String(v);
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function substitute(s, map) {
|
|
953
|
+
let out = s;
|
|
954
|
+
for (const [k, v] of Object.entries(map)) out = out.replaceAll('__' + k + '__', String(v));
|
|
955
|
+
return out;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
function build(profile, P) {
|
|
959
|
+
const frame = profile.frame || { gate: true, tps: 30, renderFps: 0, interpolation: false, turbo: false };
|
|
960
|
+
const size = profile.stageSize || { width: 480, height: 360 };
|
|
961
|
+
const obf = profile.antiReverse === 'obf';
|
|
962
|
+
if (obf) console.warn('\x1b[33mWASM 后端暂不启用资产混淆(obf),已按 normal 生成\x1b[m');
|
|
963
|
+
|
|
964
|
+
let stage = '';
|
|
965
|
+
let newWithStage = '';
|
|
966
|
+
let defaultImpl = '';
|
|
967
|
+
if (profile.hasStage) {
|
|
968
|
+
stage = substitute(WEB_STAGE, {
|
|
969
|
+
RCOMPILER_STAGE_W: f64lit(size.width, 480),
|
|
970
|
+
RCOMPILER_STAGE_H: f64lit(size.height, 360),
|
|
971
|
+
RCOMPILER_TPS: f64lit(frame.tps || 30, 30),
|
|
972
|
+
RCOMPILER_RENDER_FPS: f64lit(frame.renderFps || 0, 0),
|
|
973
|
+
RCOMPILER_FRAME_GATE: frame.gate ? 'true' : 'false',
|
|
974
|
+
RCOMPILER_INTERP: frame.interpolation ? 'true' : 'false',
|
|
975
|
+
RCOMPILER_ASK_RUNTIME: P.askRuntime
|
|
976
|
+
});
|
|
977
|
+
// 复用 native 的 s_* 桥接方法:只替换时间/让出/tokio 依赖。
|
|
978
|
+
const tail = P.defaultBridges.slice(P.defaultBridges.indexOf(' pub fn s_get_x'));
|
|
979
|
+
const bridges = `
|
|
980
|
+
pub async fn frame_wait(&self) {
|
|
981
|
+
while RCOMPILER_PAUSED.load(std::sync::atomic::Ordering::Relaxed) { rcompiler_sleep(0.01).await; }
|
|
982
|
+
if !RCOMPILER_FRAME_GATE { return; }
|
|
983
|
+
rcompiler_wait_tick().await;
|
|
984
|
+
}
|
|
985
|
+
pub async fn frame_delay(&self, secs: f64) {
|
|
986
|
+
let t0 = RcompilerInstant::now();
|
|
987
|
+
if RCOMPILER_FRAME_GATE {
|
|
988
|
+
rcompiler_wait_tick().await;
|
|
989
|
+
while t0.elapsed().as_secs_f64() < secs { rcompiler_wait_tick().await; }
|
|
990
|
+
} else if secs > 0.0 {
|
|
991
|
+
rcompiler_sleep(secs).await;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
// 舞台询问:共享队列 + DOM 输入框(JS 每帧读取 ask_view 并渲染)
|
|
995
|
+
pub async fn s_ask_and_wait(&self, idx: usize, question: String, is_stage: bool) {
|
|
996
|
+
let was_visible = {
|
|
997
|
+
let sp_arc = self.stage.sprite(idx);
|
|
998
|
+
let sp = sp_arc.lock().unwrap();
|
|
999
|
+
sp.visible && !sp.dead
|
|
1000
|
+
};
|
|
1001
|
+
let id = self.stage.ask_enqueue(question, idx, is_stage, was_visible);
|
|
1002
|
+
if let Some(ans) = self.stage.ask_wait(id).await {
|
|
1003
|
+
self.stage.ask_set_answer(ans);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
` + tail
|
|
1007
|
+
.replaceAll('std::time::Instant', 'RcompilerInstant')
|
|
1008
|
+
.replaceAll('tokio::time::sleep', 'rcompiler_sleep')
|
|
1009
|
+
.replaceAll('rcompiler_sleep(std::time::Duration::from_millis(16))', 'rcompiler_sleep(0.016)')
|
|
1010
|
+
.replaceAll('std::thread::yield_now', 'rcompiler_yield_now')
|
|
1011
|
+
.replaceAll('__RCOMPILER_STOP_SOUNDS__', profile.hasSound ? 'self.snd_stop_all();' : '');
|
|
1012
|
+
defaultImpl = bridges;
|
|
1013
|
+
|
|
1014
|
+
const lines = [
|
|
1015
|
+
'pub fn new_with_stage(stage: std::sync::Arc<StageShared>) -> Default {',
|
|
1016
|
+
' let mut d = Default::new();',
|
|
1017
|
+
' d.stage = std::sync::Arc::clone(&stage);'
|
|
1018
|
+
];
|
|
1019
|
+
profile.targets.forEach((t) => {
|
|
1020
|
+
if (t.isStage) return;
|
|
1021
|
+
lines.push(` stage.configure_sprite(${t.index}, ${f64lit(t.x)}, ${f64lit(t.y)}, ${f64lit(t.direction, 90)}, ${f64lit(t.size, 100)}, ${t.visible ? 'true' : 'false'}, ${t.index}i32, ${t.currentCostume || 0});`);
|
|
1022
|
+
});
|
|
1023
|
+
lines.push(' d.sprite_index = usize::MAX;', ' d', '}');
|
|
1024
|
+
newWithStage = lines.join('\n');
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
return {
|
|
1028
|
+
base: WEB_BASE,
|
|
1029
|
+
stage,
|
|
1030
|
+
sound: '',
|
|
1031
|
+
soundImpl: profile.hasSound ? WEB_SOUND_BRIDGES : '',
|
|
1032
|
+
taskMulti: require('./preludes').taskMultiWeb || makeTaskMultiWeb(),
|
|
1033
|
+
newWithStage,
|
|
1034
|
+
defaultImpl,
|
|
1035
|
+
warpMulti: WEB_WARP,
|
|
1036
|
+
warpSingle: WEB_WARP_SINGLE,
|
|
1037
|
+
clockMulti: substitute(WEB_CLOCK_MULTI, { RCOMPILER_TPS: f64lit(frame.tps || 30, 30) }),
|
|
1038
|
+
clockSingle: substitute(WEB_CLOCK_SINGLE, { RCOMPILER_TPS: f64lit(frame.tps || 30, 30) })
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// WASM 任务注册表(tokio 兼容层的类型)
|
|
1043
|
+
function makeTaskMultiWeb() {
|
|
1044
|
+
return `
|
|
1045
|
+
pub struct rcompiler_TaskRef {
|
|
1046
|
+
pub id: tokio::task::Id,
|
|
1047
|
+
pub idx: usize,
|
|
1048
|
+
pub abort: tokio::task::AbortHandle,
|
|
1049
|
+
}
|
|
1050
|
+
pub static RCOMPILER_TASKS: std::sync::Mutex<Vec<rcompiler_TaskRef>> = std::sync::Mutex::new(Vec::new());
|
|
1051
|
+
pub fn rcompiler_track_task(idx: usize, h: &tokio::task::JoinHandle<()>) {
|
|
1052
|
+
RCOMPILER_TASKS.lock().unwrap().push(rcompiler_TaskRef { id: h.id(), idx, abort: h.abort_handle() });
|
|
1053
|
+
}
|
|
1054
|
+
#[allow(unused_variables)]
|
|
1055
|
+
pub fn rcompiler_stop_tasks(idx_filter: Option<usize>) -> bool {
|
|
1056
|
+
let tasks = RCOMPILER_TASKS.lock().unwrap();
|
|
1057
|
+
let cur = tokio::task::try_id();
|
|
1058
|
+
let mut stopped_self = false;
|
|
1059
|
+
for t in tasks.iter() {
|
|
1060
|
+
if let Some(f) = idx_filter { if t.idx != f { continue; } }
|
|
1061
|
+
if let Some(cid) = cur { if t.id == cid { stopped_self = true; continue; } }
|
|
1062
|
+
t.abort.abort();
|
|
1063
|
+
}
|
|
1064
|
+
stopped_self
|
|
1065
|
+
}
|
|
1066
|
+
`;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// 让 preludes 无需知道 web.js(避免循环 require)
|
|
1070
|
+
require('./preludes').taskMultiWeb = makeTaskMultiWeb();
|
|
1071
|
+
|
|
1072
|
+
// ---------------------------------------------------------------------------
|
|
1073
|
+
// JS 宿主生成
|
|
1074
|
+
// ---------------------------------------------------------------------------
|
|
1075
|
+
|
|
1076
|
+
function writeWebHost(outDir, profile, opts = {}) {
|
|
1077
|
+
const webDir = path.join(outDir, 'web');
|
|
1078
|
+
fs.mkdirSync(webDir, { recursive: true });
|
|
1079
|
+
const title = String(opts.title || (profile.app && profile.app.title) || opts.name || 'rCompiler');
|
|
1080
|
+
const hasStage = !!profile.hasStage;
|
|
1081
|
+
const html = `<!doctype html>
|
|
1082
|
+
<html lang="zh-CN">
|
|
1083
|
+
<head>
|
|
1084
|
+
<meta charset="utf-8">
|
|
1085
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1086
|
+
<title>${escapeHtml(title)}</title>
|
|
1087
|
+
<style>
|
|
1088
|
+
html,body{margin:0;height:100%;background:#000;color:#fff;font:14px/1.4 system-ui,sans-serif;overflow:hidden}
|
|
1089
|
+
#wrap{position:fixed;inset:0;display:flex;align-items:center;justify-content:center}
|
|
1090
|
+
#stage-layer{position:relative;display:inline-block;line-height:0}
|
|
1091
|
+
#stage-layer canvas{display:block;max-width:100%;max-height:100%;width:auto;height:auto;image-rendering:auto}
|
|
1092
|
+
#stage-overlay{position:absolute;inset:0;overflow:hidden;pointer-events:none}
|
|
1093
|
+
#bar{position:fixed;left:8px;top:8px;display:flex;gap:6px;z-index:100}
|
|
1094
|
+
#bar button{background:#222;color:#fff;border:1px solid #555;border-radius:6px;padding:5px 10px;cursor:pointer}
|
|
1095
|
+
#bar button:hover{background:#333}
|
|
1096
|
+
.mon{position:absolute;font:12px/1.2 system-ui,sans-serif;color:#575e75;background:#fff;border:1px solid #ccd3dd;border-radius:4px;padding:2px 5px;z-index:5;user-select:none;white-space:pre-wrap;box-sizing:border-box}
|
|
1097
|
+
.mon.large{background:#ff8c1a;color:#fff;font-size:14px}
|
|
1098
|
+
.mon.list{max-height:200px;overflow:hidden;min-width:104px}
|
|
1099
|
+
.mon b{font-weight:600;margin-right:4px}
|
|
1100
|
+
.bubble{position:absolute;background:#fff;color:#575e75;border:1px solid rgba(0,0,0,.15);border-radius:16px;padding:10px 14px;font:14px/16px system-ui,sans-serif;max-width:170px;z-index:4;white-space:pre-wrap;pointer-events:none}
|
|
1101
|
+
.bubble.think{border-radius:16px}
|
|
1102
|
+
.question-wrap{position:absolute;left:8px;right:8px;bottom:8px;z-index:6;pointer-events:auto;background:#fff;border:2px solid rgba(0,0,0,.15);border-radius:8px;padding:16px;box-sizing:border-box}
|
|
1103
|
+
.question-label{font:bold 12px/15px system-ui,sans-serif;color:#575e75;padding-bottom:8px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
|
|
1104
|
+
.question-input{position:relative;display:flex}
|
|
1105
|
+
.question-input input{width:100%;height:32px;box-sizing:border-box;border:1px solid rgba(0,0,0,.15);border-radius:4px;padding:0 36px 0 8px;font:14px/32px system-ui,sans-serif;color:#575e75;background:#fff;outline:none}
|
|
1106
|
+
.question-input input:focus{box-shadow:0 0 0 3px rgba(76,151,255,.25)}
|
|
1107
|
+
.question-submit{position:absolute;right:4px;top:4px;width:24px;height:24px;border:none;border-radius:50%;background:#ff8c1a;color:#fff;cursor:pointer;font:14px/24px system-ui,sans-serif;padding:0}
|
|
1108
|
+
</style>
|
|
1109
|
+
</head>
|
|
1110
|
+
<body>
|
|
1111
|
+
<div id="wrap"><div id="stage-layer"><canvas id="stage"></canvas><div id="stage-overlay"></div></div></div>
|
|
1112
|
+
<div id="bar"></div>
|
|
1113
|
+
<script src="https://cdn.jsdelivr.net/npm/scratch-render@2.2.84/dist/web/scratch-render.min.js"></script>
|
|
1114
|
+
<script type="module">
|
|
1115
|
+
import { start } from './host.js';
|
|
1116
|
+
start({ hasStage: ${hasStage ? 'true' : 'false'} }).catch(e => {
|
|
1117
|
+
document.body.innerHTML = '<pre style="color:#f88;padding:20px;white-space:pre-wrap">' + (e && e.stack || e) + '</pre>';
|
|
1118
|
+
});
|
|
1119
|
+
</script>
|
|
1120
|
+
</body>
|
|
1121
|
+
</html>`;
|
|
1122
|
+
fs.writeFileSync(path.join(webDir, 'index.html'), html);
|
|
1123
|
+
fs.writeFileSync(path.join(webDir, 'host.js'), HOST_JS);
|
|
1124
|
+
fs.writeFileSync(path.join(webDir, '.gitignore'), 'rcompiler_wasm.js\nrcompiler_wasm_bg.wasm\nrcompiler_bg.wasm\n');
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
function escapeHtml(s) {
|
|
1128
|
+
return String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// 浏览器宿主:加载 manifest → 建 skin/drawable → init wasm → tick/draw
|
|
1132
|
+
const HOST_JS = String.raw`
|
|
1133
|
+
let manifest = null;
|
|
1134
|
+
let wasm = null;
|
|
1135
|
+
let audioCtx = null;
|
|
1136
|
+
let masterGain = null;
|
|
1137
|
+
let soundBuffers = new Map();
|
|
1138
|
+
let soundPlaying = new Map();
|
|
1139
|
+
let soundSeq = 1;
|
|
1140
|
+
let sndVolume = 100;
|
|
1141
|
+
|
|
1142
|
+
// 声音宿主(WASM 侧 SoundMixer 只持有 id)
|
|
1143
|
+
window.rcompilerHostSndPlay = (name) => {
|
|
1144
|
+
const buf = soundBuffers.get(name);
|
|
1145
|
+
if (!buf) return 0;
|
|
1146
|
+
try {
|
|
1147
|
+
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
|
1148
|
+
if (!masterGain) { masterGain = audioCtx.createGain(); masterGain.gain.value = sndVolume / 100; masterGain.connect(audioCtx.destination); }
|
|
1149
|
+
if (audioCtx.state === 'suspended') audioCtx.resume();
|
|
1150
|
+
const src = audioCtx.createBufferSource();
|
|
1151
|
+
src.buffer = buf; src.connect(masterGain); src.start();
|
|
1152
|
+
const id = soundSeq++;
|
|
1153
|
+
soundPlaying.set(id, src);
|
|
1154
|
+
src.onended = () => soundPlaying.delete(id);
|
|
1155
|
+
return id;
|
|
1156
|
+
} catch (_) { return 0; }
|
|
1157
|
+
};
|
|
1158
|
+
window.rcompilerHostSndStop = (id) => { const s = soundPlaying.get(id); if (s) { try { s.stop(); } catch (_) {} soundPlaying.delete(id); } };
|
|
1159
|
+
window.rcompilerHostSndStopAll = () => { for (const s of soundPlaying.values()) { try { s.stop(); } catch (_) {} } soundPlaying.clear(); };
|
|
1160
|
+
window.rcompilerHostSndVolume = (v) => { sndVolume = v; if (masterGain) masterGain.gain.value = v / 100; };
|
|
1161
|
+
window.rcompilerHostSndGetVolume = () => sndVolume;
|
|
1162
|
+
window.rcompilerHostSndPlaying = (id) => soundPlaying.has(id);
|
|
1163
|
+
// 无舞台 Web 项目回退(舞台项目使用 DOM 输入框,不经过这里)
|
|
1164
|
+
window.rcompilerHostAsk = (q) => { const a = window.prompt(q); return a == null ? '' : String(a); };
|
|
1165
|
+
window.rcompilerHostLog = (s) => { try { console.log(s); } catch (_) {} };
|
|
1166
|
+
let renderer = null;
|
|
1167
|
+
let penSkin = -1;
|
|
1168
|
+
let penDrawable = -1;
|
|
1169
|
+
let bgDrawable = -1;
|
|
1170
|
+
let spriteDrawables = new Map();
|
|
1171
|
+
let skinByCostume = new Map();
|
|
1172
|
+
let bubbleEls = new Map();
|
|
1173
|
+
let sayCache = new Map();
|
|
1174
|
+
let monitorEls = new Map();
|
|
1175
|
+
let monitorMeta = null;
|
|
1176
|
+
let lastState = new Map();
|
|
1177
|
+
let running = false;
|
|
1178
|
+
let overlayEl = null;
|
|
1179
|
+
let askEls = null;
|
|
1180
|
+
let askId = 0;
|
|
1181
|
+
|
|
1182
|
+
function findCostume(target, index) {
|
|
1183
|
+
return manifest.costumes.find(c => c.target === target && c.index === index);
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
function scratchToClient(x, y, canvas) {
|
|
1187
|
+
const r = canvas.getBoundingClientRect();
|
|
1188
|
+
return {
|
|
1189
|
+
x: r.left + ((x + manifest.stage.width / 2) / manifest.stage.width) * r.width,
|
|
1190
|
+
y: r.top + ((manifest.stage.height / 2 - y) / manifest.stage.height) * r.height
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
function clientToScratch(clientX, clientY, canvas) {
|
|
1194
|
+
const r = canvas.getBoundingClientRect();
|
|
1195
|
+
return {
|
|
1196
|
+
x: ((clientX - r.left) / r.width) * manifest.stage.width - manifest.stage.width / 2,
|
|
1197
|
+
y: manifest.stage.height / 2 - ((clientY - r.top) / r.height) * manifest.stage.height
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
async function loadSounds() {
|
|
1202
|
+
if (!manifest || !manifest.sounds) return;
|
|
1203
|
+
for (const s of manifest.sounds) {
|
|
1204
|
+
try {
|
|
1205
|
+
const buf = await (await fetch(s.file)).arrayBuffer();
|
|
1206
|
+
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
|
1207
|
+
const decoded = await audioCtx.decodeAudioData(buf.slice(0));
|
|
1208
|
+
soundBuffers.set(s.name, decoded);
|
|
1209
|
+
} catch (e) { console.warn('sound load failed', s, e); }
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
async function loadSkins() {
|
|
1214
|
+
for (const c of manifest.costumes) {
|
|
1215
|
+
try {
|
|
1216
|
+
if (c.svg) {
|
|
1217
|
+
const svg = await (await fetch(c.file)).text();
|
|
1218
|
+
// scratch-render 的 SVG skin 旋转中心使用原始 costume 坐标
|
|
1219
|
+
const id = renderer.createSVGSkin(svg, [c.rcx, c.rcy]);
|
|
1220
|
+
skinByCostume.set(c.target + ':' + c.index, id);
|
|
1221
|
+
} else {
|
|
1222
|
+
const img = new Image();
|
|
1223
|
+
img.crossOrigin = 'anonymous';
|
|
1224
|
+
img.src = c.file;
|
|
1225
|
+
await img.decode();
|
|
1226
|
+
const cv = document.createElement('canvas');
|
|
1227
|
+
cv.width = img.naturalWidth || c.w; cv.height = img.naturalHeight || c.h;
|
|
1228
|
+
const ctx = cv.getContext('2d');
|
|
1229
|
+
ctx.drawImage(img, 0, 0);
|
|
1230
|
+
const data = ctx.getImageData(0, 0, cv.width, cv.height);
|
|
1231
|
+
const id = renderer.createBitmapSkin(data, c.bmr || 1, [c.rcx, c.rcy]);
|
|
1232
|
+
skinByCostume.set(c.target + ':' + c.index, id);
|
|
1233
|
+
}
|
|
1234
|
+
} catch (e) {
|
|
1235
|
+
console.warn('costume load failed', c, e);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
function spriteInitialState(t) {
|
|
1241
|
+
return { x: t.x, y: t.y, dir: t.direction, scale: t.size / 100, alpha: 1, visible: t.visible, skin: 0, rot: 0 };
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
function ensureDrawable(i, st) {
|
|
1245
|
+
if (spriteDrawables.has(i)) return spriteDrawables.get(i);
|
|
1246
|
+
if (!renderer) return -1;
|
|
1247
|
+
const id = renderer.createDrawable(i === 0 ? 'background' : 'sprite');
|
|
1248
|
+
renderer.updateDrawableVisible(id, false);
|
|
1249
|
+
spriteDrawables.set(i, id);
|
|
1250
|
+
return id;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
function currentSkinFor(i, st) {
|
|
1254
|
+
const t = manifest.targets.find(t => t.index === i);
|
|
1255
|
+
if (!t) return null;
|
|
1256
|
+
const c = findCostume(i, t.currentCostume || 0);
|
|
1257
|
+
if (!c) return null;
|
|
1258
|
+
return skinByCostume.get(i + ':' + (t.currentCostume || 0));
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
async function syncSprites() {
|
|
1262
|
+
if (!renderer || !wasm) return;
|
|
1263
|
+
const n = wasm.rcompiler_web_sprite_count();
|
|
1264
|
+
const order = wasm.rcompiler_web_order();
|
|
1265
|
+
const orderPos = new Map(order.map((v, i) => [v, i]));
|
|
1266
|
+
for (let i = 0; i < n; i++) {
|
|
1267
|
+
const s = wasm.rcompiler_web_sprite_state(i);
|
|
1268
|
+
if (!s || s.length < 9) continue;
|
|
1269
|
+
const [x, y, dir, scale, alpha, visible, skin, rot] = s;
|
|
1270
|
+
const extra = wasm.rcompiler_web_sprite_extra(i);
|
|
1271
|
+
const dead = extra && extra[1] === 1;
|
|
1272
|
+
if (dead) {
|
|
1273
|
+
const d = spriteDrawables.get(i);
|
|
1274
|
+
if (d != null) renderer.updateDrawableVisible(d, false);
|
|
1275
|
+
const b = bubbleEls.get(i);
|
|
1276
|
+
if (b) b.style.display = 'none';
|
|
1277
|
+
continue;
|
|
1278
|
+
}
|
|
1279
|
+
let d = ensureDrawable(i, s);
|
|
1280
|
+
if (d < 0) continue;
|
|
1281
|
+
if (i === 0) continue;
|
|
1282
|
+
// skin 是全局 costume 索引;scratch-render 需要 skinId
|
|
1283
|
+
let skinId = null;
|
|
1284
|
+
if (wasm.rcompiler_web_sprite_skin) {
|
|
1285
|
+
const g = wasm.rcompiler_web_sprite_skin(i);
|
|
1286
|
+
const c = manifest.costumes.find(c => c.globalIndex === g);
|
|
1287
|
+
if (c) skinId = skinByCostume.get(c.target + ':' + c.index);
|
|
1288
|
+
}
|
|
1289
|
+
if (skinId == null) {
|
|
1290
|
+
const c = manifest.costumes.find(c => c.target === i);
|
|
1291
|
+
if (c) skinId = skinByCostume.get(c.target + ':' + c.index);
|
|
1292
|
+
}
|
|
1293
|
+
if (skinId != null) renderer.updateDrawableSkinId(d, skinId);
|
|
1294
|
+
renderer.updateDrawablePosition(d, [x, y]);
|
|
1295
|
+
renderer.updateDrawableDirectionScale(d, dir, [scale, scale]);
|
|
1296
|
+
renderer.updateDrawableVisible(d, visible !== 0);
|
|
1297
|
+
renderer.updateDrawableEffect(d, 'ghost', (1 - Math.max(0, Math.min(1, alpha))) * 100);
|
|
1298
|
+
const ord = orderPos.has(i) ? orderPos.get(i) : i;
|
|
1299
|
+
try { renderer.setDrawableOrder(d, ord, i === 0 ? 'background' : 'sprite', false); } catch (_) {}
|
|
1300
|
+
// 气泡
|
|
1301
|
+
const say = wasm.rcompiler_web_sprite_say(i);
|
|
1302
|
+
const kind = extra && extra[0] || 0;
|
|
1303
|
+
updateBubble(i, say, kind, x, y);
|
|
1304
|
+
}
|
|
1305
|
+
// 背景
|
|
1306
|
+
if (bgDrawable >= 0) {
|
|
1307
|
+
const bid = wasm.rcompiler_web_backdrop();
|
|
1308
|
+
const c = manifest.costumes.find(c => c.globalIndex === bid);
|
|
1309
|
+
if (c) { const sid = skinByCostume.get(c.target + ':' + c.index); if (sid != null) renderer.updateDrawableSkinId(bgDrawable, sid); }
|
|
1310
|
+
}
|
|
1311
|
+
// 画笔
|
|
1312
|
+
if (penSkin >= 0) {
|
|
1313
|
+
const cmds = wasm.rcompiler_web_pen_drain();
|
|
1314
|
+
let p = 0;
|
|
1315
|
+
while (p < cmds.length) {
|
|
1316
|
+
const k = cmds[p++];
|
|
1317
|
+
if (k === 2) { renderer.penClear(penSkin); }
|
|
1318
|
+
else if (k === 0) {
|
|
1319
|
+
const x0=cmds[p++], y0=cmds[p++], x1=cmds[p++], y1=cmds[p++];
|
|
1320
|
+
const r=cmds[p++], g=cmds[p++], b=cmds[p++], a=cmds[p++], size=cmds[p++];
|
|
1321
|
+
renderer.penLine(penSkin, {color4f:[r,g,b,a], diameter: size}, x0, y0, x1, y1);
|
|
1322
|
+
} else if (k === 1) {
|
|
1323
|
+
const sx=cmds[p++], sy=cmds[p++], dir=cmds[p++], scale=cmds[p++], alpha=cmds[p++], skin=cmds[p++], rot=cmds[p++];
|
|
1324
|
+
// 用临时 drawable 盖章;没有稳定 skin 映射时跳过
|
|
1325
|
+
const c = manifest.costumes.find(c => c.globalIndex === skin);
|
|
1326
|
+
if (c) {
|
|
1327
|
+
const sid = skinByCostume.get(c.target + ':' + c.index);
|
|
1328
|
+
if (sid != null) {
|
|
1329
|
+
let stamp = renderer.createDrawable('sprite');
|
|
1330
|
+
renderer.updateDrawableSkinId(stamp, sid);
|
|
1331
|
+
renderer.updateDrawablePosition(stamp, [sx, sy]);
|
|
1332
|
+
renderer.updateDrawableDirectionScale(stamp, dir, [scale, scale]);
|
|
1333
|
+
renderer.updateDrawableVisible(stamp, true);
|
|
1334
|
+
renderer.updateDrawableEffect(stamp, 'ghost', (1 - alpha) * 100);
|
|
1335
|
+
renderer.penStamp(penSkin, stamp);
|
|
1336
|
+
renderer.destroyDrawable(stamp, 'sprite');
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
updateMonitors();
|
|
1343
|
+
updateAsk();
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
function updateBubble(i, text, kind, x, y) {
|
|
1347
|
+
let el = bubbleEls.get(i);
|
|
1348
|
+
if (!text) { if (el) el.style.display = 'none'; return; }
|
|
1349
|
+
if (!el) {
|
|
1350
|
+
el = document.createElement('div');
|
|
1351
|
+
el.className = 'bubble' + (kind === 2 ? ' think' : '');
|
|
1352
|
+
(overlayEl || document.body).appendChild(el);
|
|
1353
|
+
bubbleEls.set(i, el);
|
|
1354
|
+
}
|
|
1355
|
+
if (sayCache.get(i) !== text) { el.textContent = text; sayCache.set(i, text); }
|
|
1356
|
+
el.style.display = 'block';
|
|
1357
|
+
el.style.left = ((x + manifest.stage.width / 2) + 20) + 'px';
|
|
1358
|
+
el.style.top = ((manifest.stage.height / 2 - y) - 20) + 'px';
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
function updateMonitors() {
|
|
1362
|
+
if (!wasm || !wasm.rcompiler_web_monitor_rows) return;
|
|
1363
|
+
if (!monitorMeta && wasm.rcompiler_web_monitor_meta) {
|
|
1364
|
+
try { monitorMeta = JSON.parse(wasm.rcompiler_web_monitor_meta()); } catch (_) { monitorMeta = []; }
|
|
1365
|
+
}
|
|
1366
|
+
let rows; try { rows = JSON.parse(wasm.rcompiler_web_monitor_rows()); } catch (_) { rows = []; }
|
|
1367
|
+
for (let i = 0; i < rows.length; i++) {
|
|
1368
|
+
const arr = rows[i] || [];
|
|
1369
|
+
let el = monitorEls.get(i);
|
|
1370
|
+
const m = (monitorMeta && monitorMeta[i]) || (manifest.monitors && manifest.monitors[i]) || {};
|
|
1371
|
+
if (!el) {
|
|
1372
|
+
el = document.createElement('div');
|
|
1373
|
+
el.className = 'mon' + (m.kind === 1 ? ' large' : (m.kind === 3 ? ' list' : ''));
|
|
1374
|
+
(overlayEl || document.body).appendChild(el);
|
|
1375
|
+
el.style.left = (m.x || 0) + 'px';
|
|
1376
|
+
el.style.top = (m.y || 0) + 'px';
|
|
1377
|
+
monitorEls.set(i, el);
|
|
1378
|
+
}
|
|
1379
|
+
const label = m.label || m.params && (m.params.VARIABLE || m.params.LIST) || m.opcode || '';
|
|
1380
|
+
if (m.kind === 3) el.textContent = label + '\n' + arr.map((v, j) => (j + 1) + '. ' + v).join('\n');
|
|
1381
|
+
else el.textContent = label + ' ' + (arr[0] == null ? '' : arr[0]);
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
function ensureAsk() {
|
|
1386
|
+
if (askEls) return askEls;
|
|
1387
|
+
const wrap = document.createElement('div');
|
|
1388
|
+
wrap.className = 'question-wrap';
|
|
1389
|
+
wrap.style.display = 'none';
|
|
1390
|
+
const label = document.createElement('div');
|
|
1391
|
+
label.className = 'question-label';
|
|
1392
|
+
const row = document.createElement('div');
|
|
1393
|
+
row.className = 'question-input';
|
|
1394
|
+
const input = document.createElement('input');
|
|
1395
|
+
input.type = 'text';
|
|
1396
|
+
input.autocomplete = 'off';
|
|
1397
|
+
const btn = document.createElement('button');
|
|
1398
|
+
btn.className = 'question-submit';
|
|
1399
|
+
btn.textContent = '➜';
|
|
1400
|
+
row.appendChild(input);
|
|
1401
|
+
row.appendChild(btn);
|
|
1402
|
+
wrap.appendChild(label);
|
|
1403
|
+
wrap.appendChild(row);
|
|
1404
|
+
(overlayEl || document.body).appendChild(wrap);
|
|
1405
|
+
const submit = () => {
|
|
1406
|
+
if (!askId || !wasm) return;
|
|
1407
|
+
const id = askId;
|
|
1408
|
+
askId = 0;
|
|
1409
|
+
wasm.rcompiler_web_ask_submit(id, input.value);
|
|
1410
|
+
input.value = '';
|
|
1411
|
+
wrap.style.display = 'none';
|
|
1412
|
+
};
|
|
1413
|
+
input.addEventListener('keydown', e => {
|
|
1414
|
+
if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); submit(); }
|
|
1415
|
+
});
|
|
1416
|
+
btn.addEventListener('click', submit);
|
|
1417
|
+
askEls = { wrap, label, input, btn };
|
|
1418
|
+
return askEls;
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
function updateAsk() {
|
|
1422
|
+
if (!wasm || !wasm.rcompiler_web_ask_view) return;
|
|
1423
|
+
let v;
|
|
1424
|
+
try { v = wasm.rcompiler_web_ask_view(); } catch (_) { v = []; }
|
|
1425
|
+
if (!v || !v.length) {
|
|
1426
|
+
if (askId) { askId = 0; if (askEls) { askEls.wrap.style.display = 'none'; askEls.input.blur(); } }
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
const els = ensureAsk();
|
|
1430
|
+
const id = Number(v[0]);
|
|
1431
|
+
const label = v[1] || '';
|
|
1432
|
+
const bubble = v[2] === '1';
|
|
1433
|
+
if (id !== askId) {
|
|
1434
|
+
askId = id;
|
|
1435
|
+
els.input.value = '';
|
|
1436
|
+
els.wrap.style.display = 'block';
|
|
1437
|
+
els.input.focus();
|
|
1438
|
+
}
|
|
1439
|
+
els.label.textContent = bubble ? '' : label;
|
|
1440
|
+
els.label.style.display = (!bubble && label) ? 'block' : 'none';
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
async function start({ hasStage }) {
|
|
1444
|
+
const canvas = document.getElementById('stage');
|
|
1445
|
+
overlayEl = document.getElementById('stage-overlay');
|
|
1446
|
+
const init = (await import('./rcompiler_wasm.js')).default;
|
|
1447
|
+
if (!hasStage) {
|
|
1448
|
+
await init();
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
manifest = await (await fetch('../assets/rcompiler_manifest.json')).json();
|
|
1452
|
+
const dpr = Math.max(1, Math.min(2, window.devicePixelRatio || 1));
|
|
1453
|
+
canvas.width = Math.round(manifest.stage.width * dpr);
|
|
1454
|
+
canvas.height = Math.round(manifest.stage.height * dpr);
|
|
1455
|
+
canvas.style.width = manifest.stage.width + 'px';
|
|
1456
|
+
canvas.style.height = manifest.stage.height + 'px';
|
|
1457
|
+
renderer = new window.ScratchRender(canvas);
|
|
1458
|
+
renderer.setStageSize(-manifest.stage.width / 2, manifest.stage.width / 2, -manifest.stage.height / 2, manifest.stage.height / 2);
|
|
1459
|
+
renderer.setLayerGroupOrdering(['background', 'pen', 'sprite', 'bubble']);
|
|
1460
|
+
await loadSkins();
|
|
1461
|
+
await loadSounds();
|
|
1462
|
+
bgDrawable = renderer.createDrawable('background');
|
|
1463
|
+
const bd = manifest.costumes.find(c => c.target === 0);
|
|
1464
|
+
if (bd) { const sid = skinByCostume.get(bd.target + ':' + bd.index); if (sid != null) { renderer.updateDrawableSkinId(bgDrawable, sid); renderer.updateDrawablePosition(bgDrawable, [0, 0]); renderer.updateDrawableVisible(bgDrawable, true); } }
|
|
1465
|
+
penSkin = renderer.createPenSkin();
|
|
1466
|
+
penDrawable = renderer.createDrawable('pen');
|
|
1467
|
+
renderer.updateDrawableSkinId(penDrawable, penSkin);
|
|
1468
|
+
renderer.updateDrawablePosition(penDrawable, [0, 0]);
|
|
1469
|
+
renderer.updateDrawableVisible(penDrawable, true);
|
|
1470
|
+
for (const t of manifest.targets) {
|
|
1471
|
+
if (t.isStage) continue;
|
|
1472
|
+
const d = renderer.createDrawable('sprite');
|
|
1473
|
+
spriteDrawables.set(t.index, d);
|
|
1474
|
+
const c = manifest.costumes.find(c => c.target === t.index);
|
|
1475
|
+
if (c) { const sid = skinByCostume.get(t.index + ':' + c.index); if (sid != null) renderer.updateDrawableSkinId(d, sid); }
|
|
1476
|
+
renderer.updateDrawablePosition(d, [t.x, t.y]);
|
|
1477
|
+
renderer.updateDrawableDirectionScale(d, t.direction, [(t.size || 100) / 100, (t.size || 100) / 100]);
|
|
1478
|
+
renderer.updateDrawableVisible(d, t.visible !== false);
|
|
1479
|
+
}
|
|
1480
|
+
// 顶栏
|
|
1481
|
+
const bar = document.getElementById('bar');
|
|
1482
|
+
const app = manifest.app || {};
|
|
1483
|
+
if (app.btnFlag !== false) { const b = document.createElement('button'); b.textContent = '▶'; b.onclick = () => { if (wasm) wasm.rcompiler_web_green_flag(); }; bar.appendChild(b); }
|
|
1484
|
+
if (app.btnPause) { const b = document.createElement('button'); b.textContent = '⏸'; b.onclick = () => { running = !running; if (wasm) wasm.rcompiler_web_pause(!running); b.textContent = running ? '⏸' : '▶'; }; bar.appendChild(b); }
|
|
1485
|
+
if (app.btnStop) { const b = document.createElement('button'); b.textContent = '■'; b.onclick = () => { if (wasm) wasm.rcompiler_web_stop(); }; bar.appendChild(b); }
|
|
1486
|
+
// 输入
|
|
1487
|
+
canvas.addEventListener('pointermove', e => {
|
|
1488
|
+
const p = clientToScratch(e.clientX, e.clientY, canvas);
|
|
1489
|
+
if (wasm) wasm.rcompiler_web_mouse(p.x, p.y, e.buttons !== 0);
|
|
1490
|
+
});
|
|
1491
|
+
canvas.addEventListener('pointerdown', e => {
|
|
1492
|
+
const p = clientToScratch(e.clientX, e.clientY, canvas);
|
|
1493
|
+
if (wasm) wasm.rcompiler_web_mouse(p.x, p.y, true);
|
|
1494
|
+
const hit = renderer.pick(e.clientX, e.clientY);
|
|
1495
|
+
let target = -1;
|
|
1496
|
+
for (const [i, d] of spriteDrawables) if (d === hit) target = i;
|
|
1497
|
+
if (wasm) wasm.rcompiler_web_click(target);
|
|
1498
|
+
});
|
|
1499
|
+
canvas.addEventListener('pointerup', e => {
|
|
1500
|
+
const p = clientToScratch(e.clientX, e.clientY, canvas);
|
|
1501
|
+
if (wasm) wasm.rcompiler_web_mouse(p.x, p.y, false);
|
|
1502
|
+
});
|
|
1503
|
+
canvas.addEventListener('pointerleave', () => { if (wasm) wasm.rcompiler_web_mouse(0, 0, false); });
|
|
1504
|
+
window.addEventListener('keydown', e => {
|
|
1505
|
+
if (!wasm) return;
|
|
1506
|
+
if (e.target && e.target.tagName === 'INPUT') return;
|
|
1507
|
+
wasm.rcompiler_web_key(normalizeKey(e.key), true);
|
|
1508
|
+
if (e.key.length === 1 || e.key === ' ') e.preventDefault();
|
|
1509
|
+
});
|
|
1510
|
+
window.addEventListener('keyup', e => { if (wasm) wasm.rcompiler_web_key(normalizeKey(e.key), false); });
|
|
1511
|
+
|
|
1512
|
+
await init();
|
|
1513
|
+
wasm = await import('./rcompiler_wasm.js').then(m => m);
|
|
1514
|
+
running = true;
|
|
1515
|
+
const tps = (manifest.frame && manifest.frame.tps > 0) ? manifest.frame.tps : 30;
|
|
1516
|
+
let last = performance.now(), acc = 0;
|
|
1517
|
+
const frame = (now) => {
|
|
1518
|
+
if (!running) { last = now; requestAnimationFrame(frame); return; }
|
|
1519
|
+
acc += now - last; last = now;
|
|
1520
|
+
const period = 1000 / tps;
|
|
1521
|
+
let n = 0;
|
|
1522
|
+
while (acc >= period && n < 8) { if (wasm) wasm.rcompiler_web_tick(); acc -= period; n++; }
|
|
1523
|
+
if (acc > period * 8) acc = 0;
|
|
1524
|
+
syncSprites().then(() => { renderer.draw(); requestAnimationFrame(frame); })
|
|
1525
|
+
.catch(e => { console.error(e); requestAnimationFrame(frame); });
|
|
1526
|
+
};
|
|
1527
|
+
requestAnimationFrame(frame);
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
function normalizeKey(k) {
|
|
1531
|
+
if (k === ' ') return 'space';
|
|
1532
|
+
if (k === 'ArrowUp') return 'up arrow';
|
|
1533
|
+
if (k === 'ArrowDown') return 'down arrow';
|
|
1534
|
+
if (k === 'ArrowLeft') return 'left arrow';
|
|
1535
|
+
if (k === 'ArrowRight') return 'right arrow';
|
|
1536
|
+
if (k === 'Enter') return 'enter';
|
|
1537
|
+
if (k === 'Escape') return 'escape';
|
|
1538
|
+
if (k === 'Backspace') return 'backspace';
|
|
1539
|
+
if (k === 'Delete') return 'delete';
|
|
1540
|
+
if (k === 'Home') return 'home';
|
|
1541
|
+
if (k === 'End') return 'end';
|
|
1542
|
+
return k.length === 1 ? k.toLowerCase() : k.toLowerCase();
|
|
1543
|
+
}
|
|
1544
|
+
`;
|
|
1545
|
+
|
|
1546
|
+
// ---------------------------------------------------------------------------
|
|
1547
|
+
// 构建后处理:wasm-bindgen → web/rcompiler_wasm.js + rcompiler_wasm_bg.wasm
|
|
1548
|
+
// ---------------------------------------------------------------------------
|
|
1549
|
+
|
|
1550
|
+
function finishWebBuild(projectDir, profile, opts = {}) {
|
|
1551
|
+
return Promise.resolve().then(() => {
|
|
1552
|
+
const targetDir = path.join(projectDir, 'target', 'wasm32-unknown-unknown', opts.release ? 'release' : 'debug');
|
|
1553
|
+
const wasmCandidates = [
|
|
1554
|
+
path.join(targetDir, `${opts.name}.wasm`),
|
|
1555
|
+
path.join(targetDir, 'rcompiler_app.wasm')
|
|
1556
|
+
];
|
|
1557
|
+
let input = wasmCandidates.find(p => fs.existsSync(p));
|
|
1558
|
+
if (!input && fs.existsSync(targetDir)) {
|
|
1559
|
+
// cdylib 产物名可能随包名净化/下划线规则变化:兜底扫描
|
|
1560
|
+
const found = fs.readdirSync(targetDir).filter(f => f.endsWith('.wasm'))
|
|
1561
|
+
.map(f => path.join(targetDir, f));
|
|
1562
|
+
if (found.length) input = found[0];
|
|
1563
|
+
}
|
|
1564
|
+
if (!input) throw new Error('找不到 wasm 产物:' + wasmCandidates.join(' 或 '));
|
|
1565
|
+
const outDir = opts.outDir ? path.join(opts.outDir, 'web') : path.join(projectDir, 'web');
|
|
1566
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
1567
|
+
const pkgRoot = opts.outDir || projectDir;
|
|
1568
|
+
const bin = process.env.WASM_BINDGEN || 'wasm-bindgen';
|
|
1569
|
+
const r = spawnSync(bin, ['--target', 'web', '--out-dir', outDir, '--out-name', 'rcompiler_wasm', input], { stdio: 'inherit' });
|
|
1570
|
+
if (r.error || r.status !== 0) {
|
|
1571
|
+
throw new Error(`wasm-bindgen 失败(${r.error ? r.error.message : 'exit ' + r.status})。请安装:cargo install wasm-bindgen-cli`);
|
|
1572
|
+
}
|
|
1573
|
+
// 复制 index/host 到目标目录(若产物目录不同)
|
|
1574
|
+
if (opts.outDir) {
|
|
1575
|
+
const srcWeb = path.join(projectDir, 'web');
|
|
1576
|
+
for (const f of ['index.html', 'host.js']) {
|
|
1577
|
+
if (fs.existsSync(path.join(srcWeb, f))) fs.copyFileSync(path.join(srcWeb, f), path.join(outDir, f));
|
|
1578
|
+
}
|
|
1579
|
+
if (fs.existsSync(path.join(projectDir, 'assets'))) {
|
|
1580
|
+
fs.cpSync(path.join(projectDir, 'assets'), path.join(pkgRoot, 'assets'), { recursive: true });
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
const index = path.join(outDir, 'index.html');
|
|
1584
|
+
console.log(`\x1b[32m构建完成\x1b[m: ${index}`);
|
|
1585
|
+
if (opts.run) {
|
|
1586
|
+
console.log(`用静态服务器打开:cd ${projectDir} && python3 -m http.server 8080`);
|
|
1587
|
+
console.log('然后访问 http://localhost:8080/web/');
|
|
1588
|
+
}
|
|
1589
|
+
return { index, wasm: input };
|
|
1590
|
+
});
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
module.exports = { build, writeWebHost, finishWebBuild, WEB_BASE, WEB_STAGE };
|