Skip to main content

ling/runtime/
mod.rs

1// src/runtime/mod.rs — tree-walking interpreter with graphics support
2use std::cell::RefCell;
3use std::collections::HashMap;
4use crate::parser::ast::*;
5use crate::gfx::{GfxState, Light};
6#[cfg(not(target_arch = "wasm32"))]
7use crate::gfx::raster::{fill_triangle, draw_line};
8#[cfg(not(target_arch = "wasm32"))]
9use ling_audio::{AudioEngine, ToneParams, Wave};
10
11#[cfg(not(target_arch = "wasm32"))]
12use ling_audio::FftAnalyzer;
13
14#[cfg(not(target_arch = "wasm32"))]
15use ling_mic;
16
17// ─── Values ──────────────────────────────────────────────────────────────────
18
19#[derive(Debug, Clone)]
20pub enum Value {
21    Str(String),
22    Number(f64),
23    Bool(bool),
24    Unit,
25    List(Vec<Value>),
26    Ok(Box<Value>),
27    Err(Box<Value>),
28    Fn(Vec<String>, Vec<Stmt>, Env),
29}
30
31type Env = HashMap<String, Value>;
32
33impl std::fmt::Display for Value {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Value::Str(s)    => write!(f, "{s}"),
37            Value::Number(n) => {
38                if n.fract() == 0.0 && n.abs() < 1e15 { write!(f, "{}", *n as i64) }
39                else { write!(f, "{n}") }
40            }
41            Value::Bool(b)   => write!(f, "{b}"),
42            Value::Unit      => write!(f, "()"),
43            Value::List(v)   => {
44                write!(f, "[")?;
45                for (i, x) in v.iter().enumerate() {
46                    if i > 0 { write!(f, ", ")?; }
47                    write!(f, "{x}")?;
48                }
49                write!(f, "]")
50            }
51            Value::Ok(v)     => write!(f, "Ok({v})"),
52            Value::Err(v)    => write!(f, "Err({v})"),
53            Value::Fn(_, _, _) => write!(f, "<fn>"),
54        }
55    }
56}
57
58// ─── Control flow ────────────────────────────────────────────────────────────
59
60#[derive(Debug)]
61enum EvalErr {
62    Runtime(String),
63    Return(Value),
64    #[allow(dead_code)] // reserved for future `break` statement support
65    Break,
66}
67
68impl From<String> for EvalErr {
69    fn from(s: String) -> Self { EvalErr::Runtime(s) }
70}
71
72type EvalResult = Result<Value, EvalErr>;
73
74// GfxState is now defined in crate::gfx — see src/gfx/mod.rs.
75
76// ─── SVG writer ───────────────────────────────────────────────────────────────
77
78struct SvgWriter {
79    path:     String,
80    width:    f64,
81    height:   f64,
82    elements: Vec<String>,
83}
84
85impl SvgWriter {
86    fn new(path: String, width: f64, height: f64) -> Self {
87        let bg = format!(
88            "<rect width=\"{width}\" height=\"{height}\" fill=\"#0a0a0a\"/>"
89        );
90        Self { path, width, height, elements: vec![bg] }
91    }
92
93    fn save(&self) -> std::io::Result<()> {
94        let w = self.width;
95        let h = self.height;
96        let mut out = format!(
97            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
98             <svg xmlns=\"http://www.w3.org/2000/svg\" \
99             width=\"{w}\" height=\"{h}\" viewBox=\"0 0 {w} {h}\">\n"
100        );
101        for elem in &self.elements {
102            out.push_str("  ");
103            out.push_str(elem);
104            out.push('\n');
105        }
106        out.push_str("</svg>\n");
107        // Create parent directory if it doesn't exist.
108        if let Some(parent) = std::path::Path::new(&self.path).parent() {
109            if !parent.as_os_str().is_empty() {
110                let _ = std::fs::create_dir_all(parent);
111            }
112        }
113        std::fs::write(&self.path, out.as_bytes())
114    }
115}
116
117fn hsl_to_hex(h: f64, s: f64, l: f64) -> String {
118    let s = s / 100.0;
119    let l = l / 100.0;
120    let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
121    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
122    let m = l - c / 2.0;
123    let (r1, g1, b1) = if h < 60.0       { (c, x, 0.0) }
124                       else if h < 120.0  { (x, c, 0.0) }
125                       else if h < 180.0  { (0.0, c, x) }
126                       else if h < 240.0  { (0.0, x, c) }
127                       else if h < 300.0  { (x, 0.0, c) }
128                       else               { (c, 0.0, x) };
129    let r = ((r1 + m) * 255.0).round() as u8;
130    let g = ((g1 + m) * 255.0).round() as u8;
131    let b = ((b1 + m) * 255.0).round() as u8;
132    format!("#{r:02x}{g:02x}{b:02x}")
133}
134
135// ─── Procedural texture helpers ───────────────────────────────────────────────
136
137fn tex_hash(x: i32, y: i32, seed: u32) -> f32 {
138    let mut h = (x as u32).wrapping_add((y as u32).wrapping_mul(2654435769)).wrapping_add(seed.wrapping_mul(1234567891));
139    h ^= h >> 16; h = h.wrapping_mul(0x45d9f3b); h ^= h >> 16;
140    h as f32 / u32::MAX as f32
141}
142
143fn tex_vnoise(x: f32, y: f32, seed: u32) -> f32 {
144    let xi = x.floor() as i32; let yi = y.floor() as i32;
145    let sm = |t: f32| t * t * (3.0 - 2.0 * t);
146    let xf = sm(x - xi as f32); let yf = sm(y - yi as f32);
147    let a = tex_hash(xi, yi, seed); let b = tex_hash(xi+1, yi, seed);
148    let c = tex_hash(xi, yi+1, seed); let d = tex_hash(xi+1, yi+1, seed);
149    a + (b-a)*xf + (c-a)*yf + (a-b-c+d)*xf*yf
150}
151
152fn tex_fbm(x: f32, y: f32, octaves: u32, seed: u32) -> f32 {
153    let mut v = 0.0f32; let mut amp = 0.5f32; let mut f = 1.0f32;
154    for i in 0..octaves {
155        v += tex_vnoise(x * f, y * f, seed.wrapping_add(i * 7919)) * amp;
156        amp *= 0.5; f *= 2.0;
157    }
158    v
159}
160
161fn tex_palette(name: &str, t: f32) -> [f32; 3] {
162    let (a, b, c, d): ([f32;3],[f32;3],[f32;3],[f32;3]) = match name {
163        "fire"        => ([0.8,0.4,0.1],[0.7,0.3,0.1],[1.0,0.5,0.3],[0.0,0.5,0.8]),
164        "ocean"       => ([0.1,0.4,0.7],[0.3,0.3,0.4],[0.8,1.0,0.5],[0.3,0.0,0.6]),
165        "psychedelic" => ([0.5,0.5,0.5],[0.8,0.8,0.8],[1.0,1.3,0.7],[0.0,0.15,0.3]),
166        "neon"        => ([0.5,0.5,0.5],[0.5,0.5,0.5],[2.0,1.0,0.0],[0.5,0.2,0.25]),
167        "forest"      => ([0.3,0.5,0.2],[0.2,0.3,0.1],[1.0,0.5,0.8],[0.1,0.3,0.6]),
168        _             => ([0.5,0.5,0.5],[0.5,0.5,0.5],[1.0,1.0,1.0],[0.0,0.333,0.667]),
169    };
170    [0,1,2].map(|i| (a[i] + b[i] * (std::f32::consts::TAU * (c[i] * t + d[i])).cos()).clamp(0.0, 1.0))
171}
172
173/// Map a physical key to a typed character for ling-ui text input (lowercase).
174#[cfg(not(target_arch = "wasm32"))]
175fn key_char(k: minifb::Key) -> Option<char> {
176    use minifb::Key::*;
177    Some(match k {
178        A=>'a',B=>'b',C=>'c',D=>'d',E=>'e',F=>'f',G=>'g',H=>'h',I=>'i',J=>'j',K=>'k',L=>'l',M=>'m',
179        N=>'n',O=>'o',P=>'p',Q=>'q',R=>'r',S=>'s',T=>'t',U=>'u',V=>'v',W=>'w',X=>'x',Y=>'y',Z=>'z',
180        Key0=>'0',Key1=>'1',Key2=>'2',Key3=>'3',Key4=>'4',Key5=>'5',Key6=>'6',Key7=>'7',Key8=>'8',Key9=>'9',
181        Space=>' ', Minus=>'-', Period=>'.',
182        _ => return None,
183    })
184}
185
186/// Lowercase-hex encode bytes (the wire format for crypto values in Ling).
187fn hex_encode(bytes: &[u8]) -> String {
188    let mut s = String::with_capacity(bytes.len() * 2);
189    for b in bytes { s.push_str(&format!("{b:02x}")); }
190    s
191}
192
193/// Decode a lowercase/uppercase hex string to bytes (ignores malformed tail).
194fn hex_decode(s: &str) -> Vec<u8> {
195    let s = s.trim();
196    (0..s.len() / 2)
197        .filter_map(|i| u8::from_str_radix(s.get(i * 2..i * 2 + 2)?, 16).ok())
198        .collect()
199}
200
201/// Decode a hex string into a fixed 32-byte key (zero-padded / truncated).
202fn hex_to_32(s: &str) -> [u8; 32] {
203    let v = hex_decode(s);
204    let mut out = [0u8; 32];
205    let n = v.len().min(32);
206    out[..n].copy_from_slice(&v[..n]);
207    out
208}
209
210fn tex_rgb(r: f32, g: f32, b: f32) -> u32 {
211    ((r * 255.0) as u32) << 16 | ((g * 255.0) as u32) << 8 | (b * 255.0) as u32
212}
213
214// ─── 3D Perlin Noise (Improved Perlin 2002) ───────────────────────────────────
215
216const PERM: [u8; 512] = [
217    151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,
218    140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,
219    247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,
220    57,177,33,88,237,149,56,87,174,35,63,189,114,56,42,123,
221    165,38,72,93,69,139,138,78,149,159,56,89,152,78,61,140,
222    63,26,142,76,124,132,72,11,90,44,82,59,96,41,148,126,
223    157,13,49,27,176,33,47,14,97,78,71,40,87,183,4,122,
224    92,7,72,3,246,17,225,87,91,106,203,190,57,74,76,88,
225    207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,
226    168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,
227    210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,
228    115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,
229    219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,
230    121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,
231    8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,
232    138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,
233    158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,
234    223,140,161,137,13,191,230,66,104,153,199,167,147,99,179,92,
235    // Duplicate for wrap-around indexing
236    151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,
237    140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,
238    247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,
239    57,177,33,88,237,149,56,87,174,35,63,189,114,56,42,123,
240    165,38,72,93,69,139,138,78,149,159,56,89,152,78,61,140,
241    63,26,142,76,124,132,72,11,90,44,82,59,96,41,148,126,
242    157,13,49,27,176,33,47,14,97,78,71,40,87,183,4,122,
243    92,7,72,3,246,17,225,87,91,106,203,190,57,74,76,88,
244    207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,
245    168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,
246    210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,
247    115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,
248    219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,
249    121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,
250];
251
252fn fade(t: f32) -> f32 {
253    t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
254}
255
256fn grad(hash: u8, x: f32, y: f32, z: f32) -> f32 {
257    let h = hash & 15;
258    let u = if h < 8 { x } else { y };
259    let v = if h < 8 { y } else { z };
260    (if (h & 1) == 0 { u } else { -u }) + (if (h & 2) == 0 { v } else { -v })
261}
262
263fn perlin3(x: f32, y: f32, z: f32) -> f32 {
264    let xi = (x.floor() as i32) & 255;
265    let yi = (y.floor() as i32) & 255;
266    let zi = (z.floor() as i32) & 255;
267
268    let xf = x - x.floor();
269    let yf = y - y.floor();
270    let zf = z - z.floor();
271
272    let u = fade(xf);
273    let v = fade(yf);
274    let w = fade(zf);
275
276    let p0 = PERM[xi as usize] as usize;
277    let p1 = PERM[((xi + 1) & 255) as usize] as usize;
278    let pa = PERM[(p0 + yi as usize) & 255] as usize;
279    let pb = PERM[(p0 + ((yi + 1) & 255) as usize) & 255] as usize;
280    let pc = PERM[(p1 + yi as usize) & 255] as usize;
281    let pd = PERM[(p1 + ((yi + 1) & 255) as usize) & 255] as usize;
282
283    let g000 = grad(PERM[(pa + zi as usize) & 255], xf, yf, zf);
284    let g001 = grad(PERM[(pa + ((zi + 1) & 255) as usize) & 255], xf, yf, zf - 1.0);
285    let g010 = grad(PERM[(pb + zi as usize) & 255], xf, yf - 1.0, zf);
286    let g011 = grad(PERM[(pb + ((zi + 1) & 255) as usize) & 255], xf, yf - 1.0, zf - 1.0);
287    let g100 = grad(PERM[(pc + zi as usize) & 255], xf - 1.0, yf, zf);
288    let g101 = grad(PERM[(pc + ((zi + 1) & 255) as usize) & 255], xf - 1.0, yf, zf - 1.0);
289    let g110 = grad(PERM[(pd + zi as usize) & 255], xf - 1.0, yf - 1.0, zf);
290    let g111 = grad(PERM[(pd + ((zi + 1) & 255) as usize) & 255], xf - 1.0, yf - 1.0, zf - 1.0);
291
292    let l00 = g000 + u * (g100 - g000);
293    let l01 = g001 + u * (g101 - g001);
294    let l10 = g010 + u * (g110 - g010);
295    let l11 = g011 + u * (g111 - g011);
296
297    let l0 = l00 + v * (l10 - l00);
298    let l1 = l01 + v * (l11 - l01);
299
300    l0 + w * (l1 - l0)
301}
302
303fn fast_rand_f64(state: &mut u64) -> f64 {
304    *state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
305    ((*state >> 32) as u32) as f64 / 4294967296.0
306}
307
308// ─── Circle Drawing Primitives ────────────────────────────────────────────────
309
310/// Write one pixel into the framebuffer (normal or additive blend).
311#[inline]
312fn put_px(buf: &mut [u32], idx: usize, color: u32, blend: u8) {
313    if idx >= buf.len() { return; }
314    if blend == 0 {
315        buf[idx] = color;
316    } else {
317        let old = buf[idx];
318        let r = (((old >> 16) & 255) + ((color >> 16) & 255)).min(255);
319        let g = (((old >> 8) & 255) + ((color >> 8) & 255)).min(255);
320        let b = ((old & 255) + (color & 255)).min(255);
321        buf[idx] = (r << 16) | (g << 8) | b;
322    }
323}
324
325fn draw_circle_outline(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, r: i32, color: u32, blend: u8) {
326    let r = r.clamp(0, 20000); // guard against overflow / runaway from tiny depths
327    if r == 0 { return; }
328    let mut x = 0;
329    let mut y = r;
330    let mut d = 3 - 2 * r;
331    while x <= y {
332        plot_circle_points(buf, w, h, cx, cy, x, y, color, blend);
333        if d < 0 {
334            d += 4 * x + 6;
335        } else {
336            d += 4 * (x - y) + 10;
337            y -= 1;
338        }
339        x += 1;
340    }
341}
342
343fn plot_circle_points(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, x: i32, y: i32, color: u32, blend: u8) {
344    let points = [(cx+x, cy+y), (cx-x, cy+y), (cx+x, cy-y), (cx-x, cy-y),
345                  (cx+y, cy+x), (cx-y, cy+x), (cx+y, cy-x), (cx-y, cy-x)];
346    for &(px, py) in &points {
347        if px >= 0 && px < w && py >= 0 && py < h {
348            put_px(buf, (py * w + px) as usize, color, blend);
349        }
350    }
351}
352
353fn draw_circle_filled(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, r: i32, color: u32, blend: u8) {
354    if r <= 0 { return; }
355    for dy in -r..=r {
356        let dx_max = ((r*r - dy*dy) as f64).sqrt() as i32;
357        let py = cy + dy;
358        if py < 0 || py >= h { continue; }
359        for dx in -dx_max..=dx_max {
360            let px = cx + dx;
361            if px >= 0 && px < w {
362                put_px(buf, (py * w + px) as usize, color, blend);
363            }
364        }
365    }
366}
367
368#[cfg(test)]
369mod draw_tests {
370    use super::*;
371
372    #[test]
373    fn filled_circle_actually_writes_pixels() {
374        let mut buf = vec![0u32; 100 * 100];
375        draw_circle_filled(&mut buf, 100, 100, 50, 50, 10, 0xFF00FF, 0);
376        assert_eq!(buf[50 * 100 + 50], 0xFF00FF, "centre pixel must be filled");
377        assert_eq!(buf[0], 0, "far corner must stay clear");
378        let n = buf.iter().filter(|&&p| p != 0).count();
379        assert!(n > 200 && n < 500, "r=10 disc area ≈ 314, got {n}");
380    }
381
382    #[test]
383    fn circle_outline_writes_a_ring() {
384        let mut buf = vec![0u32; 100 * 100];
385        draw_circle_outline(&mut buf, 100, 100, 50, 50, 20, 0x00FF00, 0);
386        assert_eq!(buf[50 * 100 + 50], 0, "outline must NOT fill the centre");
387        assert!(buf.iter().any(|&p| p == 0x00FF00), "outline must draw a ring");
388    }
389
390    #[test]
391    fn additive_blend_accumulates_channels() {
392        let mut buf = vec![0x202020u32; 1];
393        put_px(&mut buf, 0, 0x404040, 1);
394        assert_eq!(buf[0], 0x606060);
395    }
396}
397
398// ─── Interpreter ─────────────────────────────────────────────────────────────
399
400/// Customizable colour palette for the vector UI toolkit (packed 0x00RRGGBB).
401/// `ui_theme(...)` sets it; every widget falls back to these and accepts a
402/// trailing `r,g,b` override.
403#[derive(Clone, Copy)]
404pub struct UiTheme {
405    pub primary: u32,
406    pub accent:  u32,
407    pub track:   u32,
408    pub warn:    u32,
409    pub text:    u32,
410    pub bg:      u32,
411}
412
413impl Default for UiTheme {
414    fn default() -> Self {
415        Self {
416            primary: 0x00D2FF, // holographic cyan
417            accent:  0x28FFB4, // mint
418            track:   0x2C3E64, // dim slate
419            warn:    0xFF5A5A, // alert red
420            text:    0xBEEBFF, // pale cyan
421            bg:      0x0A1018, // near-black panel
422        }
423    }
424}
425
426pub struct Interpreter {
427    globals:   HashMap<String, Expr>,
428    functions: HashMap<String, FnDef>,
429    _modules:  HashMap<String, Vec<FnDef>>,
430    gfx:       RefCell<GfxState>,
431    svg:       RefCell<Option<SvgWriter>>,
432    /// Directory of the primary source file, for relative `use` resolution.
433    pub source_dir: Option<std::path::PathBuf>,
434    /// Files already loaded — prevents circular imports.
435    loaded_files: std::collections::HashSet<String>,
436    /// Optional audio engine — `None` if no audio device is available.
437    #[cfg(not(target_arch = "wasm32"))]
438    audio:     Option<AudioEngine>,
439    #[cfg(not(target_arch = "wasm32"))]
440    fft:       RefCell<FftAnalyzer>,
441    fft_bands_cache: RefCell<Vec<f32>>,
442    /// Real-time clock — initialized at startup
443    start_time: std::time::Instant,
444    /// Frame counter — incremented at each present()
445    frame_num: u64,
446    /// Random state for rand() builtin (xorshift)
447    rand_state: u64,
448    /// Microphone input (Phase 1 audio reactivity)
449    #[cfg(not(target_arch = "wasm32"))]
450    mic: Option<ling_mic::MicInput>,
451    /// Persistent KEM keypairs (knot / hybrid identities), referenced by handle.
452    #[cfg(not(target_arch = "wasm32"))]
453    crypto_ids: Vec<ling_crypto::KnotIdentity>,
454    /// Editable text-input buffer (ling-ui text fields).
455    text_buffer: String,
456    /// Frame counter for record_frame().
457    record_n: u32,
458    /// Accumulated microphone samples (for turning sound into crypto donuts).
459    #[cfg(not(target_arch = "wasm32"))]
460    mic_buffer: Vec<f32>,
461    /// Loaded vector UI fonts, referenced by handle (index) from `font_load`.
462    #[cfg(not(target_arch = "wasm32"))]
463    fonts: Vec<ling_graphics::VectorFont>,
464    /// Customizable UI colour palette (set via `ui_theme`).
465    ui_theme: UiTheme,
466    /// Left-mouse state on the previous frame — for widget click-edge detection.
467    mouse_was_down: bool,
468    /// Live music engine (decode playback + GM synth) — lazily initialised.
469    #[cfg(not(target_arch = "wasm32"))]
470    music: Option<ling_music::MusicEngine>,
471    #[cfg(not(target_arch = "wasm32"))]
472    music_init: bool,
473    /// Decoded tracks (for analysis + playback), by `music_load` handle.
474    #[cfg(not(target_arch = "wasm32"))]
475    tracks: Vec<ling_music::DecodedAudio>,
476    /// Parsed `.lrc` lyrics, by `music_lrc` handle.
477    #[cfg(not(target_arch = "wasm32"))]
478    lyrics: Vec<ling_music::Lyrics>,
479    /// Parsed MIDI songs, by `music_midi_load` handle.
480    #[cfg(not(target_arch = "wasm32"))]
481    midis: Vec<ling_music::MidiSong>,
482    /// Soft bodies (deformable balls), by `soft_ball` handle.
483    soft_bodies: Vec<ling_physics::soft::SoftBody>,
484    /// Rigid-body world (angular dynamics), shared by `rb_*`.
485    rigid_world: ling_physics::rigid::PhysicsWorld,
486    /// Liquid grids (water/oil), by `liquid_new` handle.
487    liquids: Vec<ling_physics::liquid::LiquidGrid>,
488    /// Active cinematic dialog box (Ocarina/Majora-style), if any.
489    dialog: Option<ling_game::dialog::Dialog>,
490    /// Dialog highlight colours by role: text, name, place, item (0x00RRGGBB).
491    dialog_colors: [u32; 4],
492}
493
494impl Interpreter {
495    pub fn new() -> Self {
496        #[cfg(not(target_arch = "wasm32"))]
497        let audio = AudioEngine::new()
498            .map_err(|e| eprintln!("audio init failed (no sound): {e}"))
499            .ok();
500        Self {
501            globals:   HashMap::new(),
502            functions: HashMap::new(),
503            _modules:  HashMap::new(),
504            gfx:       RefCell::new(GfxState::new()),
505            svg:       RefCell::new(None),
506            source_dir: None,
507            loaded_files: std::collections::HashSet::new(),
508            #[cfg(not(target_arch = "wasm32"))]
509            audio,
510            #[cfg(not(target_arch = "wasm32"))]
511            fft: RefCell::new(FftAnalyzer::new(2048, 44100)),
512            fft_bands_cache: RefCell::new(vec![]),
513            start_time: std::time::Instant::now(),
514            frame_num: 0,
515            rand_state: 0x123456789ABCDEF,
516            #[cfg(not(target_arch = "wasm32"))]
517            mic: None,
518            #[cfg(not(target_arch = "wasm32"))]
519            crypto_ids: Vec::new(),
520            text_buffer: String::new(),
521            record_n: 0,
522            #[cfg(not(target_arch = "wasm32"))]
523            mic_buffer: Vec::new(),
524            #[cfg(not(target_arch = "wasm32"))]
525            fonts: Vec::new(),
526            ui_theme: UiTheme::default(),
527            mouse_was_down: false,
528            #[cfg(not(target_arch = "wasm32"))]
529            music: None,
530            #[cfg(not(target_arch = "wasm32"))]
531            music_init: false,
532            #[cfg(not(target_arch = "wasm32"))]
533            tracks: Vec::new(),
534            #[cfg(not(target_arch = "wasm32"))]
535            lyrics: Vec::new(),
536            #[cfg(not(target_arch = "wasm32"))]
537            midis: Vec::new(),
538            soft_bodies: Vec::new(),
539            rigid_world: ling_physics::rigid::PhysicsWorld::new(),
540            liquids: Vec::new(),
541            dialog: None,
542            dialog_colors: [0xE6F2FF, 0xFFD24A, 0x4AD2FF, 0x6CFF8C], // text · name · place · item
543        }
544    }
545
546    /// Render the active dialog box: beveled frame + dark fill, then the visible
547    /// (typewriter-revealed) text word-wrapped with colour-coded runs, plus a
548    /// blinking advance arrow once the page is fully typed.
549    #[cfg(not(target_arch = "wasm32"))]
550    fn render_dialog(&mut self, x: f32, y: f32, w: f32, h: f32, font: i64, t: f32) {
551        let (runs, typing) = match &self.dialog {
552            Some(d) if !d.is_closed() => {
553                let runs: Vec<(String, usize, bool)> = d.visible_runs().into_iter()
554                    .map(|r| (r.text, r.role.index(), r.newline_before)).collect();
555                (runs, d.is_typing())
556            }
557            _ => return,
558        };
559        let colors = self.dialog_colors;
560        // ── frame + fill ──
561        let b = 12.0;
562        let corners: Vec<[f32; 2]> = vec![
563            [x+b,y],[x+w-b,y],[x+w,y+b],[x+w,y+h-b],[x+w-b,y+h],[x+b,y+h],[x,y+h-b],[x,y+b],[x+b,y],
564        ];
565        {
566            let mut gfx = self.gfx.borrow_mut();
567            let (bw, bh) = (gfx.width, gfx.height);
568            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, bw, bh, 0x0A1018, false, std::slice::from_ref(&corners));
569            for seg in corners.windows(2) {
570                crate::gfx::raster::draw_line_aa(&mut gfx.buffer, bw, bh, 0x00D2FF, false, seg[0][0], seg[0][1], seg[1][0], seg[1][1]);
571            }
572        }
573        // ── word-wrapped, colour-coded text ──
574        let px = 22.0f32;
575        let pad = 20.0f32;
576        let line_h = px * 1.45;
577        let mut cx = x + pad;
578        let mut cy = y + pad;
579        let use_font = font >= 0 && (font as usize) < self.fonts.len();
580        for (text, role, nl) in &runs {
581            if *nl { cx = x + pad; cy += line_h; }
582            for word in text.split_inclusive(' ') {
583                let wpx = if use_font { self.fonts[font as usize].measure(word, px) }
584                          else { ling_ui::holo::text_width(word, px * 0.6, px * 0.24) };
585                if cx + wpx > x + w - pad && cx > x + pad + 1.0 { cx = x + pad; cy += line_h; }
586                if cy + line_h > y + h { break; }
587                let col = colors[(*role).min(3)];
588                if use_font {
589                    let glyphs = self.font_layout_2d_glyphs(font as usize, cx, cy, px, word);
590                    let mut gfx = self.gfx.borrow_mut();
591                    let (bw, bh, add) = (gfx.width, gfx.height, gfx.blend == 1);
592                    for contours in &glyphs {
593                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, bw, bh, col, add, contours);
594                    }
595                } else {
596                    let segs = ling_ui::holo::text_lines(word, cx, cy, px * 0.6, px, px * 0.24);
597                    let mut gfx = self.gfx.borrow_mut();
598                    let (bw, bh) = (gfx.width, gfx.height);
599                    for s in segs { draw_line(&mut gfx.buffer, bw, bh, col, s[0], s[1], s[2], s[3]); }
600                }
601                cx += wpx;
602            }
603        }
604        // ── blinking advance arrow when fully typed ──
605        if !typing && (t * 3.0).sin() > 0.0 {
606            let ax = x + w - 26.0; let ay = y + h - 22.0;
607            let mut gfx = self.gfx.borrow_mut();
608            let (bw, bh) = (gfx.width, gfx.height);
609            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, bw, bh, 0x00D2FF, false,
610                std::slice::from_ref(&vec![[ax-7.0,ay],[ax+7.0,ay],[ax,ay+9.0],[ax-7.0,ay]]));
611        }
612    }
613
614    /// Lazily start the music engine on first use (playback/synth need a device;
615    /// analysis/decoding do not). Returns `false` if no audio device is available.
616    #[cfg(not(target_arch = "wasm32"))]
617    fn ensure_music(&mut self) -> bool {
618        if self.music.is_some() { return true; }
619        if self.music_init { return false; }
620        self.music_init = true;
621        match ling_music::MusicEngine::new() {
622            Ok(m) => { self.music = Some(m); true }
623            Err(e) => { eprintln!("music engine init failed (no music playback): {e}"); false }
624        }
625    }
626
627    /// Lay out `text` for font `id` at size `px`, returning every glyph contour as
628    /// a screen-space polyline (x→right, y→down). `(x, y)` is the text box top-left;
629    /// the baseline is placed `ascent*px` below it. Curves are flattened to 0.3 px.
630    #[cfg(not(target_arch = "wasm32"))]
631    fn font_layout_2d(&mut self, id: usize, x: f32, y: f32, px: f32, text: &str) -> Vec<Vec<[f32; 2]>> {
632        let mut out = Vec::new();
633        for g in self.font_layout_2d_glyphs(id, x, y, px, text) { out.extend(g); }
634        out
635    }
636
637    /// Same as [`font_layout_2d`] but grouped per glyph (so a fill can apply the
638    /// non-zero winding rule within each glyph, preserving interior holes).
639    #[cfg(not(target_arch = "wasm32"))]
640    fn font_layout_2d_glyphs(&mut self, id: usize, x: f32, y: f32, px: f32, text: &str) -> Vec<Vec<Vec<[f32; 2]>>> {
641        let font = &mut self.fonts[id];
642        let asc = font.ascent();
643        let tol = 0.3 / px;
644        let mut pen = 0.0f32;
645        let mut glyphs = Vec::new();
646        for ch in text.chars() {
647            let go = font.glyph_outline(ch, tol);
648            let mut contours = Vec::with_capacity(go.polylines.len());
649            for pl in &go.polylines {
650                let mapped: Vec<[f32; 2]> = pl.iter()
651                    .map(|p| [x + (pen + p[0]) * px, y + (asc - p[1]) * px])
652                    .collect();
653                contours.push(mapped);
654            }
655            glyphs.push(contours);
656            pen += go.advance;
657        }
658        glyphs
659    }
660
661    pub fn run_program(&mut self, program: &Program) -> Result<(), String> {
662        for item in &program.items {
663            self.register_item("", item)?;
664        }
665        let entry = self.find_entry()
666            .ok_or("no entry point — need `bind start = do {...}` or `ผูก เริ่ม = ทำ {...}`")?;
667        // Seed the entry env with non-Do globals so top-level `令` bindings
668        // are visible in the main Do block (same two-pass logic as call_named).
669        let mut env = Env::new();
670        let non_do: Vec<_> = self.globals.iter()
671            .filter(|(_, e)| !matches!(e, Expr::Do(_)))
672            .map(|(k, e)| (k.clone(), e.clone()))
673            .collect();
674        let mut pending: Vec<(String, Expr)> = Vec::new();
675        for (k, expr) in &non_do {
676            let mut tmp = Env::new();
677            if let Ok(v) = self.eval_expr(expr, &mut tmp) {
678                env.insert(k.clone(), v);
679            } else {
680                pending.push((k.clone(), expr.clone()));
681            }
682        }
683        for (k, expr) in &pending {
684            let mut tmp = env.clone();
685            if let Ok(v) = self.eval_expr(expr, &mut tmp) {
686                env.insert(k.clone(), v);
687            }
688        }
689        self.eval_expr(&entry, &mut env).map(|_| ()).map_err(|e| match e {
690            EvalErr::Runtime(s) => s,
691            EvalErr::Return(_)  => "unexpected top-level return".to_string(),
692            EvalErr::Break      => "unexpected break at top level".to_string(),
693        })
694    }
695
696    fn register_item(&mut self, ns: &str, item: &Item) -> Result<(), String> {
697        match item {
698            Item::Bind(name, expr) => {
699                let key = if ns.is_empty() { name.clone() } else { format!("{ns}::{name}") };
700                self.globals.insert(key, expr.clone());
701            }
702            Item::Fn(def) => {
703                let key = if ns.is_empty() { def.name.clone() } else { format!("{ns}::{}", def.name) };
704                self.functions.insert(key, def.clone());
705            }
706            Item::Mod(name, body) => {
707                let child_ns = if ns.is_empty() { name.clone() } else { format!("{ns}::{name}") };
708                for child in body {
709                    self.register_item(&child_ns, child)?;
710                }
711            }
712            Item::TypeAlias(_, _) => {}
713            Item::Use { path, alias } => {
714                self.load_module(path, alias.as_deref(), ns)?;
715            }
716        }
717        Ok(())
718    }
719
720    /// Resolve `path` relative to `source_dir`, load and parse it, then
721    /// register all its definitions.  If `alias` is given, every name is
722    /// prefixed with `<parent_ns>::<alias>`.  Circular imports are silently
723    /// skipped.
724    fn load_module(&mut self, path: &str, alias: Option<&str>, parent_ns: &str) -> Result<(), String> {
725        // Build candidate file paths (.ling extension variants)
726        let base_dir = self.source_dir.clone().unwrap_or_else(|| std::path::PathBuf::from("."));
727        let raw = std::path::Path::new(path);
728        let candidates: Vec<std::path::PathBuf> = vec![
729            base_dir.join(format!("{}.ling", path)),
730            base_dir.join(format!("{}.灵", path)),
731            base_dir.join(format!("{}.령", path)),
732            base_dir.join(format!("{}.霊", path)),
733            base_dir.join(format!("{}.ลิง", path)),
734            // exact path if already has extension
735            base_dir.join(raw),
736            std::path::PathBuf::from(format!("{}.ling", path)),
737            std::path::PathBuf::from(path),
738        ];
739
740        let resolved = candidates.into_iter().find(|p| p.exists())
741            .ok_or_else(|| format!("use: cannot find module '{path}'"))?;
742
743        let canonical = resolved.canonicalize()
744            .unwrap_or_else(|_| resolved.clone())
745            .to_string_lossy()
746            .to_string();
747
748        // Skip if already loaded (circular import guard)
749        if self.loaded_files.contains(&canonical) {
750            return Ok(());
751        }
752        self.loaded_files.insert(canonical.clone());
753
754        let source = std::fs::read_to_string(&resolved)
755            .map_err(|e| format!("use: failed to read '{path}': {e}"))?;
756
757        // Save/restore source_dir for nested relative imports
758        let prev_dir = self.source_dir.clone();
759        self.source_dir = resolved.parent().map(|p| p.to_path_buf());
760
761        let program = crate::parser::parse(&source)
762            .map_err(|e| format!("use: parse error in '{path}': {e}"))?;
763
764        // Compute target namespace: parent_ns :: alias (or just alias, or just parent_ns)
765        let target_ns = match (parent_ns.is_empty(), alias) {
766            (_, Some(a)) if !parent_ns.is_empty() => format!("{parent_ns}::{a}"),
767            (_, Some(a)) => a.to_string(),
768            (false, None) => parent_ns.to_string(),
769            (true,  None) => String::new(),
770        };
771
772        for item in &program.items {
773            self.register_item(&target_ns, item)?;
774        }
775
776        self.source_dir = prev_dir;
777        Ok(())
778    }
779
780    fn find_entry(&self) -> Option<Expr> {
781        // Try all known entry-point names in multiple human languages
782        for key in &[
783            "start", "main",
784            "启",
785            "เริ่ม",           // Thai
786            "시작",
787            "начать", "начало",
788            "inicio", "comenzar",
789            "début", "commencer",
790            "anfang", "starten",
791            "início",
792            "शुरू",
793            "ابدأ",
794        ] {
795            if let Some(e) = self.globals.get(*key) { return Some(e.clone()); }
796        }
797        self.globals.values().find(|e| matches!(e, Expr::Do(_))).cloned()
798    }
799
800    // ─── Expression evaluation ────────────────────────────────────────────────
801
802    fn eval_expr(&mut self, expr: &Expr, env: &mut Env) -> EvalResult {
803        match expr {
804            Expr::Str(s)    => Ok(Value::Str(s.clone())),
805            Expr::Number(n) => Ok(Value::Number(*n)),
806            Expr::Bool(b)   => Ok(Value::Bool(*b)),
807            Expr::Unit      => Ok(Value::Unit),
808            Expr::Array(elems) => {
809                let vs: Vec<_> = elems.iter()
810                    .map(|e| self.eval_expr(e, env))
811                    .collect::<Result<_,_>>()?;
812                Ok(Value::List(vs))
813            }
814
815            Expr::Ident(name) => self.lookup(name, env),
816
817            Expr::Path(segs) => {
818                if segs.len() == 1 { return self.lookup(&segs[0], env); }
819                Ok(Value::Str(segs.join("::")))
820            }
821
822            Expr::Ref(inner) => self.eval_expr(inner, env),
823            Expr::Await(inner) => self.eval_expr(inner, env),
824
825            Expr::Do(stmts) => {
826                let mut local = env.clone();
827                Ok(self.exec_block(stmts, &mut local)?.unwrap_or(Value::Unit))
828            }
829
830            Expr::BinOp(op, lhs, rhs) => {
831                let l = self.eval_expr(lhs, env)?;
832                let r = self.eval_expr(rhs, env)?;
833                self.apply_binop(op, l, r)
834            }
835
836            Expr::If { cond, then, elseifs, else_body } => {
837                let cond_val = self.eval_expr(cond, env)?;
838                if self.is_truthy(&cond_val) {
839                    return Ok(self.exec_block(then, env)?.unwrap_or(Value::Unit));
840                }
841                for (ei_cond, ei_body) in elseifs {
842                    let ei_cond_val = self.eval_expr(ei_cond, env)?;
843                    if self.is_truthy(&ei_cond_val) {
844                        return Ok(self.exec_block(ei_body, env)?.unwrap_or(Value::Unit));
845                    }
846                }
847                if let Some(eb) = else_body {
848                    return Ok(self.exec_block(eb, env)?.unwrap_or(Value::Unit));
849                }
850                Ok(Value::Unit)
851            }
852
853            Expr::While { cond, body } => {
854                // Run the body directly in the *outer* env so that
855                // `bind counter = counter + 1` persists across iterations,
856                // which is the expected behaviour in a scripting language.
857                loop {
858                    let cv = self.eval_expr(cond, env)?;
859                    if !self.is_truthy(&cv) { break; }
860                    match self.exec_block(body, env) {
861                        Ok(_) => {}
862                        Err(EvalErr::Break) => break,
863                        Err(e) => return Err(e),
864                    }
865                }
866                Ok(Value::Unit)
867            }
868
869            Expr::For { var, iter, body } => {
870                let iter_val = self.eval_expr(iter, env)?;
871                let items = self.value_to_iter(iter_val)?;
872                for item in items {
873                    let mut local = env.clone();
874                    local.insert(var.clone(), item);
875                    match self.exec_block(body, &mut local) {
876                        Ok(_) => {}
877                        Err(EvalErr::Break) => break,
878                        Err(e) => return Err(e),
879                    }
880                }
881                Ok(Value::Unit)
882            }
883
884            Expr::Match(subject, arms) => {
885                let subj = self.eval_expr(subject, env)?;
886                for arm in arms {
887                    if let Some(bindings) = self.match_pattern(&arm.pattern, &subj) {
888                        let mut local = env.clone();
889                        local.extend(bindings);
890                        return self.eval_expr(&arm.body, &mut local);
891                    }
892                }
893                Ok(Value::Unit)
894            }
895
896            Expr::Range(lo, hi) => {
897                let lo_v = self.eval_expr(lo, env)?;
898                let hi_v = self.eval_expr(hi, env)?;
899                let lo_n = self.to_number(&lo_v)? as i64;
900                let hi_n = self.to_number(&hi_v)? as i64;
901                Ok(Value::List((lo_n..hi_n).map(|i| Value::Number(i as f64)).collect()))
902            }
903
904            Expr::Index(base, idx) => {
905                let b = self.eval_expr(base, env)?;
906                let i = self.eval_expr(idx, env)?;
907                let n = self.to_number(&i)? as usize;
908                match b {
909                    Value::List(v) => v.get(n).cloned()
910                        .ok_or_else(|| EvalErr::from(format!("index {n} out of bounds"))),
911                    Value::Str(s)  => s.chars().nth(n)
912                        .map(|c| Value::Str(c.to_string()))
913                        .ok_or_else(|| EvalErr::from(format!("index {n} out of bounds"))),
914                    other => Err(EvalErr::from(format!("cannot index {:?}", other))),
915                }
916            }
917
918            Expr::Call(callee, args) => {
919                let arg_vals: Vec<Value> = args.iter()
920                    .map(|a| self.eval_expr(a, env))
921                    .collect::<Result<_,_>>()?;
922                match callee.as_ref() {
923                    Expr::Ident(name) => self.call_named(name, arg_vals, env),
924                    Expr::Path(segs)  => self.call_named(&segs.join("::"), arg_vals, env),
925                    _ => {
926                        let v = self.eval_expr(callee, env)?;
927                        self.call_value(v, arg_vals)
928                    }
929                }
930            }
931
932            Expr::MethodCall { receiver, method, args } => {
933                let recv = self.eval_expr(receiver, env)?;
934                let arg_vals: Vec<Value> = args.iter()
935                    .map(|a| self.eval_expr(a, env))
936                    .collect::<Result<_,_>>()?;
937                self.call_method(recv, method, arg_vals)
938            }
939
940            Expr::Closure(params, body) => {
941                Ok(Value::Fn(params.clone(), vec![Stmt::Expr(*body.clone())], env.clone()))
942            }
943        }
944    }
945
946    // ─── Block execution ─────────────────────────────────────────────────────
947
948    fn exec_block(&mut self, stmts: &[Stmt], env: &mut Env) -> Result<Option<Value>, EvalErr> {
949        let mut last: Option<Value> = None;
950        for stmt in stmts {
951            match stmt {
952                Stmt::Bind(name, expr) => {
953                    let v = self.eval_expr(expr, env)?;
954                    env.insert(name.clone(), v);
955                    last = None;
956                }
957                Stmt::Return(expr) => {
958                    let v = self.eval_expr(expr, env)?;
959                    return Err(EvalErr::Return(v));
960                }
961                Stmt::Expr(expr) => {
962                    last = Some(self.eval_expr(expr, env)?);
963                }
964            }
965        }
966        Ok(last)
967    }
968
969    // ─── Dispatch helpers ─────────────────────────────────────────────────────
970
971    fn lookup(&self, name: &str, env: &Env) -> EvalResult {
972        if let Some(v) = env.get(name) { return Ok(v.clone()); }
973        if self.functions.contains_key(name) {
974            let def = &self.functions[name];
975            return Ok(Value::Fn(def.params.clone(), def.body.clone(), Env::new()));
976        }
977        // Math constants usable as plain identifiers (e.g. `sin(pi)`)
978        match name {
979            "pi" | "π" | "พาย" | "圆周率" | "円周率" | "파이" => return Ok(Value::Number(std::f64::consts::PI)),
980            "tau" | "τ" | "双周率" | "タウ" | "타우" | "ทาว"        => return Ok(Value::Number(std::f64::consts::TAU)),
981            _ => {}
982        }
983        Err(EvalErr::from(format!("undefined: '{name}'")))
984    }
985
986    fn call_named(&mut self, name: &str, args: Vec<Value>, env: &Env) -> EvalResult {
987        match name {
988            // ── Print ──
989            "print" | "println" | "印" | "打印" | "印刷" | "พิมพ์" | "출력" | "вывести" | "imprimir" | "afficher" => {
990                let s = args.iter().map(|v| v.to_string()).collect::<Vec<_>>().join("");
991                println!("{s}");
992                return Ok(Value::Unit);
993            }
994            // ── Format ──
995            "format" | "格式" | "フォーマット" | "서식" | "รูปแบบ" | "форматировать" | "formatear" | "formater" => {
996                return Ok(Value::Str(self.builtin_format(&args)?));
997            }
998            // ── String join / concatenation ──
999            "格式::拼接" | "format::join" => {
1000                match args.first() {
1001                    Some(Value::List(items)) => {
1002                        return Ok(Value::Str(items.iter().map(|v| v.to_string()).collect()));
1003                    }
1004                    _ => return Ok(Value::Str(self.builtin_format(&args)?)),
1005                }
1006            }
1007            // ── Result constructors ──
1008            "ok" | "好" | "良し" | "좋아" | "โอเค" => {
1009                let val = args.into_iter().next().unwrap_or(Value::Unit);
1010                return Ok(Value::Ok(Box::new(val)));
1011            }
1012            "bad" | "坏" | "err" | "悪い" | "나쁨" | "ผิด" => {
1013                let val = args.into_iter().next().unwrap_or(Value::Unit);
1014                return Ok(Value::Err(Box::new(val)));
1015            }
1016            // ── Vec constructors ──
1017            "向量::从" | "Vec::from" => {
1018                if let Some(Value::List(v)) = args.first() {
1019                    return Ok(Value::List(v.clone()));
1020                }
1021                return Ok(Value::List(args));
1022            }
1023            "向量::有容量" | "Vec::with_capacity" => return Ok(Value::List(Vec::new())),
1024            // ── Timer stubs ──
1025            "计时::获取当前小时" | "Timer::hour" => return Ok(Value::Number(14.0)),
1026            "计时::现在" | "Timer::now"          => return Ok(Value::Number(1000.0)),
1027            // ── Sleep ──
1028            "sleep" | "หยุด" | "นอน" | "sleep_ms" | "睡眠" | "眠る" | "スリープ" | "잠자기" | "잠" | "流水::睡眠" | "Flow::sleep" => {
1029                if let Some(ms_val) = args.first() {
1030                    if let Ok(ms) = self.to_number(ms_val) {
1031                        std::thread::sleep(std::time::Duration::from_millis(ms as u64));
1032                    }
1033                }
1034                return Ok(Value::Unit);
1035            }
1036            // ── Flow::parallel stub ──
1037            "流水::并行" | "Flow::parallel" => {
1038                if let Some(Value::Fn(params, body, mut cap)) = args.first().cloned() {
1039                    let _ = params;
1040                    match self.exec_block(&body, &mut cap) {
1041                        Ok(Some(v)) => return Ok(v),
1042                        Ok(None) => return Ok(Value::Unit),
1043                        Err(EvalErr::Return(v)) => return Ok(v),
1044                        Err(e) => return Err(e),
1045                    }
1046                }
1047                return Ok(Value::Unit);
1048            }
1049
1050            // ══════════════════════════════════════════════════════════════════
1051            // MATH BUILTINS  (all args and results are f64)
1052            // Thai aliases: ไซน์ โคไซน์ แทนเจนต์ รากที่สอง ค่าสัมบูรณ์
1053            //               ปัดลง ปัดขึ้น ปัดเศษ ตัดทศนิยม ต่ำสุด สูงสุด
1054            //               จำกัด ยกกำลัง ลอการิทึม พาย
1055            // ══════════════════════════════════════════════════════════════════
1056
1057            // ── Trigonometry (input in radians) ──
1058            "sin" | "ไซน์" | "正弦" | "サイン" | "사인" => {
1059                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.sin()));
1060            }
1061            "cos" | "โคไซน์" | "余弦" | "コサイン" | "코사인" => {
1062                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.cos()));
1063            }
1064
1065            // ── Hyperbolic functions ──
1066            // Hyperbolic tangent
1067            "tanh" | "tanhf" | "双曲正切" | "双曲線正接" | "쌍곡탄젠트" => {
1068                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.tanh()));
1069            }
1070
1071
1072            "tan" | "แทนเจนต์" | "正切" | "タンジェント" | "탄젠트" => {
1073                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.tan()));
1074            }
1075            "asin" | "arcsin" | "反正弦" | "アークサイン" | "아크사인" | "อาร์กไซน์" => {
1076                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.asin()));
1077            }
1078            "acos" | "arccos" | "反余弦" | "アークコサイン" | "아크코사인" | "อาร์กโคไซน์" => {
1079                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.acos()));
1080            }
1081            "atan" | "arctan" | "反正切" | "アークタンジェント" | "아크탄젠트" | "อาร์กแทนเจนต์" => {
1082                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.atan()));
1083            }
1084            "atan2" | "arctan2" | "反正切2" | "アークタンジェント2" | "아크탄젠트2" => {
1085                let y = self.arg_num(&args, 0, 0.0)?;
1086                let x = self.arg_num(&args, 1, 1.0)?;
1087                return Ok(Value::Number(y.atan2(x)));
1088            }
1089
1090            // ── Roots / powers ──
1091            "sqrt" | "รากที่สอง" | "平方根" | "根" | "제곱근" => {
1092                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.sqrt()));
1093            }
1094            "cbrt" | "立方根" | "세제곱근" | "รากที่สาม" => {
1095                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.cbrt()));
1096            }
1097            "pow" | "ยกกำลัง" | "幂" | "べき乗" | "거듭제곱" => {
1098                let base = self.arg_num(&args, 0, 0.0)?;
1099                let exp  = self.arg_num(&args, 1, 1.0)?;
1100                return Ok(Value::Number(base.powf(exp)));
1101            }
1102            "exp" | "指数" | "指数関数" | "지수" => {
1103                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.exp()));
1104            }
1105            "hypot" | "斜边" | "斜辺" | "빗변" => {
1106                let x = self.arg_num(&args, 0, 0.0)?;
1107                let y = self.arg_num(&args, 1, 0.0)?;
1108                return Ok(Value::Number(x.hypot(y)));
1109            }
1110
1111            // ── Logarithms ──
1112            "ln" | "log" | "ลอการิทึม" | "对数" | "対数" | "로그" => {
1113                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.ln()));
1114            }
1115            "log2" | "对数2" | "対数2" | "로그2" => {
1116                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.log2()));
1117            }
1118            "log10" | "对数10" | "対数10" | "로그10" => {
1119                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.log10()));
1120            }
1121
1122            // ── Rounding / truncation ──
1123            "abs" | "ค่าสัมบูรณ์" | "绝对值" | "绝对" | "絶対値" | "절댓값" | "절대값" => {
1124                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.abs()));
1125            }
1126            "floor" | "ปัดลง" | "向下取整" | "下整" | "床関数" | "내림" => {
1127                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.floor()));
1128            }
1129            "ceil" | "ปัดขึ้น" | "向上取整" | "上整" | "天井関数" | "올림" => {
1130                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.ceil()));
1131            }
1132            "round" | "ปัดเศษ" | "四舍五入" | "四舍" | "四捨五入" | "반올림" => {
1133                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.round()));
1134            }
1135            "trunc" | "int" | "ตัดทศนิยม" | "取整" | "整数化" | "整数" | "截整"
1136                    | "정수화" | "정수" | "切り捨て" | "버림" => {
1137                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.trunc()));
1138            }
1139            "fract" | "小数部分" | "小数部" | "소수부" => {
1140                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.fract()));
1141            }
1142
1143            // ── min / max / clamp ──
1144            "min" | "ต่ำสุด" | "最小" | "최솟값" => {
1145                let a = self.arg_num(&args, 0, 0.0)?;
1146                let b = self.arg_num(&args, 1, 0.0)?;
1147                return Ok(Value::Number(a.min(b)));
1148            }
1149            "max" | "สูงสุด" | "最大" | "최댓값" => {
1150                let a = self.arg_num(&args, 0, 0.0)?;
1151                let b = self.arg_num(&args, 1, 0.0)?;
1152                return Ok(Value::Number(a.max(b)));
1153            }
1154            "clamp" | "จำกัด" | "截取" | "範囲制限" | "범위제한" => {
1155                let x  = self.arg_num(&args, 0, 0.0)?;
1156                let lo = self.arg_num(&args, 1, 0.0)?;
1157                let hi = self.arg_num(&args, 2, 1.0)?;
1158                return Ok(Value::Number(x.clamp(lo, hi)));
1159            }
1160
1161            // ── Constants (also accessible as plain identifiers via lookup) ──
1162            "pi" | "π" | "พาย" | "圆周率" | "円周率" | "파이" => return Ok(Value::Number(std::f64::consts::PI)),
1163            "tau" | "τ" | "双周率" | "タウ" | "타우" | "ทาว"        => return Ok(Value::Number(std::f64::consts::TAU)),
1164
1165            // ══════════════════════════════════════════════════════════════════
1166            // PHASE 1: DMT TRIP CODER FEATURES
1167            // ══════════════════════════════════════════════════════════════════
1168
1169            // ── Step 1: Noise Functions ──
1170            "vnoise" | "noise2" | "นอยส์2ดี" | "柏林噪声2D" | "バリューノイズ2D" | "값노이즈2D" => {
1171                let x = self.arg_num(&args, 0, 0.0)? as f32;
1172                let y = self.arg_num(&args, 1, 0.0)? as f32;
1173                let seed = self.arg_num(&args, 2, 0.0)? as u32;
1174                return Ok(Value::Number(tex_vnoise(x, y, seed) as f64));
1175            }
1176
1177            "fbm" | "นอยส์ออร์แกนิก" | "分形噪声" | "フラクタルノイズ" | "프랙탈노이즈" => {
1178                let x = self.arg_num(&args, 0, 0.0)? as f32;
1179                let y = self.arg_num(&args, 1, 0.0)? as f32;
1180                let octaves = self.arg_num(&args, 2, 4.0)? as u32;
1181                let seed = self.arg_num(&args, 3, 0.0)? as u32;
1182                return Ok(Value::Number(tex_fbm(x, y, octaves, seed) as f64));
1183            }
1184
1185            "perlin" | "perlin3" | "เพอร์ลิน3ดี" | "柏林噪声3D" | "パーリンノイズ3D" | "펄린노이즈3D" => {
1186                let x = self.arg_num(&args, 0, 0.0)? as f32;
1187                let y = self.arg_num(&args, 1, 0.0)? as f32;
1188                let z = self.arg_num(&args, 2, 0.0)? as f32;
1189                return Ok(Value::Number(perlin3(x, y, z) as f64));
1190            }
1191
1192            // ── Step 2: Math Ergonomics ──
1193            "lerp" | "ค่าระหว่าง" | "线性插值" | "線形補間" | "선형보간" => {
1194                let a = self.arg_num(&args, 0, 0.0)?;
1195                let b = self.arg_num(&args, 1, 1.0)?;
1196                let t = self.arg_num(&args, 2, 0.0)?;
1197                return Ok(Value::Number(a + (b - a) * t));
1198            }
1199
1200            "smoothstep" | "เปลี่ยนแบบนุ่ม" | "平滑步进" | "スムーズステップ" | "스무스스텝" => {
1201                let lo = self.arg_num(&args, 0, 0.0)?;
1202                let hi = self.arg_num(&args, 1, 1.0)?;
1203                let x = self.arg_num(&args, 2, 0.5)?;
1204                let t = ((x - lo) / (hi - lo)).clamp(0.0, 1.0);
1205                return Ok(Value::Number(t * t * (3.0 - 2.0 * t)));
1206            }
1207
1208            "rand" | "สุ่ม" | "随机" | "乱数" | "난수" => {
1209                let val = fast_rand_f64(&mut self.rand_state);
1210                return Ok(Value::Number(val));
1211            }
1212
1213            "sign" | "เครื่องหมาย" | "符号" | "符号関数" | "부호" => {
1214                let x = self.arg_num(&args, 0, 0.0)?;
1215                return Ok(Value::Number(x.signum()));
1216            }
1217
1218            "hsv_to_rgb" | "เอชเอสวีเป็นRGB" | "HSV转RGB" | "HSV変換RGB" | "HSV변환RGB" => {
1219                let h = self.arg_num(&args, 0, 0.0)?; // 0-360
1220                let s = self.arg_num(&args, 1, 1.0)?; // 0-1
1221                let v = self.arg_num(&args, 2, 1.0)?; // 0-1
1222                let c = v * s;
1223                let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs());
1224                let m = v - c;
1225                let (r1, g1, b1) = if h < 60.0       { (c, x, 0.0) }
1226                                    else if h < 120.0  { (x, c, 0.0) }
1227                                    else if h < 180.0  { (0.0, c, x) }
1228                                    else if h < 240.0  { (0.0, x, c) }
1229                                    else if h < 300.0  { (x, 0.0, c) }
1230                                    else               { (c, 0.0, x) };
1231                let r = ((r1 + m) * 255.0).round();
1232                let g = ((g1 + m) * 255.0).round();
1233                let b = ((b1 + m) * 255.0).round();
1234                return Ok(Value::List(vec![Value::Number(r), Value::Number(g), Value::Number(b)]));
1235            }
1236
1237            "lerp_color" | "ไล่สี" | "颜色插值" | "色補間" | "색보간" => {
1238                let r1 = self.arg_num(&args, 0, 0.0)?;
1239                let g1 = self.arg_num(&args, 1, 0.0)?;
1240                let b1 = self.arg_num(&args, 2, 0.0)?;
1241                let r2 = self.arg_num(&args, 3, 255.0)?;
1242                let g2 = self.arg_num(&args, 4, 255.0)?;
1243                let b2 = self.arg_num(&args, 5, 255.0)?;
1244                let t = self.arg_num(&args, 6, 0.0)?;
1245                let r = r1 + (r2 - r1) * t;
1246                let g = g1 + (g2 - g1) * t;
1247                let b = b1 + (b2 - b1) * t;
1248                let c = ((r as u32) << 16) | ((g as u32) << 8) | (b as u32);
1249                self.gfx.borrow_mut().color = c;
1250                return Ok(Value::Unit);
1251            }
1252
1253            // ── Step 3: Real-Time Clock ──
1254            "time_now" | "เวลาปัจจุบัน" | "当前时间" | "経過時間" | "현재시간" => {
1255                return Ok(Value::Number(self.start_time.elapsed().as_secs_f64()));
1256            }
1257
1258            "frame_count" | "เฟรม" | "帧数" | "フレーム数" | "프레임수" => {
1259                return Ok(Value::Number(self.frame_num as f64));
1260            }
1261
1262            // ── Step 4: Microphone Input ──
1263            "mic_open" | "เปิดไมค์" | "开麦克风" | "マイク開く" | "마이크열기" => {
1264                #[cfg(not(target_arch = "wasm32"))]
1265                {
1266                    match ling_mic::MicInput::open(Default::default()) {
1267                        Ok(mic) => {
1268                            let _ = mic.start(|_samples: &[f32]| {});  // No-op callback
1269                            self.mic = Some(mic);
1270                            return Ok(Value::Unit);
1271                        }
1272                        Err(e) => return Err(EvalErr::from(format!("mic_open failed: {e}"))),
1273                    }
1274                }
1275                #[cfg(target_arch = "wasm32")]
1276                return Ok(Value::Unit);
1277            }
1278
1279            "mic_rms" | "เสียงRMS" | "麦克风音量" | "マイクRMS" | "마이크RMS" => {
1280                #[cfg(not(target_arch = "wasm32"))]
1281                {
1282                    let rms = self.mic.as_ref().map(|m: &ling_mic::MicInput| m.rms()).unwrap_or(0.0);
1283                    return Ok(Value::Number(rms as f64));
1284                }
1285                #[cfg(target_arch = "wasm32")]
1286                return Ok(Value::Number(0.0));
1287            }
1288
1289            "mic_peak" | "เสียงพีค" | "麦克风峰值" | "マイクピーク" | "마이크피크" => {
1290                #[cfg(not(target_arch = "wasm32"))]
1291                {
1292                    let peak = self.mic.as_ref().map(|m: &ling_mic::MicInput| m.peak()).unwrap_or(0.0);
1293                    return Ok(Value::Number(peak as f64));
1294                }
1295                #[cfg(target_arch = "wasm32")]
1296                return Ok(Value::Number(0.0));
1297            }
1298
1299            "mic_fft" | "วิเคราะห์เสียงสด" | "实时频谱" | "リアルタイムFFT" | "실시간FFT" => {
1300                #[cfg(not(target_arch = "wasm32"))]
1301                {
1302                    let n = self.arg_num(&args, 0, 8.0)? as usize;
1303                    if let Some(mic) = self.mic.as_ref() {
1304                        let samples = mic.latest_samples();
1305                        self.fft.borrow_mut().push_samples(&samples);
1306                    }
1307                    let bands = self.fft.borrow().freq_bands(n);
1308                    let result = bands.iter().map(|&v| Value::Number(v as f64)).collect();
1309                    return Ok(Value::List(result));
1310                }
1311                #[cfg(target_arch = "wasm32")]
1312                return Ok(Value::List(vec![]));
1313            }
1314
1315            // ── Step 5: Additive Blend Mode ──
1316            "set_blend" | "โหมดผสม" | "混合模式" | "ブレンドモード" | "블렌드모드" => {
1317                let mode = self.arg_num(&args, 0, 0.0)? as u8;
1318                self.gfx.borrow_mut().blend = mode;
1319                return Ok(Value::Unit);
1320            }
1321
1322            // ── Step 6: Circle Primitives ──
1323            "draw_circle" | "วาดวงกลม" | "画圆" | "円描画" | "원그리기" => {
1324                let cx = self.arg_num(&args, 0, 0.0)? as i32;
1325                let cy = self.arg_num(&args, 1, 0.0)? as i32;
1326                let r = self.arg_num(&args, 2, 10.0)? as i32;
1327                let mut gfx = self.gfx.borrow_mut();
1328                let (w, h, color, blend) = (gfx.width as i32, gfx.height as i32, gfx.color, gfx.blend);
1329                draw_circle_outline(&mut gfx.buffer, w, h, cx, cy, r, color, blend);
1330                return Ok(Value::Unit);
1331            }
1332
1333            "draw_filled_circle" | "draw_disc" | "วาดวงกลมทึบ" | "画实心圆" | "塗りつぶし円" | "원채우기" => {
1334                let cx = self.arg_num(&args, 0, 0.0)? as i32;
1335                let cy = self.arg_num(&args, 1, 0.0)? as i32;
1336                let r = self.arg_num(&args, 2, 10.0)? as i32;
1337                let mut gfx = self.gfx.borrow_mut();
1338                let (w, h, color, blend) = (gfx.width as i32, gfx.height as i32, gfx.color, gfx.blend);
1339                draw_circle_filled(&mut gfx.buffer, w, h, cx, cy, r, color, blend);
1340                return Ok(Value::Unit);
1341            }
1342
1343            // ══════════════════════════════════════════════════════════════════
1344            // GRAPHICS BUILTINS
1345            // Thai names first, then English aliases.
1346            // ══════════════════════════════════════════════════════════════════
1347
1348            // ── เปิดหน้าต่าง(width, height, title) — open_window ──
1349            "เปิดหน้าต่าง" | "open_window" | "gfx_window" | "开窗" | "ウィンドウ開く" | "창열기" => {
1350                let w = self.arg_num(&args, 0, 800.0)? as usize;
1351                let h = self.arg_num(&args, 1, 600.0)? as usize;
1352                #[cfg(not(target_arch = "wasm32"))]
1353                {
1354                    let title = args.get(2).map(|v| v.to_string()).unwrap_or_else(|| "Ling".into());
1355                    let mut gfx = self.gfx.borrow_mut();
1356                    let mut win = minifb::Window::new(
1357                        &title, w, h,
1358                        minifb::WindowOptions {
1359                            resize: false,
1360                            scale: minifb::Scale::X1,
1361                            ..Default::default()
1362                        },
1363                    ).map_err(|e| EvalErr::from(format!("cannot open window: {e}")))?;
1364                    #[allow(deprecated)]
1365                    win.limit_update_rate(Some(std::time::Duration::from_millis(8)));
1366                    gfx.buffer = vec![0u32; w * h];
1367                    gfx.width  = w;
1368                    gfx.height = h;
1369                    gfx.window = Some(win);
1370                    gfx.sync_projection();
1371                    hide_console_window();
1372                }
1373                #[cfg(target_arch = "wasm32")]
1374                {
1375                    let mut gfx = self.gfx.borrow_mut();
1376                    gfx.width  = w;
1377                    gfx.height = h;
1378                    gfx.sync_projection();
1379                    crate::gfx::webgl::resize(w as u32, h as u32);
1380                }
1381                return Ok(Value::Unit);
1382            }
1383
1384            // ── เติม(r, g, b) — fill / clear screen with colour ──
1385            "เติม" | "fill" | "gfx_fill" | "clear" | "填" | "塗り潰し" | "채우기" | "清" | "消去" | "지우기" => {
1386                let r = self.arg_num(&args, 0, 0.0)? as u32;
1387                let g = self.arg_num(&args, 1, 0.0)? as u32;
1388                let b = self.arg_num(&args, 2, 0.0)? as u32;
1389                #[cfg(not(target_arch = "wasm32"))]
1390                {
1391                    let c = (r << 16) | (g << 8) | b;
1392                    self.gfx.borrow_mut().buffer.fill(c);
1393                }
1394                #[cfg(target_arch = "wasm32")]
1395                {
1396                    let mut gfx = self.gfx.borrow_mut();
1397                    gfx.fill_r = r as f32 / 255.0;
1398                    gfx.fill_g = g as f32 / 255.0;
1399                    gfx.fill_b = b as f32 / 255.0;
1400                }
1401                return Ok(Value::Unit);
1402            }
1403
1404            // ── set_color_hsl(h, s, l) — set drawing colour from HSL ──
1405            // h: 0–360 degrees, s: 0–100 saturation, l: 0–100 lightness
1406            "set_color_hsl" | "颜色HSL" | "色相" | "HSL色" | "HSL색설정" | "สีHSLวาด" => {
1407                let h = self.arg_num(&args, 0, 0.0)?;
1408                let s = self.arg_num(&args, 1, 70.0)?;
1409                let l = self.arg_num(&args, 2, 50.0)?;
1410                let hex = hsl_to_hex(h, s, l);
1411                let r = u32::from_str_radix(&hex[1..3], 16).unwrap_or(255);
1412                let g = u32::from_str_radix(&hex[3..5], 16).unwrap_or(255);
1413                let b = u32::from_str_radix(&hex[5..7], 16).unwrap_or(255);
1414                self.gfx.borrow_mut().color = (r << 16) | (g << 8) | b;
1415                return Ok(Value::Unit);
1416            }
1417
1418            // ── สีดินสอ(r, g, b) — set drawing colour ──
1419            "สีดินสอ" | "set_color" | "gfx_color" | "color" | "设色" | "色設定" | "색설정" => {
1420                let r = self.arg_num(&args, 0, 255.0)? as u32;
1421                let g = self.arg_num(&args, 1, 255.0)? as u32;
1422                let b = self.arg_num(&args, 2, 255.0)? as u32;
1423                self.gfx.borrow_mut().color = (r << 16) | (g << 8) | b;
1424                return Ok(Value::Unit);
1425            }
1426
1427            // ── วาดสามเหลี่ยม(x1,y1, x2,y2, x3,y3) — draw filled triangle ──
1428            "วาดสามเหลี่ยม" | "draw_triangle" | "gfx_triangle" | "triangle" | "画三角" | "三角形描画" | "삼각형그리기" => {
1429                let x0 = self.arg_num(&args, 0, 0.0)? as f32;
1430                let y0 = self.arg_num(&args, 1, 0.0)? as f32;
1431                let x1 = self.arg_num(&args, 2, 0.0)? as f32;
1432                let y1 = self.arg_num(&args, 3, 0.0)? as f32;
1433                let x2 = self.arg_num(&args, 4, 0.0)? as f32;
1434                let y2 = self.arg_num(&args, 5, 0.0)? as f32;
1435                let mut gfx = self.gfx.borrow_mut();
1436                let color = gfx.color;
1437                #[cfg(not(target_arch = "wasm32"))]
1438                {
1439                    let w = gfx.width;
1440                    let h = gfx.height;
1441                    fill_triangle(&mut gfx.buffer, w, h, color, x0, y0, x1, y1, x2, y2);
1442                }
1443                #[cfg(target_arch = "wasm32")]
1444                gfx.depth_queue.push_triangle(0.0, color, x0, y0, x1, y1, x2, y2);
1445                return Ok(Value::Unit);
1446            }
1447
1448            // ── วาดเส้น(x1,y1, x2,y2) — draw line ──
1449            "วาดเส้น" | "draw_line" | "gfx_line" | "line" | "画线" | "線描く" | "선그리기" => {
1450                let x0 = self.arg_num(&args, 0, 0.0)? as f32;
1451                let y0 = self.arg_num(&args, 1, 0.0)? as f32;
1452                let x1 = self.arg_num(&args, 2, 0.0)? as f32;
1453                let y1 = self.arg_num(&args, 3, 0.0)? as f32;
1454                let mut gfx = self.gfx.borrow_mut();
1455                let color = gfx.color;
1456                #[cfg(not(target_arch = "wasm32"))]
1457                {
1458                    let w = gfx.width;
1459                    let h = gfx.height;
1460                    draw_line(&mut gfx.buffer, w, h, color, x0, y0, x1, y1);
1461                }
1462                #[cfg(target_arch = "wasm32")]
1463                gfx.depth_queue.push_line(0.0, color, x0, y0, x1, y1);
1464                return Ok(Value::Unit);
1465            }
1466
1467            // ── วาดจุด(x, y) — plot a single pixel ──
1468            "วาดจุด" | "draw_pixel" | "gfx_pixel" | "pixel" | "画点" | "点描く" | "점그리기" => {
1469                let px = self.arg_num(&args, 0, 0.0)? as i32;
1470                let py = self.arg_num(&args, 1, 0.0)? as i32;
1471                #[cfg(not(target_arch = "wasm32"))]
1472                {
1473                    let mut gfx = self.gfx.borrow_mut();
1474                    let color = gfx.color;
1475                    let w = gfx.width;
1476                    let h = gfx.height;
1477                    if px >= 0 && py >= 0 && (px as usize) < w && (py as usize) < h {
1478                        gfx.buffer[py as usize * w + px as usize] = color;
1479                    }
1480                }
1481                #[cfg(target_arch = "wasm32")]
1482                {
1483                    // Render pixel as a 1×1 square via two triangles.
1484                    let mut gfx = self.gfx.borrow_mut();
1485                    let color = gfx.color;
1486                    let x = px as f32; let y = py as f32;
1487                    gfx.depth_queue.push_triangle(0.0, color, x, y, x+1.0, y, x+1.0, y+1.0);
1488                    gfx.depth_queue.push_triangle(0.0, color, x, y, x+1.0, y+1.0, x, y+1.0);
1489                }
1490                return Ok(Value::Unit);
1491            }
1492
1493            // ── แสดงผล() — flush depth queue, then present frame to screen ──
1494            "แสดงผล" | "present" | "gfx_present" | "show" | "显" | "呈现" | "表示" | "표시" => {
1495                #[cfg(not(target_arch = "wasm32"))]
1496                {
1497                    // Flush depth queue and present — release borrow before reading mouse.
1498                    {
1499                        let mut gfx = self.gfx.borrow_mut();
1500                        if !gfx.depth_queue.is_empty() {
1501                            let w = gfx.width;
1502                            let h = gfx.height;
1503                            let queue = std::mem::take(&mut gfx.depth_queue);
1504                            queue.flush(&mut gfx.buffer, w, h);
1505                        }
1506                        let buf = gfx.buffer.clone();
1507                        let w   = gfx.width;
1508                        let h   = gfx.height;
1509                        if let Some(win) = gfx.window.as_mut() {
1510                            win.update_with_buffer(&buf, w, h)
1511                                .map_err(|e| EvalErr::from(format!("present error: {e}")))?;
1512                        }
1513                    }
1514                    // Read mouse AFTER update_with_buffer so events are processed.
1515                    let mouse_pos = {
1516                        let gfx = self.gfx.borrow();
1517                        gfx.window.as_ref()
1518                            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp))
1519                    };
1520                    let mut gfx = self.gfx.borrow_mut();
1521                    if gfx.mouse_captured {
1522                        if let Some((mx, my)) = mouse_pos {
1523                            if gfx.last_mx.is_nan() {
1524                                gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1525                            } else {
1526                                gfx.mouse_dx = mx - gfx.last_mx;
1527                                gfx.mouse_dy = my - gfx.last_my;
1528                            }
1529                            gfx.last_mx = mx; gfx.last_my = my;
1530                        } else {
1531                            gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1532                        }
1533                        // Clip cursor to window bounds so it can't escape.
1534                        #[cfg(windows)]
1535                        unsafe {
1536                            #[repr(C)]
1537                            struct RECT { left: i32, top: i32, right: i32, bottom: i32 }
1538                            extern "system" {
1539                                fn ClipCursor(lpRect: *const std::ffi::c_void) -> i32;
1540                                fn GetForegroundWindow() -> isize;
1541                                fn GetWindowRect(hwnd: isize, lpRect: *mut RECT) -> i32;
1542                            }
1543                            let hwnd = GetForegroundWindow();
1544                            let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 };
1545                            if GetWindowRect(hwnd, &mut rect) != 0 {
1546                                ClipCursor(&rect as *const RECT as *const std::ffi::c_void);
1547                            }
1548                        }
1549                    } else if let Some((mx, my)) = mouse_pos {
1550                        if gfx.last_mx.is_nan() {
1551                            gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1552                        } else {
1553                            gfx.mouse_dx = mx - gfx.last_mx;
1554                            gfx.mouse_dy = my - gfx.last_my;
1555                        }
1556                        gfx.last_mx = mx; gfx.last_my = my;
1557                    } else {
1558                        gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1559                    }
1560                }
1561                #[cfg(target_arch = "wasm32")]
1562                {
1563                    let mut gfx = self.gfx.borrow_mut();
1564                    let w  = gfx.width;
1565                    let h  = gfx.height;
1566                    let fr = gfx.fill_r;
1567                    let fg = gfx.fill_g;
1568                    let fb = gfx.fill_b;
1569                    let queue = std::mem::take(&mut gfx.depth_queue);
1570                    queue.flush_to_webgl(fr, fg, fb, w, h);
1571                }
1572                // Update the click-edge latch for interactive UI widgets.
1573                #[cfg(not(target_arch = "wasm32"))]
1574                {
1575                    let (_, _, down) = self.mouse_now();
1576                    self.mouse_was_down = down;
1577                }
1578                // Increment frame counter
1579                self.frame_num += 1;
1580                return Ok(Value::Unit);
1581            }
1582
1583            // ── เปิดหน้าต่างเต็มจอ(title) — true native-res fullscreen window ──
1584            "เปิดหน้าต่างเต็มจอ" | "open_fullscreen" | "fullscreen" | "全屏" | "全画面" | "전체화면" => {
1585                // In WASM the canvas defines the viewport; use its current size
1586                // as the default so the projection matches what's actually visible.
1587                #[cfg(target_arch = "wasm32")]
1588                let (default_w, default_h) = {
1589                    let (cw, ch) = crate::gfx::webgl::canvas_size();
1590                    (cw as f64, ch as f64)
1591                };
1592                // On native: query the actual primary monitor resolution.
1593                #[cfg(all(not(target_arch = "wasm32"), windows))]
1594                let (default_w, default_h) = unsafe {
1595                    extern "system" { fn GetSystemMetrics(nIndex: i32) -> i32; }
1596                    (GetSystemMetrics(0) as f64, GetSystemMetrics(1) as f64)
1597                };
1598                #[cfg(all(not(target_arch = "wasm32"), not(windows)))]
1599                let (default_w, default_h) = native_screen_size();
1600
1601                let w = args.get(1).map(|v| self.to_number(v).unwrap_or(default_w) as usize).unwrap_or(default_w as usize);
1602                let h = args.get(2).map(|v| self.to_number(v).unwrap_or(default_h) as usize).unwrap_or(default_h as usize);
1603                #[cfg(not(target_arch = "wasm32"))]
1604                {
1605                    let title = args.get(0).map(|v| v.to_string()).unwrap_or_else(|| "Ling".into());
1606                    let mut gfx = self.gfx.borrow_mut();
1607                    let mut win = minifb::Window::new(
1608                        &title, w, h,
1609                        minifb::WindowOptions {
1610                            borderless: true,
1611                            title:      false,
1612                            resize:     false,
1613                            scale:      minifb::Scale::X1,
1614                            ..Default::default()
1615                        },
1616                    ).map_err(|e| EvalErr::from(format!("cannot open fullscreen: {e}")))?;
1617                    #[allow(deprecated)]
1618                    win.limit_update_rate(Some(std::time::Duration::from_millis(8)));
1619                    gfx.buffer = vec![0u32; w * h];
1620                    gfx.width  = w;
1621                    gfx.height = h;
1622                    gfx.window = Some(win);
1623                    gfx.sync_projection();
1624                    // Snap to top-left, cover full screen, bring above taskbar.
1625                    #[cfg(windows)]
1626                    reposition_fullscreen(w as i32, h as i32);
1627                    hide_console_window();
1628                }
1629                #[cfg(target_arch = "wasm32")]
1630                {
1631                    let mut gfx = self.gfx.borrow_mut();
1632                    gfx.width  = w;
1633                    gfx.height = h;
1634                    gfx.sync_projection();
1635                    crate::gfx::webgl::resize(w as u32, h as u32);
1636                }
1637                return Ok(Value::Unit);
1638            }
1639
1640            // ── ความกว้าง() / ความสูง() — current framebuffer size ──
1641            "get_width" | "ความกว้าง" | "宽" | "幅取得" | "너비" => {
1642                return Ok(Value::Number(self.gfx.borrow().width as f64));
1643            }
1644            "get_height" | "ความสูง" | "高" | "高取得" | "높이" => {
1645                return Ok(Value::Number(self.gfx.borrow().height as f64));
1646            }
1647
1648            // ── หน้าต่างเปิดอยู่() → bool — is the window still open? ──
1649            "หน้าต่างเปิดอยู่" | "window_is_open" | "gfx_is_open" | "is_open" | "窗开" | "開いている" | "창열림" => {
1650                #[cfg(not(target_arch = "wasm32"))]
1651                {
1652                    let gfx = self.gfx.borrow();
1653                    let open = gfx.window.as_ref()
1654                        .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
1655                        .unwrap_or(false);
1656                    return Ok(Value::Bool(open));
1657                }
1658                #[cfg(target_arch = "wasm32")]
1659                return Ok(Value::Bool(true));
1660            }
1661
1662            // ── key_down(name) → bool — is a key held? ──
1663            "key_down" | "กดค้าง" | "按键" | "キー押す" | "키누름" => {
1664                #[cfg(not(target_arch = "wasm32"))]
1665                {
1666                    let name = self.arg_str(&args, 0, "");
1667                    let gfx  = self.gfx.borrow();
1668                    let down = gfx.window.as_ref()
1669                        .and_then(|w| str_to_minifb_key(&name).map(|k| w.is_key_down(k)))
1670                        .unwrap_or(false);
1671                    return Ok(Value::Bool(down));
1672                }
1673                #[cfg(target_arch = "wasm32")]
1674                return Ok(Value::Bool(false));
1675            }
1676
1677            // ── key_pressed(name) → bool — was a key pressed this frame? ──
1678            "key_pressed" | "กดปุ่ม" | "键按" | "キー押した" | "키눌림" => {
1679                #[cfg(not(target_arch = "wasm32"))]
1680                {
1681                    let name = self.arg_str(&args, 0, "");
1682                    let gfx  = self.gfx.borrow();
1683                    let pressed = gfx.window.as_ref()
1684                        .and_then(|w| str_to_minifb_key(&name)
1685                            .map(|k| w.is_key_pressed(k, minifb::KeyRepeat::No)))
1686                        .unwrap_or(false);
1687                    return Ok(Value::Bool(pressed));
1688                }
1689                #[cfg(target_arch = "wasm32")]
1690                return Ok(Value::Bool(false));
1691            }
1692
1693            // ── mouse_dx() / mouse_dy() → f64 — delta since last frame ──
1694            "mouse_dx" | "เมาส์X" | "鼠ΔX" | "マウスΔX" | "마우스ΔX" => {
1695                #[cfg(not(target_arch = "wasm32"))]
1696                return Ok(Value::Number(self.gfx.borrow().mouse_dx as f64));
1697                #[cfg(target_arch = "wasm32")]
1698                return Ok(Value::Number(0.0));
1699            }
1700            "mouse_dy" | "เมาส์Y" | "鼠ΔY" | "マウスΔY" | "마우스ΔY" => {
1701                #[cfg(not(target_arch = "wasm32"))]
1702                return Ok(Value::Number(self.gfx.borrow().mouse_dy as f64));
1703                #[cfg(target_arch = "wasm32")]
1704                return Ok(Value::Number(0.0));
1705            }
1706
1707            // ── set_camera_pos(x, y, z) — move camera to world position ──
1708            "set_camera_pos" | "ตั้งตำแหน่งกล้อง" | "镜坐标" | "カメラ座標" | "카메라좌표" => {
1709                let x = self.arg_num(&args, 0, 0.0)? as f32;
1710                let y = self.arg_num(&args, 1, 0.0)? as f32;
1711                let z = self.arg_num(&args, 2, 0.0)? as f32;
1712                let mut gfx = self.gfx.borrow_mut();
1713                gfx.camera.tx = x; gfx.camera.ty = y; gfx.camera.tz = z;
1714                return Ok(Value::Unit);
1715            }
1716
1717            // ── move_camera(dx, dy, dz) — translate camera by delta ──
1718            "move_camera" => {
1719                let dx = self.arg_num(&args, 0, 0.0)? as f32;
1720                let dy = self.arg_num(&args, 1, 0.0)? as f32;
1721                let dz = self.arg_num(&args, 2, 0.0)? as f32;
1722                let mut gfx = self.gfx.borrow_mut();
1723                gfx.camera.tx += dx; gfx.camera.ty += dy; gfx.camera.tz += dz;
1724                return Ok(Value::Unit);
1725            }
1726
1727            // ── set_zdist(d) — set perspective z-offset (field-of-view taper) ──
1728            "set_zdist" | "ตั้งระยะห่าง" | "镜距" | "Z距離設定" | "Z거리설정" => {
1729                let d = self.arg_num(&args, 0, 5.0)? as f32;
1730                self.gfx.borrow_mut().camera.zdist = d;
1731                return Ok(Value::Unit);
1732            }
1733
1734            // ── capture_mouse() — hide cursor and warp to centre each frame ──
1735            "capture_mouse" | "จับเมาส์" | "捕鼠" | "マウス捕捉" | "마우스잡기" => {
1736                #[cfg(not(target_arch = "wasm32"))]
1737                {
1738                    let mut gfx = self.gfx.borrow_mut();
1739                    gfx.mouse_captured = true;
1740                    gfx.last_mx = f32::NAN;
1741                    if let Some(win) = gfx.window.as_mut() {
1742                        win.set_cursor_visibility(false);
1743                    }
1744                }
1745                return Ok(Value::Unit);
1746            }
1747
1748            // ── release_mouse() — restore cursor and remove clip region ──
1749            "release_mouse" => {
1750                #[cfg(not(target_arch = "wasm32"))]
1751                {
1752                    let mut gfx = self.gfx.borrow_mut();
1753                    gfx.mouse_captured = false;
1754                    gfx.last_mx = f32::NAN;
1755                    if let Some(win) = gfx.window.as_mut() {
1756                        win.set_cursor_visibility(true);
1757                    }
1758                    #[cfg(windows)]
1759                    unsafe {
1760                        // Null releases the clip; reuse the RECT-typed declaration above.
1761                        extern "system" { fn ClipCursor(lpRect: *const std::ffi::c_void) -> i32; }
1762                        ClipCursor(std::ptr::null());
1763                    }
1764                }
1765                return Ok(Value::Unit);
1766            }
1767
1768            // ══════════════════════════════════════════════════════════════════
1769            // 3-D / 4-D DRAWING — camera, lights, depth-sorted geometry
1770            // ══════════════════════════════════════════════════════════════════
1771
1772            // ── set_camera(cry, sry, crx, srx) — store precomputed camera trig ──
1773            // Call once per frame after computing cos/sin of your rotation angles.
1774            "set_camera" | "ตั้งกล้อง" | "设镜" | "设置摄像机" | "カメラ設定" | "카메라설정" => {
1775                let cry = self.arg_num(&args, 0, 1.0)? as f32;
1776                let sry = self.arg_num(&args, 1, 0.0)? as f32;
1777                let crx = self.arg_num(&args, 2, 1.0)? as f32;
1778                let srx = self.arg_num(&args, 3, 0.0)? as f32;
1779                let mut gfx = self.gfx.borrow_mut();
1780                gfx.camera.cry = cry; gfx.camera.sry = sry;
1781                gfx.camera.crx = crx; gfx.camera.srx = srx;
1782                return Ok(Value::Unit);
1783            }
1784
1785            // ── set_projection(cx, cy, focal, zdist) — override projection params ──
1786            // Automatically set when the window opens; override only if needed.
1787            "set_projection" | "ตั้งโปรเจกชัน" | "投影" | "投影設定" | "투영설정" => {
1788                let cx    = self.arg_num(&args, 0, 960.0)? as f32;
1789                let cy    = self.arg_num(&args, 1, 540.0)? as f32;
1790                let focal = self.arg_num(&args, 2, 1080.0)? as f32;
1791                let zdist = self.arg_num(&args, 3, 5.0)? as f32;
1792                let mut gfx = self.gfx.borrow_mut();
1793                gfx.camera.cx    = cx;
1794                gfx.camera.cy    = cy;
1795                gfx.camera.focal = focal;
1796                gfx.camera.zdist = zdist;
1797                return Ok(Value::Unit);
1798            }
1799
1800            // ── add_light(x, y, z, r, g, b, intensity, radius) ──
1801            // Adds a point light in world space.  r/g/b in [0..1].
1802            // radius == 0 → no distance falloff.
1803            "add_light" | "เพิ่มแสง" | "加灯" | "ライト追加" | "조명추가" => {
1804                let x   = self.arg_num(&args, 0, 0.0)? as f32;
1805                let y   = self.arg_num(&args, 1, -3.0)? as f32;
1806                let z   = self.arg_num(&args, 2, 3.0)? as f32;
1807                let mut r   = self.arg_num(&args, 3, 1.0)? as f32;
1808                let mut g   = self.arg_num(&args, 4, 1.0)? as f32;
1809                let mut b   = self.arg_num(&args, 5, 1.0)? as f32;
1810                // Forgive 0-255 colour values: if any channel is clearly > 1,
1811                // treat the triple as 0-255 and normalise. Keeps 0-1 callers exact.
1812                if r > 1.5 || g > 1.5 || b > 1.5 { r/=255.0; g/=255.0; b/=255.0; }
1813                let intensity = self.arg_num(&args, 6, 1.0)? as f32;
1814                let radius    = self.arg_num(&args, 7, 0.0)? as f32;
1815                self.gfx.borrow_mut().lights.push(Light { x, y, z, r, g, b, intensity, radius });
1816                return Ok(Value::Unit);
1817            }
1818
1819            // ── clear_lights() — remove all lights ──
1820            "clear_lights" | "ล้างแสง" | "清灯" | "ライト消去" | "조명초기화" => {
1821                self.gfx.borrow_mut().lights.clear();
1822                return Ok(Value::Unit);
1823            }
1824
1825            // ── set_ambient(v) — ambient light level [0..1] ──
1826            "set_ambient" | "ตั้งแสงรอบข้าง" | "环境光" | "環境光設定" | "환경광설정" => {
1827                let v = self.arg_num(&args, 0, 0.15)? as f32;
1828                self.gfx.borrow_mut().ambient = v;
1829                return Ok(Value::Unit);
1830            }
1831
1832            // ── วาดสามเหลี่ยม3มิติ(ax,ay,az, bx,by,bz, cx,cy,cz) ──
1833            // Computes lighting from world-space normal + active lights (cel shading),
1834            // projects via the stored camera, and pushes to the depth queue.
1835            "วาดสามเหลี่ยม3มิติ" | "draw_triangle_3d" | "triangle3d" => {
1836                let ax = self.arg_num(&args, 0, 0.0)? as f32;
1837                let ay = self.arg_num(&args, 1, 0.0)? as f32;
1838                let az = self.arg_num(&args, 2, 0.0)? as f32;
1839                let bx = self.arg_num(&args, 3, 0.0)? as f32;
1840                let by = self.arg_num(&args, 4, 0.0)? as f32;
1841                let bz = self.arg_num(&args, 5, 0.0)? as f32;
1842                let cx = self.arg_num(&args, 6, 0.0)? as f32;
1843                let cy = self.arg_num(&args, 7, 0.0)? as f32;
1844                let cz = self.arg_num(&args, 8, 0.0)? as f32;
1845
1846                let mut gfx = self.gfx.borrow_mut();
1847
1848                // World-space face normal  N = (B−A) × (C−A)
1849                let ux = bx-ax; let uy = by-ay; let uz = bz-az;
1850                let vx = cx-ax; let vy = cy-ay; let vz = cz-az;
1851                let normal = [
1852                    uy*vz - uz*vy,
1853                    uz*vx - ux*vz,
1854                    ux*vy - uy*vx,
1855                ];
1856                // World-space centroid
1857                let centroid = [
1858                    (ax+bx+cx)/3.0,
1859                    (ay+by+cy)/3.0,
1860                    (az+bz+cz)/3.0,
1861                ];
1862
1863                // Cel-shaded colour
1864                let lit_color = crate::gfx::light::compute_lit_color(
1865                    gfx.color, normal, centroid, &gfx.lights, gfx.ambient,
1866                );
1867
1868                // Near-plane cull — skip any triangle that has a vertex
1869                // behind or at the camera near plane (avoids projected-to-infinity blowup).
1870                let near = -gfx.camera.zdist + 0.05;
1871                let da_raw = gfx.camera.depth(ax, ay, az);
1872                let db_raw = gfx.camera.depth(bx, by, bz);
1873                let dc_raw = gfx.camera.depth(cx, cy, cz);
1874                if da_raw <= near || db_raw <= near || dc_raw <= near {
1875                    return Ok(Value::Unit);
1876                }
1877
1878                // Project to screen
1879                let (sax, say, da) = gfx.camera.project(ax, ay, az);
1880                let (sbx, sby, db) = gfx.camera.project(bx, by, bz);
1881                let (scx, scy, dc) = gfx.camera.project(cx, cy, cz);
1882
1883                // Average camera depth (used for painter's sort)
1884                let depth = (da + db + dc) / 3.0;
1885
1886                gfx.depth_queue.push_triangle(
1887                    depth, lit_color,
1888                    sax, say, sbx, sby, scx, scy,
1889                );
1890                return Ok(Value::Unit);
1891            }
1892
1893            // ── วาดเส้น3มิติ(ax,ay,az, bx,by,bz) ──
1894            // Projects two world-space points via the stored camera and pushes
1895            // a line to the depth queue.
1896            "วาดเส้น3มิติ" | "draw_line_3d" | "line3d" | "画3D线" | "3D線描く" | "3D선그리기" => {
1897                let ax = self.arg_num(&args, 0, 0.0)? as f32;
1898                let ay = self.arg_num(&args, 1, 0.0)? as f32;
1899                let az = self.arg_num(&args, 2, 0.0)? as f32;
1900                let bx = self.arg_num(&args, 3, 0.0)? as f32;
1901                let by = self.arg_num(&args, 4, 0.0)? as f32;
1902                let bz = self.arg_num(&args, 5, 0.0)? as f32;
1903
1904                let mut gfx = self.gfx.borrow_mut();
1905                let color = gfx.color;
1906                // Near-plane clip in 3-D before perspective divide
1907                let near = -gfx.camera.zdist + 0.05;
1908                let mut lax = ax; let mut lay = ay; let mut laz = az;
1909                let mut lbx = bx; let mut lby = by; let mut lbz = bz;
1910                let da_raw = gfx.camera.depth(lax, lay, laz);
1911                let db_raw = gfx.camera.depth(lbx, lby, lbz);
1912                if da_raw <= near && db_raw <= near {
1913                    return Ok(Value::Unit);
1914                }
1915                if da_raw <= near {
1916                    let t = (near - da_raw) / (db_raw - da_raw);
1917                    lax += t * (lbx - lax);
1918                    lay += t * (lby - lay);
1919                    laz += t * (lbz - laz);
1920                } else if db_raw <= near {
1921                    let t = (near - da_raw) / (db_raw - da_raw);
1922                    lbx = lax + t * (lbx - lax);
1923                    lby = lay + t * (lby - lay);
1924                    lbz = laz + t * (lbz - laz);
1925                }
1926                let (sax, say, da) = gfx.camera.project(lax, lay, laz);
1927                let (sbx, sby, db) = gfx.camera.project(lbx, lby, lbz);
1928                let depth = (da + db) / 2.0;
1929                gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
1930                return Ok(Value::Unit);
1931            }
1932
1933            // orb_shell(cx,cy,cz, radius, rot_y, rot_x, density, r,g,b)
1934            //   A single trippy, grayscale, depth-faded vector pattern wound around
1935            //   a sphere — two families of interleaved spherical spirals (a guilloché
1936            //   weave), NOT a lat/long cage. Each segment's brightness follows its
1937            //   facing (front bright, back dim), so it reads as a translucent
1938            //   grayscale "texture" with alpha rather than a hard wireframe; the
1939            //   inner marble shows through. `rot_y`/`rot_x` roll the texture around
1940            //   the orb; `density` = spirals per winding direction. r,g,b tint it
1941            //   (pass a gray like 230,230,230 for pure grayscale).
1942            #[cfg(not(target_arch = "wasm32"))]
1943            "orb_shell" | "球壳" | "オーブ殻" | "오브껍질" | "เปลือกทรงกลม" => {
1944                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32; let cz=self.arg_num(&args,2,0.)? as f32;
1945                let radius=self.arg_num(&args,3,1.0)? as f32;
1946                let ry=self.arg_num(&args,4,0.)? as f32; let rx=self.arg_num(&args,5,0.)? as f32;
1947                let density=(self.arg_num(&args,6,10.)? as i32).clamp(1, 48);
1948                let tr=(self.arg_num(&args,7,230.)? as f32).clamp(0.,255.);
1949                let tg=(self.arg_num(&args,8,230.)? as f32).clamp(0.,255.);
1950                let tb=(self.arg_num(&args,9,235.)? as f32).clamp(0.,255.);
1951                let (cyr, syr) = (ry.cos(), ry.sin());
1952                let (cxr, sxr) = (rx.cos(), rx.sin());
1953                let tau = std::f32::consts::TAU;
1954                let pi = std::f32::consts::PI;
1955                let turns = 6.0_f32;            // how many times each spiral wraps pole→pole
1956                let nseg  = 96;                 // segments per spiral (smoothness)
1957                let inv_r = if radius.abs() > 1e-5 { 1.0 / radius } else { 0.0 };
1958                // a point along a spiral (param u 0..1, start angle theta0, winding dir),
1959                // spun by ry/rx — returns (world point, facing 0..1 where 1 = toward camera)
1960                let pt = |u: f32, theta0: f32, dir: f32| -> ([f32;3], f32) {
1961                    let phi = pi * u;                       // 0..pi  (north → south)
1962                    let th  = dir * turns * tau * u + theta0;
1963                    let (mut x, mut y, mut z) = (phi.sin()*th.cos()*radius, phi.cos()*radius, phi.sin()*th.sin()*radius);
1964                    let x1 =  x*cyr + z*syr;                // yaw about Y
1965                    let z1 = -x*syr + z*cyr;
1966                    x = x1; z = z1;
1967                    let y2 = y*cxr - z*sxr;                 // pitch about X
1968                    let z2 = y*sxr + z*cxr;
1969                    // facing: camera sits at -zdist looking +z, so smaller z2 = nearer = brighter
1970                    let facing = (0.5 - 0.5 * z2 * inv_r).clamp(0.0, 1.0);
1971                    ([cx + x, cy + y2, cz + z2], facing)
1972                };
1973                let mut gfx = self.gfx.borrow_mut();
1974                let near = -gfx.camera.zdist + 0.05;
1975                // draw one segment (near-clipped) in a grayscale tint scaled by `lum`
1976                let mut seg = |gfx: &mut crate::gfx::GfxState, a: [f32;3], b: [f32;3], lum: f32| {
1977                    let (mut lax,mut lay,mut laz)=(a[0],a[1],a[2]);
1978                    let (mut lbx,mut lby,mut lbz)=(b[0],b[1],b[2]);
1979                    let da=gfx.camera.depth(lax,lay,laz); let db=gfx.camera.depth(lbx,lby,lbz);
1980                    if da<=near && db<=near { return; }
1981                    if da<=near { let t=(near-da)/(db-da); lax+=t*(lbx-lax); lay+=t*(lby-lay); laz+=t*(lbz-laz); }
1982                    else if db<=near { let t=(near-da)/(db-da); lbx=lax+t*(lbx-lax); lby=lay+t*(lby-lay); lbz=laz+t*(lbz-laz); }
1983                    let (sax,say,da2)=gfx.camera.project(lax,lay,laz);
1984                    let (sbx,sby,db2)=gfx.camera.project(lbx,lby,lbz);
1985                    // grayscale-alpha: front-facing bright, back faded toward black
1986                    let l = (0.12 + 0.88 * lum).clamp(0.0, 1.0);
1987                    let cr=(tr*l) as u32; let cg=(tg*l) as u32; let cb=(tb*l) as u32;
1988                    let color=(cr<<16)|(cg<<8)|cb;
1989                    gfx.depth_queue.push_line((da2+db2)*0.5, color, sax,say, sbx,sby);
1990                };
1991                // two opposite winding directions → a soft guilloché weave (not a cage)
1992                for &dir in &[1.0_f32, -1.0_f32] {
1993                    for s in 0..density {
1994                        let theta0 = s as f32 * tau / density as f32;
1995                        let mut prev = pt(0.0, theta0, dir);
1996                        for k in 1..=nseg {
1997                            let cur = pt(k as f32 / nseg as f32, theta0, dir);
1998                            seg(&mut gfx, prev.0, cur.0, (prev.1 + cur.1) * 0.5);
1999                            prev = cur;
2000                        }
2001                    }
2002                }
2003                return Ok(Value::Unit);
2004            }
2005
2006            // orb_particles(cx,cy,cz, radius, count, t, r,g,b)
2007            //   Fills the VOLUME of a sphere with `count` swirling vector points —
2008            //   like motes suspended inside a snow-globe orb. Points are distributed
2009            //   uniformly through the ball, slowly tumble as a cloud + wobble
2010            //   individually over time `t`, and are depth-shaded (near = bright,
2011            //   far = dim) so the cloud has real volume. Additive, so it layers under
2012            //   a shell / over a liquid marble.
2013            #[cfg(not(target_arch = "wasm32"))]
2014            "orb_particles" | "球内粒子" | "オーブ粒子" | "오브입자" | "อนุภาคทรงกลม" => {
2015                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32; let cz=self.arg_num(&args,2,0.)? as f32;
2016                let radius=self.arg_num(&args,3,1.0)? as f32;
2017                let count=(self.arg_num(&args,4,160.)? as i32).clamp(1, 4000);
2018                let t=self.arg_num(&args,5,0.)? as f32;
2019                let tr=(self.arg_num(&args,6,255.)? as f32).clamp(0.,255.);
2020                let tg=(self.arg_num(&args,7,255.)? as f32).clamp(0.,255.);
2021                let tb=(self.arg_num(&args,8,255.)? as f32).clamp(0.,255.);
2022                let inv_r = if radius.abs() > 1e-5 { 1.0/radius } else { 0.0 };
2023                // cheap deterministic hash → [0,1)
2024                let h = |mut x: u32| -> f32 {
2025                    x = x.wrapping_mul(747796405).wrapping_add(2891336453);
2026                    x = ((x >> ((x >> 28).wrapping_add(4))) ^ x).wrapping_mul(277803737);
2027                    (((x >> 22) ^ x) & 0xFFFFFF) as f32 / 16_777_216.0
2028                };
2029                let tau = std::f32::consts::TAU;
2030                // slow tumble of the whole cloud
2031                let (cyr, syr) = ((t*0.5).cos(), (t*0.5).sin());
2032                let (cxr, sxr) = ((t*0.23).cos(), (t*0.23).sin());
2033                let mut gfx = self.gfx.borrow_mut();
2034                let near = -gfx.camera.zdist + 0.05;
2035                let (sw, sh) = (gfx.width as i32, gfx.height as i32);
2036                for i in 0..count {
2037                    let i = i as u32;
2038                    // uniform-in-volume: r = cbrt(u) * radius; direction from two hashes
2039                    let u  = h(i.wrapping_mul(3) + 1);
2040                    let rr = u.cbrt() * radius * (0.85 + 0.15 * (t*1.3 + i as f32).sin()); // gentle pulse
2041                    let th = h(i.wrapping_mul(3) + 2) * tau + t * (0.3 + 0.5 * h(i*7+5)); // per-mote orbit
2042                    let ph = (h(i.wrapping_mul(3) + 3) * 2.0 - 1.0).acos();               // uniform cos(phi)
2043                    let (mut x, mut y, mut z) = (rr*ph.sin()*th.cos(), rr*ph.cos(), rr*ph.sin()*th.sin());
2044                    // tumble the cloud (yaw then pitch)
2045                    let x1 = x*cyr + z*syr; let z1 = -x*syr + z*cyr; x = x1; z = z1;
2046                    let y2 = y*cxr - z*sxr; let z2 = y*sxr + z*cxr;
2047                    let (wx, wy, wz) = (cx + x, cy + y2, cz + z2);
2048                    if gfx.camera.depth(wx, wy, wz) <= near { continue; }
2049                    let (sx, sy, dep) = gfx.camera.project(wx, wy, wz);
2050                    let sxi = sx as i32; let syi = sy as i32;
2051                    if sxi < 0 || syi < 0 || sxi >= sw || syi >= sh { continue; }
2052                    // depth-shade: nearer (smaller z2) = brighter
2053                    let facing = (0.5 - 0.5 * z2 * inv_r).clamp(0.15, 1.0);
2054                    let l = facing;
2055                    let cr=(tr*l) as u32; let cg=(tg*l) as u32; let cb=(tb*l) as u32;
2056                    let color=(cr<<16)|(cg<<8)|cb;
2057                    // a 1–2px dot (bigger when near) as a short segment in the depth queue
2058                    let len = if facing > 0.7 { 1.0 } else { 0.0 };
2059                    gfx.depth_queue.push_line(dep, color, sx, sy, sx + len, sy);
2060                }
2061                return Ok(Value::Unit);
2062            }
2063
2064            // project_3d(x,y,z) -> [screen_x, screen_y, depth]; behind the camera
2065            // returns a sentinel ([-99999,-99999, depth]) so scripts can skip it.
2066            // Lets scripts place 2-D overlays (e.g. filled teardrop flames) onto 3-D points.
2067            "project_3d" | "投影3D" | "3D投影" | "3D투영" | "ฉาย3มิติ" => {
2068                let x = self.arg_num(&args,0,0.0)? as f32;
2069                let y = self.arg_num(&args,1,0.0)? as f32;
2070                let z = self.arg_num(&args,2,0.0)? as f32;
2071                let gfx = self.gfx.borrow();
2072                let near = -gfx.camera.zdist + 0.05;
2073                let d = gfx.camera.depth(x, y, z);
2074                if d <= near {
2075                    return Ok(Value::List(vec![Value::Number(-99999.0), Value::Number(-99999.0), Value::Number(d as f64)]));
2076                }
2077                let (sx, sy, depth) = gfx.camera.project(x, y, z);
2078                return Ok(Value::List(vec![Value::Number(sx as f64), Value::Number(sy as f64), Value::Number(depth as f64)]));
2079            }
2080            // draw_poly([x0,y0,x1,y1,…]) — filled 2-D polygon in the current colour,
2081            // honouring the blend mode (additive → translucent glow). Auto-closes.
2082            #[cfg(not(target_arch = "wasm32"))]
2083            "draw_poly" | "填充多边形" | "ポリゴン塗り" | "다각형채우기" | "เติมรูปหลายเหลี่ยม" => {
2084                let mut pts: Vec<[f32; 2]> = Vec::new();
2085                if let Some(Value::List(v)) = args.first() {
2086                    let mut i = 0;
2087                    while i + 1 < v.len() {
2088                        let x = self.to_number(&v[i]).unwrap_or(0.0) as f32;
2089                        let y = self.to_number(&v[i + 1]).unwrap_or(0.0) as f32;
2090                        pts.push([x, y]);
2091                        i += 2;
2092                    }
2093                }
2094                if pts.len() >= 3 {
2095                    if pts[0] != pts[pts.len() - 1] { let p0 = pts[0]; pts.push(p0); } // close
2096                    let mut gfx = self.gfx.borrow_mut();
2097                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
2098                    crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, std::slice::from_ref(&pts));
2099                }
2100                return Ok(Value::Unit);
2101            }
2102
2103            // ══════════════════════════════════════════════════════════════════
2104            // VECTOR TEXTURE BUILTINS  (src/gfx/vtex.rs)
2105            // All patterns are depth-biased so they appear on top of surfaces.
2106            // Plane defined by: centre (cx,cy,cz) + U tangent + V tangent.
2107            // Last two args always: fr (frame f32), hue (phase offset f32).
2108            // ══════════════════════════════════════════════════════════════════
2109
2110            // vtex_grid(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cw,ch, fr,hue)
2111            "vtex_grid" | "ลายตาราง" | "纹格" | "格子模様" | "격자무늬" => {
2112                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2113                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2114                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2115                let cols=self.arg_num(&args,9,10.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2116                let cw=self.arg_num(&args,11,1.)?as f32;  let ch=self.arg_num(&args,12,1.)?as f32;
2117                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2118                let mut gfx = self.gfx.borrow_mut();
2119                let cam = gfx.camera.clone();
2120                crate::gfx::vtex::draw_grid(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows,cw,ch, fr,hue);
2121                return Ok(Value::Unit);
2122            }
2123
2124            // vtex_rings(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_rings,n_sides, max_r,twist, fr,hue)
2125            "vtex_rings" | "ลายวงซ้อน" | "纹环" | "同心円" | "동심원" => {
2126                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2127                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2128                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2129                let nr=self.arg_num(&args,9,6.)?as usize; let ns=self.arg_num(&args,10,6.)?as usize;
2130                let mr=self.arg_num(&args,11,3.)?as f32;  let tw=self.arg_num(&args,12,0.)?as f32;
2131                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2132                let mut gfx = self.gfx.borrow_mut();
2133                let cam = gfx.camera.clone();
2134                crate::gfx::vtex::draw_rings(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nr,ns,mr,tw, fr,hue);
2135                return Ok(Value::Unit);
2136            }
2137
2138            // vtex_star(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_pts,r_out,r_in, rot_speed, fr,hue)
2139            "vtex_star" | "ลายดาว" | "纹星" | "星模様" | "별무늬" => {
2140                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2141                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2142                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2143                let np=self.arg_num(&args,9,6.)?as usize;
2144                let ro=self.arg_num(&args,10,2.)?as f32; let ri=self.arg_num(&args,11,1.)?as f32;
2145                let rs=self.arg_num(&args,12,0.01)?as f32;
2146                let fr=self.arg_num(&args,13,0.)?as f32; let hue=self.arg_num(&args,14,0.)?as f32;
2147                let mut gfx = self.gfx.borrow_mut();
2148                let cam = gfx.camera.clone();
2149                crate::gfx::vtex::draw_star(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, np,ro,ri,rs, fr,hue);
2150                return Ok(Value::Unit);
2151            }
2152
2153            // vtex_spiral(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_turns,max_r,steps, fr,hue)
2154            "vtex_spiral" | "ลายเกลียว" | "纹螺" | "螺旋" | "나선" => {
2155                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2156                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2157                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2158                let nt=self.arg_num(&args,9,3.)?as f32; let mr=self.arg_num(&args,10,3.)?as f32;
2159                let st=self.arg_num(&args,11,120.)?as usize;
2160                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2161                let mut gfx = self.gfx.borrow_mut();
2162                let cam = gfx.camera.clone();
2163                crate::gfx::vtex::draw_spiral(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,mr,st, fr,hue);
2164                return Ok(Value::Unit);
2165            }
2166
2167            // vtex_flower(cx,cy,cz, ux,uy,uz, vx,vy,vz, radius,n_sides, fr,hue)
2168            "vtex_flower" | "ลายดอก" | "纹花" | "花模様" | "꽃무늬" => {
2169                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2170                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2171                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2172                let r=self.arg_num(&args,9,1.)?as f32; let ns=self.arg_num(&args,10,24.)?as usize;
2173                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2174                let mut gfx = self.gfx.borrow_mut();
2175                let cam = gfx.camera.clone();
2176                crate::gfx::vtex::draw_flower(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2177                return Ok(Value::Unit);
2178            }
2179
2180            // vtex_letter_rain(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_cols,n_vis, col_w,row_h, speed, fr,hue)
2181            "vtex_letter_rain" | "ลายอักษรไหล" | "纹字雨" | "文字雨" | "글자비" => {
2182                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2183                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2184                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2185                let nc=self.arg_num(&args,9,16.)?as usize; let nv=self.arg_num(&args,10,14.)?as usize;
2186                let cw=self.arg_num(&args,11,0.65)?as f32; let rh=self.arg_num(&args,12,0.60)?as f32;
2187                let sp=self.arg_num(&args,13,0.025)?as f32;
2188                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2189                let mut gfx = self.gfx.borrow_mut();
2190                let cam = gfx.camera.clone();
2191                crate::gfx::vtex::draw_letter_rain(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nc,nv,cw,rh,sp, fr,hue);
2192                return Ok(Value::Unit);
2193            }
2194
2195            // vtex_hyperbolic_uv(cx,cy,cz, ux,uy,uz, vx,vy,vz, max_r,n_circles,n_rays, fr,hue)
2196            "vtex_hyperbolic_uv" | "ลายไฮเพอร์โบลิก" | "纹曲面" | "双曲線" | "쌍곡선" => {
2197                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2198                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2199                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2200                let mr=self.arg_num(&args,9,5.)?as f32;
2201                let nc=self.arg_num(&args,10,12.)?as usize; let nr=self.arg_num(&args,11,18.)?as usize;
2202                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2203                let mut gfx = self.gfx.borrow_mut();
2204                let cam = gfx.camera.clone();
2205                crate::gfx::vtex::draw_hyperbolic_uv(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, mr,nc,nr, fr,hue);
2206                return Ok(Value::Unit);
2207            }
2208
2209            // vtex_halftone(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell_w,cell_h, density, fr,hue)
2210            "vtex_halftone" | "ลายจุด" | "纹半调" | "網点模様" | "망점" => {
2211                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2212                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2213                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2214                let cols=self.arg_num(&args,9,16.)?as usize; let rows=self.arg_num(&args,10,12.)?as usize;
2215                let cw=self.arg_num(&args,11,0.5)?as f32; let ch=self.arg_num(&args,12,0.5)?as f32;
2216                let dens=self.arg_num(&args,13,0.4)?as f32;
2217                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2218                let mut gfx = self.gfx.borrow_mut();
2219                let cam = gfx.camera.clone();
2220                crate::gfx::vtex::draw_halftone(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows,cw,ch,dens, fr,hue);
2221                return Ok(Value::Unit);
2222            }
2223
2224            // vtex_tessellated(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell, amplitude,freq, fr,hue)
2225            "vtex_tessellated" | "ลายตาข่าย" | "纹镶嵌" | "網目模様" | "격자망" => {
2226                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2227                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2228                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2229                let cols=self.arg_num(&args,9,14.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2230                let cell=self.arg_num(&args,11,0.6)?as f32;
2231                let amp=self.arg_num(&args,12,0.25)?as f32; let freq=self.arg_num(&args,13,4.)?as f32;
2232                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2233                let mut gfx = self.gfx.borrow_mut();
2234                let cam = gfx.camera.clone();
2235                crate::gfx::vtex::draw_tessellated(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows,cell,amp,freq, fr,hue);
2236                return Ok(Value::Unit);
2237            }
2238
2239            // vtex_lotus(cx,cy,cz, ux,uy,uz, vx,vy,vz, r_inner,r_outer,n_petals, fr,hue)
2240            "vtex_lotus" | "ลายดอกบัว" | "纹莲" | "蓮模様" | "연꽃무늬" => {
2241                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2242                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2243                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2244                let ri=self.arg_num(&args,9,1.)?as f32; let ro=self.arg_num(&args,10,2.)?as f32;
2245                let np=self.arg_num(&args,11,12.)?as usize;
2246                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2247                let mut gfx = self.gfx.borrow_mut();
2248                let cam = gfx.camera.clone();
2249                crate::gfx::vtex::draw_lotus(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, ri,ro,np, fr,hue);
2250                return Ok(Value::Unit);
2251            }
2252
2253            // vtex_chakra(cx,cy,cz, ux,uy,uz, vx,vy,vz, r,n_spokes, fr,hue)
2254            "vtex_chakra" | "ลายจักร" | "纹轮" | "輪模様" | "바퀴무늬" => {
2255                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2256                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2257                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2258                let r=self.arg_num(&args,9,2.)?as f32; let ns=self.arg_num(&args,10,8.)?as usize;
2259                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2260                let mut gfx = self.gfx.borrow_mut();
2261                let cam = gfx.camera.clone();
2262                crate::gfx::vtex::draw_chakra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2263                return Ok(Value::Unit);
2264            }
2265
2266            // vtex_yantra(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_layers,max_r, fr,hue)
2267            "vtex_yantra" | "ลายยันต์" | "纹咒" | "護符模様" | "부적무늬" => {
2268                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2269                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2270                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2271                let nl=self.arg_num(&args,9,4.)?as usize; let mr=self.arg_num(&args,10,3.)?as f32;
2272                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2273                let mut gfx = self.gfx.borrow_mut();
2274                let cam = gfx.camera.clone();
2275                crate::gfx::vtex::draw_yantra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nl,mr, fr,hue);
2276                return Ok(Value::Unit);
2277            }
2278
2279            // vtex_spiked_cog(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_teeth,r_body,r_spike,r_hub,n_spokes, fr,hue)
2280            "vtex_spiked_cog" | "ฟันเฟืองหนาม" | "纹棘轮" | "歯車模様" | "톱니바퀴" => {
2281                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2282                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2283                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2284                let nt=self.arg_num(&args,9,12.)?as usize; let rb=self.arg_num(&args,10,1.)?as f32;
2285                let rs=self.arg_num(&args,11,1.3)?as f32; let rh=self.arg_num(&args,12,0.2)?as f32;
2286                let ns=self.arg_num(&args,13,6.)?as usize;
2287                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2288                let mut gfx = self.gfx.borrow_mut();
2289                let cam = gfx.camera.clone();
2290                crate::gfx::vtex::draw_spiked_cog(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,rb,rs,rh,ns, fr,hue);
2291                return Ok(Value::Unit);
2292            }
2293
2294            // vtex_torii(cx,cy,cz, ux,uy,uz, vx,vy,vz, width,height, fr,hue)
2295            "vtex_torii" | "ประตูโทริอิ" | "纹鸟居" | "鳥居" | "도리이" => {
2296                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2297                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2298                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2299                let w=self.arg_num(&args,9,4.)?as f32; let h=self.arg_num(&args,10,5.)?as f32;
2300                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2301                let mut gfx = self.gfx.borrow_mut();
2302                let cam = gfx.camera.clone();
2303                crate::gfx::vtex::draw_torii(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, w,h, fr,hue);
2304                return Ok(Value::Unit);
2305            }
2306
2307            // vtex_pagoda(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_tiers,base_w,tier_h,taper,eave_out, fr,hue)
2308            "vtex_pagoda" | "เจดีย์" | "纹塔" | "塔" | "탑" => {
2309                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2310                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2311                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2312                let nt=self.arg_num(&args,9,5.)?as usize; let bw=self.arg_num(&args,10,2.)?as f32;
2313                let th=self.arg_num(&args,11,1.)?as f32; let tp=self.arg_num(&args,12,0.72)?as f32;
2314                let eo=self.arg_num(&args,13,0.28)?as f32;
2315                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2316                let mut gfx = self.gfx.borrow_mut();
2317                let cam = gfx.camera.clone();
2318                crate::gfx::vtex::draw_pagoda(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,bw,th,tp,eo, fr,hue);
2319                return Ok(Value::Unit);
2320            }
2321
2322            // ══════════════════════════════════════════════════════════════════
2323            // AUDIO BUILTINS
2324            // ══════════════════════════════════════════════════════════════════
2325
2326            // audio_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth)
2327            #[cfg(not(target_arch = "wasm32"))]
2328            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2329                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2330                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2331                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2332                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2333                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2334                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2335                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2336                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2337                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2338                if let Some(audio) = &self.audio {
2339                    audio.set_tone(idx, ToneParams { x, y, z, w, freq, amp, lfo_rate, lfo_depth });
2340                }
2341                return Ok(Value::Unit);
2342            }
2343
2344            #[cfg(not(target_arch = "wasm32"))]
2345            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2346                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2347                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2348                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2349                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2350                if let Some(audio) = &self.audio {
2351                    audio.set_listener(cry, sry, crx, srx);
2352                }
2353                return Ok(Value::Unit);
2354            }
2355
2356            #[cfg(not(target_arch = "wasm32"))]
2357            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2358                let path = match args.first() {
2359                    Some(Value::Str(s)) => s.clone(),
2360                    _ => return Ok(Value::Unit),
2361                };
2362                let vol = self.arg_num(&args, 1, 0.5)? as f32;
2363                if let Some(audio) = &self.audio {
2364                    audio.load_bgm(&path, vol);
2365                }
2366                return Ok(Value::Unit);
2367            }
2368
2369            #[cfg(not(target_arch = "wasm32"))]
2370            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2371                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2372                if let Some(audio) = &self.audio {
2373                    audio.set_bgm_volume(vol);
2374                }
2375                return Ok(Value::Unit);
2376            }
2377
2378            #[cfg(not(target_arch = "wasm32"))]
2379            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2380                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2381                if let Some(audio) = &self.audio {
2382                    audio.set_master_volume(vol);
2383                }
2384                return Ok(Value::Unit);
2385            }
2386
2387            // WASM audio builtins — delegate to Web Audio API
2388            #[cfg(target_arch = "wasm32")]
2389            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2390                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2391                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2392                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2393                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2394                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2395                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2396                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2397                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2398                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2399                crate::gfx::audio_web::set_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth);
2400                return Ok(Value::Unit);
2401            }
2402
2403            #[cfg(target_arch = "wasm32")]
2404            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2405                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2406                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2407                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2408                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2409                crate::gfx::audio_web::set_listener(cry, sry, crx, srx);
2410                return Ok(Value::Unit);
2411            }
2412
2413            #[cfg(target_arch = "wasm32")]
2414            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2415                let path = self.arg_str(&args, 0, "");
2416                let vol  = self.arg_num(&args, 1, 0.5)? as f32;
2417                crate::gfx::audio_web::load_bgm(&path, vol);
2418                return Ok(Value::Unit);
2419            }
2420
2421            #[cfg(target_arch = "wasm32")]
2422            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2423                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2424                crate::gfx::audio_web::set_bgm_volume(vol);
2425                return Ok(Value::Unit);
2426            }
2427
2428            #[cfg(target_arch = "wasm32")]
2429            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2430                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2431                crate::gfx::audio_web::set_master_volume(vol);
2432                return Ok(Value::Unit);
2433            }
2434
2435            // ── รอหน้าต่าง() — block until window closed / Escape ──
2436            "รอหน้าต่าง" | "wait_window" | "gfx_wait" => {
2437                #[cfg(not(target_arch = "wasm32"))]
2438                loop {
2439                    let still_open = {
2440                        let gfx = self.gfx.borrow();
2441                        gfx.window.as_ref()
2442                            .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
2443                            .unwrap_or(false)
2444                    };
2445                    if !still_open { break; }
2446                    let (buf, w, h) = {
2447                        let gfx = self.gfx.borrow();
2448                        (gfx.buffer.clone(), gfx.width, gfx.height)
2449                    };
2450                    let mut gfx = self.gfx.borrow_mut();
2451                    if let Some(win) = gfx.window.as_mut() {
2452                        if win.update_with_buffer(&buf, w, h).is_err() { break; }
2453                    }
2454                }
2455                return Ok(Value::Unit);
2456            }
2457
2458            // ── File I/O ──────────────────────────────────────────────────────
2459            "read_file" | "อ่านไฟล์" => {
2460                let path = self.arg_str(&args, 0, "");
2461                return std::fs::read_to_string(&path)
2462                    .map(Value::Str)
2463                    .map_err(|e| EvalErr::from(format!("read_file '{path}': {e}")));
2464            }
2465            "write_file" | "เขียนไฟล์" => {
2466                let path    = self.arg_str(&args, 0, "");
2467                let content = self.arg_str(&args, 1, "");
2468                std::fs::write(&path, content.as_bytes())
2469                    .map_err(|e| EvalErr::from(format!("write_file '{path}': {e}")))?;
2470                return Ok(Value::Unit);
2471            }
2472            "print_file" | "พิมพ์ไฟล์" => {
2473                let content = self.arg_str(&args, 0, "");
2474                print!("{content}");
2475                return Ok(Value::Unit);
2476            }
2477
2478            // ── CLI arguments ─────────────────────────────────────────────────
2479            "get_args" | "รับอาร์กิวเมนต์" => {
2480                let v: Vec<Value> = std::env::args().map(Value::Str).collect();
2481                return Ok(Value::List(v));
2482            }
2483
2484            // ── String utilities ──────────────────────────────────────────────
2485            "split" | "str_split" | "แยก" => {
2486                let s   = self.arg_str(&args, 0, "");
2487                let sep = self.arg_str(&args, 1, "\n");
2488                let sep = if sep.is_empty() { "\n".into() } else { sep };
2489                let parts: Vec<Value> = s.split(sep.as_str())
2490                    .map(|p| Value::Str(p.to_string())).collect();
2491                return Ok(Value::List(parts));
2492            }
2493            "trim" | "str_trim" | "ตัดช่องว่าง" => {
2494                let s = self.arg_str(&args, 0, "");
2495                return Ok(Value::Str(s.trim().to_string()));
2496            }
2497            "starts_with" | "str_starts_with" | "เริ่มด้วย" => {
2498                let s      = self.arg_str(&args, 0, "");
2499                let prefix = self.arg_str(&args, 1, "");
2500                return Ok(Value::Bool(s.starts_with(prefix.as_str())));
2501            }
2502            "ends_with" | "str_ends_with" | "ลงท้ายด้วย" => {
2503                let s      = self.arg_str(&args, 0, "");
2504                let suffix = self.arg_str(&args, 1, "");
2505                return Ok(Value::Bool(s.ends_with(suffix.as_str())));
2506            }
2507            "str_replace" | "แทนสตริง" => {
2508                let s    = self.arg_str(&args, 0, "");
2509                let from = self.arg_str(&args, 1, "");
2510                let to   = self.arg_str(&args, 2, "");
2511                return Ok(Value::Str(s.replace(from.as_str(), to.as_str())));
2512            }
2513            "str_find" | "หาในสตริง" => {
2514                let s      = self.arg_str(&args, 0, "");
2515                let needle = self.arg_str(&args, 1, "");
2516                // Return char index (not byte index) for consistency with substr
2517                let pos = s.find(needle.as_str())
2518                    .map(|byte_i| s[..byte_i].chars().count() as f64)
2519                    .unwrap_or(-1.0);
2520                return Ok(Value::Number(pos));
2521            }
2522            "substr" | "str_slice" | "ส่วนสตริง" => {
2523                let s     = self.arg_str(&args, 0, "");
2524                let start = self.arg_num(&args, 1, 0.0)? as usize;
2525                let len   = args.get(2)
2526                    .map(|v| self.to_number(v).unwrap_or(999999.0) as usize)
2527                    .unwrap_or_else(|| s.chars().count().saturating_sub(start));
2528                let chars: Vec<char> = s.chars().collect();
2529                let end   = (start + len).min(chars.len());
2530                let slice: String = chars.get(start..end).unwrap_or(&[]).iter().collect();
2531                return Ok(Value::Str(slice));
2532            }
2533            "to_str" | "str" | "num_str" | "แปลงสตริง" => {
2534                let v = args.into_iter().next().unwrap_or(Value::Unit);
2535                return Ok(Value::Str(v.to_string()));
2536            }
2537            "str_repeat" | "ทำซ้ำสตริง" => {
2538                let s = self.arg_str(&args, 0, "");
2539                let n = self.arg_num(&args, 1, 1.0)? as usize;
2540                return Ok(Value::Str(s.repeat(n)));
2541            }
2542            "str_upper" => {
2543                let s = self.arg_str(&args, 0, "");
2544                return Ok(Value::Str(s.to_uppercase()));
2545            }
2546            "str_lower" => {
2547                let s = self.arg_str(&args, 0, "");
2548                return Ok(Value::Str(s.to_lowercase()));
2549            }
2550            "str_len" | "len" | "ความยาว" | "长度" | "長さ" | "길이" => {
2551                match args.first() {
2552                    Some(Value::Str(s))  => return Ok(Value::Number(s.chars().count() as f64)),
2553                    Some(Value::List(v)) => return Ok(Value::Number(v.len() as f64)),
2554                    _ => return Ok(Value::Number(0.0)),
2555                }
2556            }
2557
2558            // ── FNV-1a hash (deterministic, normalized 0.0–1.0) ──────────────
2559            "hash_str" | "แฮช" => {
2560                let s = self.arg_str(&args, 0, "");
2561                let mut h: u64 = 14695981039346656037_u64;
2562                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
2563                return Ok(Value::Number((h & 0xFFFFFF) as f64 / 16777215.0));
2564            }
2565            "hash_int" | "แฮชจำนวน" => {
2566                let s = self.arg_str(&args, 0, "");
2567                let n = self.arg_num(&args, 1, 100.0)? as u64;
2568                let mut h: u64 = 14695981039346656037_u64;
2569                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
2570                return Ok(Value::Number((h % n.max(1)) as f64));
2571            }
2572
2573            // ── List utilities ────────────────────────────────────────────────
2574            "list_new" | "รายการใหม่" | "新建列表" | "新規リスト" | "새목록" => {
2575                return Ok(Value::List(Vec::new()));
2576            }
2577            "list_push" | "เพิ่มรายการ" | "列表添加" | "リスト追加" | "목록추가" => {
2578                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
2579                let val = args.get(1).cloned().unwrap_or(Value::Unit);
2580                if let Value::List(mut v) = lst { v.push(val); return Ok(Value::List(v)); }
2581                return Ok(Value::List(vec![val]));
2582            }
2583            "list_get" | "รับรายการ" | "取元素" | "要素取得" | "요소가져오기" => {
2584                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
2585                let i   = self.arg_num(&args, 1, 0.0)? as usize;
2586                if let Value::List(v) = lst {
2587                    return Ok(v.get(i).cloned().unwrap_or(Value::Str(String::new())));
2588                }
2589                return Ok(Value::Str(String::new()));
2590            }
2591            "list_join" | "join" | "รวมรายการ" | "连接" | "連結" | "연결" => {
2592                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
2593                let sep = args.get(1).map(|v| v.to_string()).unwrap_or_default();
2594                if let Value::List(v) = lst {
2595                    return Ok(Value::Str(v.iter().map(|x| x.to_string())
2596                        .collect::<Vec<_>>().join(&sep)));
2597                }
2598                return Ok(Value::Str(String::new()));
2599            }
2600
2601            // ══════════════════════════════════════════════════════════════════
2602            // SVG EXPORT  (svg_begin / svg_rect / svg_circle / svg_line /
2603            //              svg_polyline / svg_text / svg_end / hsl_color)
2604            // Chinese aliases: 开始SVG 结束SVG SVG矩形 SVG圆形 SVG线段 SVG折线 SVG文本 HSL颜色
2605            // Thai aliases:    เริ่มSVG จบSVG SVGสี่เหลี่ยม SVGวงกลม SVGเส้น SVGเส้นหัก SVGข้อความ สีHSL
2606            // ══════════════════════════════════════════════════════════════════
2607
2608            "svg_begin" | "开始SVG" | "เริ่มSVG" => {
2609                let path   = self.arg_str(&args, 0, "output.svg");
2610                let width  = self.arg_num(&args, 1, 800.0)?;
2611                let height = self.arg_num(&args, 2, 600.0)?;
2612                *self.svg.borrow_mut() = Some(SvgWriter::new(path, width, height));
2613                return Ok(Value::Unit);
2614            }
2615
2616            "svg_rect" | "SVG矩形" | "SVGสี่เหลี่ยม" => {
2617                let x    = self.arg_num(&args, 0, 0.0)?;
2618                let y    = self.arg_num(&args, 1, 0.0)?;
2619                let w    = self.arg_num(&args, 2, 10.0)?;
2620                let h    = self.arg_num(&args, 3, 10.0)?;
2621                let fill = self.arg_str(&args, 4, "#ffffff");
2622                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2623                    svg.elements.push(format!(
2624                        "<rect x=\"{x:.1}\" y=\"{y:.1}\" width=\"{w:.1}\" \
2625                         height=\"{h:.1}\" fill=\"{fill}\"/>"));
2626                }
2627                return Ok(Value::Unit);
2628            }
2629
2630            "svg_circle" | "SVG圆形" | "SVGวงกลม" => {
2631                let cx   = self.arg_num(&args, 0, 0.0)?;
2632                let cy   = self.arg_num(&args, 1, 0.0)?;
2633                let r    = self.arg_num(&args, 2, 5.0)?;
2634                let fill = self.arg_str(&args, 3, "#ffffff");
2635                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2636                    svg.elements.push(format!(
2637                        "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{fill}\"/>"));
2638                }
2639                return Ok(Value::Unit);
2640            }
2641
2642            "svg_line" | "SVG线段" | "SVGเส้น" => {
2643                let x1     = self.arg_num(&args, 0, 0.0)?;
2644                let y1     = self.arg_num(&args, 1, 0.0)?;
2645                let x2     = self.arg_num(&args, 2, 0.0)?;
2646                let y2     = self.arg_num(&args, 3, 0.0)?;
2647                let stroke = self.arg_str(&args, 4, "#ffffff");
2648                let sw     = self.arg_num(&args, 5, 1.0)?;
2649                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2650                    svg.elements.push(format!(
2651                        "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" \
2652                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
2653                }
2654                return Ok(Value::Unit);
2655            }
2656
2657            "svg_polyline" | "SVG折线" | "SVGเส้นหัก" => {
2658                let pts    = self.arg_str(&args, 0, "");
2659                let stroke = self.arg_str(&args, 1, "#ffffff");
2660                let sw     = self.arg_num(&args, 2, 1.0)?;
2661                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2662                    svg.elements.push(format!(
2663                        "<polyline points=\"{pts}\" fill=\"none\" \
2664                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
2665                }
2666                return Ok(Value::Unit);
2667            }
2668
2669            "svg_text" | "SVG文本" | "SVGข้อความ" => {
2670                let x    = self.arg_num(&args, 0, 0.0)?;
2671                let y    = self.arg_num(&args, 1, 0.0)?;
2672                let text = self.arg_str(&args, 2, "");
2673                let fill = self.arg_str(&args, 3, "#ffffff");
2674                let size = self.arg_num(&args, 4, 12.0)?;
2675                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2676                    let safe = text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
2677                    svg.elements.push(format!(
2678                        "<text x=\"{x:.1}\" y=\"{y:.1}\" fill=\"{fill}\" \
2679                         font-family=\"monospace\" font-size=\"{size:.0}\">{safe}</text>"));
2680                }
2681                return Ok(Value::Unit);
2682            }
2683
2684            "svg_end" | "结束SVG" | "จบSVG" => {
2685                {
2686                    let borrow = self.svg.borrow();
2687                    if let Some(svg) = borrow.as_ref() {
2688                        svg.save().map_err(|e| EvalErr::from(format!("svg_end: {e}")))?;
2689                    }
2690                }
2691                *self.svg.borrow_mut() = None;
2692                return Ok(Value::Unit);
2693            }
2694
2695            "hsl_color" | "HSL颜色" | "สีHSL" => {
2696                let h = self.arg_num(&args, 0, 0.0)?;
2697                let s = self.arg_num(&args, 1, 70.0)?;
2698                let l = self.arg_num(&args, 2, 50.0)?;
2699                return Ok(Value::Str(hsl_to_hex(h, s, l)));
2700            }
2701
2702            // ══════════════════════════════════════════════════════════════════
2703            // FFT / AUDIO ANALYSIS BUILTINS  (native only)
2704            // ══════════════════════════════════════════════════════════════════
2705
2706            // fft_push(samples_list) — feed raw audio samples and run FFT
2707            #[cfg(not(target_arch = "wasm32"))]
2708            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => {
2709                if let Some(Value::List(v)) = args.first() {
2710                    let samples: Vec<f32> = v.iter()
2711                        .filter_map(|x| if let Value::Number(n) = x { Some(*n as f32) } else { None })
2712                        .collect();
2713                    self.fft.borrow_mut().push_samples(&samples);
2714                }
2715                return Ok(Value::Unit);
2716            }
2717
2718            // fft_bands(n) → list of n log-spaced magnitude bands (0..1)
2719            #[cfg(not(target_arch = "wasm32"))]
2720            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
2721                let n = self.arg_num(&args, 0, 32.0)? as usize;
2722                let bands = self.fft.borrow().freq_bands(n);
2723                *self.fft_bands_cache.borrow_mut() = bands.clone();
2724                return Ok(Value::List(bands.into_iter().map(|v| Value::Number(v as f64)).collect()));
2725            }
2726
2727            // fft_beat() → bool
2728            #[cfg(not(target_arch = "wasm32"))]
2729            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => {
2730                return Ok(Value::Bool(self.fft.borrow().is_beat()));
2731            }
2732
2733            // fft_beat_ratio() → f64  (1.0 = at threshold, >1 = strong beat)
2734            #[cfg(not(target_arch = "wasm32"))]
2735            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => {
2736                return Ok(Value::Number(self.fft.borrow().beat_ratio() as f64));
2737            }
2738
2739            // fft_rms() → f64
2740            #[cfg(not(target_arch = "wasm32"))]
2741            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => {
2742                return Ok(Value::Number(self.fft.borrow().rms() as f64));
2743            }
2744
2745            // fft_dominant_freq() → f64  in Hz
2746            #[cfg(not(target_arch = "wasm32"))]
2747            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => {
2748                return Ok(Value::Number(self.fft.borrow().dominant_freq() as f64));
2749            }
2750
2751            // ── wasm32 stubs: fft builtins are no-ops on web ───────────────
2752            #[cfg(target_arch = "wasm32")]
2753            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => { return Ok(Value::Unit); }
2754            #[cfg(target_arch = "wasm32")]
2755            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
2756                let n = self.arg_num(&args, 0, 32.0)? as usize;
2757                return Ok(Value::List(vec![Value::Number(0.0); n]));
2758            }
2759            #[cfg(target_arch = "wasm32")]
2760            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => { return Ok(Value::Bool(false)); }
2761            #[cfg(target_arch = "wasm32")]
2762            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => { return Ok(Value::Number(1.0)); }
2763            #[cfg(target_arch = "wasm32")]
2764            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => { return Ok(Value::Number(0.0)); }
2765            #[cfg(target_arch = "wasm32")]
2766            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => { return Ok(Value::Number(0.0)); }
2767
2768            // ══════════════════════════════════════════════════════════════════
2769            // PROCEDURAL TEXTURE BLIT BUILTINS  (screen-space)
2770            // All: name(dst_x, dst_y, width, height, ...params, palette)
2771            // palette: "rainbow" | "fire" | "ocean" | "psychedelic" | "neon" | "forest"
2772            // ══════════════════════════════════════════════════════════════════
2773
2774            // tex_checkerboard(x, y, w, h, tiles, r1,g1,b1, r2,g2,b2)
2775            "tex_checkerboard" | "ลายตารางหมากรุก" => {
2776                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2777                let tiles = self.arg_num(&args, 4, 8.0)? as u32;
2778                let (r1,g1,b1) = (self.arg_num(&args,5,255.)? as u32, self.arg_num(&args,6,255.)? as u32, self.arg_num(&args,7,255.)? as u32);
2779                let (r2,g2,b2) = (self.arg_num(&args,8,0.)? as u32,   self.arg_num(&args,9,0.)? as u32,   self.arg_num(&args,10,0.)? as u32);
2780                let c1 = (r1<<16)|(g1<<8)|b1; let c2 = (r2<<16)|(g2<<8)|b2;
2781                let mut gfx = self.gfx.borrow_mut();
2782                let (bw, bh) = (gfx.width, gfx.height);
2783                for row in 0..th { for col in 0..tw {
2784                    let cx = col as u32 * tiles / tw as u32;
2785                    let cy = row as u32 * tiles / th as u32;
2786                    let (dx, dy) = (tx+col, ty+row);
2787                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = if (cx+cy)%2==0 { c1 } else { c2 }; }
2788                }}
2789                return Ok(Value::Unit);
2790            }
2791
2792            // tex_gradient(x, y, w, h, angle_deg, r1,g1,b1, r2,g2,b2)
2793            "tex_gradient" | "ลายไล่สี" => {
2794                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2795                let angle = self.arg_num(&args, 4, 0.0)? as f32;
2796                let (r1,g1,b1) = (self.arg_num(&args,5,0.)? as f32/255., self.arg_num(&args,6,0.)? as f32/255., self.arg_num(&args,7,0.)? as f32/255.);
2797                let (r2,g2,b2) = (self.arg_num(&args,8,255.)? as f32/255., self.arg_num(&args,9,255.)? as f32/255., self.arg_num(&args,10,255.)? as f32/255.);
2798                let (ca, sa) = (angle.to_radians().cos(), angle.to_radians().sin());
2799                let mut gfx = self.gfx.borrow_mut();
2800                let (bw, bh) = (gfx.width, gfx.height);
2801                for row in 0..th { for col in 0..tw {
2802                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
2803                    let t = ((nx*ca + ny*sa + 0.707)/1.414).clamp(0.,1.);
2804                    let (dx, dy) = (tx+col, ty+row);
2805                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r1+(r2-r1)*t, g1+(g2-g1)*t, b1+(b2-b1)*t); }
2806                }}
2807                return Ok(Value::Unit);
2808            }
2809
2810            // tex_noise(x, y, w, h, scale, octaves, seed, palette)
2811            "tex_noise" | "ลายนอยส์" => {
2812                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2813                let scale   = self.arg_num(&args, 4, 4.0)? as f32;
2814                let octaves = self.arg_num(&args, 5, 4.0)? as u32;
2815                let seed    = self.arg_num(&args, 6, 0.0)? as u32;
2816                let palette = self.arg_str(&args, 7, "rainbow");
2817                let mut gfx = self.gfx.borrow_mut();
2818                let (bw, bh) = (gfx.width, gfx.height);
2819                for row in 0..th { for col in 0..tw {
2820                    let v = tex_fbm(col as f32*scale/tw as f32, row as f32*scale/th as f32, octaves, seed);
2821                    let [r,g,b] = tex_palette(&palette, v);
2822                    let (dx, dy) = (tx+col, ty+row);
2823                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r, g, b); }
2824                }}
2825                return Ok(Value::Unit);
2826            }
2827
2828            // tex_freq_map(x, y, w, h, time, speed, palette)
2829            // Uses bands written by the last fft_bands() call.
2830            "tex_freq_map" | "ลายความถี่" => {
2831                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2832                let time    = self.arg_num(&args, 4, 0.0)? as f32;
2833                let speed   = self.arg_num(&args, 5, 0.3)? as f32;
2834                let palette = self.arg_str(&args, 6, "rainbow");
2835                let bands: Vec<f32> = {
2836                    let c = self.fft_bands_cache.borrow();
2837                    if c.is_empty() { vec![0.0; 32] } else { c.clone() }
2838                };
2839                let n = bands.len().max(1);
2840                let mut gfx = self.gfx.borrow_mut();
2841                let (bw, bh) = (gfx.width, gfx.height);
2842                for row in 0..th { for col in 0..tw {
2843                    let band_idx = (col * n / tw.max(1)).min(n-1);
2844                    let mag = bands[band_idx].clamp(0.,1.);
2845                    let fill_y = (mag * th as f32) as usize;
2846                    if row >= th.saturating_sub(fill_y) {
2847                        let t = (col as f32/tw as f32 + time*speed) % 1.0;
2848                        let [r,g,b] = tex_palette(&palette, t);
2849                        let bright = mag * (1.0 - row as f32/th as f32 * 0.5);
2850                        let (dx, dy) = (tx+col, ty+row);
2851                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r*bright, g*bright, b*bright); }
2852                    }
2853                }}
2854                return Ok(Value::Unit);
2855            }
2856
2857            // tex_spiral(x, y, w, h, freq, bands, time, palette)
2858            "tex_spiral" | "ลายเกลียวหมุน" => {
2859                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2860                let freq    = self.arg_num(&args, 4, 5.0)? as f32;
2861                let n_bands = self.arg_num(&args, 5, 8.0)? as f32;
2862                let time    = self.arg_num(&args, 6, 0.0)? as f32;
2863                let palette = self.arg_str(&args, 7, "rainbow");
2864                let mut gfx = self.gfx.borrow_mut();
2865                let (bw, bh) = (gfx.width, gfx.height);
2866                for row in 0..th { for col in 0..tw {
2867                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
2868                    let r  = (nx*nx + ny*ny).sqrt();
2869                    let theta = ny.atan2(nx);
2870                    let t = ((r*freq - theta/std::f32::consts::TAU + time*0.5) * n_bands % 1.0).abs();
2871                    let [cr,cg,cb] = tex_palette(&palette, t);
2872                    let (dx, dy) = (tx+col, ty+row);
2873                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2874                }}
2875                return Ok(Value::Unit);
2876            }
2877
2878            // tex_ripple(x, y, w, h, freq, cx, cy, time, palette)
2879            "tex_ripple" | "ลายระลอก" => {
2880                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2881                let freq    = self.arg_num(&args, 4, 10.0)? as f32;
2882                let rcx     = self.arg_num(&args, 5, 0.5)? as f32;
2883                let rcy     = self.arg_num(&args, 6, 0.5)? as f32;
2884                let time    = self.arg_num(&args, 7, 0.0)? as f32;
2885                let palette = self.arg_str(&args, 8, "ocean");
2886                let mut gfx = self.gfx.borrow_mut();
2887                let (bw, bh) = (gfx.width, gfx.height);
2888                for row in 0..th { for col in 0..tw {
2889                    let nx = col as f32/tw as f32 - rcx; let ny = row as f32/th as f32 - rcy;
2890                    let r = (nx*nx + ny*ny).sqrt();
2891                    let t = ((r*freq - time) % 1.0).abs();
2892                    let [cr,cg,cb] = tex_palette(&palette, t);
2893                    let (dx, dy) = (tx+col, ty+row);
2894                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2895                }}
2896                return Ok(Value::Unit);
2897            }
2898
2899            // tex_mandelbrot(x, y, w, h, zoom, cx, cy, max_iter, palette)
2900            "tex_mandelbrot" | "ลายแมนเดลบรอต" => {
2901                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2902                let zoom     = self.arg_num(&args, 4, 1.0)?;
2903                let mcx      = self.arg_num(&args, 5, -0.5)?;
2904                let mcy      = self.arg_num(&args, 6, 0.0)?;
2905                let max_iter = self.arg_num(&args, 7, 64.0)? as u32;
2906                let palette  = self.arg_str(&args, 8, "psychedelic");
2907                let mut gfx = self.gfx.borrow_mut();
2908                let (bw, bh) = (gfx.width, gfx.height);
2909                for row in 0..th { for col in 0..tw {
2910                    let zx0 = (col as f64/tw as f64 - 0.5)/zoom + mcx;
2911                    let zy0 = (row as f64/th as f64 - 0.5)/zoom + mcy;
2912                    let mut x = 0.0f64; let mut y = 0.0f64; let mut i = 0u32;
2913                    while i < max_iter && x*x+y*y < 4.0 { let t=x*x-y*y+zx0; y=2.0*x*y+zy0; x=t; i+=1; }
2914                    let t = if i==max_iter { 0.0f32 } else {
2915                        (i as f32 - (x as f32*x as f32+y as f32*y as f32).ln().ln()/2.0f32.ln()) / max_iter as f32
2916                    };
2917                    let [cr,cg,cb] = tex_palette(&palette, t.clamp(0.,1.));
2918                    let (dx, dy) = (tx+col, ty+row);
2919                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2920                }}
2921                return Ok(Value::Unit);
2922            }
2923
2924            // tex_julia(x, y, w, h, c_re, c_im, max_iter, palette)
2925            "tex_julia" | "ลายจูเลีย" => {
2926                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2927                let c_re     = self.arg_num(&args, 4, -0.7)?;
2928                let c_im     = self.arg_num(&args, 5, 0.27)?;
2929                let max_iter = self.arg_num(&args, 6, 64.0)? as u32;
2930                let palette  = self.arg_str(&args, 7, "neon");
2931                let mut gfx = self.gfx.borrow_mut();
2932                let (bw, bh) = (gfx.width, gfx.height);
2933                for row in 0..th { for col in 0..tw {
2934                    let mut zx = (col as f64/tw as f64 - 0.5)*3.5;
2935                    let mut zy = (row as f64/th as f64 - 0.5)*3.5;
2936                    let mut i = 0u32;
2937                    while i < max_iter && zx*zx+zy*zy < 4.0 { let t=zx*zx-zy*zy+c_re; zy=2.0*zx*zy+c_im; zx=t; i+=1; }
2938                    let t = i as f32 / max_iter as f32;
2939                    let [cr,cg,cb] = tex_palette(&palette, t);
2940                    let (dx, dy) = (tx+col, ty+row);
2941                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2942                }}
2943                return Ok(Value::Unit);
2944            }
2945
2946            // tex_voronoi(x, y, w, h, cells, seed, palette)
2947            "tex_voronoi" | "ลายโวโรนอย" => {
2948                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2949                let cells   = self.arg_num(&args, 4, 16.0)? as u32;
2950                let seed    = self.arg_num(&args, 5, 42.0)? as u32;
2951                let palette = self.arg_str(&args, 6, "rainbow");
2952                let pts: Vec<[f32;2]> = (0..cells).map(|i| [tex_hash(i as i32,0,seed), tex_hash(i as i32,1,seed+999)]).collect();
2953                let mut gfx = self.gfx.borrow_mut();
2954                let (bw, bh) = (gfx.width, gfx.height);
2955                for row in 0..th { for col in 0..tw {
2956                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
2957                    let (min_d, nearest) = pts.iter().enumerate().fold((f32::MAX,0usize), |(d,idx),(i,&[cx,cy])| {
2958                        let dd = (fx-cx).powi(2)+(fy-cy).powi(2);
2959                        if dd < d { (dd,i) } else { (d,idx) }
2960                    });
2961                    let t = (nearest as f32/cells as f32 + min_d*4.0) % 1.0;
2962                    let [cr,cg,cb] = tex_palette(&palette, t);
2963                    let (dx, dy) = (tx+col, ty+row);
2964                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2965                }}
2966                return Ok(Value::Unit);
2967            }
2968
2969            // tex_halftone(x, y, w, h, dot_size, time, palette)
2970            "tex_halftone" | "ลายฮาล์ฟโทน" => {
2971                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2972                let dot_size = self.arg_num(&args, 4, 0.05)? as f32;
2973                let time     = self.arg_num(&args, 5, 0.0)? as f32;
2974                let palette  = self.arg_str(&args, 6, "rainbow");
2975                let mut gfx = self.gfx.borrow_mut();
2976                let (bw, bh) = (gfx.width, gfx.height);
2977                for row in 0..th { for col in 0..tw {
2978                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
2979                    let gx = (fx/dot_size).floor(); let gy = (fy/dot_size).floor();
2980                    let lx = (fx/dot_size - gx - 0.5)*2.0; let ly = (fy/dot_size - gy - 0.5)*2.0;
2981                    let r = (lx*lx + ly*ly).sqrt();
2982                    let t = (gx/(1.0/dot_size) + time*0.1) % 1.0;
2983                    let a = if r < 0.7 { ((0.7-r)/0.7).clamp(0.,1.) } else { 0.0 };
2984                    if a > 0.0 {
2985                        let [cr,cg,cb] = tex_palette(&palette, t);
2986                        let (dx, dy) = (tx+col, ty+row);
2987                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2988                    }
2989                }}
2990                return Ok(Value::Unit);
2991            }
2992
2993            // ══════════════════════════════════════════════════════════════════
2994            // RENDER / LIGHTING MODES  (holographic cel shading)
2995            // ══════════════════════════════════════════════════════════════════
2996            // set_shade_mode(m) — 0 flat · 1 cel · 2 holo (default)
2997            "set_shade_mode" | "设置着色" | "シェード設定" | "셰이드모드" | "ตั้งการแรเงา" => {
2998                let m = self.arg_num(&args, 0, 2.0)? as u8;
2999                self.gfx.borrow_mut().shade_mode = m;
3000                return Ok(Value::Unit);
3001            }
3002            // set_cel_bands(n) — number of posterisation bands (>=2)
3003            "set_cel_bands" | "设置色阶" | "セル段数" | "셀밴드" | "ตั้งระดับสี" => {
3004                let n = (self.arg_num(&args, 0, 4.0)? as u32).max(2);
3005                self.gfx.borrow_mut().shade.bands = n;
3006                return Ok(Value::Unit);
3007            }
3008            // set_shadow_color(r,g,b) — coloured-shadow tint, 0-255
3009            "set_shadow_color" | "设置阴影色" | "影の色" | "그림자색" | "ตั้งสีเงา" => {
3010                let r=self.arg_num(&args,0,26.)? as f32/255.0;
3011                let g=self.arg_num(&args,1,33.)? as f32/255.0;
3012                let b=self.arg_num(&args,2,77.)? as f32/255.0;
3013                self.gfx.borrow_mut().shade.shadow = [r,g,b];
3014                return Ok(Value::Unit);
3015            }
3016            // set_rim(strength, r,g,b) — holographic fresnel edge glow
3017            // ══════════════════════════════════════════════════════════════════
3018            // CRYPTOGRAPHY (ling-crypto) — geo suite, hybrid PQ KEM, holographic
3019            // Bytes cross the language boundary as lowercase hex strings.
3020            // ══════════════════════════════════════════════════════════════════
3021            #[cfg(not(target_arch = "wasm32"))]
3022            "crypto_hash" | "แฮชเข้ารหัส" | "几何哈希" | "幾何ハッシュ" | "기하해시" => {
3023                let s = self.arg_str(&args, 0, "");
3024                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(s.as_bytes()))));
3025            }
3026            // 3-D torus-knot fingerprint of any text/key → flat [x,y,z, x,y,z, …]
3027            #[cfg(not(target_arch = "wasm32"))]
3028            "knot_points" | "จุดปม" | "结点坐标" | "結び目点" | "매듭점" => {
3029                let s = self.arg_str(&args, 0, "");
3030                let shape = ling_crypto::geo::KnotShape::from_bytes(s.as_bytes());
3031                let mut out = Vec::with_capacity(shape.points.len() * 3);
3032                for p in &shape.points {
3033                    out.push(Value::Number(p[0] as f64));
3034                    out.push(Value::Number(p[1] as f64));
3035                    out.push(Value::Number(p[2] as f64));
3036                }
3037                return Ok(Value::List(out));
3038            }
3039            #[cfg(not(target_arch = "wasm32"))]
3040            "knot_label" | "ป้ายปม" | "结点标签" | "結び目ラベル" | "매듭라벨" => {
3041                let s = self.arg_str(&args, 0, "");
3042                return Ok(Value::Str(ling_crypto::geo::KnotShape::from_bytes(s.as_bytes()).label()));
3043            }
3044            // KEM keypair (hybrid X25519+ML-KEM-768) → integer handle
3045            #[cfg(not(target_arch = "wasm32"))]
3046            "knot_keygen" | "hybrid_keygen" | "สร้างกุญแจปม" | "生成密钥" | "鍵生成" | "키생성" => {
3047                self.crypto_ids.push(ling_crypto::KnotIdentity::generate());
3048                return Ok(Value::Number((self.crypto_ids.len() - 1) as f64));
3049            }
3050            #[cfg(not(target_arch = "wasm32"))]
3051            "knot_public" | "hybrid_public" | "กุญแจสาธารณะปม" | "公钥" | "公開鍵" | "공개키" => {
3052                let h = self.arg_num(&args, 0, 0.0)? as usize;
3053                let pk = self.crypto_ids.get(h).map(|id| hex_encode(id.public_key())).unwrap_or_default();
3054                return Ok(Value::Str(pk));
3055            }
3056            // encapsulate(pubkey_hex) → [ciphertext_hex, shared_secret_hex]
3057            #[cfg(not(target_arch = "wasm32"))]
3058            "knot_encapsulate" | "hybrid_encapsulate" | "ห่อกุญแจปม" | "封装密钥" | "カプセル化" | "캡슐화" => {
3059                let pk = hex_decode(&self.arg_str(&args, 0, ""));
3060                match ling_crypto::geo::knot_encapsulate(&pk) {
3061                    Ok((ct, ss)) => return Ok(Value::List(vec![Value::Str(hex_encode(&ct)), Value::Str(hex_encode(&ss))])),
3062                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3063                }
3064            }
3065            // decapsulate(handle, ciphertext_hex) → shared_secret_hex
3066            #[cfg(not(target_arch = "wasm32"))]
3067            "knot_decapsulate" | "hybrid_decapsulate" | "แกะกุญแจปม" | "解封装密钥" | "カプセル解除" | "캡슐해제" => {
3068                let h = self.arg_num(&args, 0, 0.0)? as usize;
3069                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3070                let ss = self.crypto_ids.get(h)
3071                    .and_then(|id| id.decapsulate(&ct).ok())
3072                    .map(|s| hex_encode(&s)).unwrap_or_default();
3073                return Ok(Value::Str(ss));
3074            }
3075            // Authenticated encryption (XChaCha20-Poly1305) — seal(key_hex, text) → ct_hex
3076            #[cfg(not(target_arch = "wasm32"))]
3077            "crypto_seal" | "ผนึก" | "封印" | "封印する" | "봉인" => {
3078                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3079                let pt = self.arg_str(&args, 1, "");
3080                match ling_crypto::geo::holo_seal(key, pt.as_bytes()) {
3081                    Ok(ct) => return Ok(Value::Str(hex_encode(&ct))),
3082                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3083                }
3084            }
3085            #[cfg(not(target_arch = "wasm32"))]
3086            "crypto_open" | "เปิดผนึก" | "解封" | "封印解除" | "봉인해제" => {
3087                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3088                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3089                match ling_crypto::geo::holo_open(key, &ct) {
3090                    Ok(pt) => return Ok(Value::Str(String::from_utf8_lossy(&pt).into_owned())),
3091                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3092                }
3093            }
3094            // Holographic all-or-nothing transform — 4-D fragment coords [a,b,c,d, …]
3095            #[cfg(not(target_arch = "wasm32"))]
3096            "holo_points" | "จุดโฮโลแกรม" | "全息点" | "ホログラム点" | "홀로그램점" => {
3097                let s = self.arg_str(&args, 0, "");
3098                let frags = ling_crypto::geo::scatter(s.as_bytes());
3099                let mut out = Vec::with_capacity(frags.len() * 4);
3100                for f in &frags { for c in f.coord { out.push(Value::Number(c as f64)); } }
3101                return Ok(Value::List(out));
3102            }
3103            #[cfg(not(target_arch = "wasm32"))]
3104            "holo_fragment_count" | "จำนวนชิ้นโฮโลแกรม" | "全息碎片数" | "ホログラム断片数" | "홀로그램조각수" => {
3105                let s = self.arg_str(&args, 0, "");
3106                return Ok(Value::Number(ling_crypto::geo::scatter(s.as_bytes()).len() as f64));
3107            }
3108
3109            // ══════════════════════════════════════════════════════════════════
3110            // ling-ui — animation easings + holographic vector widgets + text I/O
3111            // ══════════════════════════════════════════════════════════════════
3112            "ease" => {
3113                let name = self.arg_str(&args, 0, "ease");
3114                let t = self.arg_num(&args, 1, 0.0)? as f32;
3115                return Ok(Value::Number(ling_ui::Easing::from_name(&name).apply(t) as f64));
3116            }
3117            #[cfg(not(target_arch = "wasm32"))]
3118            "mouse_x" => {
3119                let gfx = self.gfx.borrow();
3120                let v = gfx.window.as_ref().and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).map(|p| p.0 as f64).unwrap_or(0.0);
3121                return Ok(Value::Number(v));
3122            }
3123            #[cfg(not(target_arch = "wasm32"))]
3124            "mouse_y" => {
3125                let gfx = self.gfx.borrow();
3126                let v = gfx.window.as_ref().and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).map(|p| p.1 as f64).unwrap_or(0.0);
3127                return Ok(Value::Number(v));
3128            }
3129            #[cfg(not(target_arch = "wasm32"))]
3130            "mouse_down" => {
3131                let gfx = self.gfx.borrow();
3132                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
3133                return Ok(Value::Bool(d));
3134            }
3135            #[cfg(not(target_arch = "wasm32"))]
3136            "ui_hot" | "热区" | "ホットエリア" | "핫존" | "พื้นที่สัมผัส" => {
3137                let x = self.arg_num(&args,0,0.0)? as f32;
3138                let y = self.arg_num(&args,1,0.0)? as f32;
3139                let w = self.arg_num(&args,2,0.0)? as f32;
3140                let h = self.arg_num(&args,3,0.0)? as f32;
3141                let gfx = self.gfx.borrow();
3142                let (mx,my) = gfx.window.as_ref().and_then(|win| win.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0,0.0));
3143                return Ok(Value::Bool(ling_ui::holo::hit_rect(mx,my,x,y,w,h)));
3144            }
3145            // ui_text(x, y, scale, "string") — holographic vector text
3146            "ui_text" | "界面文字" | "UI文字" | "UI텍스트" | "ข้อความหน้าจอ" => {
3147                let x = self.arg_num(&args,0,0.0)? as f32;
3148                let y = self.arg_num(&args,1,0.0)? as f32;
3149                let scale = self.arg_num(&args,2,16.0)? as f32;
3150                let s = self.arg_str(&args,3,"");
3151                let segs = ling_ui::holo::text_lines(&s, x, y, scale*0.62, scale, scale*0.24);
3152                let mut gfx = self.gfx.borrow_mut();
3153                let (w,h,color) = (gfx.width, gfx.height, gfx.color);
3154                for sg in segs { draw_line(&mut gfx.buffer, w, h, color, sg[0], sg[1], sg[2], sg[3]); }
3155                return Ok(Value::Unit);
3156            }
3157            // font_load("path.ttf") — load a vector font (outlines cached lazily as
3158            // cache/fonts/<stem>/<codepoint>.ling). Returns a handle, or -1 on failure.
3159            #[cfg(not(target_arch = "wasm32"))]
3160            "font_load" | "โหลดฟอนต์" | "加载字体" | "フォント読込" | "글꼴로드" => {
3161                let path = self.arg_str(&args, 0, "");
3162                // Optional 2nd arg: variable-font weight (e.g. 600 for a solid, bold UI).
3163                let weight = match self.arg_num(&args, 1, 0.0)? {
3164                    w if w > 0.0 => Some(w as f32),
3165                    _ => None,
3166                };
3167                // Try the path as given, then relative to the script's directory.
3168                let mut loaded = ling_graphics::VectorFont::from_path_weight(&path, weight);
3169                if loaded.is_err() {
3170                    if let Some(dir) = &self.source_dir {
3171                        let joined = dir.join(&path);
3172                        loaded = ling_graphics::VectorFont::from_path_weight(&joined.to_string_lossy(), weight);
3173                    }
3174                }
3175                match loaded {
3176                    Ok(f) => {
3177                        let id = self.fonts.len();
3178                        self.fonts.push(f);
3179                        return Ok(Value::Number(id as f64));
3180                    }
3181                    Err(e) => {
3182                        eprintln!("font_load failed ({path}): {e}");
3183                        return Ok(Value::Number(-1.0));
3184                    }
3185                }
3186            }
3187            // font_text(handle, x, y, px, "string") — anti-aliased *stroked* vector outline
3188            // in the current set_color / set_blend. (x,y) is the text box top-left.
3189            #[cfg(not(target_arch = "wasm32"))]
3190            "font_text" | "ข้อความฟอนต์" | "字体文本" | "フォント文字" | "글꼴텍스트" => {
3191                let id = self.arg_num(&args, 0, 0.0)? as i64;
3192                let x  = self.arg_num(&args, 1, 0.0)? as f32;
3193                let y  = self.arg_num(&args, 2, 0.0)? as f32;
3194                let px = self.arg_num(&args, 3, 16.0)? as f32;
3195                let s  = self.arg_str(&args, 4, "");
3196                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
3197                    let strokes = self.font_layout_2d(id as usize, x, y, px, &s);
3198                    let mut gfx = self.gfx.borrow_mut();
3199                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3200                    for pl in &strokes {
3201                        for seg in pl.windows(2) {
3202                            crate::gfx::raster::draw_line_aa(&mut gfx.buffer, w, h, color, add,
3203                                seg[0][0], seg[0][1], seg[1][0], seg[1][1]);
3204                        }
3205                    }
3206                }
3207                return Ok(Value::Unit);
3208            }
3209            // font_text_fill(handle, x, y, px, "string") — anti-aliased *filled* vector glyphs.
3210            #[cfg(not(target_arch = "wasm32"))]
3211            "font_text_fill" | "เติมฟอนต์" | "填充字体" | "フォント塗り" | "글꼴채움" => {
3212                let id = self.arg_num(&args, 0, 0.0)? as i64;
3213                let x  = self.arg_num(&args, 1, 0.0)? as f32;
3214                let y  = self.arg_num(&args, 2, 0.0)? as f32;
3215                let px = self.arg_num(&args, 3, 16.0)? as f32;
3216                let s  = self.arg_str(&args, 4, "");
3217                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
3218                    // fill each glyph independently so interior holes (winding) stay correct
3219                    let glyphs = self.font_layout_2d_glyphs(id as usize, x, y, px, &s);
3220                    let mut gfx = self.gfx.borrow_mut();
3221                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3222                    for contours in &glyphs {
3223                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, contours);
3224                    }
3225                }
3226                return Ok(Value::Unit);
3227            }
3228            // font_text_3d(handle, cx,cy,cz, ux,uy,uz, vx,vy,vz, size, "string")
3229            // — stroked vector text on a 3D plane: u = advance dir, v = up dir, size = world/em.
3230            //   Flows through the depth-sorted line pipeline, so it rotates with the camera (and 4D).
3231            #[cfg(not(target_arch = "wasm32"))]
3232            "font_text_3d" | "ข้อความฟอนต์3มิติ" | "字体3D" | "フォント3D" | "글꼴3D" => {
3233                let id = self.arg_num(&args, 0, 0.0)? as i64;
3234                let cx=self.arg_num(&args,1,0.0)? as f32; let cy=self.arg_num(&args,2,0.0)? as f32; let cz=self.arg_num(&args,3,0.0)? as f32;
3235                let ux=self.arg_num(&args,4,1.0)? as f32; let uy=self.arg_num(&args,5,0.0)? as f32; let uz=self.arg_num(&args,6,0.0)? as f32;
3236                let vx=self.arg_num(&args,7,0.0)? as f32; let vy=self.arg_num(&args,8,1.0)? as f32; let vz=self.arg_num(&args,9,0.0)? as f32;
3237                let size=self.arg_num(&args,10,1.0)? as f32;
3238                let s = self.arg_str(&args,11,"");
3239                if id >= 0 && (id as usize) < self.fonts.len() && size > 0.0 {
3240                    // Build world-space polylines: world = C + (pen+ex)*size*U + ey*size*V
3241                    let font = &mut self.fonts[id as usize];
3242                    let asc = font.ascent();
3243                    let mut pen = 0.0f32;
3244                    let mut lines: Vec<[f32; 6]> = Vec::new();
3245                    for ch in s.chars() {
3246                        let go = font.glyph_outline(ch, 0.01);
3247                        for pl in &go.polylines {
3248                            for seg in pl.windows(2) {
3249                                let map = |p: [f32; 2]| {
3250                                    let a = pen + p[0];
3251                                    let b = p[1] - asc; // shift so the top of the cap sits near C
3252                                    [cx + a*size*ux + b*size*vx,
3253                                     cy + a*size*uy + b*size*vy,
3254                                     cz + a*size*uz + b*size*vz]
3255                                };
3256                                let p0 = map(seg[0]); let p1 = map(seg[1]);
3257                                lines.push([p0[0],p0[1],p0[2], p1[0],p1[1],p1[2]]);
3258                            }
3259                        }
3260                        pen += go.advance;
3261                    }
3262                    let mut gfx = self.gfx.borrow_mut();
3263                    let color = gfx.color;
3264                    let near = -gfx.camera.zdist + 0.05;
3265                    for l in &lines {
3266                        let (mut ax, mut ay, mut az) = (l[0], l[1], l[2]);
3267                        let (mut bx, mut by, mut bz) = (l[3], l[4], l[5]);
3268                        let da = gfx.camera.depth(ax, ay, az);
3269                        let db = gfx.camera.depth(bx, by, bz);
3270                        if da <= near && db <= near { continue; }
3271                        if da <= near {
3272                            let t = (near - da) / (db - da);
3273                            ax += t*(bx-ax); ay += t*(by-ay); az += t*(bz-az);
3274                        } else if db <= near {
3275                            let t = (near - da) / (db - da);
3276                            bx = ax + t*(bx-ax); by = ay + t*(by-ay); bz = az + t*(bz-az);
3277                        }
3278                        let (sax, say, da2) = gfx.camera.project(ax, ay, az);
3279                        let (sbx, sby, db2) = gfx.camera.project(bx, by, bz);
3280                        let depth = (da2 + db2) / 2.0;
3281                        gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
3282                    }
3283                }
3284                return Ok(Value::Unit);
3285            }
3286            // font_width(handle, px, "string") — pixel width of a string in a loaded font.
3287            #[cfg(not(target_arch = "wasm32"))]
3288            "font_width" | "ความกว้างฟอนต์" | "字体宽度" | "フォント幅" | "글꼴너비" => {
3289                let id = self.arg_num(&args, 0, 0.0)? as i64;
3290                let px = self.arg_num(&args, 1, 16.0)? as f32;
3291                let s  = self.arg_str(&args, 2, "");
3292                if id >= 0 && (id as usize) < self.fonts.len() {
3293                    return Ok(Value::Number(self.fonts[id as usize].measure(&s, px) as f64));
3294                }
3295                return Ok(Value::Number(0.0));
3296            }
3297            // ui_frame(x,y,w,h, bracketLen) — sci-fi corner brackets
3298            "ui_frame" | "边框" | "フレーム枠" | "프레임틀" | "กรอบ" => {
3299                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3300                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3301                let l=self.arg_num(&args,4,14.0)? as f32;
3302                let segs = ling_ui::holo::corner_brackets(x,y,w0,h0,l);
3303                let mut gfx = self.gfx.borrow_mut();
3304                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3305                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3306                return Ok(Value::Unit);
3307            }
3308            // ui_bevel(x,y,w,h, bevel) — beveled holographic panel outline
3309            "ui_bevel" | "斜角框" | "ベベル枠" | "베벨틀" | "กรอบเฉียง" => {
3310                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3311                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3312                let bv=self.arg_num(&args,4,10.0)? as f32;
3313                let segs = ling_ui::holo::beveled_rect(x,y,w0,h0,bv);
3314                let mut gfx = self.gfx.borrow_mut();
3315                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3316                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3317                return Ok(Value::Unit);
3318            }
3319
3320            // ══════════════════════════════════════════════════════════════════
3321            // VECTOR UI TOOLKIT  (crates/ling-ui/src/widgets.rs)
3322            // All widgets are vector + theme-coloured with an optional trailing
3323            // r,g,b override; interactive ones read the mouse and return state.
3324            // ══════════════════════════════════════════════════════════════════
3325            #[cfg(not(target_arch = "wasm32"))]
3326            "ui_theme" | "界面主题" | "UIテーマ" | "인터페이스테마" | "ธีมส่วนติดต่อ" => {
3327                let cur = self.ui_theme;
3328                let primary = self.color_at(&args, 0,  cur.primary);
3329                let accent  = self.color_at(&args, 3,  cur.accent);
3330                let track   = self.color_at(&args, 6,  cur.track);
3331                let warn    = self.color_at(&args, 9,  cur.warn);
3332                let text    = self.color_at(&args, 12, cur.text);
3333                let bg      = self.color_at(&args, 15, cur.bg);
3334                self.ui_theme = UiTheme { primary, accent, track, warn, text, bg };
3335                return Ok(Value::Unit);
3336            }
3337
3338            // ── HUD ──────────────────────────────────────────────────────────
3339            #[cfg(not(target_arch = "wasm32"))]
3340            "ui_radar" | "雷达" | "レーダー" | "레이더" | "เรดาร์" => {
3341                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3342                let r=self.arg_num(&args,2,60.)? as f32; let sweep=self.arg_num(&args,3,0.)? as f32;
3343                let th=self.ui_theme;
3344                let prim=self.color_at(&args,4,th.primary);
3345                self.draw_ui(&ling_ui::widgets::radar(cx,cy,r,sweep, prim, th.accent, th.track));
3346                return Ok(Value::Unit);
3347            }
3348            #[cfg(not(target_arch = "wasm32"))]
3349            "ui_compass" | "罗盘" | "コンパス" | "나침반" | "เข็มทิศ" => {
3350                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3351                let w0=self.arg_num(&args,2,300.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
3352                let head=self.arg_num(&args,4,0.)? as f32;
3353                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3354                self.draw_ui(&ling_ui::widgets::compass(x,y,w0,h0,head, prim, th.track));
3355                return Ok(Value::Unit);
3356            }
3357            #[cfg(not(target_arch = "wasm32"))]
3358            "ui_reticle" | "准星" | "照準" | "조준선" | "เป้าเล็ง" => {
3359                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3360                let r=self.arg_num(&args,2,30.)? as f32; let spread=self.arg_num(&args,3,0.)? as f32;
3361                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3362                self.draw_ui(&ling_ui::widgets::reticle(cx,cy,r,spread, prim));
3363                return Ok(Value::Unit);
3364            }
3365            #[cfg(not(target_arch = "wasm32"))]
3366            "ui_target" | "锁定框" | "ターゲット" | "표적" | "กรอบเป้า" => {
3367                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3368                let w0=self.arg_num(&args,2,80.)? as f32; let h0=self.arg_num(&args,3,80.)? as f32;
3369                let lock=self.arg_num(&args,4,0.)? as f32;
3370                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3371                self.draw_ui(&ling_ui::widgets::target(x,y,w0,h0,lock, prim, th.accent));
3372                return Ok(Value::Unit);
3373            }
3374            #[cfg(not(target_arch = "wasm32"))]
3375            "ui_panel" | "面板" | "パネル" | "패널" | "แผง" => {
3376                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3377                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3378                let bv=self.arg_num(&args,4,12.)? as f32;
3379                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3380                self.draw_ui(&ling_ui::widgets::panel(x,y,w0,h0,bv, prim, th.bg));
3381                return Ok(Value::Unit);
3382            }
3383            #[cfg(not(target_arch = "wasm32"))]
3384            "ui_scanlines" | "扫描线" | "走査線" | "스캔라인" | "เส้นสแกน" => {
3385                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3386                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3387                let dens=self.arg_num(&args,4,24.)? as usize;
3388                let th=self.ui_theme; let line=self.color_at(&args,5,th.track);
3389                self.draw_ui(&ling_ui::widgets::scanlines(x,y,w0,h0,dens, line));
3390                return Ok(Value::Unit);
3391            }
3392
3393            // ── Meters ───────────────────────────────────────────────────────
3394            #[cfg(not(target_arch = "wasm32"))]
3395            "ui_bar" | "进度条" | "バー" | "막대" | "แถบ" => {
3396                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3397                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3398                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3399                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
3400                self.draw_ui(&ling_ui::widgets::bar(x,y,w0,h0, val/max.max(1e-6), fill, th.track));
3401                return Ok(Value::Unit);
3402            }
3403            #[cfg(not(target_arch = "wasm32"))]
3404            "ui_segbar" | "分段条" | "分割バー" | "분할막대" | "แถบแบ่ง" => {
3405                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3406                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3407                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3408                let segs=self.arg_num(&args,6,10.)? as usize;
3409                let th=self.ui_theme; let fill=self.color_at(&args,7,th.primary);
3410                self.draw_ui(&ling_ui::widgets::segbar(x,y,w0,h0, val/max.max(1e-6), segs, fill, th.track));
3411                return Ok(Value::Unit);
3412            }
3413            #[cfg(not(target_arch = "wasm32"))]
3414            "ui_gauge" | "仪表" | "ゲージ" | "게이지" | "มาตรวัด" => {
3415                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3416                let r=self.arg_num(&args,2,50.)? as f32;
3417                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
3418                let th=self.ui_theme; let needle=self.color_at(&args,5,th.warn);
3419                self.draw_ui(&ling_ui::widgets::gauge(cx,cy,r, val/max.max(1e-6), needle, th.accent, th.track));
3420                return Ok(Value::Unit);
3421            }
3422            #[cfg(not(target_arch = "wasm32"))]
3423            "ui_ring" | "环表" | "リングメーター" | "링미터" | "วงแหวนวัด" => {
3424                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3425                let r=self.arg_num(&args,2,40.)? as f32;
3426                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
3427                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
3428                self.draw_ui(&ling_ui::widgets::ring(cx,cy,r, val/max.max(1e-6), fill, th.track));
3429                return Ok(Value::Unit);
3430            }
3431            #[cfg(not(target_arch = "wasm32"))]
3432            "ui_vu" | "音量条" | "VUメーター" | "음량막대" | "มาตรเสียง" => {
3433                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3434                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,60.)? as f32;
3435                let levels=self.arg_list_f32(&args,4);
3436                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
3437                self.draw_ui(&ling_ui::widgets::vu(x,y,w0,h0, &levels, fill, th.warn));
3438                return Ok(Value::Unit);
3439            }
3440            #[cfg(not(target_arch = "wasm32"))]
3441            "ui_spark" | "迷你图" | "スパークライン" | "스파크라인" | "กราฟจิ๋ว" => {
3442                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3443                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
3444                let vals=self.arg_list_f32(&args,4);
3445                let th=self.ui_theme; let line=self.color_at(&args,5,th.accent);
3446                self.draw_ui(&ling_ui::widgets::spark(x,y,w0,h0, &vals, line));
3447                return Ok(Value::Unit);
3448            }
3449            #[cfg(not(target_arch = "wasm32"))]
3450            "ui_battery" | "电池" | "バッテリー" | "배터리" | "แบตเตอรี่" => {
3451                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3452                let w0=self.arg_num(&args,2,50.)? as f32; let h0=self.arg_num(&args,3,22.)? as f32;
3453                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3454                let th=self.ui_theme; let fill=self.color_at(&args,6,th.accent);
3455                self.draw_ui(&ling_ui::widgets::battery(x,y,w0,h0, val/max.max(1e-6), fill, th.track, th.warn));
3456                return Ok(Value::Unit);
3457            }
3458
3459            // ── Interface controls (interactive → return state) ──────────────
3460            #[cfg(not(target_arch = "wasm32"))]
3461            "ui_button" | "按钮" | "ボタン" | "버튼" | "ปุ่ม" => {
3462                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3463                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
3464                let (mx,my,down)=self.mouse_now();
3465                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
3466                let clicked = hover && down && !self.mouse_was_down;
3467                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3468                self.draw_ui(&ling_ui::widgets::button(x,y,w0,h0, hover, down&&hover, prim, th.bg));
3469                return Ok(Value::Number(if clicked {1.0} else {0.0}));
3470            }
3471            #[cfg(not(target_arch = "wasm32"))]
3472            "ui_toggle" | "开关" | "トグル" | "토글" | "สวิตช์" => {
3473                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3474                let w0=self.arg_num(&args,2,52.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
3475                let mut state=self.arg_num(&args,4,0.)? > 0.5;
3476                let (mx,my,down)=self.mouse_now();
3477                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
3478                if hover && down && !self.mouse_was_down { state = !state; }
3479                let th=self.ui_theme; let on=self.color_at(&args,5,th.accent);
3480                self.draw_ui(&ling_ui::widgets::toggle(x,y,w0,h0, state, on, th.track));
3481                return Ok(Value::Number(if state {1.0} else {0.0}));
3482            }
3483            #[cfg(not(target_arch = "wasm32"))]
3484            "ui_slider" | "滑块" | "スライダー" | "슬라이더" | "แถบเลื่อน" => {
3485                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3486                let w0=self.arg_num(&args,2,160.)? as f32;
3487                let mut val=self.arg_num(&args,3,0.)? as f32;
3488                let mn=self.arg_num(&args,4,0.)? as f32; let mx_=self.arg_num(&args,5,1.)? as f32;
3489                let (mx,my,down)=self.mouse_now();
3490                let hover=ling_ui::holo::hit_rect(mx,my,x-8.0,y-10.0,w0+16.0,20.0);
3491                if hover && down {
3492                    let frac=((mx-x)/w0).max(0.0).min(1.0);
3493                    val = mn + (mx_-mn)*frac;
3494                }
3495                let frac=((val-mn)/(mx_-mn).abs().max(1e-6)).max(0.0).min(1.0);
3496                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
3497                self.draw_ui(&ling_ui::widgets::slider(x,y,w0, frac, hover, fill, th.track));
3498                return Ok(Value::Number(val as f64));
3499            }
3500            #[cfg(not(target_arch = "wasm32"))]
3501            "ui_checkbox" | "复选框" | "チェックボックス" | "체크박스" | "ช่องเลือก" => {
3502                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3503                let s=self.arg_num(&args,2,20.)? as f32;
3504                let mut checked=self.arg_num(&args,3,0.)? > 0.5;
3505                let (mx,my,down)=self.mouse_now();
3506                let hover=ling_ui::holo::hit_rect(mx,my,x,y,s,s);
3507                if hover && down && !self.mouse_was_down { checked = !checked; }
3508                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3509                self.draw_ui(&ling_ui::widgets::checkbox(x,y,s, checked, hover, prim, th.track));
3510                return Ok(Value::Number(if checked {1.0} else {0.0}));
3511            }
3512            #[cfg(not(target_arch = "wasm32"))]
3513            "ui_tabs" | "标签页" | "タブ" | "탭" | "แท็บ" => {
3514                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3515                let w0=self.arg_num(&args,2,240.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
3516                let count=self.arg_num(&args,4,3.)? as usize;
3517                let mut active=self.arg_num(&args,5,0.)? as i32;
3518                let (mx,my,down)=self.mouse_now();
3519                let mut hover=-1;
3520                if my>=y && my<=y+h0 && mx>=x && mx<=x+w0 && count>0 {
3521                    hover = (((mx-x)/(w0/count as f32)) as i32).max(0).min(count as i32-1);
3522                    if down && !self.mouse_was_down { active = hover; }
3523                }
3524                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
3525                self.draw_ui(&ling_ui::widgets::tabs(x,y,w0,h0, count, active as usize, hover, prim, th.track));
3526                return Ok(Value::Number(active as f64));
3527            }
3528            #[cfg(not(target_arch = "wasm32"))]
3529            "ui_progress" | "进度" | "プログレス" | "진행바" | "ความคืบหน้า" => {
3530                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3531                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,12.)? as f32;
3532                let frac=self.arg_num(&args,4,0.)? as f32;
3533                let th=self.ui_theme; let fill=self.color_at(&args,5,th.accent);
3534                self.draw_ui(&ling_ui::widgets::progress(x,y,w0,h0, frac, fill, th.track));
3535                return Ok(Value::Unit);
3536            }
3537            #[cfg(not(target_arch = "wasm32"))]
3538            "ui_tooltip" | "提示框" | "ツールチップ" | "툴팁" | "คำแนะนำ" => {
3539                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3540                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
3541                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3542                self.draw_ui(&ling_ui::widgets::tooltip(x,y,w0,h0, prim, th.bg));
3543                return Ok(Value::Unit);
3544            }
3545            #[cfg(not(target_arch = "wasm32"))]
3546            "ui_stepper" | "步进器" | "ステッパー" | "스테퍼" | "ตัวปรับค่า" => {
3547                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3548                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
3549                let mut val=self.arg_num(&args,4,0.)? as f32; let step=self.arg_num(&args,5,1.)? as f32;
3550                let (mx,my,down)=self.mouse_now();
3551                let hm=ling_ui::holo::hit_rect(mx,my,x,y,h0,h0);
3552                let hp=ling_ui::holo::hit_rect(mx,my,x+w0-h0,y,h0,h0);
3553                if down && !self.mouse_was_down { if hm { val -= step; } if hp { val += step; } }
3554                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
3555                self.draw_ui(&ling_ui::widgets::stepper(x,y,w0,h0, hm, hp, prim, th.track));
3556                return Ok(Value::Number(val as f64));
3557            }
3558
3559            // ── Game UI ──────────────────────────────────────────────────────
3560            #[cfg(not(target_arch = "wasm32"))]
3561            "ui_healthbar" | "血条" | "体力バー" | "체력바" | "แถบพลังชีวิต" => {
3562                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3563                let w0=self.arg_num(&args,2,180.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3564                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3565                let pulse=self.arg_num(&args,6,0.)? as f32;
3566                let th=self.ui_theme; let full=self.color_at(&args,7,th.accent);
3567                self.draw_ui(&ling_ui::widgets::healthbar(x,y,w0,h0, val/max.max(1e-6), pulse, full, th.warn, th.track));
3568                return Ok(Value::Unit);
3569            }
3570            #[cfg(not(target_arch = "wasm32"))]
3571            "ui_cooldown" | "冷却" | "クールダウン" | "쿨다운" | "คูลดาวน์" => {
3572                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3573                let r=self.arg_num(&args,2,28.)? as f32; let frac=self.arg_num(&args,3,0.)? as f32;
3574                let th=self.ui_theme; let fill=self.color_at(&args,4,th.primary);
3575                self.draw_ui(&ling_ui::widgets::cooldown(cx,cy,r, frac, fill, th.track));
3576                return Ok(Value::Unit);
3577            }
3578            #[cfg(not(target_arch = "wasm32"))]
3579            "ui_counter" | "计数器" | "カウンター" | "카운터" | "ตัวนับ" => {
3580                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3581                let dw=self.arg_num(&args,2,14.)? as f32; let dh=self.arg_num(&args,3,24.)? as f32;
3582                let val=self.arg_num(&args,4,0.)? as i64; let digits=self.arg_num(&args,5,4.)? as usize;
3583                let th=self.ui_theme; let on=self.color_at(&args,6,th.primary);
3584                let off=ling_ui::widgets::shade(th.track,0.5);
3585                self.draw_ui(&ling_ui::widgets::counter(x,y,dw,dh, val, digits, on, off));
3586                return Ok(Value::Unit);
3587            }
3588            #[cfg(not(target_arch = "wasm32"))]
3589            "ui_minimap" | "小地图" | "ミニマップ" | "미니맵" | "แผนที่ย่อ" => {
3590                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3591                let w0=self.arg_num(&args,2,140.)? as f32; let h0=self.arg_num(&args,3,140.)? as f32;
3592                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3593                self.draw_ui(&ling_ui::widgets::minimap(x,y,w0,h0, prim, th.bg));
3594                return Ok(Value::Unit);
3595            }
3596            #[cfg(not(target_arch = "wasm32"))]
3597            "ui_dpad" | "方向键" | "方向パッド" | "방향패드" | "ปุ่มทิศทาง" => {
3598                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3599                let r=self.arg_num(&args,2,50.)? as f32;
3600                let (mx,my,down)=self.mouse_now();
3601                let mut dir=0;
3602                if down {
3603                    let (dx,dy)=(mx-cx, my-cy);
3604                    if dx*dx+dy*dy <= r*r {
3605                        if dx.abs() > dy.abs() { dir = if dx>0.0 {2} else {4}; }
3606                        else { dir = if dy>0.0 {3} else {1}; }
3607                    }
3608                }
3609                let th=self.ui_theme; let prim=self.color_at(&args,3,th.primary);
3610                self.draw_ui(&ling_ui::widgets::dpad(cx,cy,r, dir, prim, th.track));
3611                return Ok(Value::Number(dir as f64));
3612            }
3613            #[cfg(not(target_arch = "wasm32"))]
3614            "ui_slotgrid" | "物品格" | "スロットグリッド" | "슬롯격자" | "ช่องไอเทม" => {
3615                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3616                let cols=self.arg_num(&args,2,4.)? as usize; let rows=self.arg_num(&args,3,1.)? as usize;
3617                let cell=self.arg_num(&args,4,36.)? as f32; let sel=self.arg_num(&args,5,-1.)? as i32;
3618                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
3619                self.draw_ui(&ling_ui::widgets::slotgrid(x,y,cols,rows,cell, sel, prim, th.track));
3620                return Ok(Value::Unit);
3621            }
3622            #[cfg(not(target_arch = "wasm32"))]
3623            "ui_vignette" | "暗角" | "ビネット" | "비네트" | "ขอบมืด" => {
3624                let intensity=self.arg_num(&args,0,0.5)? as f32;
3625                let (w,h)={ let g=self.gfx.borrow(); (g.width as f32, g.height as f32) };
3626                let th=self.ui_theme; let col=self.color_at(&args,1,th.warn);
3627                self.draw_ui(&ling_ui::widgets::vignette(w,h, intensity, col));
3628                return Ok(Value::Unit);
3629            }
3630
3631            // ── Faux-3D in 2D space ──────────────────────────────────────────
3632            #[cfg(not(target_arch = "wasm32"))]
3633            "ui_gauge3d" | "立体仪表" | "立体ゲージ" | "입체게이지" | "มาตรวัด3มิติ" => {
3634                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3635                let r=self.arg_num(&args,2,50.)? as f32;
3636                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
3637                let spin=self.arg_num(&args,5,0.)? as f32;
3638                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
3639                self.draw_ui(&ling_ui::widgets::gauge3d(cx,cy,r, val/max.max(1e-6), spin, fill, th.track));
3640                return Ok(Value::Unit);
3641            }
3642            #[cfg(not(target_arch = "wasm32"))]
3643            "ui_panel3d" | "立体面板" | "立体パネル" | "입체패널" | "แผง3มิติ" => {
3644                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3645                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3646                let depth=self.arg_num(&args,4,14.)? as f32;
3647                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3648                self.draw_ui(&ling_ui::widgets::panel3d(x,y,w0,h0,depth, prim, th.bg));
3649                return Ok(Value::Unit);
3650            }
3651            #[cfg(not(target_arch = "wasm32"))]
3652            "ui_radar3d" | "立体雷达" | "立体レーダー" | "입체레이더" | "เรดาร์3มิติ" => {
3653                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3654                let r=self.arg_num(&args,2,60.)? as f32; let tilt=self.arg_num(&args,3,0.9)? as f32;
3655                let sweep=self.arg_num(&args,4,0.)? as f32;
3656                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3657                self.draw_ui(&ling_ui::widgets::radar3d(cx,cy,r,tilt,sweep, prim, th.track));
3658                return Ok(Value::Unit);
3659            }
3660
3661            // ── Interface sounds ─────────────────────────────────────────────
3662            #[cfg(not(target_arch = "wasm32"))]
3663            "audio_blip" | "提示音" | "ビープ音" | "효과음" | "เสียงบี๊บ" => {
3664                let freq=self.arg_num(&args,0,660.)? as f32;
3665                let dur=self.arg_num(&args,1,0.08)? as f32;
3666                let wave=Wave::from_name(&self.arg_str(&args,2,"sine"));
3667                let amp=self.arg_num(&args,3,0.25)? as f32;
3668                if let Some(audio)=&self.audio { audio.blip(freq, amp, dur, wave); }
3669                return Ok(Value::Unit);
3670            }
3671            #[cfg(not(target_arch = "wasm32"))]
3672            "ui_sound" | "界面音" | "UI音" | "인터페이스음" | "เสียงปุ่ม" => {
3673                let name=self.arg_str(&args,0,"click");
3674                if let Some(audio)=&self.audio {
3675                    match name.as_str() {
3676                        "hover"   => audio.blip(880.0, 0.10, 0.04, Wave::Sine),
3677                        "confirm" => { audio.blip(660.0, 0.22, 0.07, Wave::Square); audio.blip(990.0, 0.18, 0.10, Wave::Square); }
3678                        "error"   => { audio.blip(180.0, 0.30, 0.16, Wave::Saw); audio.blip(140.0, 0.30, 0.18, Wave::Saw); }
3679                        "toggle"  => audio.blip(520.0, 0.22, 0.05, Wave::Triangle),
3680                        "tick"    => audio.blip(1500.0, 0.12, 0.02, Wave::Square),
3681                        _         => audio.blip(720.0, 0.26, 0.05, Wave::Square), // "click"
3682                    }
3683                }
3684                return Ok(Value::Unit);
3685            }
3686
3687            // ══════════════════════════════════════════════════════════════════
3688            // MUSIC TOOLKIT  (crates/ling-music) — decode · analysis · GM synth ·
3689            // rhythm · karaoke. Analysis/decoding need no audio device; playback
3690            // and synthesis lazily start a dedicated music engine.
3691            // ══════════════════════════════════════════════════════════════════
3692
3693            // music_load(path) -> track handle (decodes WAV/FLAC/OGG/MP3/AAC)
3694            #[cfg(not(target_arch = "wasm32"))]
3695            "music_load" | "载入音乐" | "音楽読込" | "음악로드" | "โหลดเพลง" => {
3696                let path = self.arg_str(&args, 0, "");
3697                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3698                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3699                    else { path.clone() };
3700                match ling_music::load(&resolved) {
3701                    Ok(t) => { let id = self.tracks.len(); self.tracks.push(t); return Ok(Value::Number(id as f64)); }
3702                    Err(e) => { eprintln!("music_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3703                }
3704            }
3705            #[cfg(not(target_arch = "wasm32"))]
3706            "music_duration" | "音乐时长" | "音楽長さ" | "음악길이" | "ความยาวเพลง" => {
3707                let id = self.arg_num(&args,0,0.0)? as i64;
3708                let d = self.tracks.get(id as usize).map(|t| t.duration).unwrap_or(0.0);
3709                return Ok(Value::Number(d as f64));
3710            }
3711            #[cfg(not(target_arch = "wasm32"))]
3712            "music_bpm" | "节拍速度" | "テンポ" | "템포" | "จังหวะต่อนาที" => {
3713                let id = self.arg_num(&args,0,0.0)? as i64;
3714                let b = self.tracks.get(id as usize).map(|t| ling_music::analysis::bpm(&t.mono, t.rate)).unwrap_or(0.0);
3715                return Ok(Value::Number(b as f64));
3716            }
3717            #[cfg(not(target_arch = "wasm32"))]
3718            "music_key" | "调性" | "調性" | "조성" | "คีย์เพลง" => {
3719                let id = self.arg_num(&args,0,0.0)? as i64;
3720                let k = self.tracks.get(id as usize).map(|t| ling_music::analysis::key_name(&t.mono, t.rate)).unwrap_or_default();
3721                return Ok(Value::Str(k));
3722            }
3723            #[cfg(not(target_arch = "wasm32"))]
3724            "music_onsets" | "音符起点" | "オンセット" | "온셋" | "จุดเริ่มเสียง" => {
3725                let id = self.arg_num(&args,0,0.0)? as i64;
3726                let v = self.tracks.get(id as usize).map(|t| ling_music::analysis::onsets(&t.mono, t.rate)).unwrap_or_default();
3727                return Ok(Value::List(v.into_iter().map(|x| Value::Number(x as f64)).collect()));
3728            }
3729            #[cfg(not(target_arch = "wasm32"))]
3730            "music_beat_grid" | "节拍网格" | "ビートグリッド" | "비트그리드" | "กริดจังหวะ" => {
3731                let id = self.arg_num(&args,0,0.0)? as i64;
3732                let beats = self.tracks.get(id as usize).map(|t| {
3733                    let b = ling_music::analysis::bpm(&t.mono, t.rate);
3734                    ling_music::analysis::beat_grid(&t.mono, t.rate, b)
3735                }).unwrap_or_default();
3736                return Ok(Value::List(beats.into_iter().map(|x| Value::Number(x as f64)).collect()));
3737            }
3738
3739            // ── playback ──
3740            #[cfg(not(target_arch = "wasm32"))]
3741            "music_play" | "播放音乐" | "音楽再生" | "음악재생" | "เล่นเพลง" => {
3742                let id = self.arg_num(&args,0,0.0)? as i64;
3743                if self.ensure_music() {
3744                    let track = self.tracks.get(id as usize).map(|t| (t.stereo.clone(), t.rate));
3745                    if let (Some((st, rate)), Some(m)) = (track, &self.music) { m.set_track(st, rate); m.play(); }
3746                    else if let Some(m) = &self.music { m.play(); }
3747                }
3748                return Ok(Value::Unit);
3749            }
3750            #[cfg(not(target_arch = "wasm32"))]
3751            "music_pause" | "暂停音乐" | "音楽一時停止" | "음악일시정지" | "หยุดเพลงชั่วคราว" => {
3752                if let Some(m) = &self.music { m.pause(); } return Ok(Value::Unit);
3753            }
3754            #[cfg(not(target_arch = "wasm32"))]
3755            "music_stop" | "停止音乐" | "音楽停止" | "음악정지" | "หยุดเพลง" => {
3756                if let Some(m) = &self.music { m.stop(); } return Ok(Value::Unit);
3757            }
3758            #[cfg(not(target_arch = "wasm32"))]
3759            "music_seek" | "定位音乐" | "音楽シーク" | "음악탐색" | "ค้นหาเพลง" => {
3760                let sec = self.arg_num(&args,0,0.0)? as f32;
3761                if let Some(m) = &self.music { m.seek(sec); } return Ok(Value::Unit);
3762            }
3763            #[cfg(not(target_arch = "wasm32"))]
3764            "music_pos" | "音乐位置" | "音楽位置" | "음악위치" | "ตำแหน่งเพลง" => {
3765                let p = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
3766                return Ok(Value::Number(p as f64));
3767            }
3768            #[cfg(not(target_arch = "wasm32"))]
3769            "music_volume" | "音乐音量" | "音楽音量" | "음악음량" | "ระดับเพลง" => {
3770                let v = self.arg_num(&args,0,0.8)? as f32;
3771                if self.ensure_music() { if let Some(m) = &self.music { m.set_volume(v); } }
3772                return Ok(Value::Unit);
3773            }
3774
3775            // ── synthesis (GM-capable, patches from .ling files) ──
3776            #[cfg(not(target_arch = "wasm32"))]
3777            "music_patch" | "乐器音色" | "音色読込" | "악기패치" | "แพตช์เครื่องดนตรี" => {
3778                let path = self.arg_str(&args, 0, "");
3779                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3780                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3781                    else { path.clone() };
3782                if !self.ensure_music() { return Ok(Value::Number(-1.0)); }
3783                match ling_music::patch::from_path(&resolved) {
3784                    Ok(p) => { let id = self.music.as_ref().unwrap().add_patch(p); return Ok(Value::Number(id as f64)); }
3785                    Err(e) => { eprintln!("music_patch failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3786                }
3787            }
3788            #[cfg(not(target_arch = "wasm32"))]
3789            "music_note" | "弹音符" | "音符演奏" | "음표연주" | "เล่นโน้ต" => {
3790                let inst = self.arg_num(&args,0,0.0)? as usize;
3791                let midi = self.pitch_arg(&args, 1, 60);
3792                let dur  = self.arg_num(&args,2,0.5)? as f32;
3793                let vel  = self.arg_num(&args,3,0.9)? as f32;
3794                if self.ensure_music() { if let Some(m) = &self.music { m.note(inst, midi, vel, dur); } }
3795                return Ok(Value::Unit);
3796            }
3797            #[cfg(not(target_arch = "wasm32"))]
3798            "music_note_on" | "音符开始" | "音符オン" | "음표켜기" | "โน้ตเริ่ม" => {
3799                let inst = self.arg_num(&args,0,0.0)? as usize;
3800                let midi = self.pitch_arg(&args, 1, 60);
3801                let vel  = self.arg_num(&args,2,0.9)? as f32;
3802                if self.ensure_music() { if let Some(m) = &self.music { m.note_on(inst, midi, vel); } }
3803                return Ok(Value::Unit);
3804            }
3805            #[cfg(not(target_arch = "wasm32"))]
3806            "music_note_off" | "音符结束" | "音符オフ" | "음표끄기" | "โน้ตจบ" => {
3807                let inst = self.arg_num(&args,0,0.0)? as usize;
3808                let midi = self.pitch_arg(&args, 1, 60);
3809                if let Some(m) = &self.music { m.note_off(inst, midi); }
3810                return Ok(Value::Unit);
3811            }
3812
3813            // ── rhythm-game judging ──
3814            #[cfg(not(target_arch = "wasm32"))]
3815            "music_judge" | "判定" | "判定する" | "판정" | "ตัดสินจังหวะ" => {
3816                let delta_ms = self.arg_num(&args,0,9999.0)? as f32;
3817                return Ok(Value::Number(ling_music::Grade::judge(delta_ms).index() as f64));
3818            }
3819            #[cfg(not(target_arch = "wasm32"))]
3820            "music_grade_name" | "判定名" | "判定名称" | "판정이름" | "ชื่อการตัดสิน" => {
3821                let idx = self.arg_num(&args,0,4.0)? as i32;
3822                return Ok(Value::Str(ling_music::Grade::from_index(idx).name().to_string()));
3823            }
3824
3825            // ── karaoke ──
3826            #[cfg(not(target_arch = "wasm32"))]
3827            "music_lrc" | "载入歌词" | "歌詞読込" | "가사로드" | "โหลดเนื้อเพลง" => {
3828                let path = self.arg_str(&args, 0, "");
3829                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3830                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3831                    else { path.clone() };
3832                match std::fs::read_to_string(&resolved) {
3833                    Ok(text) => { let id = self.lyrics.len(); self.lyrics.push(ling_music::Lyrics::parse(&text)); return Ok(Value::Number(id as f64)); }
3834                    Err(e) => { eprintln!("music_lrc failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3835                }
3836            }
3837            #[cfg(not(target_arch = "wasm32"))]
3838            "music_lyric" | "当前歌词" | "現在歌詞" | "현재가사" | "เนื้อเพลงปัจจุบัน" => {
3839                let id = self.arg_num(&args,0,0.0)? as i64;
3840                let t  = self.arg_num(&args,1,0.0)? as f32;
3841                let line = self.lyrics.get(id as usize).map(|l| l.line_at(t).to_string()).unwrap_or_default();
3842                return Ok(Value::Str(line));
3843            }
3844            #[cfg(not(target_arch = "wasm32"))]
3845            "music_mic_pitch" | "麦克风音高" | "マイク音程" | "마이크음정" | "ระดับเสียงไมค์" => {
3846                let hz = if let Some(mic) = self.mic.as_ref() {
3847                    let s = mic.latest_samples();
3848                    let rate = mic.sample_rate();
3849                    ling_music::pitch::detect(&s, rate).unwrap_or(0.0)
3850                } else { 0.0 };
3851                return Ok(Value::Number(hz as f64));
3852            }
3853            #[cfg(not(target_arch = "wasm32"))]
3854            "music_note_name" | "音名" | "音名称" | "음이름" | "ชื่อโน้ต" => {
3855                let hz = self.arg_num(&args,0,0.0)? as f32;
3856                return Ok(Value::Str(ling_music::note::hz_to_name(hz)));
3857            }
3858            #[cfg(not(target_arch = "wasm32"))]
3859            "music_hz" | "音符频率" | "音符周波数" | "음표주파수" | "ความถี่โน้ต" => {
3860                let midi = self.pitch_arg(&args, 0, 69);
3861                return Ok(Value::Number(ling_music::note::midi_to_hz(midi as f32) as f64));
3862            }
3863            #[cfg(not(target_arch = "wasm32"))]
3864            "music_pitch_score" | "音准评分" | "音程スコア" | "음정점수" | "คะแนนเสียง" => {
3865                let hz = self.arg_num(&args,0,0.0)? as f32;
3866                let target = self.arg_num(&args,1,0.0)? as f32;
3867                return Ok(Value::Number(ling_music::karaoke::pitch_score(hz, target) as f64));
3868            }
3869
3870            // ── MIDI (inaudible note source: drive coins, cues, etc.) ──
3871            #[cfg(not(target_arch = "wasm32"))]
3872            "music_midi_load" | "载入MIDI" | "MIDI読込" | "미디로드" | "โหลดมิดี" => {
3873                let path = self.arg_str(&args, 0, "");
3874                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3875                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3876                    else { path.clone() };
3877                match ling_music::midi::load(&resolved) {
3878                    Ok(m) => { let id = self.midis.len(); self.midis.push(m); return Ok(Value::Number(id as f64)); }
3879                    Err(e) => { eprintln!("music_midi_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3880                }
3881            }
3882            #[cfg(not(target_arch = "wasm32"))]
3883            "music_midi_count" | "MIDI数量" | "MIDI数" | "미디수" | "จำนวนมิดี" => {
3884                let id = self.arg_num(&args,0,0.0)? as i64;
3885                let n = self.midis.get(id as usize).map(|m| m.notes.len()).unwrap_or(0);
3886                return Ok(Value::Number(n as f64));
3887            }
3888            // music_midi_notes(id) -> flat [time, midi, time, midi, …]
3889            #[cfg(not(target_arch = "wasm32"))]
3890            "music_midi_notes" | "MIDI音符" | "MIDIノート" | "미디음표" | "โน้ตมิดี" => {
3891                let id = self.arg_num(&args,0,0.0)? as i64;
3892                let mut out = Vec::new();
3893                if let Some(m) = self.midis.get(id as usize) {
3894                    for n in &m.notes { out.push(Value::Number(n.time as f64)); out.push(Value::Number(n.midi as f64)); }
3895                }
3896                return Ok(Value::List(out));
3897            }
3898            // music_midi_bars(id) -> flat [time, midi, dur, …] (for karaoke note bars)
3899            #[cfg(not(target_arch = "wasm32"))]
3900            "music_midi_bars" | "MIDI音条" | "MIDIバー" | "미디바" | "แท่งมิดี" => {
3901                let id = self.arg_num(&args,0,0.0)? as i64;
3902                let mut out = Vec::new();
3903                if let Some(m) = self.midis.get(id as usize) {
3904                    for n in &m.notes {
3905                        out.push(Value::Number(n.time as f64));
3906                        out.push(Value::Number(n.midi as f64));
3907                        out.push(Value::Number(n.dur as f64));
3908                    }
3909                }
3910                return Ok(Value::List(out));
3911            }
3912
3913            // music_fft(track_id, nbands) -> spectrum at the current playback position
3914            #[cfg(not(target_arch = "wasm32"))]
3915            "music_fft" | "音乐频谱" | "音楽スペクトル" | "음악스펙트럼" | "สเปกตรัมเพลง" => {
3916                let id = self.arg_num(&args,0,0.0)? as i64;
3917                let nbands = self.arg_num(&args,1,16.0)? as usize;
3918                let pos = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
3919                if let Some(t) = self.tracks.get(id as usize) {
3920                    let idx = (pos * t.rate as f32) as usize;
3921                    let end = (idx + 2048).min(t.mono.len());
3922                    if end > idx + 64 {
3923                        self.fft.borrow_mut().push_samples(&t.mono[idx..end]);
3924                    }
3925                }
3926                let bands = self.fft.borrow().freq_bands(nbands);
3927                return Ok(Value::List(bands.into_iter().map(|x| Value::Number(x as f64)).collect()));
3928            }
3929
3930            // ── spatial (2D/3D/4D) one-shot SFX ──
3931            #[cfg(not(target_arch = "wasm32"))]
3932            "audio_sfx" | "音效" | "空間効果音" | "공간효과음" | "เสียงเอฟเฟกต์" => {
3933                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32; let z=self.arg_num(&args,2,0.0)? as f32;
3934                let w=self.arg_num(&args,3,1.0)? as f32; let freq=self.arg_num(&args,4,440.0)? as f32;
3935                let amp=self.arg_num(&args,5,0.3)? as f32; let dur=self.arg_num(&args,6,0.15)? as f32;
3936                let wave=Wave::from_name(&self.arg_str(&args,7,"sine"));
3937                if let Some(a)=&self.audio { a.sfx(x,y,z,w,freq,amp,dur,wave); }
3938                return Ok(Value::Unit);
3939            }
3940            // ── sample load / positional play / loop / stop ──
3941            #[cfg(not(target_arch = "wasm32"))]
3942            "audio_sample_load" | "载入采样" | "サンプル読込" | "샘플로드" | "โหลดตัวอย่างเสียง" => {
3943                let path = self.arg_str(&args, 0, "");
3944                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3945                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3946                    else { path.clone() };
3947                match ling_music::load(&resolved) {
3948                    Ok(t) => {
3949                        if let Some(a)=&self.audio { return Ok(Value::Number(a.add_sample(t.mono, t.rate) as f64)); }
3950                        return Ok(Value::Number(-1.0));
3951                    }
3952                    Err(e) => { eprintln!("audio_sample_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3953                }
3954            }
3955            #[cfg(not(target_arch = "wasm32"))]
3956            "audio_sample_play" | "播放采样" | "サンプル再生" | "샘플재생" | "เล่นตัวอย่างเสียง" => {
3957                let id=self.arg_num(&args,0,0.0)? as usize;
3958                let x=self.arg_num(&args,1,0.0)? as f32; let y=self.arg_num(&args,2,0.0)? as f32; let z=self.arg_num(&args,3,0.0)? as f32;
3959                let w=self.arg_num(&args,4,1.0)? as f32; let vol=self.arg_num(&args,5,1.0)? as f32;
3960                let looping=self.arg_num(&args,6,0.0)? > 0.5;
3961                let v = self.audio.as_ref().map(|a| a.play_sample(id,x,y,z,w,vol,looping)).unwrap_or(0);
3962                return Ok(Value::Number(v as f64));
3963            }
3964            #[cfg(not(target_arch = "wasm32"))]
3965            "audio_sample_stop" | "停止采样" | "サンプル停止" | "샘플정지" | "หยุดตัวอย่างเสียง" => {
3966                let v=self.arg_num(&args,0,0.0)? as u32;
3967                if let Some(a)=&self.audio { a.stop_sample(v); }
3968                return Ok(Value::Unit);
3969            }
3970            // ── master FX: delay / reverb / low-pass (underwater) ──
3971            #[cfg(not(target_arch = "wasm32"))]
3972            "audio_fx_delay" | "回声" | "ディレイ効果" | "딜레이" | "เสียงสะท้อน" => {
3973                let time=self.arg_num(&args,0,0.3)? as f32; let fb=self.arg_num(&args,1,0.3)? as f32; let mix=self.arg_num(&args,2,0.3)? as f32;
3974                if let Some(a)=&self.audio { a.fx_delay(time,fb,mix); }
3975                return Ok(Value::Unit);
3976            }
3977            #[cfg(not(target_arch = "wasm32"))]
3978            "audio_fx_reverb" | "混响" | "リバーブ" | "리버브" | "เสียงก้อง" => {
3979                let mix=self.arg_num(&args,0,0.3)? as f32;
3980                if let Some(a)=&self.audio { a.fx_reverb(mix); }
3981                return Ok(Value::Unit);
3982            }
3983            #[cfg(not(target_arch = "wasm32"))]
3984            "audio_fx_lowpass" | "低通滤波" | "ローパス" | "저역통과" | "กรองความถี่ต่ำ" => {
3985                let cutoff=self.arg_num(&args,0,1.0)? as f32;
3986                if let Some(a)=&self.audio { a.fx_lowpass(cutoff); }
3987                return Ok(Value::Unit);
3988            }
3989
3990            // ══════════════════════════════════════════════════════════════════
3991            // PHYSICS BUILTINS  (crates/ling-physics) — soft bodies, rigid+angular,
3992            // and a fast 2-D water/oil liquid sim mappable onto 3-D surfaces.
3993            // ══════════════════════════════════════════════════════════════════
3994
3995            // ── soft bodies (deformable bouncy balls) ──
3996            #[cfg(not(target_arch = "wasm32"))]
3997            "soft_ball" | "软球" | "ソフトボール" | "소프트볼" | "ลูกบอลนุ่ม" => {
3998                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32; let z=self.arg_num(&args,2,0.)? as f32;
3999                let r=self.arg_num(&args,3,1.0)? as f32;
4000                let b = ling_physics::soft::SoftBody::sphere(ling_physics::Vec3::new(x,y,z), r, 8, 12, 1.0);
4001                let id = self.soft_bodies.len(); self.soft_bodies.push(b);
4002                return Ok(Value::Number(id as f64));
4003            }
4004            #[cfg(not(target_arch = "wasm32"))]
4005            "soft_step" | "软体步进" | "ソフト更新" | "소프트스텝" | "ก้าวนุ่ม" => {
4006                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
4007                let gy=self.arg_num(&args,2,15.0)? as f32;
4008                if let Some(b)=self.soft_bodies.get_mut(id) { b.integrate(dt, ling_physics::Vec3::new(0.0,gy,0.0), 4); }
4009                return Ok(Value::Unit);
4010            }
4011            #[cfg(not(target_arch = "wasm32"))]
4012            "soft_bounce" | "软体落地" | "ソフト着地" | "소프트바운스" | "เด้งนุ่ม" => {
4013                let id=self.arg_num(&args,0,0.)? as usize; let fy=self.arg_num(&args,1,0.)? as f32; let rest=self.arg_num(&args,2,0.5)? as f32;
4014                if let Some(b)=self.soft_bodies.get_mut(id) { b.floor_collision(fy, rest); }
4015                return Ok(Value::Unit);
4016            }
4017            #[cfg(not(target_arch = "wasm32"))]
4018            "soft_contain" | "软体边界" | "ソフト箱" | "소프트경계" | "กล่องนุ่ม" => {
4019                let id=self.arg_num(&args,0,0.)? as usize;
4020                let nx=self.arg_num(&args,1,-5.)? as f32; let ny=self.arg_num(&args,2,-5.)? as f32; let nz=self.arg_num(&args,3,-5.)? as f32;
4021                let mx=self.arg_num(&args,4,5.)? as f32; let my=self.arg_num(&args,5,5.)? as f32; let mz=self.arg_num(&args,6,5.)? as f32;
4022                let rest=self.arg_num(&args,7,0.6)? as f32;
4023                if let Some(b)=self.soft_bodies.get_mut(id) { b.contain(ling_physics::Vec3::new(nx,ny,nz), ling_physics::Vec3::new(mx,my,mz), rest); }
4024                return Ok(Value::Unit);
4025            }
4026            #[cfg(not(target_arch = "wasm32"))]
4027            "soft_kick" | "软体踢" | "ソフト衝撃" | "소프트킥" | "เตะนุ่ม" => {
4028                let id=self.arg_num(&args,0,0.)? as usize;
4029                let dx=self.arg_num(&args,1,0.)? as f32; let dy=self.arg_num(&args,2,0.)? as f32; let dz=self.arg_num(&args,3,0.)? as f32;
4030                let s=self.arg_num(&args,4,0.1)? as f32;
4031                if let Some(b)=self.soft_bodies.get_mut(id) { b.kick(ling_physics::Vec3::new(dx,dy,dz), s); }
4032                return Ok(Value::Unit);
4033            }
4034            // soft_spin(id, ax, ay, az, rate) — add angular velocity about the axis
4035            // through the centroid (rate = rad/step; ≈ surface_speed / radius to roll)
4036            #[cfg(not(target_arch = "wasm32"))]
4037            "soft_spin" | "软体自旋" | "ソフト回転" | "소프트회전" | "หมุนนุ่ม" => {
4038                let id=self.arg_num(&args,0,0.)? as usize;
4039                let ax=self.arg_num(&args,1,0.)? as f32; let ay=self.arg_num(&args,2,0.)? as f32; let az=self.arg_num(&args,3,0.)? as f32;
4040                let rate=self.arg_num(&args,4,0.1)? as f32;
4041                if let Some(b)=self.soft_bodies.get_mut(id) { b.spin(ling_physics::Vec3::new(ax,ay,az), rate); }
4042                return Ok(Value::Unit);
4043            }
4044            #[cfg(not(target_arch = "wasm32"))]
4045            "soft_deform" | "形变量" | "変形量" | "변형량" | "ความบิดเบี้ยว" => {
4046                let id=self.arg_num(&args,0,0.)? as usize;
4047                let d=self.soft_bodies.get(id).map(|b| b.deformation()).unwrap_or(0.0);
4048                return Ok(Value::Number(d as f64));
4049            }
4050            // soft_angular_speed(id) -> magnitude of the body's angular velocity
4051            // (how fast it is tumbling/rolling), derived from its node velocities.
4052            #[cfg(not(target_arch = "wasm32"))]
4053            "soft_angular_speed" | "软体角速" | "ソフト角速度" | "소프트각속도" | "ความเร็วเชิงมุมนุ่ม" => {
4054                let id=self.arg_num(&args,0,0.)? as usize;
4055                let w=self.soft_bodies.get(id).map(|b| b.angular_speed()).unwrap_or(0.0);
4056                return Ok(Value::Number(w as f64));
4057            }
4058            #[cfg(not(target_arch = "wasm32"))]
4059            "soft_centroid" | "软体质心" | "ソフト重心" | "소프트중심" | "จุดศูนย์กลางนุ่ม" => {
4060                let id=self.arg_num(&args,0,0.)? as usize;
4061                let c=self.soft_bodies.get(id).map(|b| b.centroid()).unwrap_or(ling_physics::Vec3::ZERO);
4062                return Ok(Value::List(vec![Value::Number(c.x as f64),Value::Number(c.y as f64),Value::Number(c.z as f64)]));
4063            }
4064            // soft_nodes(id) -> flat [x,y,z, x,y,z, …] for rendering the deformed mesh
4065            #[cfg(not(target_arch = "wasm32"))]
4066            "soft_nodes" | "软体节点" | "ソフト節点" | "소프트노드" | "จุดนุ่ม" => {
4067                let id=self.arg_num(&args,0,0.)? as usize;
4068                let mut out=Vec::new();
4069                if let Some(b)=self.soft_bodies.get(id) {
4070                    for n in &b.nodes { out.push(Value::Number(n.pos.x as f64)); out.push(Value::Number(n.pos.y as f64)); out.push(Value::Number(n.pos.z as f64)); }
4071                }
4072                return Ok(Value::List(out));
4073            }
4074
4075            // ── rigid bodies with angular dynamics ──
4076            #[cfg(not(target_arch = "wasm32"))]
4077            "rb_add" | "刚体添加" | "剛体追加" | "강체추가" | "เพิ่มวัตถุแข็ง" => {
4078                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32; let z=self.arg_num(&args,2,0.)? as f32;
4079                let mass=self.arg_num(&args,3,1.0)? as f32;
4080                let mut b = ling_physics::rigid::RigidBody::new(ling_physics::Vec3::new(x,y,z), mass);
4081                b.restitution = 0.6;
4082                return Ok(Value::Number(self.rigid_world.add(b) as f64));
4083            }
4084            #[cfg(not(target_arch = "wasm32"))]
4085            "rb_torque" | "扭矩" | "トルク" | "토크" | "แรงบิด" => {
4086                let i=self.arg_num(&args,0,0.)? as usize;
4087                let tx=self.arg_num(&args,1,0.)? as f32; let ty=self.arg_num(&args,2,0.)? as f32; let tz=self.arg_num(&args,3,0.)? as f32;
4088                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_torque(ling_physics::Vec3::new(tx,ty,tz)); }
4089                return Ok(Value::Unit);
4090            }
4091            #[cfg(not(target_arch = "wasm32"))]
4092            "rb_spin" | "自旋" | "スピン" | "스핀" | "หมุน" => {
4093                let i=self.arg_num(&args,0,0.)? as usize;
4094                let wx=self.arg_num(&args,1,0.)? as f32; let wy=self.arg_num(&args,2,0.)? as f32; let wz=self.arg_num(&args,3,0.)? as f32;
4095                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_spin(ling_physics::Vec3::new(wx,wy,wz)); }
4096                return Ok(Value::Unit);
4097            }
4098            #[cfg(not(target_arch = "wasm32"))]
4099            "rb_impulse" | "刚体冲量" | "剛体インパルス" | "강체충격" | "แรงดลแข็ง" => {
4100                let i=self.arg_num(&args,0,0.)? as usize;
4101                let ix=self.arg_num(&args,1,0.)? as f32; let iy=self.arg_num(&args,2,0.)? as f32; let iz=self.arg_num(&args,3,0.)? as f32;
4102                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_impulse(ling_physics::Vec3::new(ix,iy,iz)); }
4103                return Ok(Value::Unit);
4104            }
4105            #[cfg(not(target_arch = "wasm32"))]
4106            "rb_floor" | "刚体落地" | "剛体着地" | "강체바닥" | "พื้นแข็ง" => {
4107                let i=self.arg_num(&args,0,0.)? as usize; let fy=self.arg_num(&args,1,0.)? as f32;
4108                let rest=self.arg_num(&args,2,0.6)? as f32; let fric=self.arg_num(&args,3,0.6)? as f32;
4109                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.bounce_floor(fy, rest, fric); }
4110                return Ok(Value::Unit);
4111            }
4112            #[cfg(not(target_arch = "wasm32"))]
4113            "rb_gravity" | "刚体重力" | "剛体重力" | "강체중력" | "แรงโน้มถ่วงแข็ง" => {
4114                let gx=self.arg_num(&args,0,0.)? as f32; let gy=self.arg_num(&args,1,9.81)? as f32; let gz=self.arg_num(&args,2,0.)? as f32;
4115                self.rigid_world.gravity = ling_physics::Vec3::new(gx,gy,gz);
4116                return Ok(Value::Unit);
4117            }
4118            #[cfg(not(target_arch = "wasm32"))]
4119            "rb_step" | "刚体步进" | "剛体更新" | "강체스텝" | "ก้าวแข็ง" => {
4120                let dt=self.arg_num(&args,0,0.016)? as f32;
4121                self.rigid_world.step(dt);
4122                return Ok(Value::Unit);
4123            }
4124            #[cfg(not(target_arch = "wasm32"))]
4125            "rb_pos" | "刚体位置" | "剛体位置" | "강체위치" | "ตำแหน่งแข็ง" => {
4126                let i=self.arg_num(&args,0,0.)? as usize;
4127                let p=self.rigid_world.bodies.get(i).map(|b| b.pos).unwrap_or(ling_physics::Vec3::ZERO);
4128                return Ok(Value::List(vec![Value::Number(p.x as f64),Value::Number(p.y as f64),Value::Number(p.z as f64)]));
4129            }
4130            #[cfg(not(target_arch = "wasm32"))]
4131            "rb_rot" | "刚体旋转" | "剛体回転" | "강체회전" | "การหมุนแข็ง" => {
4132                let i=self.arg_num(&args,0,0.)? as usize;
4133                let q=self.rigid_world.bodies.get(i).map(|b| b.orientation).unwrap_or(ling_physics::Quat::IDENTITY);
4134                return Ok(Value::List(vec![Value::Number(q.x as f64),Value::Number(q.y as f64),Value::Number(q.z as f64),Value::Number(q.w as f64)]));
4135            }
4136
4137            // ── liquid sim (water + oil, immiscible) ──
4138            #[cfg(not(target_arch = "wasm32"))]
4139            "liquid_new" | "新建液体" | "液体新規" | "액체생성" | "สร้างของเหลว" => {
4140                let w=self.arg_num(&args,0,64.)? as usize; let h=self.arg_num(&args,1,64.)? as usize;
4141                let id=self.liquids.len(); self.liquids.push(ling_physics::liquid::LiquidGrid::new(w,h));
4142                return Ok(Value::Number(id as f64));
4143            }
4144            #[cfg(not(target_arch = "wasm32"))]
4145            "liquid_splat" | "液体注入" | "液体追加" | "액체분사" | "หยดของเหลว" => {
4146                let id=self.arg_num(&args,0,0.)? as usize;
4147                let x=self.arg_num(&args,1,0.)? as f32; let y=self.arg_num(&args,2,0.)? as f32;
4148                let kind=self.arg_num(&args,3,0.)? as i32; let amt=self.arg_num(&args,4,1.0)? as f32; let rad=self.arg_num(&args,5,4.0)? as f32;
4149                if let Some(g)=self.liquids.get_mut(id) { g.splat(x,y,kind,amt,rad); }
4150                return Ok(Value::Unit);
4151            }
4152            #[cfg(not(target_arch = "wasm32"))]
4153            "liquid_gravity" | "液体重力" | "液体重力ベクトル" | "액체중력" | "แรงโน้มถ่วงเหลว" => {
4154                let id=self.arg_num(&args,0,0.)? as usize;
4155                let gx=self.arg_num(&args,1,0.)? as f32; let gy=self.arg_num(&args,2,60.)? as f32;
4156                if let Some(g)=self.liquids.get_mut(id) { g.set_gravity(gx,gy); }
4157                return Ok(Value::Unit);
4158            }
4159            #[cfg(not(target_arch = "wasm32"))]
4160            "liquid_step" | "液体步进" | "液体更新" | "액체스텝" | "ก้าวของเหลว" => {
4161                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
4162                if let Some(g)=self.liquids.get_mut(id) { g.step(dt); }
4163                return Ok(Value::Unit);
4164            }
4165            // liquid_rainbow(id, on) — colour the fluid as a flowing ROYGBIV marble
4166            #[cfg(not(target_arch = "wasm32"))]
4167            "liquid_rainbow" | "液体彩虹" | "液体虹" | "액체무지개" | "ของเหลวสายรุ้ง" => {
4168                let id=self.arg_num(&args,0,0.)? as usize;
4169                let on=self.arg_num(&args,1,1.0)? > 0.5;
4170                if let Some(g)=self.liquids.get_mut(id) { g.rainbow = on; }
4171                return Ok(Value::Unit);
4172            }
4173            // liquid_mix(id) -> 0 (oil/water separated) .. 1 (fully intermixed)
4174            #[cfg(not(target_arch = "wasm32"))]
4175            "liquid_mix" | "液体混合" | "液体混合度" | "액체혼합" | "การผสมของเหลว" => {
4176                let id=self.arg_num(&args,0,0.)? as usize;
4177                let m=self.liquids.get(id).map(|g| g.mix_amount()).unwrap_or(0.0);
4178                return Ok(Value::Number(m as f64));
4179            }
4180            // liquid_draw(id, sx, sy, scale) — fast flat 2-D blit of the colour field
4181            #[cfg(not(target_arch = "wasm32"))]
4182            "liquid_draw" | "绘制液体" | "液体描画" | "액체그리기" | "วาดของเหลว" => {
4183                let id=self.arg_num(&args,0,0.)? as usize;
4184                let sx=self.arg_num(&args,1,0.)? as i32; let sy=self.arg_num(&args,2,0.)? as i32;
4185                let scale=(self.arg_num(&args,3,4.)? as i32).max(1);
4186                if id < self.liquids.len() {
4187                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4188                    let mut gfx=self.gfx.borrow_mut(); let (w,h)=(gfx.width as i32, gfx.height as i32);
4189                    let g=&self.liquids[id];
4190                    for cy in 0..gh { for cx in 0..gw {
4191                        let col=g.sample_rgb(cx,cy);
4192                        let bx=sx + cx as i32*scale; let by=sy + cy as i32*scale;
4193                        for dy in 0..scale { for dx in 0..scale {
4194                            let px=bx+dx; let py=by+dy;
4195                            if px>=0 && py>=0 && px<w && py<h { gfx.buffer[(py*w+px) as usize]=col; }
4196                        }}
4197                    }}
4198                }
4199                return Ok(Value::Unit);
4200            }
4201            // liquid_draw_surface(id, kind, cx,cy,cz, radius, height)
4202            //   kind: 0 plane · 1 sphere · 2 cylinder · 3 cone · 4 dome
4203            #[cfg(not(target_arch = "wasm32"))]
4204            "liquid_draw_surface" | "液体贴面" | "液体曲面" | "액체곡면" | "ของเหลวบนพื้นผิว" => {
4205                let id=self.arg_num(&args,0,0.)? as usize;
4206                let kind=self.arg_num(&args,1,1.)? as i32;
4207                let cx=self.arg_num(&args,2,0.)? as f32; let cy=self.arg_num(&args,3,0.)? as f32; let cz=self.arg_num(&args,4,0.)? as f32;
4208                let radius=self.arg_num(&args,5,2.0)? as f32; let height=self.arg_num(&args,6,3.0)? as f32;
4209                if id < self.liquids.len() {
4210                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4211                    let mut gfx=self.gfx.borrow_mut();
4212                    let (w,h,add)=(gfx.width, gfx.height, gfx.blend==1);
4213                    let cam=gfx.camera.clone();
4214                    let near = -cam.zdist + 0.05;
4215                    let g=&self.liquids[id];
4216                    let tau=std::f32::consts::TAU; let pi=std::f32::consts::PI;
4217                    // surface point for a (u,v) in [0,1] on the chosen primitive
4218                    let sp = |u:f32, v:f32| -> [f32;3] {
4219                        if kind==0 { [cx+(u-0.5)*2.0*radius, cy, cz+(v-0.5)*2.0*radius] }
4220                        else if kind==2 { let th=u*tau; [cx+th.cos()*radius, cy+(v-0.5)*height, cz+th.sin()*radius] }
4221                        else if kind==3 { let th=u*tau; let rr=radius*(1.0-v); [cx+th.cos()*rr, cy+(v-0.5)*height, cz+th.sin()*rr] }
4222                        else if kind==4 { let th=u*tau; let ph=v*pi*0.5; [cx+ph.sin()*th.cos()*radius, cy-ph.cos()*radius, cz+ph.sin()*th.sin()*radius] }
4223                        else { let th=u*tau; let ph=v*pi; [cx+ph.sin()*th.cos()*radius, cy+ph.cos()*radius, cz+ph.sin()*th.sin()*radius] }
4224                    };
4225                    let nrm = |u:f32, v:f32| -> [f32;3] {
4226                        if kind==0 { [0.0,-1.0,0.0] }
4227                        else if kind==2 { let th=u*tau; [th.cos(),0.0,th.sin()] }
4228                        else if kind==3 { let th=u*tau; let s=(radius/height.max(0.01)).atan(); [th.cos()*s.cos(), s.sin(), th.sin()*s.cos()] }
4229                        else if kind==4 { let th=u*tau; let ph=v*pi*0.5; [ph.sin()*th.cos(),-ph.cos(),ph.sin()*th.sin()] }
4230                        else { let th=u*tau; let ph=v*pi; [ph.sin()*th.cos(),ph.cos(),ph.sin()*th.sin()] }
4231                    };
4232                    let gwf=gw as f32; let ghf=gh as f32;
4233                    let mut cyc=0usize;
4234                    while cyc<gh {
4235                        let mut cxc=0usize;
4236                        while cxc<gw {
4237                            // cull by the cell centre's outward normal
4238                            let uc=(cxc as f32+0.5)/gwf; let vc=(cyc as f32+0.5)/ghf;
4239                            let c=sp(uc,vc); let n=nrm(uc,vc);
4240                            let dc=cam.depth(c[0],c[1],c[2]);
4241                            if dc>near {
4242                                let cull = kind!=0 && cam.depth(c[0]+n[0]*0.06,c[1]+n[1]*0.06,c[2]+n[2]*0.06) > dc;
4243                                if !cull {
4244                                    // project the 4 cell corners → a filled AA vector quad
4245                                    let u0=cxc as f32/gwf; let u1=(cxc+1) as f32/gwf;
4246                                    let v0=cyc as f32/ghf; let v1=(cyc+1) as f32/ghf;
4247                                    let q=[sp(u0,v0),sp(u1,v0),sp(u1,v1),sp(u0,v1)];
4248                                    let mut poly: Vec<[f32;2]> = Vec::with_capacity(5);
4249                                    let mut ok=true;
4250                                    for p in &q { if cam.depth(p[0],p[1],p[2])<=near { ok=false; break; } let (sx,sy,_)=cam.project(p[0],p[1],p[2]); poly.push([sx,sy]); }
4251                                    if ok { let p0=poly[0]; poly.push(p0);
4252                                        let col=g.sample_rgb(cxc,cyc);
4253                                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, col, add, std::slice::from_ref(&poly));
4254                                    }
4255                                }
4256                            }
4257                            cxc+=1;
4258                        }
4259                        cyc+=1;
4260                    }
4261                }
4262                return Ok(Value::Unit);
4263            }
4264            // sparkle(x, y, w, h, count [, t]) — scatter twinkling vector star-sparkles
4265            // in a rect (snowglobe effect) in the current colour + blend mode.
4266            #[cfg(not(target_arch = "wasm32"))]
4267            "sparkle" | "闪光" | "きらめき" | "반짝임" | "ประกาย" => {
4268                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4269                let ww=self.arg_num(&args,2,200.)? as f32; let hh=self.arg_num(&args,3,200.)? as f32;
4270                let count=self.arg_num(&args,4,40.)? as i32;
4271                let t=self.arg_num(&args,5,0.)? as f32;
4272                let mut gfx=self.gfx.borrow_mut();
4273                let (w,h,add,color)=(gfx.width, gfx.height, gfx.blend==1, gfx.color);
4274                let (cr,cg,cb)=((color>>16&0xFF) as f32,(color>>8&0xFF) as f32,(color&0xFF) as f32);
4275                let mut n=0i32;
4276                while n<count {
4277                    let hsh=(n as u32).wrapping_mul(2654435761).wrapping_add(0x9E3779B9);
4278                    let u=((hsh>>8)&1023) as f32/1023.0;
4279                    let v=((hsh>>18)&1023) as f32/1023.0;
4280                    let phase=(hsh&255) as f32/255.0;
4281                    let tw=(t*3.0 + phase*6.2831 + n as f32).sin()*0.5+0.5;
4282                    let sz=1.5+tw*5.0;
4283                    let px=x+u*ww; let py=y+v*hh;
4284                    let b=tw*tw; // sharp twinkle
4285                    let col=(((cr*b)as u32)<<16)|(((cg*b)as u32)<<8)|((cb*b)as u32);
4286                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-sz,py, px+sz,py);
4287                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px,py-sz, px,py+sz);
4288                    let d=sz*0.55;
4289                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py-d, px+d,py+d);
4290                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py+d, px+d,py-d);
4291                    n+=1;
4292                }
4293                return Ok(Value::Unit);
4294            }
4295
4296            // ══════════════════════════════════════════════════════════════════
4297            // DIALOG BUILTINS  (crates/ling-game/src/dialog.rs) — cinematic,
4298            // typed-out, colour-coded text boxes. Markup: {n}name{/} {p}place{/}
4299            // {i}item{/}, \n newline, || page break.
4300            // ══════════════════════════════════════════════════════════════════
4301            #[cfg(not(target_arch = "wasm32"))]
4302            "dialog_show" | "对话显示" | "会話表示" | "대화표시" | "แสดงบทสนทนา" => {
4303                let text = self.arg_str(&args, 0, "");
4304                let cps = self.arg_num(&args, 1, 32.0)? as f32;
4305                self.dialog = Some(ling_game::dialog::Dialog::new(&text, cps));
4306                return Ok(Value::Unit);
4307            }
4308            #[cfg(not(target_arch = "wasm32"))]
4309            "dialog_step" | "对话步进" | "会話更新" | "대화스텝" | "ก้าวบทสนทนา" => {
4310                let dt = self.arg_num(&args, 0, 0.016)? as f32;
4311                if let Some(d) = self.dialog.as_mut() { d.update(dt); }
4312                return Ok(Value::Unit);
4313            }
4314            #[cfg(not(target_arch = "wasm32"))]
4315            "dialog_advance" | "对话推进" | "会話送り" | "대화진행" | "เลื่อนบทสนทนา" => {
4316                if let Some(d) = self.dialog.as_mut() { d.advance(); }
4317                return Ok(Value::Unit);
4318            }
4319            #[cfg(not(target_arch = "wasm32"))]
4320            "dialog_active" | "对话激活" | "会話中" | "대화중" | "บทสนทนาทำงาน" => {
4321                let a = self.dialog.as_ref().map(|d| !d.is_closed()).unwrap_or(false);
4322                return Ok(Value::Bool(a));
4323            }
4324            #[cfg(not(target_arch = "wasm32"))]
4325            "dialog_typing" | "对话打字" | "会話タイプ中" | "대화타이핑" | "กำลังพิมพ์บทสนทนา" => {
4326                use ling_game::dialog::Dialog;
4327                
4328                let a = self.dialog.as_ref().map(|d: &Dialog | !d.is_closed() && d.is_typing()).unwrap_or(false);
4329                return Ok(Value::Bool(a))
4330            }
4331            #[cfg(not(target_arch = "wasm32"))]
4332            "dialog_close" | "对话关闭" | "会話閉じる" | "대화닫기" | "ปิดบทสนทนา" => {
4333                self.dialog = None;
4334                return Ok(Value::Unit);
4335            }
4336            // dialog_color(role, r, g, b) — role: 0 text · 1 name · 2 place · 3 item
4337            #[cfg(not(target_arch = "wasm32"))]
4338            "dialog_color" | "对话颜色" | "会話色" | "대화색" | "สีบทสนทนา" => {
4339                let role = (self.arg_num(&args,0,0.0)? as usize).min(3);
4340                let r = self.arg_num(&args,1,255.0)? as u32 & 0xFF;
4341                let g = self.arg_num(&args,2,255.0)? as u32 & 0xFF;
4342                let b = self.arg_num(&args,3,255.0)? as u32 & 0xFF;
4343                self.dialog_colors[role] = (r<<16)|(g<<8)|b;
4344                return Ok(Value::Unit);
4345            }
4346            // dialog_draw(x, y, w, h [, font_handle]) — draw the box + typed text
4347            #[cfg(not(target_arch = "wasm32"))]
4348            "dialog_draw" | "对话绘制" | "会話描画" | "대화그리기" | "วาดบทสนทนา" => {
4349                let x=self.arg_num(&args,0,40.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
4350                let ww=self.arg_num(&args,2,720.0)? as f32; let hh=self.arg_num(&args,3,150.0)? as f32;
4351                let font = self.arg_num(&args,4,-1.0)? as i64;
4352                let t = self.start_time.elapsed().as_secs_f32();
4353                self.render_dialog(x, y, ww, hh, font, t);
4354                return Ok(Value::Unit);
4355            }
4356
4357            // text_poll() — fold newly-typed keys into the input buffer, return it
4358            #[cfg(not(target_arch = "wasm32"))]
4359            "text_poll" => {
4360                let keys = { let gfx = self.gfx.borrow(); gfx.window.as_ref().map(|w| w.get_keys_pressed(minifb::KeyRepeat::No)).unwrap_or_default() };
4361                for k in keys {
4362                    if k == minifb::Key::Backspace { self.text_buffer.pop(); }
4363                    else if let Some(c) = key_char(k) { self.text_buffer.push(c); }
4364                }
4365                return Ok(Value::Str(self.text_buffer.clone()));
4366            }
4367            "text_get"   => return Ok(Value::Str(self.text_buffer.clone())),
4368            "text_set"   => { self.text_buffer = self.arg_str(&args,0,""); return Ok(Value::Unit); }
4369            "text_clear" => { self.text_buffer.clear(); return Ok(Value::Unit); }
4370            // record_frame() — append the current framebuffer as a PPM, return frame #
4371            #[cfg(not(target_arch = "wasm32"))]
4372            "record_frame" => {
4373                let n = self.record_n;
4374                let (buf, w, h) = { let gfx = self.gfx.borrow(); (gfx.buffer.clone(), gfx.width, gfx.height) };
4375                let _ = std::fs::create_dir_all("recordings");
4376                let mut out = Vec::with_capacity(w*h*3 + 32);
4377                out.extend_from_slice(format!("P6\n{w} {h}\n255\n").as_bytes());
4378                for px in &buf { let p = *px; out.push((p>>16) as u8); out.push((p>>8) as u8); out.push(p as u8); }
4379                let _ = std::fs::write(format!("recordings/frame_{n:05}.ppm"), out);
4380                self.record_n += 1;
4381                return Ok(Value::Number(n as f64));
4382            }
4383            "record_count" => return Ok(Value::Number(self.record_n as f64)),
4384            // ── microphone → crypto donut ──
4385            // mic_capture() — append the latest mic samples to the record buffer
4386            // (call each frame while recording). Returns the buffer length.
4387            #[cfg(not(target_arch = "wasm32"))]
4388            "mic_capture" => {
4389                if let Some(mic) = self.mic.as_ref() {
4390                    let s = mic.latest_samples();
4391                    self.mic_buffer.extend_from_slice(&s);
4392                    let cap = 96_000usize; // ~2 s @ 48 kHz
4393                    if self.mic_buffer.len() > cap {
4394                        let drop = self.mic_buffer.len() - cap;
4395                        self.mic_buffer.drain(0..drop);
4396                    }
4397                }
4398                return Ok(Value::Number(self.mic_buffer.len() as f64));
4399            }
4400            // mic_seed() — SHA3-256 hex of the recorded audio, usable as a donut seed
4401            #[cfg(not(target_arch = "wasm32"))]
4402            "mic_seed" => {
4403                let mut bytes = Vec::with_capacity(self.mic_buffer.len() * 4);
4404                for f in &self.mic_buffer { bytes.extend_from_slice(&f.to_le_bytes()); }
4405                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(&bytes))));
4406            }
4407            #[cfg(not(target_arch = "wasm32"))]
4408            "mic_clear" => { self.mic_buffer.clear(); return Ok(Value::Number(0.0)); }
4409            // flush the 3-D depth queue onto the framebuffer WITHOUT presenting,
4410            // so 2-D UI drawn afterwards overlays the 3-D scene.
4411            #[cfg(not(target_arch = "wasm32"))]
4412            "flush_3d" | "render_3d" => {
4413                let mut gfx = self.gfx.borrow_mut();
4414                if !gfx.depth_queue.is_empty() {
4415                    let w = gfx.width; let h = gfx.height;
4416                    let queue = std::mem::take(&mut gfx.depth_queue);
4417                    queue.flush(&mut gfx.buffer, w, h);
4418                }
4419                return Ok(Value::Unit);
4420            }
4421
4422            "set_rim" | "设置边缘光" | "リム設定" | "림라이트" | "ตั้งขอบเรือง" => {
4423                let s=self.arg_num(&args,0,0.6)? as f32;
4424                let r=self.arg_num(&args,1,115.)? as f32/255.0;
4425                let g=self.arg_num(&args,2,217.)? as f32/255.0;
4426                let b=self.arg_num(&args,3,255.)? as f32/255.0;
4427                let mut gfx=self.gfx.borrow_mut();
4428                gfx.shade.rim = s; gfx.shade.rim_color = [r,g,b];
4429                return Ok(Value::Unit);
4430            }
4431
4432            // ══════════════════════════════════════════════════════════════════
4433            // 3-D PRIMITIVES  (src/gfx/shapes.rs)  — "Inkscape for 3-D"
4434            //   shape(cx,cy,cz,  sx,sy,sz,  rx,ry,rz,  mode,  e0,e1,e2)
4435            //     centre (cx,cy,cz), per-axis scale, Euler rotation (radians),
4436            //     mode: 0 filled · 1 wireframe · 2 both,
4437            //     e0..e2: shape-specific (segments / sides / ratio …).
4438            //   Pen colour (set_color) drives fill lighting and wireframe colour.
4439            // ══════════════════════════════════════════════════════════════════
4440            n if crate::gfx::shapes::canon(n).is_some() => {
4441                let kind = crate::gfx::shapes::canon(n).unwrap();
4442                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32; let cz=self.arg_num(&args,2,0.)? as f32;
4443                let sx=self.arg_num(&args,3,1.)? as f32; let sy=self.arg_num(&args,4,1.)? as f32; let sz=self.arg_num(&args,5,1.)? as f32;
4444                let rx=self.arg_num(&args,6,0.)? as f32; let ry=self.arg_num(&args,7,0.)? as f32; let rz=self.arg_num(&args,8,0.)? as f32;
4445                let mode=self.arg_num(&args,9,0.)? as i32;
4446                let e0=self.arg_num(&args,10,0.)? as f32; let e1=self.arg_num(&args,11,0.)? as f32; let e2=self.arg_num(&args,12,0.)? as f32;
4447                if let Some(mesh)=crate::gfx::shapes::build(kind,[cx,cy,cz,sx,sy,sz,rx,ry,rz],e0,e1,e2){
4448                    let mut gfx=self.gfx.borrow_mut();
4449                    gfx.emit_mesh(&mesh,mode);
4450                }
4451                return Ok(Value::Unit);
4452            }
4453
4454            _ => {}
4455        }
4456
4457        // User-defined function
4458        if let Some(def) = self.functions.get(name).cloned() {
4459            let mut call_env = Env::new();
4460            // Seed env with non-Do globals (skip entry-point blocks to avoid infinite recursion).
4461            // Pass 1: evaluate each global with the call-site env — simple literals succeed.
4462            // Pass 2: retry failed globals with the partially-built call_env so that compound
4463            //         globals (e.g. `FM = (NZ + FZ) / 2.0`) can resolve their dependencies.
4464            let non_do_globals: Vec<_> = self.globals.iter()
4465                .filter(|(_, expr)| !matches!(expr, Expr::Do(_)))
4466                .map(|(k, e)| (k.clone(), e.clone()))
4467                .collect();
4468            let mut pending: Vec<(String, Expr)> = Vec::new();
4469            for (k, expr) in &non_do_globals {
4470                let mut tmp = env.clone();
4471                if let Ok(v) = self.eval_expr(expr, &mut tmp) {
4472                    call_env.insert(k.clone(), v);
4473                } else {
4474                    pending.push((k.clone(), expr.clone()));
4475                }
4476            }
4477            // Second pass: retry compound globals now that literals are in call_env.
4478            for (k, expr) in &pending {
4479                let mut tmp = env.clone();
4480                tmp.extend(call_env.clone());
4481                if let Ok(v) = self.eval_expr(expr, &mut tmp) {
4482                    call_env.insert(k.clone(), v);
4483                }
4484            }
4485            for (param, arg) in def.params.iter().zip(args) {
4486                call_env.insert(param.clone(), arg);
4487            }
4488            return match self.exec_block(&def.body, &mut call_env) {
4489                Ok(v) => Ok(v.unwrap_or(Value::Unit)),
4490                Err(EvalErr::Return(v)) => Ok(v),
4491                Err(e) => Err(e),
4492            };
4493        }
4494
4495        Err(EvalErr::from(format!("unknown function '{name}'")))
4496    }
4497
4498    fn call_value(&mut self, v: Value, args: Vec<Value>) -> EvalResult {
4499        match v {
4500            Value::Fn(params, body, mut captured) => {
4501                for (p, a) in params.iter().zip(args) {
4502                    captured.insert(p.clone(), a);
4503                }
4504                match self.exec_block(&body, &mut captured) {
4505                    Ok(v) => Ok(v.unwrap_or(Value::Unit)),
4506                    Err(EvalErr::Return(v)) => Ok(v),
4507                    Err(e) => Err(e),
4508                }
4509            }
4510            other => Err(EvalErr::from(format!("cannot call {:?}", other))),
4511        }
4512    }
4513
4514    fn call_method(&self, recv: Value, method: &str, args: Vec<Value>) -> EvalResult {
4515        match (&recv, method) {
4516            (Value::Str(s), "is_empty" | "是空") => Ok(Value::Bool(s.is_empty())),
4517            (Value::Str(s), "len" | "长")        => Ok(Value::Number(s.len() as f64)),
4518            (Value::Str(s), "to_string" | "转文") => Ok(Value::Str(s.clone())),
4519            (Value::Str(s), "contains" | "包含") => {
4520                if let Some(Value::Str(sub)) = args.first() {
4521                    Ok(Value::Bool(s.contains(sub.as_str())))
4522                } else { Ok(Value::Bool(false)) }
4523            }
4524            (Value::Str(s), "push_str" | "推_文") => {
4525                let mut s2 = s.clone();
4526                if let Some(Value::Str(a)) = args.first() { s2.push_str(a); }
4527                Ok(Value::Str(s2))
4528            }
4529            (Value::List(v), "len" | "长") => Ok(Value::Number(v.len() as f64)),
4530            (Value::List(v), "push" | "推") => {
4531                let mut v2 = v.clone();
4532                if let Some(a) = args.first() { v2.push(a.clone()); }
4533                Ok(Value::List(v2))
4534            }
4535            (Value::Ok(inner), _) | (Value::Err(inner), _) => Ok(*inner.clone()),
4536            _ => Err(EvalErr::from(format!("no method '{method}' on {recv}"))),
4537        }
4538    }
4539
4540    // ─── Pattern matching ─────────────────────────────────────────────────────
4541
4542    fn match_pattern(&self, pat: &Pattern, val: &Value) -> Option<Env> {
4543        match (pat, val) {
4544            (Pattern::Wildcard, _) => Some(Env::new()),
4545            (Pattern::Str(s), Value::Str(v)) if s == v => Some(Env::new()),
4546            (Pattern::Number(n), Value::Number(v)) if (n - v).abs() < 1e-12 => Some(Env::new()),
4547            (Pattern::Bool(b), Value::Bool(v)) if b == v => Some(Env::new()),
4548            (Pattern::Ident(name), _) => {
4549                let mut e = Env::new();
4550                e.insert(name.clone(), val.clone());
4551                Some(e)
4552            }
4553            (Pattern::Constructor(ctor, inner_pat), _) => {
4554                let (matches, inner_val) = match (ctor.as_str(), val) {
4555                    ("ok"  | "好", Value::Ok(v))  => (true, Some(v.as_ref().clone())),
4556                    ("bad" | "坏", Value::Err(v)) => (true, Some(v.as_ref().clone())),
4557                    ("ok"  | "好", v) if !matches!(v, Value::Err(_)) => (true, Some(v.clone())),
4558                    _ => (false, None),
4559                };
4560                if !matches { return None; }
4561                match (inner_pat, inner_val) {
4562                    (Some(p), Some(v)) => self.match_pattern(p, &v),
4563                    (None, _)          => Some(Env::new()),
4564                    (Some(p), None)    => self.match_pattern(p, &Value::Unit),
4565                }
4566            }
4567            _ => None,
4568        }
4569    }
4570
4571    // ─── Utilities ───────────────────────────────────────────────────────────
4572
4573    fn value_to_iter(&self, val: Value) -> Result<Vec<Value>, EvalErr> {
4574        match val {
4575            Value::List(v)   => Ok(v),
4576            Value::Str(s)    => Ok(s.chars().map(|c| Value::Str(c.to_string())).collect()),
4577            Value::Number(n) => Ok((0..n as i64).map(|i| Value::Number(i as f64)).collect()),
4578            other => Err(EvalErr::from(format!("cannot iterate over {:?}", other))),
4579        }
4580    }
4581
4582    fn is_truthy(&self, val: &Value) -> bool {
4583        match val {
4584            Value::Bool(b)     => *b,
4585            Value::Unit        => false,
4586            Value::Number(n)   => *n != 0.0,
4587            Value::Str(s)      => !s.is_empty(),
4588            Value::List(v)     => !v.is_empty(),
4589            Value::Ok(_)       => true,
4590            Value::Err(_)      => false,
4591            Value::Fn(_, _, _) => true,
4592        }
4593    }
4594
4595    fn to_number(&self, val: &Value) -> Result<f64, EvalErr> {
4596        match val {
4597            Value::Number(n) => Ok(*n),
4598            Value::Str(s)    => s.parse().map_err(|_| EvalErr::from(format!("cannot convert '{s}' to number"))),
4599            other => Err(EvalErr::from(format!("expected number, got {:?}", other))),
4600        }
4601    }
4602
4603    /// Get the n-th argument as f64, falling back to `default` if missing.
4604    fn arg_num(&self, args: &[Value], n: usize, default: f64) -> Result<f64, EvalErr> {
4605        match args.get(n) {
4606            Some(v) => self.to_number(v),
4607            None    => Ok(default),
4608        }
4609    }
4610
4611    fn arg_str(&self, args: &[Value], n: usize, default: &str) -> String {
4612        args.get(n).map(|v| v.to_string()).unwrap_or_else(|| default.to_string())
4613    }
4614
4615    /// Read a list-of-numbers argument as `Vec<f32>` (empty if absent/not a list).
4616    #[allow(dead_code)]
4617    fn arg_list_f32(&self, args: &[Value], n: usize) -> Vec<f32> {
4618        match args.get(n) {
4619            Some(Value::List(v)) => v.iter().filter_map(|x| match x {
4620                Value::Number(n) => Some(*n as f32),
4621                _ => None,
4622            }).collect(),
4623            _ => Vec::new(),
4624        }
4625    }
4626
4627    /// Optional `r,g,b` colour override starting at arg `i` → packed 0x00RRGGBB,
4628    /// or `default` if those three numeric args aren't present.
4629    #[cfg(not(target_arch = "wasm32"))]
4630    fn color_at(&self, args: &[Value], i: usize, default: u32) -> u32 {
4631        match (args.get(i), args.get(i + 1), args.get(i + 2)) {
4632            (Some(a), Some(b), Some(c)) => match (self.to_number(a), self.to_number(b), self.to_number(c)) {
4633                (Ok(r), Ok(g), Ok(bl)) =>
4634                    ((r as u32 & 0xFF) << 16) | ((g as u32 & 0xFF) << 8) | (bl as u32 & 0xFF),
4635                _ => default,
4636            },
4637            _ => default,
4638        }
4639    }
4640
4641    /// A pitch argument: a note-name string (`"C4"`, `"A#3"`) or a numeric MIDI value.
4642    #[cfg(not(target_arch = "wasm32"))]
4643    fn pitch_arg(&self, args: &[Value], i: usize, default: i32) -> i32 {
4644        match args.get(i) {
4645            Some(Value::Str(s)) => ling_music::note::parse_pitch(s).unwrap_or(default),
4646            Some(Value::Number(n)) => *n as i32,
4647            _ => default,
4648        }
4649    }
4650
4651    /// Current mouse position + left-button-down (native window only).
4652    #[cfg(not(target_arch = "wasm32"))]
4653    fn mouse_now(&self) -> (f32, f32, bool) {
4654        let gfx = self.gfx.borrow();
4655        let (mx, my) = gfx.window.as_ref()
4656            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0, 0.0));
4657        let down = gfx.window.as_ref()
4658            .map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
4659        (mx, my, down)
4660    }
4661
4662    /// Rasterize a UI [`ling_ui::widgets::Draw`] into the framebuffer: filled
4663    /// polygons via the AA scanline fill, polylines via AA lines, honouring the
4664    /// current blend mode.
4665    #[cfg(not(target_arch = "wasm32"))]
4666    fn draw_ui(&self, d: &ling_ui::widgets::Draw) {
4667        let mut gfx = self.gfx.borrow_mut();
4668        let (w, h, add) = (gfx.width, gfx.height, gfx.blend == 1);
4669        for (c, poly) in &d.fills {
4670            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, *c, add, std::slice::from_ref(poly));
4671        }
4672        for (c, pl) in &d.strokes {
4673            for s in pl.windows(2) {
4674                crate::gfx::raster::draw_line_aa(&mut gfx.buffer, w, h, *c, add, s[0][0], s[0][1], s[1][0], s[1][1]);
4675            }
4676        }
4677    }
4678
4679    /// Parse (dst_x, dst_y, width, height) from the first four args of a tex_* builtin.
4680    fn tex_rect(&self, args: &[Value]) -> Result<(usize, usize, usize, usize), EvalErr> {
4681        let tx = self.arg_num(args, 0, 0.0)? as usize;
4682        let ty = self.arg_num(args, 1, 0.0)? as usize;
4683        let tw = self.arg_num(args, 2, 256.0)? as usize;
4684        let th = self.arg_num(args, 3, 256.0)? as usize;
4685        Ok((tx, ty, tw.max(1), th.max(1)))
4686    }
4687
4688    fn apply_binop(&self, op: &BinOp, l: Value, r: Value) -> EvalResult {
4689        match op {
4690            BinOp::Add => match (l, r) {
4691                (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
4692                (Value::Str(a), Value::Str(b))       => Ok(Value::Str(a + &b)),
4693                (Value::Str(a), b)                   => Ok(Value::Str(a + &b.to_string())),
4694                (a, Value::Str(b))                   => Ok(Value::Str(a.to_string() + &b)),
4695                (a, b) => Err(EvalErr::from(format!("cannot add {:?} and {:?}", a, b))),
4696            },
4697            BinOp::Sub => Ok(Value::Number(self.to_number(&l)? - self.to_number(&r)?)),
4698            BinOp::Mul => Ok(Value::Number(self.to_number(&l)? * self.to_number(&r)?)),
4699            BinOp::Div => Ok(Value::Number(self.to_number(&l)? / self.to_number(&r)?)),
4700            BinOp::Rem => Ok(Value::Number(self.to_number(&l)? % self.to_number(&r)?)),
4701            BinOp::Eq  => Ok(Value::Bool(values_equal(&l, &r))),
4702            BinOp::Ne  => Ok(Value::Bool(!values_equal(&l, &r))),
4703            BinOp::Lt  => Ok(Value::Bool(self.to_number(&l)? < self.to_number(&r)?)),
4704            BinOp::Gt  => Ok(Value::Bool(self.to_number(&l)? > self.to_number(&r)?)),
4705            BinOp::Le  => Ok(Value::Bool(self.to_number(&l)? <= self.to_number(&r)?)),
4706            BinOp::Ge  => Ok(Value::Bool(self.to_number(&l)? >= self.to_number(&r)?)),
4707            BinOp::And => Ok(Value::Bool(self.is_truthy(&l) && self.is_truthy(&r))),
4708            BinOp::Or  => Ok(Value::Bool(self.is_truthy(&l) || self.is_truthy(&r))),
4709        }
4710    }
4711
4712    fn builtin_format(&self, args: &[Value]) -> Result<String, EvalErr> {
4713        if args.is_empty() { return Ok(String::new()); }
4714        let fmt = match &args[0] {
4715            Value::Str(s) => s.clone(),
4716            other => return Ok(other.to_string()),
4717        };
4718
4719        let mut result = String::new();
4720        let mut arg_idx = 1usize;
4721        let mut chars = fmt.chars().peekable();
4722        while let Some(c) = chars.next() {
4723            if c == '{' {
4724                if chars.peek() == Some(&'}') {
4725                    chars.next();
4726                    if arg_idx < args.len() {
4727                        result.push_str(&args[arg_idx].to_string());
4728                        arg_idx += 1;
4729                    }
4730                } else {
4731                    let mut spec = String::new();
4732                    for ch in chars.by_ref() {
4733                        if ch == '}' { break; }
4734                        spec.push(ch);
4735                    }
4736                    if arg_idx < args.len() {
4737                        if spec.starts_with(":.") {
4738                            if let Value::Number(n) = &args[arg_idx] {
4739                                let prec: usize = spec[2..].trim_end_matches('f')
4740                                    .parse().unwrap_or(2);
4741                                result.push_str(&format!("{:.prec$}", n));
4742                                arg_idx += 1;
4743                                continue;
4744                            }
4745                        }
4746                        result.push_str(&args[arg_idx].to_string());
4747                        arg_idx += 1;
4748                    }
4749                }
4750            } else {
4751                result.push(c);
4752            }
4753        }
4754        Ok(result)
4755    }
4756}
4757
4758#[cfg(not(target_arch = "wasm32"))]
4759fn str_to_minifb_key(name: &str) -> Option<minifb::Key> {
4760    use minifb::Key;
4761    Some(match name {
4762        "numpad0" | "kp0" => Key::NumPad0,
4763        "numpad1" | "kp1" => Key::NumPad1,
4764        "numpad2" | "kp2" => Key::NumPad2,
4765        "numpad3" | "kp3" => Key::NumPad3,
4766        "numpad4" | "kp4" => Key::NumPad4,
4767        "numpad5" | "kp5" => Key::NumPad5,
4768        "numpad6" | "kp6" => Key::NumPad6,
4769        "numpad7" | "kp7" => Key::NumPad7,
4770        "numpad8" | "kp8" => Key::NumPad8,
4771        "numpad9" | "kp9" => Key::NumPad9,
4772        "numpad+" | "kp+" => Key::NumPadPlus,
4773        "numpad-" | "kp-" => Key::NumPadMinus,
4774        "numpad*" | "kp*" => Key::NumPadAsterisk,
4775        "numpad/" | "kp/" => Key::NumPadSlash,
4776        "left"   => Key::Left,
4777        "right"  => Key::Right,
4778        "up"     => Key::Up,
4779        "down"   => Key::Down,
4780        "space"  => Key::Space,
4781        "enter"  => Key::Enter,
4782        "escape" => Key::Escape,
4783        "pageup" => Key::PageUp,
4784        "pagedown" => Key::PageDown,
4785        "lshift" | "leftshift"  => Key::LeftShift,
4786        "rshift" | "rightshift" => Key::RightShift,
4787        "lctrl"  | "leftctrl"   => Key::LeftCtrl,
4788        "rctrl"  | "rightctrl"  => Key::RightCtrl,
4789        "tab"    => Key::Tab,
4790        "backspace" => Key::Backspace,
4791        "delete" => Key::Delete,
4792        "insert" => Key::Insert,
4793        "home"   => Key::Home,
4794        "end"    => Key::End,
4795        "a" => Key::A, "b" => Key::B, "c" => Key::C, "d" => Key::D,
4796        "e" => Key::E, "f" => Key::F, "g" => Key::G, "h" => Key::H,
4797        "i" => Key::I, "j" => Key::J, "k" => Key::K, "l" => Key::L,
4798        "m" => Key::M, "n" => Key::N, "o" => Key::O, "p" => Key::P,
4799        "q" => Key::Q, "r" => Key::R, "s" => Key::S, "t" => Key::T,
4800        "u" => Key::U, "v" => Key::V, "w" => Key::W, "x" => Key::X,
4801        "y" => Key::Y, "z" => Key::Z,
4802        "0" => Key::Key0, "1" => Key::Key1, "2" => Key::Key2,
4803        "3" => Key::Key3, "4" => Key::Key4, "5" => Key::Key5,
4804        "6" => Key::Key6, "7" => Key::Key7, "8" => Key::Key8,
4805        "9" => Key::Key9,
4806        _ => return None,
4807    })
4808}
4809
4810fn values_equal(a: &Value, b: &Value) -> bool {
4811    match (a, b) {
4812        (Value::Number(x), Value::Number(y)) => (x - y).abs() < 1e-12,
4813        (Value::Str(x), Value::Str(y))       => x == y,
4814        (Value::Bool(x), Value::Bool(y))     => x == y,
4815        (Value::Unit, Value::Unit)            => true,
4816        _ => false,
4817    }
4818}
4819
4820// Rasteriser functions live in crate::gfx::raster — imported at top of file.
4821
4822// ── Window platform helpers ────────────────────────────────────────────────────
4823
4824/// Hide the console window that the OS auto-attaches to console-subsystem
4825/// processes. No-op on non-Windows and when no console is present.
4826#[cfg(not(target_arch = "wasm32"))]
4827fn hide_console_window() {
4828    #[cfg(windows)]
4829    unsafe {
4830        extern "system" {
4831            fn GetConsoleWindow() -> isize;
4832            fn ShowWindow(hwnd: isize, nCmdShow: i32) -> i32;
4833        }
4834        let hwnd = GetConsoleWindow();
4835        if hwnd != 0 {
4836            ShowWindow(hwnd, 0); // SW_HIDE = 0
4837        }
4838    }
4839}
4840
4841/// Move and resize the foreground window so it fills the primary monitor
4842/// (0,0 → screen_w × screen_h) and sits above the taskbar (HWND_TOPMOST).
4843#[cfg(all(not(target_arch = "wasm32"), windows))]
4844fn reposition_fullscreen(screen_w: i32, screen_h: i32) {
4845    unsafe {
4846        extern "system" {
4847            fn GetForegroundWindow() -> isize;
4848            fn SetWindowPos(hwnd: isize, insert_after: isize,
4849                            x: i32, y: i32, cx: i32, cy: i32,
4850                            flags: u32) -> i32;
4851        }
4852        let hwnd = GetForegroundWindow();
4853        if hwnd != 0 {
4854            // HWND_TOPMOST = -1, SWP_SHOWWINDOW = 0x0040
4855            SetWindowPos(hwnd, -1isize, 0, 0, screen_w, screen_h, 0x0040);
4856        }
4857    }
4858}
4859
4860/// Query the primary display resolution on non-Windows platforms.
4861/// Falls back to 1920×1080 if the size cannot be determined.
4862#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
4863fn native_screen_size() -> (f64, f64) {
4864    // On Linux/macOS we don't have an easy dependency-free call; return a
4865    // sensible default. Callers can always pass explicit dimensions.
4866    (1920.0, 1080.0)
4867}