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            // project_3d(x,y,z) -> [screen_x, screen_y, depth]; behind the camera
2007            // returns a sentinel ([-99999,-99999, depth]) so scripts can skip it.
2008            // Lets scripts place 2-D overlays (e.g. filled teardrop flames) onto 3-D points.
2009            "project_3d" | "投影3D" | "3D投影" | "3D투영" | "ฉาย3มิติ" => {
2010                let x = self.arg_num(&args,0,0.0)? as f32;
2011                let y = self.arg_num(&args,1,0.0)? as f32;
2012                let z = self.arg_num(&args,2,0.0)? as f32;
2013                let gfx = self.gfx.borrow();
2014                let near = -gfx.camera.zdist + 0.05;
2015                let d = gfx.camera.depth(x, y, z);
2016                if d <= near {
2017                    return Ok(Value::List(vec![Value::Number(-99999.0), Value::Number(-99999.0), Value::Number(d as f64)]));
2018                }
2019                let (sx, sy, depth) = gfx.camera.project(x, y, z);
2020                return Ok(Value::List(vec![Value::Number(sx as f64), Value::Number(sy as f64), Value::Number(depth as f64)]));
2021            }
2022            // draw_poly([x0,y0,x1,y1,…]) — filled 2-D polygon in the current colour,
2023            // honouring the blend mode (additive → translucent glow). Auto-closes.
2024            #[cfg(not(target_arch = "wasm32"))]
2025            "draw_poly" | "填充多边形" | "ポリゴン塗り" | "다각형채우기" | "เติมรูปหลายเหลี่ยม" => {
2026                let mut pts: Vec<[f32; 2]> = Vec::new();
2027                if let Some(Value::List(v)) = args.first() {
2028                    let mut i = 0;
2029                    while i + 1 < v.len() {
2030                        let x = self.to_number(&v[i]).unwrap_or(0.0) as f32;
2031                        let y = self.to_number(&v[i + 1]).unwrap_or(0.0) as f32;
2032                        pts.push([x, y]);
2033                        i += 2;
2034                    }
2035                }
2036                if pts.len() >= 3 {
2037                    if pts[0] != pts[pts.len() - 1] { let p0 = pts[0]; pts.push(p0); } // close
2038                    let mut gfx = self.gfx.borrow_mut();
2039                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
2040                    crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, std::slice::from_ref(&pts));
2041                }
2042                return Ok(Value::Unit);
2043            }
2044
2045            // ══════════════════════════════════════════════════════════════════
2046            // VECTOR TEXTURE BUILTINS  (src/gfx/vtex.rs)
2047            // All patterns are depth-biased so they appear on top of surfaces.
2048            // Plane defined by: centre (cx,cy,cz) + U tangent + V tangent.
2049            // Last two args always: fr (frame f32), hue (phase offset f32).
2050            // ══════════════════════════════════════════════════════════════════
2051
2052            // vtex_grid(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cw,ch, fr,hue)
2053            "vtex_grid" | "ลายตาราง" | "纹格" | "格子模様" | "격자무늬" => {
2054                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;
2055                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;
2056                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;
2057                let cols=self.arg_num(&args,9,10.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2058                let cw=self.arg_num(&args,11,1.)?as f32;  let ch=self.arg_num(&args,12,1.)?as f32;
2059                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2060                let mut gfx = self.gfx.borrow_mut();
2061                let cam = gfx.camera.clone();
2062                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);
2063                return Ok(Value::Unit);
2064            }
2065
2066            // vtex_rings(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_rings,n_sides, max_r,twist, fr,hue)
2067            "vtex_rings" | "ลายวงซ้อน" | "纹环" | "同心円" | "동심원" => {
2068                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;
2069                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;
2070                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;
2071                let nr=self.arg_num(&args,9,6.)?as usize; let ns=self.arg_num(&args,10,6.)?as usize;
2072                let mr=self.arg_num(&args,11,3.)?as f32;  let tw=self.arg_num(&args,12,0.)?as f32;
2073                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2074                let mut gfx = self.gfx.borrow_mut();
2075                let cam = gfx.camera.clone();
2076                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);
2077                return Ok(Value::Unit);
2078            }
2079
2080            // vtex_star(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_pts,r_out,r_in, rot_speed, fr,hue)
2081            "vtex_star" | "ลายดาว" | "纹星" | "星模様" | "별무늬" => {
2082                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;
2083                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;
2084                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;
2085                let np=self.arg_num(&args,9,6.)?as usize;
2086                let ro=self.arg_num(&args,10,2.)?as f32; let ri=self.arg_num(&args,11,1.)?as f32;
2087                let rs=self.arg_num(&args,12,0.01)?as f32;
2088                let fr=self.arg_num(&args,13,0.)?as f32; let hue=self.arg_num(&args,14,0.)?as f32;
2089                let mut gfx = self.gfx.borrow_mut();
2090                let cam = gfx.camera.clone();
2091                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);
2092                return Ok(Value::Unit);
2093            }
2094
2095            // vtex_spiral(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_turns,max_r,steps, fr,hue)
2096            "vtex_spiral" | "ลายเกลียว" | "纹螺" | "螺旋" | "나선" => {
2097                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;
2098                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;
2099                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;
2100                let nt=self.arg_num(&args,9,3.)?as f32; let mr=self.arg_num(&args,10,3.)?as f32;
2101                let st=self.arg_num(&args,11,120.)?as usize;
2102                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2103                let mut gfx = self.gfx.borrow_mut();
2104                let cam = gfx.camera.clone();
2105                crate::gfx::vtex::draw_spiral(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,mr,st, fr,hue);
2106                return Ok(Value::Unit);
2107            }
2108
2109            // vtex_flower(cx,cy,cz, ux,uy,uz, vx,vy,vz, radius,n_sides, fr,hue)
2110            "vtex_flower" | "ลายดอก" | "纹花" | "花模様" | "꽃무늬" => {
2111                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;
2112                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;
2113                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;
2114                let r=self.arg_num(&args,9,1.)?as f32; let ns=self.arg_num(&args,10,24.)?as usize;
2115                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2116                let mut gfx = self.gfx.borrow_mut();
2117                let cam = gfx.camera.clone();
2118                crate::gfx::vtex::draw_flower(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2119                return Ok(Value::Unit);
2120            }
2121
2122            // vtex_letter_rain(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_cols,n_vis, col_w,row_h, speed, fr,hue)
2123            "vtex_letter_rain" | "ลายอักษรไหล" | "纹字雨" | "文字雨" | "글자비" => {
2124                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;
2125                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;
2126                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;
2127                let nc=self.arg_num(&args,9,16.)?as usize; let nv=self.arg_num(&args,10,14.)?as usize;
2128                let cw=self.arg_num(&args,11,0.65)?as f32; let rh=self.arg_num(&args,12,0.60)?as f32;
2129                let sp=self.arg_num(&args,13,0.025)?as f32;
2130                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2131                let mut gfx = self.gfx.borrow_mut();
2132                let cam = gfx.camera.clone();
2133                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);
2134                return Ok(Value::Unit);
2135            }
2136
2137            // vtex_hyperbolic_uv(cx,cy,cz, ux,uy,uz, vx,vy,vz, max_r,n_circles,n_rays, fr,hue)
2138            "vtex_hyperbolic_uv" | "ลายไฮเพอร์โบลิก" | "纹曲面" | "双曲線" | "쌍곡선" => {
2139                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;
2140                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;
2141                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;
2142                let mr=self.arg_num(&args,9,5.)?as f32;
2143                let nc=self.arg_num(&args,10,12.)?as usize; let nr=self.arg_num(&args,11,18.)?as usize;
2144                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2145                let mut gfx = self.gfx.borrow_mut();
2146                let cam = gfx.camera.clone();
2147                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);
2148                return Ok(Value::Unit);
2149            }
2150
2151            // vtex_halftone(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell_w,cell_h, density, fr,hue)
2152            "vtex_halftone" | "ลายจุด" | "纹半调" | "網点模様" | "망점" => {
2153                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;
2154                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;
2155                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;
2156                let cols=self.arg_num(&args,9,16.)?as usize; let rows=self.arg_num(&args,10,12.)?as usize;
2157                let cw=self.arg_num(&args,11,0.5)?as f32; let ch=self.arg_num(&args,12,0.5)?as f32;
2158                let dens=self.arg_num(&args,13,0.4)?as f32;
2159                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2160                let mut gfx = self.gfx.borrow_mut();
2161                let cam = gfx.camera.clone();
2162                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);
2163                return Ok(Value::Unit);
2164            }
2165
2166            // vtex_tessellated(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell, amplitude,freq, fr,hue)
2167            "vtex_tessellated" | "ลายตาข่าย" | "纹镶嵌" | "網目模様" | "격자망" => {
2168                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;
2169                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;
2170                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;
2171                let cols=self.arg_num(&args,9,14.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2172                let cell=self.arg_num(&args,11,0.6)?as f32;
2173                let amp=self.arg_num(&args,12,0.25)?as f32; let freq=self.arg_num(&args,13,4.)?as f32;
2174                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2175                let mut gfx = self.gfx.borrow_mut();
2176                let cam = gfx.camera.clone();
2177                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);
2178                return Ok(Value::Unit);
2179            }
2180
2181            // vtex_lotus(cx,cy,cz, ux,uy,uz, vx,vy,vz, r_inner,r_outer,n_petals, fr,hue)
2182            "vtex_lotus" | "ลายดอกบัว" | "纹莲" | "蓮模様" | "연꽃무늬" => {
2183                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;
2184                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;
2185                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;
2186                let ri=self.arg_num(&args,9,1.)?as f32; let ro=self.arg_num(&args,10,2.)?as f32;
2187                let np=self.arg_num(&args,11,12.)?as usize;
2188                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2189                let mut gfx = self.gfx.borrow_mut();
2190                let cam = gfx.camera.clone();
2191                crate::gfx::vtex::draw_lotus(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, ri,ro,np, fr,hue);
2192                return Ok(Value::Unit);
2193            }
2194
2195            // vtex_chakra(cx,cy,cz, ux,uy,uz, vx,vy,vz, r,n_spokes, fr,hue)
2196            "vtex_chakra" | "ลายจักร" | "纹轮" | "輪模様" | "바퀴무늬" => {
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 r=self.arg_num(&args,9,2.)?as f32; let ns=self.arg_num(&args,10,8.)?as usize;
2201                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2202                let mut gfx = self.gfx.borrow_mut();
2203                let cam = gfx.camera.clone();
2204                crate::gfx::vtex::draw_chakra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2205                return Ok(Value::Unit);
2206            }
2207
2208            // vtex_yantra(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_layers,max_r, fr,hue)
2209            "vtex_yantra" | "ลายยันต์" | "纹咒" | "護符模様" | "부적무늬" => {
2210                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;
2211                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;
2212                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;
2213                let nl=self.arg_num(&args,9,4.)?as usize; let mr=self.arg_num(&args,10,3.)?as f32;
2214                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2215                let mut gfx = self.gfx.borrow_mut();
2216                let cam = gfx.camera.clone();
2217                crate::gfx::vtex::draw_yantra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nl,mr, fr,hue);
2218                return Ok(Value::Unit);
2219            }
2220
2221            // vtex_spiked_cog(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_teeth,r_body,r_spike,r_hub,n_spokes, fr,hue)
2222            "vtex_spiked_cog" | "ฟันเฟืองหนาม" | "纹棘轮" | "歯車模様" | "톱니바퀴" => {
2223                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;
2224                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;
2225                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;
2226                let nt=self.arg_num(&args,9,12.)?as usize; let rb=self.arg_num(&args,10,1.)?as f32;
2227                let rs=self.arg_num(&args,11,1.3)?as f32; let rh=self.arg_num(&args,12,0.2)?as f32;
2228                let ns=self.arg_num(&args,13,6.)?as usize;
2229                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2230                let mut gfx = self.gfx.borrow_mut();
2231                let cam = gfx.camera.clone();
2232                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);
2233                return Ok(Value::Unit);
2234            }
2235
2236            // vtex_torii(cx,cy,cz, ux,uy,uz, vx,vy,vz, width,height, fr,hue)
2237            "vtex_torii" | "ประตูโทริอิ" | "纹鸟居" | "鳥居" | "도리이" => {
2238                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;
2239                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;
2240                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;
2241                let w=self.arg_num(&args,9,4.)?as f32; let h=self.arg_num(&args,10,5.)?as f32;
2242                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2243                let mut gfx = self.gfx.borrow_mut();
2244                let cam = gfx.camera.clone();
2245                crate::gfx::vtex::draw_torii(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, w,h, fr,hue);
2246                return Ok(Value::Unit);
2247            }
2248
2249            // vtex_pagoda(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_tiers,base_w,tier_h,taper,eave_out, fr,hue)
2250            "vtex_pagoda" | "เจดีย์" | "纹塔" | "塔" | "탑" => {
2251                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;
2252                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;
2253                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;
2254                let nt=self.arg_num(&args,9,5.)?as usize; let bw=self.arg_num(&args,10,2.)?as f32;
2255                let th=self.arg_num(&args,11,1.)?as f32; let tp=self.arg_num(&args,12,0.72)?as f32;
2256                let eo=self.arg_num(&args,13,0.28)?as f32;
2257                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2258                let mut gfx = self.gfx.borrow_mut();
2259                let cam = gfx.camera.clone();
2260                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);
2261                return Ok(Value::Unit);
2262            }
2263
2264            // ══════════════════════════════════════════════════════════════════
2265            // AUDIO BUILTINS
2266            // ══════════════════════════════════════════════════════════════════
2267
2268            // audio_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth)
2269            #[cfg(not(target_arch = "wasm32"))]
2270            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2271                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2272                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2273                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2274                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2275                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2276                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2277                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2278                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2279                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2280                if let Some(audio) = &self.audio {
2281                    audio.set_tone(idx, ToneParams { x, y, z, w, freq, amp, lfo_rate, lfo_depth });
2282                }
2283                return Ok(Value::Unit);
2284            }
2285
2286            #[cfg(not(target_arch = "wasm32"))]
2287            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2288                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2289                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2290                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2291                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2292                if let Some(audio) = &self.audio {
2293                    audio.set_listener(cry, sry, crx, srx);
2294                }
2295                return Ok(Value::Unit);
2296            }
2297
2298            #[cfg(not(target_arch = "wasm32"))]
2299            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2300                let path = match args.first() {
2301                    Some(Value::Str(s)) => s.clone(),
2302                    _ => return Ok(Value::Unit),
2303                };
2304                let vol = self.arg_num(&args, 1, 0.5)? as f32;
2305                if let Some(audio) = &self.audio {
2306                    audio.load_bgm(&path, vol);
2307                }
2308                return Ok(Value::Unit);
2309            }
2310
2311            #[cfg(not(target_arch = "wasm32"))]
2312            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2313                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2314                if let Some(audio) = &self.audio {
2315                    audio.set_bgm_volume(vol);
2316                }
2317                return Ok(Value::Unit);
2318            }
2319
2320            #[cfg(not(target_arch = "wasm32"))]
2321            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2322                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2323                if let Some(audio) = &self.audio {
2324                    audio.set_master_volume(vol);
2325                }
2326                return Ok(Value::Unit);
2327            }
2328
2329            // WASM audio builtins — delegate to Web Audio API
2330            #[cfg(target_arch = "wasm32")]
2331            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2332                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2333                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2334                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2335                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2336                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2337                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2338                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2339                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2340                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2341                crate::gfx::audio_web::set_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth);
2342                return Ok(Value::Unit);
2343            }
2344
2345            #[cfg(target_arch = "wasm32")]
2346            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2347                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2348                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2349                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2350                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2351                crate::gfx::audio_web::set_listener(cry, sry, crx, srx);
2352                return Ok(Value::Unit);
2353            }
2354
2355            #[cfg(target_arch = "wasm32")]
2356            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2357                let path = self.arg_str(&args, 0, "");
2358                let vol  = self.arg_num(&args, 1, 0.5)? as f32;
2359                crate::gfx::audio_web::load_bgm(&path, vol);
2360                return Ok(Value::Unit);
2361            }
2362
2363            #[cfg(target_arch = "wasm32")]
2364            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2365                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2366                crate::gfx::audio_web::set_bgm_volume(vol);
2367                return Ok(Value::Unit);
2368            }
2369
2370            #[cfg(target_arch = "wasm32")]
2371            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2372                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2373                crate::gfx::audio_web::set_master_volume(vol);
2374                return Ok(Value::Unit);
2375            }
2376
2377            // ── รอหน้าต่าง() — block until window closed / Escape ──
2378            "รอหน้าต่าง" | "wait_window" | "gfx_wait" => {
2379                #[cfg(not(target_arch = "wasm32"))]
2380                loop {
2381                    let still_open = {
2382                        let gfx = self.gfx.borrow();
2383                        gfx.window.as_ref()
2384                            .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
2385                            .unwrap_or(false)
2386                    };
2387                    if !still_open { break; }
2388                    let (buf, w, h) = {
2389                        let gfx = self.gfx.borrow();
2390                        (gfx.buffer.clone(), gfx.width, gfx.height)
2391                    };
2392                    let mut gfx = self.gfx.borrow_mut();
2393                    if let Some(win) = gfx.window.as_mut() {
2394                        if win.update_with_buffer(&buf, w, h).is_err() { break; }
2395                    }
2396                }
2397                return Ok(Value::Unit);
2398            }
2399
2400            // ── File I/O ──────────────────────────────────────────────────────
2401            "read_file" | "อ่านไฟล์" => {
2402                let path = self.arg_str(&args, 0, "");
2403                return std::fs::read_to_string(&path)
2404                    .map(Value::Str)
2405                    .map_err(|e| EvalErr::from(format!("read_file '{path}': {e}")));
2406            }
2407            "write_file" | "เขียนไฟล์" => {
2408                let path    = self.arg_str(&args, 0, "");
2409                let content = self.arg_str(&args, 1, "");
2410                std::fs::write(&path, content.as_bytes())
2411                    .map_err(|e| EvalErr::from(format!("write_file '{path}': {e}")))?;
2412                return Ok(Value::Unit);
2413            }
2414            "print_file" | "พิมพ์ไฟล์" => {
2415                let content = self.arg_str(&args, 0, "");
2416                print!("{content}");
2417                return Ok(Value::Unit);
2418            }
2419
2420            // ── CLI arguments ─────────────────────────────────────────────────
2421            "get_args" | "รับอาร์กิวเมนต์" => {
2422                let v: Vec<Value> = std::env::args().map(Value::Str).collect();
2423                return Ok(Value::List(v));
2424            }
2425
2426            // ── String utilities ──────────────────────────────────────────────
2427            "split" | "str_split" | "แยก" => {
2428                let s   = self.arg_str(&args, 0, "");
2429                let sep = self.arg_str(&args, 1, "\n");
2430                let sep = if sep.is_empty() { "\n".into() } else { sep };
2431                let parts: Vec<Value> = s.split(sep.as_str())
2432                    .map(|p| Value::Str(p.to_string())).collect();
2433                return Ok(Value::List(parts));
2434            }
2435            "trim" | "str_trim" | "ตัดช่องว่าง" => {
2436                let s = self.arg_str(&args, 0, "");
2437                return Ok(Value::Str(s.trim().to_string()));
2438            }
2439            "starts_with" | "str_starts_with" | "เริ่มด้วย" => {
2440                let s      = self.arg_str(&args, 0, "");
2441                let prefix = self.arg_str(&args, 1, "");
2442                return Ok(Value::Bool(s.starts_with(prefix.as_str())));
2443            }
2444            "ends_with" | "str_ends_with" | "ลงท้ายด้วย" => {
2445                let s      = self.arg_str(&args, 0, "");
2446                let suffix = self.arg_str(&args, 1, "");
2447                return Ok(Value::Bool(s.ends_with(suffix.as_str())));
2448            }
2449            "str_replace" | "แทนสตริง" => {
2450                let s    = self.arg_str(&args, 0, "");
2451                let from = self.arg_str(&args, 1, "");
2452                let to   = self.arg_str(&args, 2, "");
2453                return Ok(Value::Str(s.replace(from.as_str(), to.as_str())));
2454            }
2455            "str_find" | "หาในสตริง" => {
2456                let s      = self.arg_str(&args, 0, "");
2457                let needle = self.arg_str(&args, 1, "");
2458                // Return char index (not byte index) for consistency with substr
2459                let pos = s.find(needle.as_str())
2460                    .map(|byte_i| s[..byte_i].chars().count() as f64)
2461                    .unwrap_or(-1.0);
2462                return Ok(Value::Number(pos));
2463            }
2464            "substr" | "str_slice" | "ส่วนสตริง" => {
2465                let s     = self.arg_str(&args, 0, "");
2466                let start = self.arg_num(&args, 1, 0.0)? as usize;
2467                let len   = args.get(2)
2468                    .map(|v| self.to_number(v).unwrap_or(999999.0) as usize)
2469                    .unwrap_or_else(|| s.chars().count().saturating_sub(start));
2470                let chars: Vec<char> = s.chars().collect();
2471                let end   = (start + len).min(chars.len());
2472                let slice: String = chars.get(start..end).unwrap_or(&[]).iter().collect();
2473                return Ok(Value::Str(slice));
2474            }
2475            "to_str" | "str" | "num_str" | "แปลงสตริง" => {
2476                let v = args.into_iter().next().unwrap_or(Value::Unit);
2477                return Ok(Value::Str(v.to_string()));
2478            }
2479            "str_repeat" | "ทำซ้ำสตริง" => {
2480                let s = self.arg_str(&args, 0, "");
2481                let n = self.arg_num(&args, 1, 1.0)? as usize;
2482                return Ok(Value::Str(s.repeat(n)));
2483            }
2484            "str_upper" => {
2485                let s = self.arg_str(&args, 0, "");
2486                return Ok(Value::Str(s.to_uppercase()));
2487            }
2488            "str_lower" => {
2489                let s = self.arg_str(&args, 0, "");
2490                return Ok(Value::Str(s.to_lowercase()));
2491            }
2492            "str_len" | "len" | "ความยาว" | "长度" | "長さ" | "길이" => {
2493                match args.first() {
2494                    Some(Value::Str(s))  => return Ok(Value::Number(s.chars().count() as f64)),
2495                    Some(Value::List(v)) => return Ok(Value::Number(v.len() as f64)),
2496                    _ => return Ok(Value::Number(0.0)),
2497                }
2498            }
2499
2500            // ── FNV-1a hash (deterministic, normalized 0.0–1.0) ──────────────
2501            "hash_str" | "แฮช" => {
2502                let s = self.arg_str(&args, 0, "");
2503                let mut h: u64 = 14695981039346656037_u64;
2504                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
2505                return Ok(Value::Number((h & 0xFFFFFF) as f64 / 16777215.0));
2506            }
2507            "hash_int" | "แฮชจำนวน" => {
2508                let s = self.arg_str(&args, 0, "");
2509                let n = self.arg_num(&args, 1, 100.0)? as u64;
2510                let mut h: u64 = 14695981039346656037_u64;
2511                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
2512                return Ok(Value::Number((h % n.max(1)) as f64));
2513            }
2514
2515            // ── List utilities ────────────────────────────────────────────────
2516            "list_new" | "รายการใหม่" | "新建列表" | "新規リスト" | "새목록" => {
2517                return Ok(Value::List(Vec::new()));
2518            }
2519            "list_push" | "เพิ่มรายการ" | "列表添加" | "リスト追加" | "목록추가" => {
2520                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
2521                let val = args.get(1).cloned().unwrap_or(Value::Unit);
2522                if let Value::List(mut v) = lst { v.push(val); return Ok(Value::List(v)); }
2523                return Ok(Value::List(vec![val]));
2524            }
2525            "list_get" | "รับรายการ" | "取元素" | "要素取得" | "요소가져오기" => {
2526                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
2527                let i   = self.arg_num(&args, 1, 0.0)? as usize;
2528                if let Value::List(v) = lst {
2529                    return Ok(v.get(i).cloned().unwrap_or(Value::Str(String::new())));
2530                }
2531                return Ok(Value::Str(String::new()));
2532            }
2533            "list_join" | "join" | "รวมรายการ" | "连接" | "連結" | "연결" => {
2534                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
2535                let sep = args.get(1).map(|v| v.to_string()).unwrap_or_default();
2536                if let Value::List(v) = lst {
2537                    return Ok(Value::Str(v.iter().map(|x| x.to_string())
2538                        .collect::<Vec<_>>().join(&sep)));
2539                }
2540                return Ok(Value::Str(String::new()));
2541            }
2542
2543            // ══════════════════════════════════════════════════════════════════
2544            // SVG EXPORT  (svg_begin / svg_rect / svg_circle / svg_line /
2545            //              svg_polyline / svg_text / svg_end / hsl_color)
2546            // Chinese aliases: 开始SVG 结束SVG SVG矩形 SVG圆形 SVG线段 SVG折线 SVG文本 HSL颜色
2547            // Thai aliases:    เริ่มSVG จบSVG SVGสี่เหลี่ยม SVGวงกลม SVGเส้น SVGเส้นหัก SVGข้อความ สีHSL
2548            // ══════════════════════════════════════════════════════════════════
2549
2550            "svg_begin" | "开始SVG" | "เริ่มSVG" => {
2551                let path   = self.arg_str(&args, 0, "output.svg");
2552                let width  = self.arg_num(&args, 1, 800.0)?;
2553                let height = self.arg_num(&args, 2, 600.0)?;
2554                *self.svg.borrow_mut() = Some(SvgWriter::new(path, width, height));
2555                return Ok(Value::Unit);
2556            }
2557
2558            "svg_rect" | "SVG矩形" | "SVGสี่เหลี่ยม" => {
2559                let x    = self.arg_num(&args, 0, 0.0)?;
2560                let y    = self.arg_num(&args, 1, 0.0)?;
2561                let w    = self.arg_num(&args, 2, 10.0)?;
2562                let h    = self.arg_num(&args, 3, 10.0)?;
2563                let fill = self.arg_str(&args, 4, "#ffffff");
2564                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2565                    svg.elements.push(format!(
2566                        "<rect x=\"{x:.1}\" y=\"{y:.1}\" width=\"{w:.1}\" \
2567                         height=\"{h:.1}\" fill=\"{fill}\"/>"));
2568                }
2569                return Ok(Value::Unit);
2570            }
2571
2572            "svg_circle" | "SVG圆形" | "SVGวงกลม" => {
2573                let cx   = self.arg_num(&args, 0, 0.0)?;
2574                let cy   = self.arg_num(&args, 1, 0.0)?;
2575                let r    = self.arg_num(&args, 2, 5.0)?;
2576                let fill = self.arg_str(&args, 3, "#ffffff");
2577                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2578                    svg.elements.push(format!(
2579                        "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{fill}\"/>"));
2580                }
2581                return Ok(Value::Unit);
2582            }
2583
2584            "svg_line" | "SVG线段" | "SVGเส้น" => {
2585                let x1     = self.arg_num(&args, 0, 0.0)?;
2586                let y1     = self.arg_num(&args, 1, 0.0)?;
2587                let x2     = self.arg_num(&args, 2, 0.0)?;
2588                let y2     = self.arg_num(&args, 3, 0.0)?;
2589                let stroke = self.arg_str(&args, 4, "#ffffff");
2590                let sw     = self.arg_num(&args, 5, 1.0)?;
2591                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2592                    svg.elements.push(format!(
2593                        "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" \
2594                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
2595                }
2596                return Ok(Value::Unit);
2597            }
2598
2599            "svg_polyline" | "SVG折线" | "SVGเส้นหัก" => {
2600                let pts    = self.arg_str(&args, 0, "");
2601                let stroke = self.arg_str(&args, 1, "#ffffff");
2602                let sw     = self.arg_num(&args, 2, 1.0)?;
2603                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2604                    svg.elements.push(format!(
2605                        "<polyline points=\"{pts}\" fill=\"none\" \
2606                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
2607                }
2608                return Ok(Value::Unit);
2609            }
2610
2611            "svg_text" | "SVG文本" | "SVGข้อความ" => {
2612                let x    = self.arg_num(&args, 0, 0.0)?;
2613                let y    = self.arg_num(&args, 1, 0.0)?;
2614                let text = self.arg_str(&args, 2, "");
2615                let fill = self.arg_str(&args, 3, "#ffffff");
2616                let size = self.arg_num(&args, 4, 12.0)?;
2617                if let Some(svg) = self.svg.borrow_mut().as_mut() {
2618                    let safe = text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
2619                    svg.elements.push(format!(
2620                        "<text x=\"{x:.1}\" y=\"{y:.1}\" fill=\"{fill}\" \
2621                         font-family=\"monospace\" font-size=\"{size:.0}\">{safe}</text>"));
2622                }
2623                return Ok(Value::Unit);
2624            }
2625
2626            "svg_end" | "结束SVG" | "จบSVG" => {
2627                {
2628                    let borrow = self.svg.borrow();
2629                    if let Some(svg) = borrow.as_ref() {
2630                        svg.save().map_err(|e| EvalErr::from(format!("svg_end: {e}")))?;
2631                    }
2632                }
2633                *self.svg.borrow_mut() = None;
2634                return Ok(Value::Unit);
2635            }
2636
2637            "hsl_color" | "HSL颜色" | "สีHSL" => {
2638                let h = self.arg_num(&args, 0, 0.0)?;
2639                let s = self.arg_num(&args, 1, 70.0)?;
2640                let l = self.arg_num(&args, 2, 50.0)?;
2641                return Ok(Value::Str(hsl_to_hex(h, s, l)));
2642            }
2643
2644            // ══════════════════════════════════════════════════════════════════
2645            // FFT / AUDIO ANALYSIS BUILTINS  (native only)
2646            // ══════════════════════════════════════════════════════════════════
2647
2648            // fft_push(samples_list) — feed raw audio samples and run FFT
2649            #[cfg(not(target_arch = "wasm32"))]
2650            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => {
2651                if let Some(Value::List(v)) = args.first() {
2652                    let samples: Vec<f32> = v.iter()
2653                        .filter_map(|x| if let Value::Number(n) = x { Some(*n as f32) } else { None })
2654                        .collect();
2655                    self.fft.borrow_mut().push_samples(&samples);
2656                }
2657                return Ok(Value::Unit);
2658            }
2659
2660            // fft_bands(n) → list of n log-spaced magnitude bands (0..1)
2661            #[cfg(not(target_arch = "wasm32"))]
2662            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
2663                let n = self.arg_num(&args, 0, 32.0)? as usize;
2664                let bands = self.fft.borrow().freq_bands(n);
2665                *self.fft_bands_cache.borrow_mut() = bands.clone();
2666                return Ok(Value::List(bands.into_iter().map(|v| Value::Number(v as f64)).collect()));
2667            }
2668
2669            // fft_beat() → bool
2670            #[cfg(not(target_arch = "wasm32"))]
2671            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => {
2672                return Ok(Value::Bool(self.fft.borrow().is_beat()));
2673            }
2674
2675            // fft_beat_ratio() → f64  (1.0 = at threshold, >1 = strong beat)
2676            #[cfg(not(target_arch = "wasm32"))]
2677            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => {
2678                return Ok(Value::Number(self.fft.borrow().beat_ratio() as f64));
2679            }
2680
2681            // fft_rms() → f64
2682            #[cfg(not(target_arch = "wasm32"))]
2683            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => {
2684                return Ok(Value::Number(self.fft.borrow().rms() as f64));
2685            }
2686
2687            // fft_dominant_freq() → f64  in Hz
2688            #[cfg(not(target_arch = "wasm32"))]
2689            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => {
2690                return Ok(Value::Number(self.fft.borrow().dominant_freq() as f64));
2691            }
2692
2693            // ── wasm32 stubs: fft builtins are no-ops on web ───────────────
2694            #[cfg(target_arch = "wasm32")]
2695            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => { return Ok(Value::Unit); }
2696            #[cfg(target_arch = "wasm32")]
2697            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
2698                let n = self.arg_num(&args, 0, 32.0)? as usize;
2699                return Ok(Value::List(vec![Value::Number(0.0); n]));
2700            }
2701            #[cfg(target_arch = "wasm32")]
2702            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => { return Ok(Value::Bool(false)); }
2703            #[cfg(target_arch = "wasm32")]
2704            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => { return Ok(Value::Number(1.0)); }
2705            #[cfg(target_arch = "wasm32")]
2706            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => { return Ok(Value::Number(0.0)); }
2707            #[cfg(target_arch = "wasm32")]
2708            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => { return Ok(Value::Number(0.0)); }
2709
2710            // ══════════════════════════════════════════════════════════════════
2711            // PROCEDURAL TEXTURE BLIT BUILTINS  (screen-space)
2712            // All: name(dst_x, dst_y, width, height, ...params, palette)
2713            // palette: "rainbow" | "fire" | "ocean" | "psychedelic" | "neon" | "forest"
2714            // ══════════════════════════════════════════════════════════════════
2715
2716            // tex_checkerboard(x, y, w, h, tiles, r1,g1,b1, r2,g2,b2)
2717            "tex_checkerboard" | "ลายตารางหมากรุก" => {
2718                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2719                let tiles = self.arg_num(&args, 4, 8.0)? as u32;
2720                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);
2721                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);
2722                let c1 = (r1<<16)|(g1<<8)|b1; let c2 = (r2<<16)|(g2<<8)|b2;
2723                let mut gfx = self.gfx.borrow_mut();
2724                let (bw, bh) = (gfx.width, gfx.height);
2725                for row in 0..th { for col in 0..tw {
2726                    let cx = col as u32 * tiles / tw as u32;
2727                    let cy = row as u32 * tiles / th as u32;
2728                    let (dx, dy) = (tx+col, ty+row);
2729                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = if (cx+cy)%2==0 { c1 } else { c2 }; }
2730                }}
2731                return Ok(Value::Unit);
2732            }
2733
2734            // tex_gradient(x, y, w, h, angle_deg, r1,g1,b1, r2,g2,b2)
2735            "tex_gradient" | "ลายไล่สี" => {
2736                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2737                let angle = self.arg_num(&args, 4, 0.0)? as f32;
2738                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.);
2739                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.);
2740                let (ca, sa) = (angle.to_radians().cos(), angle.to_radians().sin());
2741                let mut gfx = self.gfx.borrow_mut();
2742                let (bw, bh) = (gfx.width, gfx.height);
2743                for row in 0..th { for col in 0..tw {
2744                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
2745                    let t = ((nx*ca + ny*sa + 0.707)/1.414).clamp(0.,1.);
2746                    let (dx, dy) = (tx+col, ty+row);
2747                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r1+(r2-r1)*t, g1+(g2-g1)*t, b1+(b2-b1)*t); }
2748                }}
2749                return Ok(Value::Unit);
2750            }
2751
2752            // tex_noise(x, y, w, h, scale, octaves, seed, palette)
2753            "tex_noise" | "ลายนอยส์" => {
2754                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2755                let scale   = self.arg_num(&args, 4, 4.0)? as f32;
2756                let octaves = self.arg_num(&args, 5, 4.0)? as u32;
2757                let seed    = self.arg_num(&args, 6, 0.0)? as u32;
2758                let palette = self.arg_str(&args, 7, "rainbow");
2759                let mut gfx = self.gfx.borrow_mut();
2760                let (bw, bh) = (gfx.width, gfx.height);
2761                for row in 0..th { for col in 0..tw {
2762                    let v = tex_fbm(col as f32*scale/tw as f32, row as f32*scale/th as f32, octaves, seed);
2763                    let [r,g,b] = tex_palette(&palette, v);
2764                    let (dx, dy) = (tx+col, ty+row);
2765                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r, g, b); }
2766                }}
2767                return Ok(Value::Unit);
2768            }
2769
2770            // tex_freq_map(x, y, w, h, time, speed, palette)
2771            // Uses bands written by the last fft_bands() call.
2772            "tex_freq_map" | "ลายความถี่" => {
2773                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2774                let time    = self.arg_num(&args, 4, 0.0)? as f32;
2775                let speed   = self.arg_num(&args, 5, 0.3)? as f32;
2776                let palette = self.arg_str(&args, 6, "rainbow");
2777                let bands: Vec<f32> = {
2778                    let c = self.fft_bands_cache.borrow();
2779                    if c.is_empty() { vec![0.0; 32] } else { c.clone() }
2780                };
2781                let n = bands.len().max(1);
2782                let mut gfx = self.gfx.borrow_mut();
2783                let (bw, bh) = (gfx.width, gfx.height);
2784                for row in 0..th { for col in 0..tw {
2785                    let band_idx = (col * n / tw.max(1)).min(n-1);
2786                    let mag = bands[band_idx].clamp(0.,1.);
2787                    let fill_y = (mag * th as f32) as usize;
2788                    if row >= th.saturating_sub(fill_y) {
2789                        let t = (col as f32/tw as f32 + time*speed) % 1.0;
2790                        let [r,g,b] = tex_palette(&palette, t);
2791                        let bright = mag * (1.0 - row as f32/th as f32 * 0.5);
2792                        let (dx, dy) = (tx+col, ty+row);
2793                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r*bright, g*bright, b*bright); }
2794                    }
2795                }}
2796                return Ok(Value::Unit);
2797            }
2798
2799            // tex_spiral(x, y, w, h, freq, bands, time, palette)
2800            "tex_spiral" | "ลายเกลียวหมุน" => {
2801                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2802                let freq    = self.arg_num(&args, 4, 5.0)? as f32;
2803                let n_bands = self.arg_num(&args, 5, 8.0)? as f32;
2804                let time    = self.arg_num(&args, 6, 0.0)? as f32;
2805                let palette = self.arg_str(&args, 7, "rainbow");
2806                let mut gfx = self.gfx.borrow_mut();
2807                let (bw, bh) = (gfx.width, gfx.height);
2808                for row in 0..th { for col in 0..tw {
2809                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
2810                    let r  = (nx*nx + ny*ny).sqrt();
2811                    let theta = ny.atan2(nx);
2812                    let t = ((r*freq - theta/std::f32::consts::TAU + time*0.5) * n_bands % 1.0).abs();
2813                    let [cr,cg,cb] = tex_palette(&palette, t);
2814                    let (dx, dy) = (tx+col, ty+row);
2815                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2816                }}
2817                return Ok(Value::Unit);
2818            }
2819
2820            // tex_ripple(x, y, w, h, freq, cx, cy, time, palette)
2821            "tex_ripple" | "ลายระลอก" => {
2822                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2823                let freq    = self.arg_num(&args, 4, 10.0)? as f32;
2824                let rcx     = self.arg_num(&args, 5, 0.5)? as f32;
2825                let rcy     = self.arg_num(&args, 6, 0.5)? as f32;
2826                let time    = self.arg_num(&args, 7, 0.0)? as f32;
2827                let palette = self.arg_str(&args, 8, "ocean");
2828                let mut gfx = self.gfx.borrow_mut();
2829                let (bw, bh) = (gfx.width, gfx.height);
2830                for row in 0..th { for col in 0..tw {
2831                    let nx = col as f32/tw as f32 - rcx; let ny = row as f32/th as f32 - rcy;
2832                    let r = (nx*nx + ny*ny).sqrt();
2833                    let t = ((r*freq - time) % 1.0).abs();
2834                    let [cr,cg,cb] = tex_palette(&palette, t);
2835                    let (dx, dy) = (tx+col, ty+row);
2836                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2837                }}
2838                return Ok(Value::Unit);
2839            }
2840
2841            // tex_mandelbrot(x, y, w, h, zoom, cx, cy, max_iter, palette)
2842            "tex_mandelbrot" | "ลายแมนเดลบรอต" => {
2843                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2844                let zoom     = self.arg_num(&args, 4, 1.0)?;
2845                let mcx      = self.arg_num(&args, 5, -0.5)?;
2846                let mcy      = self.arg_num(&args, 6, 0.0)?;
2847                let max_iter = self.arg_num(&args, 7, 64.0)? as u32;
2848                let palette  = self.arg_str(&args, 8, "psychedelic");
2849                let mut gfx = self.gfx.borrow_mut();
2850                let (bw, bh) = (gfx.width, gfx.height);
2851                for row in 0..th { for col in 0..tw {
2852                    let zx0 = (col as f64/tw as f64 - 0.5)/zoom + mcx;
2853                    let zy0 = (row as f64/th as f64 - 0.5)/zoom + mcy;
2854                    let mut x = 0.0f64; let mut y = 0.0f64; let mut i = 0u32;
2855                    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; }
2856                    let t = if i==max_iter { 0.0f32 } else {
2857                        (i as f32 - (x as f32*x as f32+y as f32*y as f32).ln().ln()/2.0f32.ln()) / max_iter as f32
2858                    };
2859                    let [cr,cg,cb] = tex_palette(&palette, t.clamp(0.,1.));
2860                    let (dx, dy) = (tx+col, ty+row);
2861                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2862                }}
2863                return Ok(Value::Unit);
2864            }
2865
2866            // tex_julia(x, y, w, h, c_re, c_im, max_iter, palette)
2867            "tex_julia" | "ลายจูเลีย" => {
2868                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2869                let c_re     = self.arg_num(&args, 4, -0.7)?;
2870                let c_im     = self.arg_num(&args, 5, 0.27)?;
2871                let max_iter = self.arg_num(&args, 6, 64.0)? as u32;
2872                let palette  = self.arg_str(&args, 7, "neon");
2873                let mut gfx = self.gfx.borrow_mut();
2874                let (bw, bh) = (gfx.width, gfx.height);
2875                for row in 0..th { for col in 0..tw {
2876                    let mut zx = (col as f64/tw as f64 - 0.5)*3.5;
2877                    let mut zy = (row as f64/th as f64 - 0.5)*3.5;
2878                    let mut i = 0u32;
2879                    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; }
2880                    let t = i as f32 / max_iter as f32;
2881                    let [cr,cg,cb] = tex_palette(&palette, t);
2882                    let (dx, dy) = (tx+col, ty+row);
2883                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2884                }}
2885                return Ok(Value::Unit);
2886            }
2887
2888            // tex_voronoi(x, y, w, h, cells, seed, palette)
2889            "tex_voronoi" | "ลายโวโรนอย" => {
2890                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2891                let cells   = self.arg_num(&args, 4, 16.0)? as u32;
2892                let seed    = self.arg_num(&args, 5, 42.0)? as u32;
2893                let palette = self.arg_str(&args, 6, "rainbow");
2894                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();
2895                let mut gfx = self.gfx.borrow_mut();
2896                let (bw, bh) = (gfx.width, gfx.height);
2897                for row in 0..th { for col in 0..tw {
2898                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
2899                    let (min_d, nearest) = pts.iter().enumerate().fold((f32::MAX,0usize), |(d,idx),(i,&[cx,cy])| {
2900                        let dd = (fx-cx).powi(2)+(fy-cy).powi(2);
2901                        if dd < d { (dd,i) } else { (d,idx) }
2902                    });
2903                    let t = (nearest as f32/cells as f32 + min_d*4.0) % 1.0;
2904                    let [cr,cg,cb] = tex_palette(&palette, t);
2905                    let (dx, dy) = (tx+col, ty+row);
2906                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2907                }}
2908                return Ok(Value::Unit);
2909            }
2910
2911            // tex_halftone(x, y, w, h, dot_size, time, palette)
2912            "tex_halftone" | "ลายฮาล์ฟโทน" => {
2913                let (tx,ty,tw,th) = self.tex_rect(&args)?;
2914                let dot_size = self.arg_num(&args, 4, 0.05)? as f32;
2915                let time     = self.arg_num(&args, 5, 0.0)? as f32;
2916                let palette  = self.arg_str(&args, 6, "rainbow");
2917                let mut gfx = self.gfx.borrow_mut();
2918                let (bw, bh) = (gfx.width, gfx.height);
2919                for row in 0..th { for col in 0..tw {
2920                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
2921                    let gx = (fx/dot_size).floor(); let gy = (fy/dot_size).floor();
2922                    let lx = (fx/dot_size - gx - 0.5)*2.0; let ly = (fy/dot_size - gy - 0.5)*2.0;
2923                    let r = (lx*lx + ly*ly).sqrt();
2924                    let t = (gx/(1.0/dot_size) + time*0.1) % 1.0;
2925                    let a = if r < 0.7 { ((0.7-r)/0.7).clamp(0.,1.) } else { 0.0 };
2926                    if a > 0.0 {
2927                        let [cr,cg,cb] = tex_palette(&palette, t);
2928                        let (dx, dy) = (tx+col, ty+row);
2929                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
2930                    }
2931                }}
2932                return Ok(Value::Unit);
2933            }
2934
2935            // ══════════════════════════════════════════════════════════════════
2936            // RENDER / LIGHTING MODES  (holographic cel shading)
2937            // ══════════════════════════════════════════════════════════════════
2938            // set_shade_mode(m) — 0 flat · 1 cel · 2 holo (default)
2939            "set_shade_mode" | "设置着色" | "シェード設定" | "셰이드모드" | "ตั้งการแรเงา" => {
2940                let m = self.arg_num(&args, 0, 2.0)? as u8;
2941                self.gfx.borrow_mut().shade_mode = m;
2942                return Ok(Value::Unit);
2943            }
2944            // set_cel_bands(n) — number of posterisation bands (>=2)
2945            "set_cel_bands" | "设置色阶" | "セル段数" | "셀밴드" | "ตั้งระดับสี" => {
2946                let n = (self.arg_num(&args, 0, 4.0)? as u32).max(2);
2947                self.gfx.borrow_mut().shade.bands = n;
2948                return Ok(Value::Unit);
2949            }
2950            // set_shadow_color(r,g,b) — coloured-shadow tint, 0-255
2951            "set_shadow_color" | "设置阴影色" | "影の色" | "그림자색" | "ตั้งสีเงา" => {
2952                let r=self.arg_num(&args,0,26.)? as f32/255.0;
2953                let g=self.arg_num(&args,1,33.)? as f32/255.0;
2954                let b=self.arg_num(&args,2,77.)? as f32/255.0;
2955                self.gfx.borrow_mut().shade.shadow = [r,g,b];
2956                return Ok(Value::Unit);
2957            }
2958            // set_rim(strength, r,g,b) — holographic fresnel edge glow
2959            // ══════════════════════════════════════════════════════════════════
2960            // CRYPTOGRAPHY (ling-crypto) — geo suite, hybrid PQ KEM, holographic
2961            // Bytes cross the language boundary as lowercase hex strings.
2962            // ══════════════════════════════════════════════════════════════════
2963            #[cfg(not(target_arch = "wasm32"))]
2964            "crypto_hash" | "แฮชเข้ารหัส" | "几何哈希" | "幾何ハッシュ" | "기하해시" => {
2965                let s = self.arg_str(&args, 0, "");
2966                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(s.as_bytes()))));
2967            }
2968            // 3-D torus-knot fingerprint of any text/key → flat [x,y,z, x,y,z, …]
2969            #[cfg(not(target_arch = "wasm32"))]
2970            "knot_points" | "จุดปม" | "结点坐标" | "結び目点" | "매듭점" => {
2971                let s = self.arg_str(&args, 0, "");
2972                let shape = ling_crypto::geo::KnotShape::from_bytes(s.as_bytes());
2973                let mut out = Vec::with_capacity(shape.points.len() * 3);
2974                for p in &shape.points {
2975                    out.push(Value::Number(p[0] as f64));
2976                    out.push(Value::Number(p[1] as f64));
2977                    out.push(Value::Number(p[2] as f64));
2978                }
2979                return Ok(Value::List(out));
2980            }
2981            #[cfg(not(target_arch = "wasm32"))]
2982            "knot_label" | "ป้ายปม" | "结点标签" | "結び目ラベル" | "매듭라벨" => {
2983                let s = self.arg_str(&args, 0, "");
2984                return Ok(Value::Str(ling_crypto::geo::KnotShape::from_bytes(s.as_bytes()).label()));
2985            }
2986            // KEM keypair (hybrid X25519+ML-KEM-768) → integer handle
2987            #[cfg(not(target_arch = "wasm32"))]
2988            "knot_keygen" | "hybrid_keygen" | "สร้างกุญแจปม" | "生成密钥" | "鍵生成" | "키생성" => {
2989                self.crypto_ids.push(ling_crypto::KnotIdentity::generate());
2990                return Ok(Value::Number((self.crypto_ids.len() - 1) as f64));
2991            }
2992            #[cfg(not(target_arch = "wasm32"))]
2993            "knot_public" | "hybrid_public" | "กุญแจสาธารณะปม" | "公钥" | "公開鍵" | "공개키" => {
2994                let h = self.arg_num(&args, 0, 0.0)? as usize;
2995                let pk = self.crypto_ids.get(h).map(|id| hex_encode(id.public_key())).unwrap_or_default();
2996                return Ok(Value::Str(pk));
2997            }
2998            // encapsulate(pubkey_hex) → [ciphertext_hex, shared_secret_hex]
2999            #[cfg(not(target_arch = "wasm32"))]
3000            "knot_encapsulate" | "hybrid_encapsulate" | "ห่อกุญแจปม" | "封装密钥" | "カプセル化" | "캡슐화" => {
3001                let pk = hex_decode(&self.arg_str(&args, 0, ""));
3002                match ling_crypto::geo::knot_encapsulate(&pk) {
3003                    Ok((ct, ss)) => return Ok(Value::List(vec![Value::Str(hex_encode(&ct)), Value::Str(hex_encode(&ss))])),
3004                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3005                }
3006            }
3007            // decapsulate(handle, ciphertext_hex) → shared_secret_hex
3008            #[cfg(not(target_arch = "wasm32"))]
3009            "knot_decapsulate" | "hybrid_decapsulate" | "แกะกุญแจปม" | "解封装密钥" | "カプセル解除" | "캡슐해제" => {
3010                let h = self.arg_num(&args, 0, 0.0)? as usize;
3011                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3012                let ss = self.crypto_ids.get(h)
3013                    .and_then(|id| id.decapsulate(&ct).ok())
3014                    .map(|s| hex_encode(&s)).unwrap_or_default();
3015                return Ok(Value::Str(ss));
3016            }
3017            // Authenticated encryption (XChaCha20-Poly1305) — seal(key_hex, text) → ct_hex
3018            #[cfg(not(target_arch = "wasm32"))]
3019            "crypto_seal" | "ผนึก" | "封印" | "封印する" | "봉인" => {
3020                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3021                let pt = self.arg_str(&args, 1, "");
3022                match ling_crypto::geo::holo_seal(key, pt.as_bytes()) {
3023                    Ok(ct) => return Ok(Value::Str(hex_encode(&ct))),
3024                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3025                }
3026            }
3027            #[cfg(not(target_arch = "wasm32"))]
3028            "crypto_open" | "เปิดผนึก" | "解封" | "封印解除" | "봉인해제" => {
3029                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3030                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3031                match ling_crypto::geo::holo_open(key, &ct) {
3032                    Ok(pt) => return Ok(Value::Str(String::from_utf8_lossy(&pt).into_owned())),
3033                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3034                }
3035            }
3036            // Holographic all-or-nothing transform — 4-D fragment coords [a,b,c,d, …]
3037            #[cfg(not(target_arch = "wasm32"))]
3038            "holo_points" | "จุดโฮโลแกรม" | "全息点" | "ホログラム点" | "홀로그램점" => {
3039                let s = self.arg_str(&args, 0, "");
3040                let frags = ling_crypto::geo::scatter(s.as_bytes());
3041                let mut out = Vec::with_capacity(frags.len() * 4);
3042                for f in &frags { for c in f.coord { out.push(Value::Number(c as f64)); } }
3043                return Ok(Value::List(out));
3044            }
3045            #[cfg(not(target_arch = "wasm32"))]
3046            "holo_fragment_count" | "จำนวนชิ้นโฮโลแกรม" | "全息碎片数" | "ホログラム断片数" | "홀로그램조각수" => {
3047                let s = self.arg_str(&args, 0, "");
3048                return Ok(Value::Number(ling_crypto::geo::scatter(s.as_bytes()).len() as f64));
3049            }
3050
3051            // ══════════════════════════════════════════════════════════════════
3052            // ling-ui — animation easings + holographic vector widgets + text I/O
3053            // ══════════════════════════════════════════════════════════════════
3054            "ease" => {
3055                let name = self.arg_str(&args, 0, "ease");
3056                let t = self.arg_num(&args, 1, 0.0)? as f32;
3057                return Ok(Value::Number(ling_ui::Easing::from_name(&name).apply(t) as f64));
3058            }
3059            #[cfg(not(target_arch = "wasm32"))]
3060            "mouse_x" => {
3061                let gfx = self.gfx.borrow();
3062                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);
3063                return Ok(Value::Number(v));
3064            }
3065            #[cfg(not(target_arch = "wasm32"))]
3066            "mouse_y" => {
3067                let gfx = self.gfx.borrow();
3068                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);
3069                return Ok(Value::Number(v));
3070            }
3071            #[cfg(not(target_arch = "wasm32"))]
3072            "mouse_down" => {
3073                let gfx = self.gfx.borrow();
3074                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
3075                return Ok(Value::Bool(d));
3076            }
3077            #[cfg(not(target_arch = "wasm32"))]
3078            "ui_hot" | "热区" | "ホットエリア" | "핫존" | "พื้นที่สัมผัส" => {
3079                let x = self.arg_num(&args,0,0.0)? as f32;
3080                let y = self.arg_num(&args,1,0.0)? as f32;
3081                let w = self.arg_num(&args,2,0.0)? as f32;
3082                let h = self.arg_num(&args,3,0.0)? as f32;
3083                let gfx = self.gfx.borrow();
3084                let (mx,my) = gfx.window.as_ref().and_then(|win| win.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0,0.0));
3085                return Ok(Value::Bool(ling_ui::holo::hit_rect(mx,my,x,y,w,h)));
3086            }
3087            // ui_text(x, y, scale, "string") — holographic vector text
3088            "ui_text" | "界面文字" | "UI文字" | "UI텍스트" | "ข้อความหน้าจอ" => {
3089                let x = self.arg_num(&args,0,0.0)? as f32;
3090                let y = self.arg_num(&args,1,0.0)? as f32;
3091                let scale = self.arg_num(&args,2,16.0)? as f32;
3092                let s = self.arg_str(&args,3,"");
3093                let segs = ling_ui::holo::text_lines(&s, x, y, scale*0.62, scale, scale*0.24);
3094                let mut gfx = self.gfx.borrow_mut();
3095                let (w,h,color) = (gfx.width, gfx.height, gfx.color);
3096                for sg in segs { draw_line(&mut gfx.buffer, w, h, color, sg[0], sg[1], sg[2], sg[3]); }
3097                return Ok(Value::Unit);
3098            }
3099            // font_load("path.ttf") — load a vector font (outlines cached lazily as
3100            // cache/fonts/<stem>/<codepoint>.ling). Returns a handle, or -1 on failure.
3101            #[cfg(not(target_arch = "wasm32"))]
3102            "font_load" | "โหลดฟอนต์" | "加载字体" | "フォント読込" | "글꼴로드" => {
3103                let path = self.arg_str(&args, 0, "");
3104                // Optional 2nd arg: variable-font weight (e.g. 600 for a solid, bold UI).
3105                let weight = match self.arg_num(&args, 1, 0.0)? {
3106                    w if w > 0.0 => Some(w as f32),
3107                    _ => None,
3108                };
3109                // Try the path as given, then relative to the script's directory.
3110                let mut loaded = ling_graphics::VectorFont::from_path_weight(&path, weight);
3111                if loaded.is_err() {
3112                    if let Some(dir) = &self.source_dir {
3113                        let joined = dir.join(&path);
3114                        loaded = ling_graphics::VectorFont::from_path_weight(&joined.to_string_lossy(), weight);
3115                    }
3116                }
3117                match loaded {
3118                    Ok(f) => {
3119                        let id = self.fonts.len();
3120                        self.fonts.push(f);
3121                        return Ok(Value::Number(id as f64));
3122                    }
3123                    Err(e) => {
3124                        eprintln!("font_load failed ({path}): {e}");
3125                        return Ok(Value::Number(-1.0));
3126                    }
3127                }
3128            }
3129            // font_text(handle, x, y, px, "string") — anti-aliased *stroked* vector outline
3130            // in the current set_color / set_blend. (x,y) is the text box top-left.
3131            #[cfg(not(target_arch = "wasm32"))]
3132            "font_text" | "ข้อความฟอนต์" | "字体文本" | "フォント文字" | "글꼴텍스트" => {
3133                let id = self.arg_num(&args, 0, 0.0)? as i64;
3134                let x  = self.arg_num(&args, 1, 0.0)? as f32;
3135                let y  = self.arg_num(&args, 2, 0.0)? as f32;
3136                let px = self.arg_num(&args, 3, 16.0)? as f32;
3137                let s  = self.arg_str(&args, 4, "");
3138                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
3139                    let strokes = self.font_layout_2d(id as usize, x, y, px, &s);
3140                    let mut gfx = self.gfx.borrow_mut();
3141                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3142                    for pl in &strokes {
3143                        for seg in pl.windows(2) {
3144                            crate::gfx::raster::draw_line_aa(&mut gfx.buffer, w, h, color, add,
3145                                seg[0][0], seg[0][1], seg[1][0], seg[1][1]);
3146                        }
3147                    }
3148                }
3149                return Ok(Value::Unit);
3150            }
3151            // font_text_fill(handle, x, y, px, "string") — anti-aliased *filled* vector glyphs.
3152            #[cfg(not(target_arch = "wasm32"))]
3153            "font_text_fill" | "เติมฟอนต์" | "填充字体" | "フォント塗り" | "글꼴채움" => {
3154                let id = self.arg_num(&args, 0, 0.0)? as i64;
3155                let x  = self.arg_num(&args, 1, 0.0)? as f32;
3156                let y  = self.arg_num(&args, 2, 0.0)? as f32;
3157                let px = self.arg_num(&args, 3, 16.0)? as f32;
3158                let s  = self.arg_str(&args, 4, "");
3159                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
3160                    // fill each glyph independently so interior holes (winding) stay correct
3161                    let glyphs = self.font_layout_2d_glyphs(id as usize, x, y, px, &s);
3162                    let mut gfx = self.gfx.borrow_mut();
3163                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3164                    for contours in &glyphs {
3165                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, contours);
3166                    }
3167                }
3168                return Ok(Value::Unit);
3169            }
3170            // font_text_3d(handle, cx,cy,cz, ux,uy,uz, vx,vy,vz, size, "string")
3171            // — stroked vector text on a 3D plane: u = advance dir, v = up dir, size = world/em.
3172            //   Flows through the depth-sorted line pipeline, so it rotates with the camera (and 4D).
3173            #[cfg(not(target_arch = "wasm32"))]
3174            "font_text_3d" | "ข้อความฟอนต์3มิติ" | "字体3D" | "フォント3D" | "글꼴3D" => {
3175                let id = self.arg_num(&args, 0, 0.0)? as i64;
3176                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;
3177                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;
3178                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;
3179                let size=self.arg_num(&args,10,1.0)? as f32;
3180                let s = self.arg_str(&args,11,"");
3181                if id >= 0 && (id as usize) < self.fonts.len() && size > 0.0 {
3182                    // Build world-space polylines: world = C + (pen+ex)*size*U + ey*size*V
3183                    let font = &mut self.fonts[id as usize];
3184                    let asc = font.ascent();
3185                    let mut pen = 0.0f32;
3186                    let mut lines: Vec<[f32; 6]> = Vec::new();
3187                    for ch in s.chars() {
3188                        let go = font.glyph_outline(ch, 0.01);
3189                        for pl in &go.polylines {
3190                            for seg in pl.windows(2) {
3191                                let map = |p: [f32; 2]| {
3192                                    let a = pen + p[0];
3193                                    let b = p[1] - asc; // shift so the top of the cap sits near C
3194                                    [cx + a*size*ux + b*size*vx,
3195                                     cy + a*size*uy + b*size*vy,
3196                                     cz + a*size*uz + b*size*vz]
3197                                };
3198                                let p0 = map(seg[0]); let p1 = map(seg[1]);
3199                                lines.push([p0[0],p0[1],p0[2], p1[0],p1[1],p1[2]]);
3200                            }
3201                        }
3202                        pen += go.advance;
3203                    }
3204                    let mut gfx = self.gfx.borrow_mut();
3205                    let color = gfx.color;
3206                    let near = -gfx.camera.zdist + 0.05;
3207                    for l in &lines {
3208                        let (mut ax, mut ay, mut az) = (l[0], l[1], l[2]);
3209                        let (mut bx, mut by, mut bz) = (l[3], l[4], l[5]);
3210                        let da = gfx.camera.depth(ax, ay, az);
3211                        let db = gfx.camera.depth(bx, by, bz);
3212                        if da <= near && db <= near { continue; }
3213                        if da <= near {
3214                            let t = (near - da) / (db - da);
3215                            ax += t*(bx-ax); ay += t*(by-ay); az += t*(bz-az);
3216                        } else if db <= near {
3217                            let t = (near - da) / (db - da);
3218                            bx = ax + t*(bx-ax); by = ay + t*(by-ay); bz = az + t*(bz-az);
3219                        }
3220                        let (sax, say, da2) = gfx.camera.project(ax, ay, az);
3221                        let (sbx, sby, db2) = gfx.camera.project(bx, by, bz);
3222                        let depth = (da2 + db2) / 2.0;
3223                        gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
3224                    }
3225                }
3226                return Ok(Value::Unit);
3227            }
3228            // font_width(handle, px, "string") — pixel width of a string in a loaded font.
3229            #[cfg(not(target_arch = "wasm32"))]
3230            "font_width" | "ความกว้างฟอนต์" | "字体宽度" | "フォント幅" | "글꼴너비" => {
3231                let id = self.arg_num(&args, 0, 0.0)? as i64;
3232                let px = self.arg_num(&args, 1, 16.0)? as f32;
3233                let s  = self.arg_str(&args, 2, "");
3234                if id >= 0 && (id as usize) < self.fonts.len() {
3235                    return Ok(Value::Number(self.fonts[id as usize].measure(&s, px) as f64));
3236                }
3237                return Ok(Value::Number(0.0));
3238            }
3239            // ui_frame(x,y,w,h, bracketLen) — sci-fi corner brackets
3240            "ui_frame" | "边框" | "フレーム枠" | "프레임틀" | "กรอบ" => {
3241                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3242                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3243                let l=self.arg_num(&args,4,14.0)? as f32;
3244                let segs = ling_ui::holo::corner_brackets(x,y,w0,h0,l);
3245                let mut gfx = self.gfx.borrow_mut();
3246                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3247                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3248                return Ok(Value::Unit);
3249            }
3250            // ui_bevel(x,y,w,h, bevel) — beveled holographic panel outline
3251            "ui_bevel" | "斜角框" | "ベベル枠" | "베벨틀" | "กรอบเฉียง" => {
3252                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3253                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3254                let bv=self.arg_num(&args,4,10.0)? as f32;
3255                let segs = ling_ui::holo::beveled_rect(x,y,w0,h0,bv);
3256                let mut gfx = self.gfx.borrow_mut();
3257                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3258                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3259                return Ok(Value::Unit);
3260            }
3261
3262            // ══════════════════════════════════════════════════════════════════
3263            // VECTOR UI TOOLKIT  (crates/ling-ui/src/widgets.rs)
3264            // All widgets are vector + theme-coloured with an optional trailing
3265            // r,g,b override; interactive ones read the mouse and return state.
3266            // ══════════════════════════════════════════════════════════════════
3267            #[cfg(not(target_arch = "wasm32"))]
3268            "ui_theme" | "界面主题" | "UIテーマ" | "인터페이스테마" | "ธีมส่วนติดต่อ" => {
3269                let cur = self.ui_theme;
3270                let primary = self.color_at(&args, 0,  cur.primary);
3271                let accent  = self.color_at(&args, 3,  cur.accent);
3272                let track   = self.color_at(&args, 6,  cur.track);
3273                let warn    = self.color_at(&args, 9,  cur.warn);
3274                let text    = self.color_at(&args, 12, cur.text);
3275                let bg      = self.color_at(&args, 15, cur.bg);
3276                self.ui_theme = UiTheme { primary, accent, track, warn, text, bg };
3277                return Ok(Value::Unit);
3278            }
3279
3280            // ── HUD ──────────────────────────────────────────────────────────
3281            #[cfg(not(target_arch = "wasm32"))]
3282            "ui_radar" | "雷达" | "レーダー" | "레이더" | "เรดาร์" => {
3283                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3284                let r=self.arg_num(&args,2,60.)? as f32; let sweep=self.arg_num(&args,3,0.)? as f32;
3285                let th=self.ui_theme;
3286                let prim=self.color_at(&args,4,th.primary);
3287                self.draw_ui(&ling_ui::widgets::radar(cx,cy,r,sweep, prim, th.accent, th.track));
3288                return Ok(Value::Unit);
3289            }
3290            #[cfg(not(target_arch = "wasm32"))]
3291            "ui_compass" | "罗盘" | "コンパス" | "나침반" | "เข็มทิศ" => {
3292                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3293                let w0=self.arg_num(&args,2,300.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
3294                let head=self.arg_num(&args,4,0.)? as f32;
3295                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3296                self.draw_ui(&ling_ui::widgets::compass(x,y,w0,h0,head, prim, th.track));
3297                return Ok(Value::Unit);
3298            }
3299            #[cfg(not(target_arch = "wasm32"))]
3300            "ui_reticle" | "准星" | "照準" | "조준선" | "เป้าเล็ง" => {
3301                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3302                let r=self.arg_num(&args,2,30.)? as f32; let spread=self.arg_num(&args,3,0.)? as f32;
3303                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3304                self.draw_ui(&ling_ui::widgets::reticle(cx,cy,r,spread, prim));
3305                return Ok(Value::Unit);
3306            }
3307            #[cfg(not(target_arch = "wasm32"))]
3308            "ui_target" | "锁定框" | "ターゲット" | "표적" | "กรอบเป้า" => {
3309                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3310                let w0=self.arg_num(&args,2,80.)? as f32; let h0=self.arg_num(&args,3,80.)? as f32;
3311                let lock=self.arg_num(&args,4,0.)? as f32;
3312                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3313                self.draw_ui(&ling_ui::widgets::target(x,y,w0,h0,lock, prim, th.accent));
3314                return Ok(Value::Unit);
3315            }
3316            #[cfg(not(target_arch = "wasm32"))]
3317            "ui_panel" | "面板" | "パネル" | "패널" | "แผง" => {
3318                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3319                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3320                let bv=self.arg_num(&args,4,12.)? as f32;
3321                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3322                self.draw_ui(&ling_ui::widgets::panel(x,y,w0,h0,bv, prim, th.bg));
3323                return Ok(Value::Unit);
3324            }
3325            #[cfg(not(target_arch = "wasm32"))]
3326            "ui_scanlines" | "扫描线" | "走査線" | "스캔라인" | "เส้นสแกน" => {
3327                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3328                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3329                let dens=self.arg_num(&args,4,24.)? as usize;
3330                let th=self.ui_theme; let line=self.color_at(&args,5,th.track);
3331                self.draw_ui(&ling_ui::widgets::scanlines(x,y,w0,h0,dens, line));
3332                return Ok(Value::Unit);
3333            }
3334
3335            // ── Meters ───────────────────────────────────────────────────────
3336            #[cfg(not(target_arch = "wasm32"))]
3337            "ui_bar" | "进度条" | "バー" | "막대" | "แถบ" => {
3338                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3339                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3340                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3341                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
3342                self.draw_ui(&ling_ui::widgets::bar(x,y,w0,h0, val/max.max(1e-6), fill, th.track));
3343                return Ok(Value::Unit);
3344            }
3345            #[cfg(not(target_arch = "wasm32"))]
3346            "ui_segbar" | "分段条" | "分割バー" | "분할막대" | "แถบแบ่ง" => {
3347                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3348                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3349                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3350                let segs=self.arg_num(&args,6,10.)? as usize;
3351                let th=self.ui_theme; let fill=self.color_at(&args,7,th.primary);
3352                self.draw_ui(&ling_ui::widgets::segbar(x,y,w0,h0, val/max.max(1e-6), segs, fill, th.track));
3353                return Ok(Value::Unit);
3354            }
3355            #[cfg(not(target_arch = "wasm32"))]
3356            "ui_gauge" | "仪表" | "ゲージ" | "게이지" | "มาตรวัด" => {
3357                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3358                let r=self.arg_num(&args,2,50.)? as f32;
3359                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
3360                let th=self.ui_theme; let needle=self.color_at(&args,5,th.warn);
3361                self.draw_ui(&ling_ui::widgets::gauge(cx,cy,r, val/max.max(1e-6), needle, th.accent, th.track));
3362                return Ok(Value::Unit);
3363            }
3364            #[cfg(not(target_arch = "wasm32"))]
3365            "ui_ring" | "环表" | "リングメーター" | "링미터" | "วงแหวนวัด" => {
3366                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3367                let r=self.arg_num(&args,2,40.)? as f32;
3368                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
3369                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
3370                self.draw_ui(&ling_ui::widgets::ring(cx,cy,r, val/max.max(1e-6), fill, th.track));
3371                return Ok(Value::Unit);
3372            }
3373            #[cfg(not(target_arch = "wasm32"))]
3374            "ui_vu" | "音量条" | "VUメーター" | "음량막대" | "มาตรเสียง" => {
3375                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3376                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,60.)? as f32;
3377                let levels=self.arg_list_f32(&args,4);
3378                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
3379                self.draw_ui(&ling_ui::widgets::vu(x,y,w0,h0, &levels, fill, th.warn));
3380                return Ok(Value::Unit);
3381            }
3382            #[cfg(not(target_arch = "wasm32"))]
3383            "ui_spark" | "迷你图" | "スパークライン" | "스파크라인" | "กราฟจิ๋ว" => {
3384                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3385                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
3386                let vals=self.arg_list_f32(&args,4);
3387                let th=self.ui_theme; let line=self.color_at(&args,5,th.accent);
3388                self.draw_ui(&ling_ui::widgets::spark(x,y,w0,h0, &vals, line));
3389                return Ok(Value::Unit);
3390            }
3391            #[cfg(not(target_arch = "wasm32"))]
3392            "ui_battery" | "电池" | "バッテリー" | "배터리" | "แบตเตอรี่" => {
3393                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3394                let w0=self.arg_num(&args,2,50.)? as f32; let h0=self.arg_num(&args,3,22.)? as f32;
3395                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3396                let th=self.ui_theme; let fill=self.color_at(&args,6,th.accent);
3397                self.draw_ui(&ling_ui::widgets::battery(x,y,w0,h0, val/max.max(1e-6), fill, th.track, th.warn));
3398                return Ok(Value::Unit);
3399            }
3400
3401            // ── Interface controls (interactive → return state) ──────────────
3402            #[cfg(not(target_arch = "wasm32"))]
3403            "ui_button" | "按钮" | "ボタン" | "버튼" | "ปุ่ม" => {
3404                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3405                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
3406                let (mx,my,down)=self.mouse_now();
3407                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
3408                let clicked = hover && down && !self.mouse_was_down;
3409                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3410                self.draw_ui(&ling_ui::widgets::button(x,y,w0,h0, hover, down&&hover, prim, th.bg));
3411                return Ok(Value::Number(if clicked {1.0} else {0.0}));
3412            }
3413            #[cfg(not(target_arch = "wasm32"))]
3414            "ui_toggle" | "开关" | "トグル" | "토글" | "สวิตช์" => {
3415                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3416                let w0=self.arg_num(&args,2,52.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
3417                let mut state=self.arg_num(&args,4,0.)? > 0.5;
3418                let (mx,my,down)=self.mouse_now();
3419                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
3420                if hover && down && !self.mouse_was_down { state = !state; }
3421                let th=self.ui_theme; let on=self.color_at(&args,5,th.accent);
3422                self.draw_ui(&ling_ui::widgets::toggle(x,y,w0,h0, state, on, th.track));
3423                return Ok(Value::Number(if state {1.0} else {0.0}));
3424            }
3425            #[cfg(not(target_arch = "wasm32"))]
3426            "ui_slider" | "滑块" | "スライダー" | "슬라이더" | "แถบเลื่อน" => {
3427                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3428                let w0=self.arg_num(&args,2,160.)? as f32;
3429                let mut val=self.arg_num(&args,3,0.)? as f32;
3430                let mn=self.arg_num(&args,4,0.)? as f32; let mx_=self.arg_num(&args,5,1.)? as f32;
3431                let (mx,my,down)=self.mouse_now();
3432                let hover=ling_ui::holo::hit_rect(mx,my,x-8.0,y-10.0,w0+16.0,20.0);
3433                if hover && down {
3434                    let frac=((mx-x)/w0).max(0.0).min(1.0);
3435                    val = mn + (mx_-mn)*frac;
3436                }
3437                let frac=((val-mn)/(mx_-mn).abs().max(1e-6)).max(0.0).min(1.0);
3438                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
3439                self.draw_ui(&ling_ui::widgets::slider(x,y,w0, frac, hover, fill, th.track));
3440                return Ok(Value::Number(val as f64));
3441            }
3442            #[cfg(not(target_arch = "wasm32"))]
3443            "ui_checkbox" | "复选框" | "チェックボックス" | "체크박스" | "ช่องเลือก" => {
3444                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3445                let s=self.arg_num(&args,2,20.)? as f32;
3446                let mut checked=self.arg_num(&args,3,0.)? > 0.5;
3447                let (mx,my,down)=self.mouse_now();
3448                let hover=ling_ui::holo::hit_rect(mx,my,x,y,s,s);
3449                if hover && down && !self.mouse_was_down { checked = !checked; }
3450                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3451                self.draw_ui(&ling_ui::widgets::checkbox(x,y,s, checked, hover, prim, th.track));
3452                return Ok(Value::Number(if checked {1.0} else {0.0}));
3453            }
3454            #[cfg(not(target_arch = "wasm32"))]
3455            "ui_tabs" | "标签页" | "タブ" | "탭" | "แท็บ" => {
3456                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3457                let w0=self.arg_num(&args,2,240.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
3458                let count=self.arg_num(&args,4,3.)? as usize;
3459                let mut active=self.arg_num(&args,5,0.)? as i32;
3460                let (mx,my,down)=self.mouse_now();
3461                let mut hover=-1;
3462                if my>=y && my<=y+h0 && mx>=x && mx<=x+w0 && count>0 {
3463                    hover = (((mx-x)/(w0/count as f32)) as i32).max(0).min(count as i32-1);
3464                    if down && !self.mouse_was_down { active = hover; }
3465                }
3466                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
3467                self.draw_ui(&ling_ui::widgets::tabs(x,y,w0,h0, count, active as usize, hover, prim, th.track));
3468                return Ok(Value::Number(active as f64));
3469            }
3470            #[cfg(not(target_arch = "wasm32"))]
3471            "ui_progress" | "进度" | "プログレス" | "진행바" | "ความคืบหน้า" => {
3472                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3473                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,12.)? as f32;
3474                let frac=self.arg_num(&args,4,0.)? as f32;
3475                let th=self.ui_theme; let fill=self.color_at(&args,5,th.accent);
3476                self.draw_ui(&ling_ui::widgets::progress(x,y,w0,h0, frac, fill, th.track));
3477                return Ok(Value::Unit);
3478            }
3479            #[cfg(not(target_arch = "wasm32"))]
3480            "ui_tooltip" | "提示框" | "ツールチップ" | "툴팁" | "คำแนะนำ" => {
3481                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3482                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
3483                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3484                self.draw_ui(&ling_ui::widgets::tooltip(x,y,w0,h0, prim, th.bg));
3485                return Ok(Value::Unit);
3486            }
3487            #[cfg(not(target_arch = "wasm32"))]
3488            "ui_stepper" | "步进器" | "ステッパー" | "스테퍼" | "ตัวปรับค่า" => {
3489                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3490                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
3491                let mut val=self.arg_num(&args,4,0.)? as f32; let step=self.arg_num(&args,5,1.)? as f32;
3492                let (mx,my,down)=self.mouse_now();
3493                let hm=ling_ui::holo::hit_rect(mx,my,x,y,h0,h0);
3494                let hp=ling_ui::holo::hit_rect(mx,my,x+w0-h0,y,h0,h0);
3495                if down && !self.mouse_was_down { if hm { val -= step; } if hp { val += step; } }
3496                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
3497                self.draw_ui(&ling_ui::widgets::stepper(x,y,w0,h0, hm, hp, prim, th.track));
3498                return Ok(Value::Number(val as f64));
3499            }
3500
3501            // ── Game UI ──────────────────────────────────────────────────────
3502            #[cfg(not(target_arch = "wasm32"))]
3503            "ui_healthbar" | "血条" | "体力バー" | "체력바" | "แถบพลังชีวิต" => {
3504                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3505                let w0=self.arg_num(&args,2,180.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3506                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3507                let pulse=self.arg_num(&args,6,0.)? as f32;
3508                let th=self.ui_theme; let full=self.color_at(&args,7,th.accent);
3509                self.draw_ui(&ling_ui::widgets::healthbar(x,y,w0,h0, val/max.max(1e-6), pulse, full, th.warn, th.track));
3510                return Ok(Value::Unit);
3511            }
3512            #[cfg(not(target_arch = "wasm32"))]
3513            "ui_cooldown" | "冷却" | "クールダウン" | "쿨다운" | "คูลดาวน์" => {
3514                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3515                let r=self.arg_num(&args,2,28.)? as f32; let frac=self.arg_num(&args,3,0.)? as f32;
3516                let th=self.ui_theme; let fill=self.color_at(&args,4,th.primary);
3517                self.draw_ui(&ling_ui::widgets::cooldown(cx,cy,r, frac, fill, th.track));
3518                return Ok(Value::Unit);
3519            }
3520            #[cfg(not(target_arch = "wasm32"))]
3521            "ui_counter" | "计数器" | "カウンター" | "카운터" | "ตัวนับ" => {
3522                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3523                let dw=self.arg_num(&args,2,14.)? as f32; let dh=self.arg_num(&args,3,24.)? as f32;
3524                let val=self.arg_num(&args,4,0.)? as i64; let digits=self.arg_num(&args,5,4.)? as usize;
3525                let th=self.ui_theme; let on=self.color_at(&args,6,th.primary);
3526                let off=ling_ui::widgets::shade(th.track,0.5);
3527                self.draw_ui(&ling_ui::widgets::counter(x,y,dw,dh, val, digits, on, off));
3528                return Ok(Value::Unit);
3529            }
3530            #[cfg(not(target_arch = "wasm32"))]
3531            "ui_minimap" | "小地图" | "ミニマップ" | "미니맵" | "แผนที่ย่อ" => {
3532                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3533                let w0=self.arg_num(&args,2,140.)? as f32; let h0=self.arg_num(&args,3,140.)? as f32;
3534                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3535                self.draw_ui(&ling_ui::widgets::minimap(x,y,w0,h0, prim, th.bg));
3536                return Ok(Value::Unit);
3537            }
3538            #[cfg(not(target_arch = "wasm32"))]
3539            "ui_dpad" | "方向键" | "方向パッド" | "방향패드" | "ปุ่มทิศทาง" => {
3540                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3541                let r=self.arg_num(&args,2,50.)? as f32;
3542                let (mx,my,down)=self.mouse_now();
3543                let mut dir=0;
3544                if down {
3545                    let (dx,dy)=(mx-cx, my-cy);
3546                    if dx*dx+dy*dy <= r*r {
3547                        if dx.abs() > dy.abs() { dir = if dx>0.0 {2} else {4}; }
3548                        else { dir = if dy>0.0 {3} else {1}; }
3549                    }
3550                }
3551                let th=self.ui_theme; let prim=self.color_at(&args,3,th.primary);
3552                self.draw_ui(&ling_ui::widgets::dpad(cx,cy,r, dir, prim, th.track));
3553                return Ok(Value::Number(dir as f64));
3554            }
3555            #[cfg(not(target_arch = "wasm32"))]
3556            "ui_slotgrid" | "物品格" | "スロットグリッド" | "슬롯격자" | "ช่องไอเทม" => {
3557                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3558                let cols=self.arg_num(&args,2,4.)? as usize; let rows=self.arg_num(&args,3,1.)? as usize;
3559                let cell=self.arg_num(&args,4,36.)? as f32; let sel=self.arg_num(&args,5,-1.)? as i32;
3560                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
3561                self.draw_ui(&ling_ui::widgets::slotgrid(x,y,cols,rows,cell, sel, prim, th.track));
3562                return Ok(Value::Unit);
3563            }
3564            #[cfg(not(target_arch = "wasm32"))]
3565            "ui_vignette" | "暗角" | "ビネット" | "비네트" | "ขอบมืด" => {
3566                let intensity=self.arg_num(&args,0,0.5)? as f32;
3567                let (w,h)={ let g=self.gfx.borrow(); (g.width as f32, g.height as f32) };
3568                let th=self.ui_theme; let col=self.color_at(&args,1,th.warn);
3569                self.draw_ui(&ling_ui::widgets::vignette(w,h, intensity, col));
3570                return Ok(Value::Unit);
3571            }
3572
3573            // ── Faux-3D in 2D space ──────────────────────────────────────────
3574            #[cfg(not(target_arch = "wasm32"))]
3575            "ui_gauge3d" | "立体仪表" | "立体ゲージ" | "입체게이지" | "มาตรวัด3มิติ" => {
3576                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3577                let r=self.arg_num(&args,2,50.)? as f32;
3578                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
3579                let spin=self.arg_num(&args,5,0.)? as f32;
3580                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
3581                self.draw_ui(&ling_ui::widgets::gauge3d(cx,cy,r, val/max.max(1e-6), spin, fill, th.track));
3582                return Ok(Value::Unit);
3583            }
3584            #[cfg(not(target_arch = "wasm32"))]
3585            "ui_panel3d" | "立体面板" | "立体パネル" | "입체패널" | "แผง3มิติ" => {
3586                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3587                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3588                let depth=self.arg_num(&args,4,14.)? as f32;
3589                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3590                self.draw_ui(&ling_ui::widgets::panel3d(x,y,w0,h0,depth, prim, th.bg));
3591                return Ok(Value::Unit);
3592            }
3593            #[cfg(not(target_arch = "wasm32"))]
3594            "ui_radar3d" | "立体雷达" | "立体レーダー" | "입체레이더" | "เรดาร์3มิติ" => {
3595                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3596                let r=self.arg_num(&args,2,60.)? as f32; let tilt=self.arg_num(&args,3,0.9)? as f32;
3597                let sweep=self.arg_num(&args,4,0.)? as f32;
3598                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3599                self.draw_ui(&ling_ui::widgets::radar3d(cx,cy,r,tilt,sweep, prim, th.track));
3600                return Ok(Value::Unit);
3601            }
3602
3603            // ── Interface sounds ─────────────────────────────────────────────
3604            #[cfg(not(target_arch = "wasm32"))]
3605            "audio_blip" | "提示音" | "ビープ音" | "효과음" | "เสียงบี๊บ" => {
3606                let freq=self.arg_num(&args,0,660.)? as f32;
3607                let dur=self.arg_num(&args,1,0.08)? as f32;
3608                let wave=Wave::from_name(&self.arg_str(&args,2,"sine"));
3609                let amp=self.arg_num(&args,3,0.25)? as f32;
3610                if let Some(audio)=&self.audio { audio.blip(freq, amp, dur, wave); }
3611                return Ok(Value::Unit);
3612            }
3613            #[cfg(not(target_arch = "wasm32"))]
3614            "ui_sound" | "界面音" | "UI音" | "인터페이스음" | "เสียงปุ่ม" => {
3615                let name=self.arg_str(&args,0,"click");
3616                if let Some(audio)=&self.audio {
3617                    match name.as_str() {
3618                        "hover"   => audio.blip(880.0, 0.10, 0.04, Wave::Sine),
3619                        "confirm" => { audio.blip(660.0, 0.22, 0.07, Wave::Square); audio.blip(990.0, 0.18, 0.10, Wave::Square); }
3620                        "error"   => { audio.blip(180.0, 0.30, 0.16, Wave::Saw); audio.blip(140.0, 0.30, 0.18, Wave::Saw); }
3621                        "toggle"  => audio.blip(520.0, 0.22, 0.05, Wave::Triangle),
3622                        "tick"    => audio.blip(1500.0, 0.12, 0.02, Wave::Square),
3623                        _         => audio.blip(720.0, 0.26, 0.05, Wave::Square), // "click"
3624                    }
3625                }
3626                return Ok(Value::Unit);
3627            }
3628
3629            // ══════════════════════════════════════════════════════════════════
3630            // MUSIC TOOLKIT  (crates/ling-music) — decode · analysis · GM synth ·
3631            // rhythm · karaoke. Analysis/decoding need no audio device; playback
3632            // and synthesis lazily start a dedicated music engine.
3633            // ══════════════════════════════════════════════════════════════════
3634
3635            // music_load(path) -> track handle (decodes WAV/FLAC/OGG/MP3/AAC)
3636            #[cfg(not(target_arch = "wasm32"))]
3637            "music_load" | "载入音乐" | "音楽読込" | "음악로드" | "โหลดเพลง" => {
3638                let path = self.arg_str(&args, 0, "");
3639                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3640                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3641                    else { path.clone() };
3642                match ling_music::load(&resolved) {
3643                    Ok(t) => { let id = self.tracks.len(); self.tracks.push(t); return Ok(Value::Number(id as f64)); }
3644                    Err(e) => { eprintln!("music_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3645                }
3646            }
3647            #[cfg(not(target_arch = "wasm32"))]
3648            "music_duration" | "音乐时长" | "音楽長さ" | "음악길이" | "ความยาวเพลง" => {
3649                let id = self.arg_num(&args,0,0.0)? as i64;
3650                let d = self.tracks.get(id as usize).map(|t| t.duration).unwrap_or(0.0);
3651                return Ok(Value::Number(d as f64));
3652            }
3653            #[cfg(not(target_arch = "wasm32"))]
3654            "music_bpm" | "节拍速度" | "テンポ" | "템포" | "จังหวะต่อนาที" => {
3655                let id = self.arg_num(&args,0,0.0)? as i64;
3656                let b = self.tracks.get(id as usize).map(|t| ling_music::analysis::bpm(&t.mono, t.rate)).unwrap_or(0.0);
3657                return Ok(Value::Number(b as f64));
3658            }
3659            #[cfg(not(target_arch = "wasm32"))]
3660            "music_key" | "调性" | "調性" | "조성" | "คีย์เพลง" => {
3661                let id = self.arg_num(&args,0,0.0)? as i64;
3662                let k = self.tracks.get(id as usize).map(|t| ling_music::analysis::key_name(&t.mono, t.rate)).unwrap_or_default();
3663                return Ok(Value::Str(k));
3664            }
3665            #[cfg(not(target_arch = "wasm32"))]
3666            "music_onsets" | "音符起点" | "オンセット" | "온셋" | "จุดเริ่มเสียง" => {
3667                let id = self.arg_num(&args,0,0.0)? as i64;
3668                let v = self.tracks.get(id as usize).map(|t| ling_music::analysis::onsets(&t.mono, t.rate)).unwrap_or_default();
3669                return Ok(Value::List(v.into_iter().map(|x| Value::Number(x as f64)).collect()));
3670            }
3671            #[cfg(not(target_arch = "wasm32"))]
3672            "music_beat_grid" | "节拍网格" | "ビートグリッド" | "비트그리드" | "กริดจังหวะ" => {
3673                let id = self.arg_num(&args,0,0.0)? as i64;
3674                let beats = self.tracks.get(id as usize).map(|t| {
3675                    let b = ling_music::analysis::bpm(&t.mono, t.rate);
3676                    ling_music::analysis::beat_grid(&t.mono, t.rate, b)
3677                }).unwrap_or_default();
3678                return Ok(Value::List(beats.into_iter().map(|x| Value::Number(x as f64)).collect()));
3679            }
3680
3681            // ── playback ──
3682            #[cfg(not(target_arch = "wasm32"))]
3683            "music_play" | "播放音乐" | "音楽再生" | "음악재생" | "เล่นเพลง" => {
3684                let id = self.arg_num(&args,0,0.0)? as i64;
3685                if self.ensure_music() {
3686                    let track = self.tracks.get(id as usize).map(|t| (t.stereo.clone(), t.rate));
3687                    if let (Some((st, rate)), Some(m)) = (track, &self.music) { m.set_track(st, rate); m.play(); }
3688                    else if let Some(m) = &self.music { m.play(); }
3689                }
3690                return Ok(Value::Unit);
3691            }
3692            #[cfg(not(target_arch = "wasm32"))]
3693            "music_pause" | "暂停音乐" | "音楽一時停止" | "음악일시정지" | "หยุดเพลงชั่วคราว" => {
3694                if let Some(m) = &self.music { m.pause(); } return Ok(Value::Unit);
3695            }
3696            #[cfg(not(target_arch = "wasm32"))]
3697            "music_stop" | "停止音乐" | "音楽停止" | "음악정지" | "หยุดเพลง" => {
3698                if let Some(m) = &self.music { m.stop(); } return Ok(Value::Unit);
3699            }
3700            #[cfg(not(target_arch = "wasm32"))]
3701            "music_seek" | "定位音乐" | "音楽シーク" | "음악탐색" | "ค้นหาเพลง" => {
3702                let sec = self.arg_num(&args,0,0.0)? as f32;
3703                if let Some(m) = &self.music { m.seek(sec); } return Ok(Value::Unit);
3704            }
3705            #[cfg(not(target_arch = "wasm32"))]
3706            "music_pos" | "音乐位置" | "音楽位置" | "음악위치" | "ตำแหน่งเพลง" => {
3707                let p = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
3708                return Ok(Value::Number(p as f64));
3709            }
3710            #[cfg(not(target_arch = "wasm32"))]
3711            "music_volume" | "音乐音量" | "音楽音量" | "음악음량" | "ระดับเพลง" => {
3712                let v = self.arg_num(&args,0,0.8)? as f32;
3713                if self.ensure_music() { if let Some(m) = &self.music { m.set_volume(v); } }
3714                return Ok(Value::Unit);
3715            }
3716
3717            // ── synthesis (GM-capable, patches from .ling files) ──
3718            #[cfg(not(target_arch = "wasm32"))]
3719            "music_patch" | "乐器音色" | "音色読込" | "악기패치" | "แพตช์เครื่องดนตรี" => {
3720                let path = self.arg_str(&args, 0, "");
3721                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3722                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3723                    else { path.clone() };
3724                if !self.ensure_music() { return Ok(Value::Number(-1.0)); }
3725                match ling_music::patch::from_path(&resolved) {
3726                    Ok(p) => { let id = self.music.as_ref().unwrap().add_patch(p); return Ok(Value::Number(id as f64)); }
3727                    Err(e) => { eprintln!("music_patch failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3728                }
3729            }
3730            #[cfg(not(target_arch = "wasm32"))]
3731            "music_note" | "弹音符" | "音符演奏" | "음표연주" | "เล่นโน้ต" => {
3732                let inst = self.arg_num(&args,0,0.0)? as usize;
3733                let midi = self.pitch_arg(&args, 1, 60);
3734                let dur  = self.arg_num(&args,2,0.5)? as f32;
3735                let vel  = self.arg_num(&args,3,0.9)? as f32;
3736                if self.ensure_music() { if let Some(m) = &self.music { m.note(inst, midi, vel, dur); } }
3737                return Ok(Value::Unit);
3738            }
3739            #[cfg(not(target_arch = "wasm32"))]
3740            "music_note_on" | "音符开始" | "音符オン" | "음표켜기" | "โน้ตเริ่ม" => {
3741                let inst = self.arg_num(&args,0,0.0)? as usize;
3742                let midi = self.pitch_arg(&args, 1, 60);
3743                let vel  = self.arg_num(&args,2,0.9)? as f32;
3744                if self.ensure_music() { if let Some(m) = &self.music { m.note_on(inst, midi, vel); } }
3745                return Ok(Value::Unit);
3746            }
3747            #[cfg(not(target_arch = "wasm32"))]
3748            "music_note_off" | "音符结束" | "音符オフ" | "음표끄기" | "โน้ตจบ" => {
3749                let inst = self.arg_num(&args,0,0.0)? as usize;
3750                let midi = self.pitch_arg(&args, 1, 60);
3751                if let Some(m) = &self.music { m.note_off(inst, midi); }
3752                return Ok(Value::Unit);
3753            }
3754
3755            // ── rhythm-game judging ──
3756            #[cfg(not(target_arch = "wasm32"))]
3757            "music_judge" | "判定" | "判定する" | "판정" | "ตัดสินจังหวะ" => {
3758                let delta_ms = self.arg_num(&args,0,9999.0)? as f32;
3759                return Ok(Value::Number(ling_music::Grade::judge(delta_ms).index() as f64));
3760            }
3761            #[cfg(not(target_arch = "wasm32"))]
3762            "music_grade_name" | "判定名" | "判定名称" | "판정이름" | "ชื่อการตัดสิน" => {
3763                let idx = self.arg_num(&args,0,4.0)? as i32;
3764                return Ok(Value::Str(ling_music::Grade::from_index(idx).name().to_string()));
3765            }
3766
3767            // ── karaoke ──
3768            #[cfg(not(target_arch = "wasm32"))]
3769            "music_lrc" | "载入歌词" | "歌詞読込" | "가사로드" | "โหลดเนื้อเพลง" => {
3770                let path = self.arg_str(&args, 0, "");
3771                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3772                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3773                    else { path.clone() };
3774                match std::fs::read_to_string(&resolved) {
3775                    Ok(text) => { let id = self.lyrics.len(); self.lyrics.push(ling_music::Lyrics::parse(&text)); return Ok(Value::Number(id as f64)); }
3776                    Err(e) => { eprintln!("music_lrc failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3777                }
3778            }
3779            #[cfg(not(target_arch = "wasm32"))]
3780            "music_lyric" | "当前歌词" | "現在歌詞" | "현재가사" | "เนื้อเพลงปัจจุบัน" => {
3781                let id = self.arg_num(&args,0,0.0)? as i64;
3782                let t  = self.arg_num(&args,1,0.0)? as f32;
3783                let line = self.lyrics.get(id as usize).map(|l| l.line_at(t).to_string()).unwrap_or_default();
3784                return Ok(Value::Str(line));
3785            }
3786            #[cfg(not(target_arch = "wasm32"))]
3787            "music_mic_pitch" | "麦克风音高" | "マイク音程" | "마이크음정" | "ระดับเสียงไมค์" => {
3788                let hz = if let Some(mic) = self.mic.as_ref() {
3789                    let s = mic.latest_samples();
3790                    let rate = mic.sample_rate();
3791                    ling_music::pitch::detect(&s, rate).unwrap_or(0.0)
3792                } else { 0.0 };
3793                return Ok(Value::Number(hz as f64));
3794            }
3795            #[cfg(not(target_arch = "wasm32"))]
3796            "music_note_name" | "音名" | "音名称" | "음이름" | "ชื่อโน้ต" => {
3797                let hz = self.arg_num(&args,0,0.0)? as f32;
3798                return Ok(Value::Str(ling_music::note::hz_to_name(hz)));
3799            }
3800            #[cfg(not(target_arch = "wasm32"))]
3801            "music_hz" | "音符频率" | "音符周波数" | "음표주파수" | "ความถี่โน้ต" => {
3802                let midi = self.pitch_arg(&args, 0, 69);
3803                return Ok(Value::Number(ling_music::note::midi_to_hz(midi as f32) as f64));
3804            }
3805            #[cfg(not(target_arch = "wasm32"))]
3806            "music_pitch_score" | "音准评分" | "音程スコア" | "음정점수" | "คะแนนเสียง" => {
3807                let hz = self.arg_num(&args,0,0.0)? as f32;
3808                let target = self.arg_num(&args,1,0.0)? as f32;
3809                return Ok(Value::Number(ling_music::karaoke::pitch_score(hz, target) as f64));
3810            }
3811
3812            // ── MIDI (inaudible note source: drive coins, cues, etc.) ──
3813            #[cfg(not(target_arch = "wasm32"))]
3814            "music_midi_load" | "载入MIDI" | "MIDI読込" | "미디로드" | "โหลดมิดี" => {
3815                let path = self.arg_str(&args, 0, "");
3816                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3817                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3818                    else { path.clone() };
3819                match ling_music::midi::load(&resolved) {
3820                    Ok(m) => { let id = self.midis.len(); self.midis.push(m); return Ok(Value::Number(id as f64)); }
3821                    Err(e) => { eprintln!("music_midi_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3822                }
3823            }
3824            #[cfg(not(target_arch = "wasm32"))]
3825            "music_midi_count" | "MIDI数量" | "MIDI数" | "미디수" | "จำนวนมิดี" => {
3826                let id = self.arg_num(&args,0,0.0)? as i64;
3827                let n = self.midis.get(id as usize).map(|m| m.notes.len()).unwrap_or(0);
3828                return Ok(Value::Number(n as f64));
3829            }
3830            // music_midi_notes(id) -> flat [time, midi, time, midi, …]
3831            #[cfg(not(target_arch = "wasm32"))]
3832            "music_midi_notes" | "MIDI音符" | "MIDIノート" | "미디음표" | "โน้ตมิดี" => {
3833                let id = self.arg_num(&args,0,0.0)? as i64;
3834                let mut out = Vec::new();
3835                if let Some(m) = self.midis.get(id as usize) {
3836                    for n in &m.notes { out.push(Value::Number(n.time as f64)); out.push(Value::Number(n.midi as f64)); }
3837                }
3838                return Ok(Value::List(out));
3839            }
3840            // music_midi_bars(id) -> flat [time, midi, dur, …] (for karaoke note bars)
3841            #[cfg(not(target_arch = "wasm32"))]
3842            "music_midi_bars" | "MIDI音条" | "MIDIバー" | "미디바" | "แท่งมิดี" => {
3843                let id = self.arg_num(&args,0,0.0)? as i64;
3844                let mut out = Vec::new();
3845                if let Some(m) = self.midis.get(id as usize) {
3846                    for n in &m.notes {
3847                        out.push(Value::Number(n.time as f64));
3848                        out.push(Value::Number(n.midi as f64));
3849                        out.push(Value::Number(n.dur as f64));
3850                    }
3851                }
3852                return Ok(Value::List(out));
3853            }
3854
3855            // music_fft(track_id, nbands) -> spectrum at the current playback position
3856            #[cfg(not(target_arch = "wasm32"))]
3857            "music_fft" | "音乐频谱" | "音楽スペクトル" | "음악스펙트럼" | "สเปกตรัมเพลง" => {
3858                let id = self.arg_num(&args,0,0.0)? as i64;
3859                let nbands = self.arg_num(&args,1,16.0)? as usize;
3860                let pos = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
3861                if let Some(t) = self.tracks.get(id as usize) {
3862                    let idx = (pos * t.rate as f32) as usize;
3863                    let end = (idx + 2048).min(t.mono.len());
3864                    if end > idx + 64 {
3865                        self.fft.borrow_mut().push_samples(&t.mono[idx..end]);
3866                    }
3867                }
3868                let bands = self.fft.borrow().freq_bands(nbands);
3869                return Ok(Value::List(bands.into_iter().map(|x| Value::Number(x as f64)).collect()));
3870            }
3871
3872            // ── spatial (2D/3D/4D) one-shot SFX ──
3873            #[cfg(not(target_arch = "wasm32"))]
3874            "audio_sfx" | "音效" | "空間効果音" | "공간효과음" | "เสียงเอฟเฟกต์" => {
3875                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;
3876                let w=self.arg_num(&args,3,1.0)? as f32; let freq=self.arg_num(&args,4,440.0)? as f32;
3877                let amp=self.arg_num(&args,5,0.3)? as f32; let dur=self.arg_num(&args,6,0.15)? as f32;
3878                let wave=Wave::from_name(&self.arg_str(&args,7,"sine"));
3879                if let Some(a)=&self.audio { a.sfx(x,y,z,w,freq,amp,dur,wave); }
3880                return Ok(Value::Unit);
3881            }
3882            // ── sample load / positional play / loop / stop ──
3883            #[cfg(not(target_arch = "wasm32"))]
3884            "audio_sample_load" | "载入采样" | "サンプル読込" | "샘플로드" | "โหลดตัวอย่างเสียง" => {
3885                let path = self.arg_str(&args, 0, "");
3886                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
3887                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
3888                    else { path.clone() };
3889                match ling_music::load(&resolved) {
3890                    Ok(t) => {
3891                        if let Some(a)=&self.audio { return Ok(Value::Number(a.add_sample(t.mono, t.rate) as f64)); }
3892                        return Ok(Value::Number(-1.0));
3893                    }
3894                    Err(e) => { eprintln!("audio_sample_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
3895                }
3896            }
3897            #[cfg(not(target_arch = "wasm32"))]
3898            "audio_sample_play" | "播放采样" | "サンプル再生" | "샘플재생" | "เล่นตัวอย่างเสียง" => {
3899                let id=self.arg_num(&args,0,0.0)? as usize;
3900                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;
3901                let w=self.arg_num(&args,4,1.0)? as f32; let vol=self.arg_num(&args,5,1.0)? as f32;
3902                let looping=self.arg_num(&args,6,0.0)? > 0.5;
3903                let v = self.audio.as_ref().map(|a| a.play_sample(id,x,y,z,w,vol,looping)).unwrap_or(0);
3904                return Ok(Value::Number(v as f64));
3905            }
3906            #[cfg(not(target_arch = "wasm32"))]
3907            "audio_sample_stop" | "停止采样" | "サンプル停止" | "샘플정지" | "หยุดตัวอย่างเสียง" => {
3908                let v=self.arg_num(&args,0,0.0)? as u32;
3909                if let Some(a)=&self.audio { a.stop_sample(v); }
3910                return Ok(Value::Unit);
3911            }
3912            // ── master FX: delay / reverb / low-pass (underwater) ──
3913            #[cfg(not(target_arch = "wasm32"))]
3914            "audio_fx_delay" | "回声" | "ディレイ効果" | "딜레이" | "เสียงสะท้อน" => {
3915                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;
3916                if let Some(a)=&self.audio { a.fx_delay(time,fb,mix); }
3917                return Ok(Value::Unit);
3918            }
3919            #[cfg(not(target_arch = "wasm32"))]
3920            "audio_fx_reverb" | "混响" | "リバーブ" | "리버브" | "เสียงก้อง" => {
3921                let mix=self.arg_num(&args,0,0.3)? as f32;
3922                if let Some(a)=&self.audio { a.fx_reverb(mix); }
3923                return Ok(Value::Unit);
3924            }
3925            #[cfg(not(target_arch = "wasm32"))]
3926            "audio_fx_lowpass" | "低通滤波" | "ローパス" | "저역통과" | "กรองความถี่ต่ำ" => {
3927                let cutoff=self.arg_num(&args,0,1.0)? as f32;
3928                if let Some(a)=&self.audio { a.fx_lowpass(cutoff); }
3929                return Ok(Value::Unit);
3930            }
3931
3932            // ══════════════════════════════════════════════════════════════════
3933            // PHYSICS BUILTINS  (crates/ling-physics) — soft bodies, rigid+angular,
3934            // and a fast 2-D water/oil liquid sim mappable onto 3-D surfaces.
3935            // ══════════════════════════════════════════════════════════════════
3936
3937            // ── soft bodies (deformable bouncy balls) ──
3938            #[cfg(not(target_arch = "wasm32"))]
3939            "soft_ball" | "软球" | "ソフトボール" | "소프트볼" | "ลูกบอลนุ่ม" => {
3940                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;
3941                let r=self.arg_num(&args,3,1.0)? as f32;
3942                let b = ling_physics::soft::SoftBody::sphere(ling_physics::Vec3::new(x,y,z), r, 8, 12, 1.0);
3943                let id = self.soft_bodies.len(); self.soft_bodies.push(b);
3944                return Ok(Value::Number(id as f64));
3945            }
3946            #[cfg(not(target_arch = "wasm32"))]
3947            "soft_step" | "软体步进" | "ソフト更新" | "소프트스텝" | "ก้าวนุ่ม" => {
3948                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
3949                let gy=self.arg_num(&args,2,15.0)? as f32;
3950                if let Some(b)=self.soft_bodies.get_mut(id) { b.integrate(dt, ling_physics::Vec3::new(0.0,gy,0.0), 4); }
3951                return Ok(Value::Unit);
3952            }
3953            #[cfg(not(target_arch = "wasm32"))]
3954            "soft_bounce" | "软体落地" | "ソフト着地" | "소프트바운스" | "เด้งนุ่ม" => {
3955                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;
3956                if let Some(b)=self.soft_bodies.get_mut(id) { b.floor_collision(fy, rest); }
3957                return Ok(Value::Unit);
3958            }
3959            #[cfg(not(target_arch = "wasm32"))]
3960            "soft_contain" | "软体边界" | "ソフト箱" | "소프트경계" | "กล่องนุ่ม" => {
3961                let id=self.arg_num(&args,0,0.)? as usize;
3962                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;
3963                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;
3964                let rest=self.arg_num(&args,7,0.6)? as f32;
3965                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); }
3966                return Ok(Value::Unit);
3967            }
3968            #[cfg(not(target_arch = "wasm32"))]
3969            "soft_kick" | "软体踢" | "ソフト衝撃" | "소프트킥" | "เตะนุ่ม" => {
3970                let id=self.arg_num(&args,0,0.)? as usize;
3971                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;
3972                let s=self.arg_num(&args,4,0.1)? as f32;
3973                if let Some(b)=self.soft_bodies.get_mut(id) { b.kick(ling_physics::Vec3::new(dx,dy,dz), s); }
3974                return Ok(Value::Unit);
3975            }
3976            // soft_spin(id, ax, ay, az, rate) — add angular velocity about the axis
3977            // through the centroid (rate = rad/step; ≈ surface_speed / radius to roll)
3978            #[cfg(not(target_arch = "wasm32"))]
3979            "soft_spin" | "软体自旋" | "ソフト回転" | "소프트회전" | "หมุนนุ่ม" => {
3980                let id=self.arg_num(&args,0,0.)? as usize;
3981                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;
3982                let rate=self.arg_num(&args,4,0.1)? as f32;
3983                if let Some(b)=self.soft_bodies.get_mut(id) { b.spin(ling_physics::Vec3::new(ax,ay,az), rate); }
3984                return Ok(Value::Unit);
3985            }
3986            #[cfg(not(target_arch = "wasm32"))]
3987            "soft_deform" | "形变量" | "変形量" | "변형량" | "ความบิดเบี้ยว" => {
3988                let id=self.arg_num(&args,0,0.)? as usize;
3989                let d=self.soft_bodies.get(id).map(|b| b.deformation()).unwrap_or(0.0);
3990                return Ok(Value::Number(d as f64));
3991            }
3992            #[cfg(not(target_arch = "wasm32"))]
3993            "soft_centroid" | "软体质心" | "ソフト重心" | "소프트중심" | "จุดศูนย์กลางนุ่ม" => {
3994                let id=self.arg_num(&args,0,0.)? as usize;
3995                let c=self.soft_bodies.get(id).map(|b| b.centroid()).unwrap_or(ling_physics::Vec3::ZERO);
3996                return Ok(Value::List(vec![Value::Number(c.x as f64),Value::Number(c.y as f64),Value::Number(c.z as f64)]));
3997            }
3998            // soft_nodes(id) -> flat [x,y,z, x,y,z, …] for rendering the deformed mesh
3999            #[cfg(not(target_arch = "wasm32"))]
4000            "soft_nodes" | "软体节点" | "ソフト節点" | "소프트노드" | "จุดนุ่ม" => {
4001                let id=self.arg_num(&args,0,0.)? as usize;
4002                let mut out=Vec::new();
4003                if let Some(b)=self.soft_bodies.get(id) {
4004                    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)); }
4005                }
4006                return Ok(Value::List(out));
4007            }
4008
4009            // ── rigid bodies with angular dynamics ──
4010            #[cfg(not(target_arch = "wasm32"))]
4011            "rb_add" | "刚体添加" | "剛体追加" | "강체추가" | "เพิ่มวัตถุแข็ง" => {
4012                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;
4013                let mass=self.arg_num(&args,3,1.0)? as f32;
4014                let mut b = ling_physics::rigid::RigidBody::new(ling_physics::Vec3::new(x,y,z), mass);
4015                b.restitution = 0.6;
4016                return Ok(Value::Number(self.rigid_world.add(b) as f64));
4017            }
4018            #[cfg(not(target_arch = "wasm32"))]
4019            "rb_torque" | "扭矩" | "トルク" | "토크" | "แรงบิด" => {
4020                let i=self.arg_num(&args,0,0.)? as usize;
4021                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;
4022                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_torque(ling_physics::Vec3::new(tx,ty,tz)); }
4023                return Ok(Value::Unit);
4024            }
4025            #[cfg(not(target_arch = "wasm32"))]
4026            "rb_spin" | "自旋" | "スピン" | "스핀" | "หมุน" => {
4027                let i=self.arg_num(&args,0,0.)? as usize;
4028                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;
4029                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_spin(ling_physics::Vec3::new(wx,wy,wz)); }
4030                return Ok(Value::Unit);
4031            }
4032            #[cfg(not(target_arch = "wasm32"))]
4033            "rb_impulse" | "刚体冲量" | "剛体インパルス" | "강체충격" | "แรงดลแข็ง" => {
4034                let i=self.arg_num(&args,0,0.)? as usize;
4035                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;
4036                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_impulse(ling_physics::Vec3::new(ix,iy,iz)); }
4037                return Ok(Value::Unit);
4038            }
4039            #[cfg(not(target_arch = "wasm32"))]
4040            "rb_floor" | "刚体落地" | "剛体着地" | "강체바닥" | "พื้นแข็ง" => {
4041                let i=self.arg_num(&args,0,0.)? as usize; let fy=self.arg_num(&args,1,0.)? as f32;
4042                let rest=self.arg_num(&args,2,0.6)? as f32; let fric=self.arg_num(&args,3,0.6)? as f32;
4043                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.bounce_floor(fy, rest, fric); }
4044                return Ok(Value::Unit);
4045            }
4046            #[cfg(not(target_arch = "wasm32"))]
4047            "rb_gravity" | "刚体重力" | "剛体重力" | "강체중력" | "แรงโน้มถ่วงแข็ง" => {
4048                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;
4049                self.rigid_world.gravity = ling_physics::Vec3::new(gx,gy,gz);
4050                return Ok(Value::Unit);
4051            }
4052            #[cfg(not(target_arch = "wasm32"))]
4053            "rb_step" | "刚体步进" | "剛体更新" | "강체스텝" | "ก้าวแข็ง" => {
4054                let dt=self.arg_num(&args,0,0.016)? as f32;
4055                self.rigid_world.step(dt);
4056                return Ok(Value::Unit);
4057            }
4058            #[cfg(not(target_arch = "wasm32"))]
4059            "rb_pos" | "刚体位置" | "剛体位置" | "강체위치" | "ตำแหน่งแข็ง" => {
4060                let i=self.arg_num(&args,0,0.)? as usize;
4061                let p=self.rigid_world.bodies.get(i).map(|b| b.pos).unwrap_or(ling_physics::Vec3::ZERO);
4062                return Ok(Value::List(vec![Value::Number(p.x as f64),Value::Number(p.y as f64),Value::Number(p.z as f64)]));
4063            }
4064            #[cfg(not(target_arch = "wasm32"))]
4065            "rb_rot" | "刚体旋转" | "剛体回転" | "강체회전" | "การหมุนแข็ง" => {
4066                let i=self.arg_num(&args,0,0.)? as usize;
4067                let q=self.rigid_world.bodies.get(i).map(|b| b.orientation).unwrap_or(ling_physics::Quat::IDENTITY);
4068                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)]));
4069            }
4070
4071            // ── liquid sim (water + oil, immiscible) ──
4072            #[cfg(not(target_arch = "wasm32"))]
4073            "liquid_new" | "新建液体" | "液体新規" | "액체생성" | "สร้างของเหลว" => {
4074                let w=self.arg_num(&args,0,64.)? as usize; let h=self.arg_num(&args,1,64.)? as usize;
4075                let id=self.liquids.len(); self.liquids.push(ling_physics::liquid::LiquidGrid::new(w,h));
4076                return Ok(Value::Number(id as f64));
4077            }
4078            #[cfg(not(target_arch = "wasm32"))]
4079            "liquid_splat" | "液体注入" | "液体追加" | "액체분사" | "หยดของเหลว" => {
4080                let id=self.arg_num(&args,0,0.)? as usize;
4081                let x=self.arg_num(&args,1,0.)? as f32; let y=self.arg_num(&args,2,0.)? as f32;
4082                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;
4083                if let Some(g)=self.liquids.get_mut(id) { g.splat(x,y,kind,amt,rad); }
4084                return Ok(Value::Unit);
4085            }
4086            #[cfg(not(target_arch = "wasm32"))]
4087            "liquid_gravity" | "液体重力" | "液体重力ベクトル" | "액체중력" | "แรงโน้มถ่วงเหลว" => {
4088                let id=self.arg_num(&args,0,0.)? as usize;
4089                let gx=self.arg_num(&args,1,0.)? as f32; let gy=self.arg_num(&args,2,60.)? as f32;
4090                if let Some(g)=self.liquids.get_mut(id) { g.set_gravity(gx,gy); }
4091                return Ok(Value::Unit);
4092            }
4093            #[cfg(not(target_arch = "wasm32"))]
4094            "liquid_step" | "液体步进" | "液体更新" | "액체스텝" | "ก้าวของเหลว" => {
4095                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
4096                if let Some(g)=self.liquids.get_mut(id) { g.step(dt); }
4097                return Ok(Value::Unit);
4098            }
4099            // liquid_rainbow(id, on) — colour the fluid as a flowing ROYGBIV marble
4100            #[cfg(not(target_arch = "wasm32"))]
4101            "liquid_rainbow" | "液体彩虹" | "液体虹" | "액체무지개" | "ของเหลวสายรุ้ง" => {
4102                let id=self.arg_num(&args,0,0.)? as usize;
4103                let on=self.arg_num(&args,1,1.0)? > 0.5;
4104                if let Some(g)=self.liquids.get_mut(id) { g.rainbow = on; }
4105                return Ok(Value::Unit);
4106            }
4107            // liquid_draw(id, sx, sy, scale) — fast flat 2-D blit of the colour field
4108            #[cfg(not(target_arch = "wasm32"))]
4109            "liquid_draw" | "绘制液体" | "液体描画" | "액체그리기" | "วาดของเหลว" => {
4110                let id=self.arg_num(&args,0,0.)? as usize;
4111                let sx=self.arg_num(&args,1,0.)? as i32; let sy=self.arg_num(&args,2,0.)? as i32;
4112                let scale=(self.arg_num(&args,3,4.)? as i32).max(1);
4113                if id < self.liquids.len() {
4114                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4115                    let mut gfx=self.gfx.borrow_mut(); let (w,h)=(gfx.width as i32, gfx.height as i32);
4116                    let g=&self.liquids[id];
4117                    for cy in 0..gh { for cx in 0..gw {
4118                        let col=g.sample_rgb(cx,cy);
4119                        let bx=sx + cx as i32*scale; let by=sy + cy as i32*scale;
4120                        for dy in 0..scale { for dx in 0..scale {
4121                            let px=bx+dx; let py=by+dy;
4122                            if px>=0 && py>=0 && px<w && py<h { gfx.buffer[(py*w+px) as usize]=col; }
4123                        }}
4124                    }}
4125                }
4126                return Ok(Value::Unit);
4127            }
4128            // liquid_draw_surface(id, kind, cx,cy,cz, radius, height)
4129            //   kind: 0 plane · 1 sphere · 2 cylinder · 3 cone · 4 dome
4130            #[cfg(not(target_arch = "wasm32"))]
4131            "liquid_draw_surface" | "液体贴面" | "液体曲面" | "액체곡면" | "ของเหลวบนพื้นผิว" => {
4132                let id=self.arg_num(&args,0,0.)? as usize;
4133                let kind=self.arg_num(&args,1,1.)? as i32;
4134                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;
4135                let radius=self.arg_num(&args,5,2.0)? as f32; let height=self.arg_num(&args,6,3.0)? as f32;
4136                if id < self.liquids.len() {
4137                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4138                    let mut gfx=self.gfx.borrow_mut();
4139                    let (w,h,add)=(gfx.width, gfx.height, gfx.blend==1);
4140                    let cam=gfx.camera.clone();
4141                    let near = -cam.zdist + 0.05;
4142                    let g=&self.liquids[id];
4143                    let tau=std::f32::consts::TAU; let pi=std::f32::consts::PI;
4144                    // surface point for a (u,v) in [0,1] on the chosen primitive
4145                    let sp = |u:f32, v:f32| -> [f32;3] {
4146                        if kind==0 { [cx+(u-0.5)*2.0*radius, cy, cz+(v-0.5)*2.0*radius] }
4147                        else if kind==2 { let th=u*tau; [cx+th.cos()*radius, cy+(v-0.5)*height, cz+th.sin()*radius] }
4148                        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] }
4149                        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] }
4150                        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] }
4151                    };
4152                    let nrm = |u:f32, v:f32| -> [f32;3] {
4153                        if kind==0 { [0.0,-1.0,0.0] }
4154                        else if kind==2 { let th=u*tau; [th.cos(),0.0,th.sin()] }
4155                        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()] }
4156                        else if kind==4 { let th=u*tau; let ph=v*pi*0.5; [ph.sin()*th.cos(),-ph.cos(),ph.sin()*th.sin()] }
4157                        else { let th=u*tau; let ph=v*pi; [ph.sin()*th.cos(),ph.cos(),ph.sin()*th.sin()] }
4158                    };
4159                    let gwf=gw as f32; let ghf=gh as f32;
4160                    let mut cyc=0usize;
4161                    while cyc<gh {
4162                        let mut cxc=0usize;
4163                        while cxc<gw {
4164                            // cull by the cell centre's outward normal
4165                            let uc=(cxc as f32+0.5)/gwf; let vc=(cyc as f32+0.5)/ghf;
4166                            let c=sp(uc,vc); let n=nrm(uc,vc);
4167                            let dc=cam.depth(c[0],c[1],c[2]);
4168                            if dc>near {
4169                                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;
4170                                if !cull {
4171                                    // project the 4 cell corners → a filled AA vector quad
4172                                    let u0=cxc as f32/gwf; let u1=(cxc+1) as f32/gwf;
4173                                    let v0=cyc as f32/ghf; let v1=(cyc+1) as f32/ghf;
4174                                    let q=[sp(u0,v0),sp(u1,v0),sp(u1,v1),sp(u0,v1)];
4175                                    let mut poly: Vec<[f32;2]> = Vec::with_capacity(5);
4176                                    let mut ok=true;
4177                                    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]); }
4178                                    if ok { let p0=poly[0]; poly.push(p0);
4179                                        let col=g.sample_rgb(cxc,cyc);
4180                                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, col, add, std::slice::from_ref(&poly));
4181                                    }
4182                                }
4183                            }
4184                            cxc+=1;
4185                        }
4186                        cyc+=1;
4187                    }
4188                }
4189                return Ok(Value::Unit);
4190            }
4191            // sparkle(x, y, w, h, count [, t]) — scatter twinkling vector star-sparkles
4192            // in a rect (snowglobe effect) in the current colour + blend mode.
4193            #[cfg(not(target_arch = "wasm32"))]
4194            "sparkle" | "闪光" | "きらめき" | "반짝임" | "ประกาย" => {
4195                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4196                let ww=self.arg_num(&args,2,200.)? as f32; let hh=self.arg_num(&args,3,200.)? as f32;
4197                let count=self.arg_num(&args,4,40.)? as i32;
4198                let t=self.arg_num(&args,5,0.)? as f32;
4199                let mut gfx=self.gfx.borrow_mut();
4200                let (w,h,add,color)=(gfx.width, gfx.height, gfx.blend==1, gfx.color);
4201                let (cr,cg,cb)=((color>>16&0xFF) as f32,(color>>8&0xFF) as f32,(color&0xFF) as f32);
4202                let mut n=0i32;
4203                while n<count {
4204                    let hsh=(n as u32).wrapping_mul(2654435761).wrapping_add(0x9E3779B9);
4205                    let u=((hsh>>8)&1023) as f32/1023.0;
4206                    let v=((hsh>>18)&1023) as f32/1023.0;
4207                    let phase=(hsh&255) as f32/255.0;
4208                    let tw=(t*3.0 + phase*6.2831 + n as f32).sin()*0.5+0.5;
4209                    let sz=1.5+tw*5.0;
4210                    let px=x+u*ww; let py=y+v*hh;
4211                    let b=tw*tw; // sharp twinkle
4212                    let col=(((cr*b)as u32)<<16)|(((cg*b)as u32)<<8)|((cb*b)as u32);
4213                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-sz,py, px+sz,py);
4214                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px,py-sz, px,py+sz);
4215                    let d=sz*0.55;
4216                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py-d, px+d,py+d);
4217                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py+d, px+d,py-d);
4218                    n+=1;
4219                }
4220                return Ok(Value::Unit);
4221            }
4222
4223            // ══════════════════════════════════════════════════════════════════
4224            // DIALOG BUILTINS  (crates/ling-game/src/dialog.rs) — cinematic,
4225            // typed-out, colour-coded text boxes. Markup: {n}name{/} {p}place{/}
4226            // {i}item{/}, \n newline, || page break.
4227            // ══════════════════════════════════════════════════════════════════
4228            #[cfg(not(target_arch = "wasm32"))]
4229            "dialog_show" | "对话显示" | "会話表示" | "대화표시" | "แสดงบทสนทนา" => {
4230                let text = self.arg_str(&args, 0, "");
4231                let cps = self.arg_num(&args, 1, 32.0)? as f32;
4232                self.dialog = Some(ling_game::dialog::Dialog::new(&text, cps));
4233                return Ok(Value::Unit);
4234            }
4235            #[cfg(not(target_arch = "wasm32"))]
4236            "dialog_step" | "对话步进" | "会話更新" | "대화스텝" | "ก้าวบทสนทนา" => {
4237                let dt = self.arg_num(&args, 0, 0.016)? as f32;
4238                if let Some(d) = self.dialog.as_mut() { d.update(dt); }
4239                return Ok(Value::Unit);
4240            }
4241            #[cfg(not(target_arch = "wasm32"))]
4242            "dialog_advance" | "对话推进" | "会話送り" | "대화진행" | "เลื่อนบทสนทนา" => {
4243                if let Some(d) = self.dialog.as_mut() { d.advance(); }
4244                return Ok(Value::Unit);
4245            }
4246            #[cfg(not(target_arch = "wasm32"))]
4247            "dialog_active" | "对话激活" | "会話中" | "대화중" | "บทสนทนาทำงาน" => {
4248                let a = self.dialog.as_ref().map(|d| !d.is_closed()).unwrap_or(false);
4249                return Ok(Value::Bool(a));
4250            }
4251            #[cfg(not(target_arch = "wasm32"))]
4252            "dialog_typing" | "对话打字" | "会話タイプ中" | "대화타이핑" | "กำลังพิมพ์บทสนทนา" => {
4253                use ling_game::dialog::Dialog;
4254                
4255                let a = self.dialog.as_ref().map(|d: &Dialog | !d.is_closed() && d.is_typing()).unwrap_or(false);
4256                return Ok(Value::Bool(a))
4257            }
4258            #[cfg(not(target_arch = "wasm32"))]
4259            "dialog_close" | "对话关闭" | "会話閉じる" | "대화닫기" | "ปิดบทสนทนา" => {
4260                self.dialog = None;
4261                return Ok(Value::Unit);
4262            }
4263            // dialog_color(role, r, g, b) — role: 0 text · 1 name · 2 place · 3 item
4264            #[cfg(not(target_arch = "wasm32"))]
4265            "dialog_color" | "对话颜色" | "会話色" | "대화색" | "สีบทสนทนา" => {
4266                let role = (self.arg_num(&args,0,0.0)? as usize).min(3);
4267                let r = self.arg_num(&args,1,255.0)? as u32 & 0xFF;
4268                let g = self.arg_num(&args,2,255.0)? as u32 & 0xFF;
4269                let b = self.arg_num(&args,3,255.0)? as u32 & 0xFF;
4270                self.dialog_colors[role] = (r<<16)|(g<<8)|b;
4271                return Ok(Value::Unit);
4272            }
4273            // dialog_draw(x, y, w, h [, font_handle]) — draw the box + typed text
4274            #[cfg(not(target_arch = "wasm32"))]
4275            "dialog_draw" | "对话绘制" | "会話描画" | "대화그리기" | "วาดบทสนทนา" => {
4276                let x=self.arg_num(&args,0,40.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
4277                let ww=self.arg_num(&args,2,720.0)? as f32; let hh=self.arg_num(&args,3,150.0)? as f32;
4278                let font = self.arg_num(&args,4,-1.0)? as i64;
4279                let t = self.start_time.elapsed().as_secs_f32();
4280                self.render_dialog(x, y, ww, hh, font, t);
4281                return Ok(Value::Unit);
4282            }
4283
4284            // text_poll() — fold newly-typed keys into the input buffer, return it
4285            #[cfg(not(target_arch = "wasm32"))]
4286            "text_poll" => {
4287                let keys = { let gfx = self.gfx.borrow(); gfx.window.as_ref().map(|w| w.get_keys_pressed(minifb::KeyRepeat::No)).unwrap_or_default() };
4288                for k in keys {
4289                    if k == minifb::Key::Backspace { self.text_buffer.pop(); }
4290                    else if let Some(c) = key_char(k) { self.text_buffer.push(c); }
4291                }
4292                return Ok(Value::Str(self.text_buffer.clone()));
4293            }
4294            "text_get"   => return Ok(Value::Str(self.text_buffer.clone())),
4295            "text_set"   => { self.text_buffer = self.arg_str(&args,0,""); return Ok(Value::Unit); }
4296            "text_clear" => { self.text_buffer.clear(); return Ok(Value::Unit); }
4297            // record_frame() — append the current framebuffer as a PPM, return frame #
4298            #[cfg(not(target_arch = "wasm32"))]
4299            "record_frame" => {
4300                let n = self.record_n;
4301                let (buf, w, h) = { let gfx = self.gfx.borrow(); (gfx.buffer.clone(), gfx.width, gfx.height) };
4302                let _ = std::fs::create_dir_all("recordings");
4303                let mut out = Vec::with_capacity(w*h*3 + 32);
4304                out.extend_from_slice(format!("P6\n{w} {h}\n255\n").as_bytes());
4305                for px in &buf { let p = *px; out.push((p>>16) as u8); out.push((p>>8) as u8); out.push(p as u8); }
4306                let _ = std::fs::write(format!("recordings/frame_{n:05}.ppm"), out);
4307                self.record_n += 1;
4308                return Ok(Value::Number(n as f64));
4309            }
4310            "record_count" => return Ok(Value::Number(self.record_n as f64)),
4311            // ── microphone → crypto donut ──
4312            // mic_capture() — append the latest mic samples to the record buffer
4313            // (call each frame while recording). Returns the buffer length.
4314            #[cfg(not(target_arch = "wasm32"))]
4315            "mic_capture" => {
4316                if let Some(mic) = self.mic.as_ref() {
4317                    let s = mic.latest_samples();
4318                    self.mic_buffer.extend_from_slice(&s);
4319                    let cap = 96_000usize; // ~2 s @ 48 kHz
4320                    if self.mic_buffer.len() > cap {
4321                        let drop = self.mic_buffer.len() - cap;
4322                        self.mic_buffer.drain(0..drop);
4323                    }
4324                }
4325                return Ok(Value::Number(self.mic_buffer.len() as f64));
4326            }
4327            // mic_seed() — SHA3-256 hex of the recorded audio, usable as a donut seed
4328            #[cfg(not(target_arch = "wasm32"))]
4329            "mic_seed" => {
4330                let mut bytes = Vec::with_capacity(self.mic_buffer.len() * 4);
4331                for f in &self.mic_buffer { bytes.extend_from_slice(&f.to_le_bytes()); }
4332                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(&bytes))));
4333            }
4334            #[cfg(not(target_arch = "wasm32"))]
4335            "mic_clear" => { self.mic_buffer.clear(); return Ok(Value::Number(0.0)); }
4336            // flush the 3-D depth queue onto the framebuffer WITHOUT presenting,
4337            // so 2-D UI drawn afterwards overlays the 3-D scene.
4338            #[cfg(not(target_arch = "wasm32"))]
4339            "flush_3d" | "render_3d" => {
4340                let mut gfx = self.gfx.borrow_mut();
4341                if !gfx.depth_queue.is_empty() {
4342                    let w = gfx.width; let h = gfx.height;
4343                    let queue = std::mem::take(&mut gfx.depth_queue);
4344                    queue.flush(&mut gfx.buffer, w, h);
4345                }
4346                return Ok(Value::Unit);
4347            }
4348
4349            "set_rim" | "设置边缘光" | "リム設定" | "림라이트" | "ตั้งขอบเรือง" => {
4350                let s=self.arg_num(&args,0,0.6)? as f32;
4351                let r=self.arg_num(&args,1,115.)? as f32/255.0;
4352                let g=self.arg_num(&args,2,217.)? as f32/255.0;
4353                let b=self.arg_num(&args,3,255.)? as f32/255.0;
4354                let mut gfx=self.gfx.borrow_mut();
4355                gfx.shade.rim = s; gfx.shade.rim_color = [r,g,b];
4356                return Ok(Value::Unit);
4357            }
4358
4359            // ══════════════════════════════════════════════════════════════════
4360            // 3-D PRIMITIVES  (src/gfx/shapes.rs)  — "Inkscape for 3-D"
4361            //   shape(cx,cy,cz,  sx,sy,sz,  rx,ry,rz,  mode,  e0,e1,e2)
4362            //     centre (cx,cy,cz), per-axis scale, Euler rotation (radians),
4363            //     mode: 0 filled · 1 wireframe · 2 both,
4364            //     e0..e2: shape-specific (segments / sides / ratio …).
4365            //   Pen colour (set_color) drives fill lighting and wireframe colour.
4366            // ══════════════════════════════════════════════════════════════════
4367            n if crate::gfx::shapes::canon(n).is_some() => {
4368                let kind = crate::gfx::shapes::canon(n).unwrap();
4369                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;
4370                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;
4371                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;
4372                let mode=self.arg_num(&args,9,0.)? as i32;
4373                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;
4374                if let Some(mesh)=crate::gfx::shapes::build(kind,[cx,cy,cz,sx,sy,sz,rx,ry,rz],e0,e1,e2){
4375                    let mut gfx=self.gfx.borrow_mut();
4376                    gfx.emit_mesh(&mesh,mode);
4377                }
4378                return Ok(Value::Unit);
4379            }
4380
4381            _ => {}
4382        }
4383
4384        // User-defined function
4385        if let Some(def) = self.functions.get(name).cloned() {
4386            let mut call_env = Env::new();
4387            // Seed env with non-Do globals (skip entry-point blocks to avoid infinite recursion).
4388            // Pass 1: evaluate each global with the call-site env — simple literals succeed.
4389            // Pass 2: retry failed globals with the partially-built call_env so that compound
4390            //         globals (e.g. `FM = (NZ + FZ) / 2.0`) can resolve their dependencies.
4391            let non_do_globals: Vec<_> = self.globals.iter()
4392                .filter(|(_, expr)| !matches!(expr, Expr::Do(_)))
4393                .map(|(k, e)| (k.clone(), e.clone()))
4394                .collect();
4395            let mut pending: Vec<(String, Expr)> = Vec::new();
4396            for (k, expr) in &non_do_globals {
4397                let mut tmp = env.clone();
4398                if let Ok(v) = self.eval_expr(expr, &mut tmp) {
4399                    call_env.insert(k.clone(), v);
4400                } else {
4401                    pending.push((k.clone(), expr.clone()));
4402                }
4403            }
4404            // Second pass: retry compound globals now that literals are in call_env.
4405            for (k, expr) in &pending {
4406                let mut tmp = env.clone();
4407                tmp.extend(call_env.clone());
4408                if let Ok(v) = self.eval_expr(expr, &mut tmp) {
4409                    call_env.insert(k.clone(), v);
4410                }
4411            }
4412            for (param, arg) in def.params.iter().zip(args) {
4413                call_env.insert(param.clone(), arg);
4414            }
4415            return match self.exec_block(&def.body, &mut call_env) {
4416                Ok(v) => Ok(v.unwrap_or(Value::Unit)),
4417                Err(EvalErr::Return(v)) => Ok(v),
4418                Err(e) => Err(e),
4419            };
4420        }
4421
4422        Err(EvalErr::from(format!("unknown function '{name}'")))
4423    }
4424
4425    fn call_value(&mut self, v: Value, args: Vec<Value>) -> EvalResult {
4426        match v {
4427            Value::Fn(params, body, mut captured) => {
4428                for (p, a) in params.iter().zip(args) {
4429                    captured.insert(p.clone(), a);
4430                }
4431                match self.exec_block(&body, &mut captured) {
4432                    Ok(v) => Ok(v.unwrap_or(Value::Unit)),
4433                    Err(EvalErr::Return(v)) => Ok(v),
4434                    Err(e) => Err(e),
4435                }
4436            }
4437            other => Err(EvalErr::from(format!("cannot call {:?}", other))),
4438        }
4439    }
4440
4441    fn call_method(&self, recv: Value, method: &str, args: Vec<Value>) -> EvalResult {
4442        match (&recv, method) {
4443            (Value::Str(s), "is_empty" | "是空") => Ok(Value::Bool(s.is_empty())),
4444            (Value::Str(s), "len" | "长")        => Ok(Value::Number(s.len() as f64)),
4445            (Value::Str(s), "to_string" | "转文") => Ok(Value::Str(s.clone())),
4446            (Value::Str(s), "contains" | "包含") => {
4447                if let Some(Value::Str(sub)) = args.first() {
4448                    Ok(Value::Bool(s.contains(sub.as_str())))
4449                } else { Ok(Value::Bool(false)) }
4450            }
4451            (Value::Str(s), "push_str" | "推_文") => {
4452                let mut s2 = s.clone();
4453                if let Some(Value::Str(a)) = args.first() { s2.push_str(a); }
4454                Ok(Value::Str(s2))
4455            }
4456            (Value::List(v), "len" | "长") => Ok(Value::Number(v.len() as f64)),
4457            (Value::List(v), "push" | "推") => {
4458                let mut v2 = v.clone();
4459                if let Some(a) = args.first() { v2.push(a.clone()); }
4460                Ok(Value::List(v2))
4461            }
4462            (Value::Ok(inner), _) | (Value::Err(inner), _) => Ok(*inner.clone()),
4463            _ => Err(EvalErr::from(format!("no method '{method}' on {recv}"))),
4464        }
4465    }
4466
4467    // ─── Pattern matching ─────────────────────────────────────────────────────
4468
4469    fn match_pattern(&self, pat: &Pattern, val: &Value) -> Option<Env> {
4470        match (pat, val) {
4471            (Pattern::Wildcard, _) => Some(Env::new()),
4472            (Pattern::Str(s), Value::Str(v)) if s == v => Some(Env::new()),
4473            (Pattern::Number(n), Value::Number(v)) if (n - v).abs() < 1e-12 => Some(Env::new()),
4474            (Pattern::Bool(b), Value::Bool(v)) if b == v => Some(Env::new()),
4475            (Pattern::Ident(name), _) => {
4476                let mut e = Env::new();
4477                e.insert(name.clone(), val.clone());
4478                Some(e)
4479            }
4480            (Pattern::Constructor(ctor, inner_pat), _) => {
4481                let (matches, inner_val) = match (ctor.as_str(), val) {
4482                    ("ok"  | "好", Value::Ok(v))  => (true, Some(v.as_ref().clone())),
4483                    ("bad" | "坏", Value::Err(v)) => (true, Some(v.as_ref().clone())),
4484                    ("ok"  | "好", v) if !matches!(v, Value::Err(_)) => (true, Some(v.clone())),
4485                    _ => (false, None),
4486                };
4487                if !matches { return None; }
4488                match (inner_pat, inner_val) {
4489                    (Some(p), Some(v)) => self.match_pattern(p, &v),
4490                    (None, _)          => Some(Env::new()),
4491                    (Some(p), None)    => self.match_pattern(p, &Value::Unit),
4492                }
4493            }
4494            _ => None,
4495        }
4496    }
4497
4498    // ─── Utilities ───────────────────────────────────────────────────────────
4499
4500    fn value_to_iter(&self, val: Value) -> Result<Vec<Value>, EvalErr> {
4501        match val {
4502            Value::List(v)   => Ok(v),
4503            Value::Str(s)    => Ok(s.chars().map(|c| Value::Str(c.to_string())).collect()),
4504            Value::Number(n) => Ok((0..n as i64).map(|i| Value::Number(i as f64)).collect()),
4505            other => Err(EvalErr::from(format!("cannot iterate over {:?}", other))),
4506        }
4507    }
4508
4509    fn is_truthy(&self, val: &Value) -> bool {
4510        match val {
4511            Value::Bool(b)     => *b,
4512            Value::Unit        => false,
4513            Value::Number(n)   => *n != 0.0,
4514            Value::Str(s)      => !s.is_empty(),
4515            Value::List(v)     => !v.is_empty(),
4516            Value::Ok(_)       => true,
4517            Value::Err(_)      => false,
4518            Value::Fn(_, _, _) => true,
4519        }
4520    }
4521
4522    fn to_number(&self, val: &Value) -> Result<f64, EvalErr> {
4523        match val {
4524            Value::Number(n) => Ok(*n),
4525            Value::Str(s)    => s.parse().map_err(|_| EvalErr::from(format!("cannot convert '{s}' to number"))),
4526            other => Err(EvalErr::from(format!("expected number, got {:?}", other))),
4527        }
4528    }
4529
4530    /// Get the n-th argument as f64, falling back to `default` if missing.
4531    fn arg_num(&self, args: &[Value], n: usize, default: f64) -> Result<f64, EvalErr> {
4532        match args.get(n) {
4533            Some(v) => self.to_number(v),
4534            None    => Ok(default),
4535        }
4536    }
4537
4538    fn arg_str(&self, args: &[Value], n: usize, default: &str) -> String {
4539        args.get(n).map(|v| v.to_string()).unwrap_or_else(|| default.to_string())
4540    }
4541
4542    /// Read a list-of-numbers argument as `Vec<f32>` (empty if absent/not a list).
4543    #[allow(dead_code)]
4544    fn arg_list_f32(&self, args: &[Value], n: usize) -> Vec<f32> {
4545        match args.get(n) {
4546            Some(Value::List(v)) => v.iter().filter_map(|x| match x {
4547                Value::Number(n) => Some(*n as f32),
4548                _ => None,
4549            }).collect(),
4550            _ => Vec::new(),
4551        }
4552    }
4553
4554    /// Optional `r,g,b` colour override starting at arg `i` → packed 0x00RRGGBB,
4555    /// or `default` if those three numeric args aren't present.
4556    #[cfg(not(target_arch = "wasm32"))]
4557    fn color_at(&self, args: &[Value], i: usize, default: u32) -> u32 {
4558        match (args.get(i), args.get(i + 1), args.get(i + 2)) {
4559            (Some(a), Some(b), Some(c)) => match (self.to_number(a), self.to_number(b), self.to_number(c)) {
4560                (Ok(r), Ok(g), Ok(bl)) =>
4561                    ((r as u32 & 0xFF) << 16) | ((g as u32 & 0xFF) << 8) | (bl as u32 & 0xFF),
4562                _ => default,
4563            },
4564            _ => default,
4565        }
4566    }
4567
4568    /// A pitch argument: a note-name string (`"C4"`, `"A#3"`) or a numeric MIDI value.
4569    #[cfg(not(target_arch = "wasm32"))]
4570    fn pitch_arg(&self, args: &[Value], i: usize, default: i32) -> i32 {
4571        match args.get(i) {
4572            Some(Value::Str(s)) => ling_music::note::parse_pitch(s).unwrap_or(default),
4573            Some(Value::Number(n)) => *n as i32,
4574            _ => default,
4575        }
4576    }
4577
4578    /// Current mouse position + left-button-down (native window only).
4579    #[cfg(not(target_arch = "wasm32"))]
4580    fn mouse_now(&self) -> (f32, f32, bool) {
4581        let gfx = self.gfx.borrow();
4582        let (mx, my) = gfx.window.as_ref()
4583            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0, 0.0));
4584        let down = gfx.window.as_ref()
4585            .map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
4586        (mx, my, down)
4587    }
4588
4589    /// Rasterize a UI [`ling_ui::widgets::Draw`] into the framebuffer: filled
4590    /// polygons via the AA scanline fill, polylines via AA lines, honouring the
4591    /// current blend mode.
4592    #[cfg(not(target_arch = "wasm32"))]
4593    fn draw_ui(&self, d: &ling_ui::widgets::Draw) {
4594        let mut gfx = self.gfx.borrow_mut();
4595        let (w, h, add) = (gfx.width, gfx.height, gfx.blend == 1);
4596        for (c, poly) in &d.fills {
4597            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, *c, add, std::slice::from_ref(poly));
4598        }
4599        for (c, pl) in &d.strokes {
4600            for s in pl.windows(2) {
4601                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]);
4602            }
4603        }
4604    }
4605
4606    /// Parse (dst_x, dst_y, width, height) from the first four args of a tex_* builtin.
4607    fn tex_rect(&self, args: &[Value]) -> Result<(usize, usize, usize, usize), EvalErr> {
4608        let tx = self.arg_num(args, 0, 0.0)? as usize;
4609        let ty = self.arg_num(args, 1, 0.0)? as usize;
4610        let tw = self.arg_num(args, 2, 256.0)? as usize;
4611        let th = self.arg_num(args, 3, 256.0)? as usize;
4612        Ok((tx, ty, tw.max(1), th.max(1)))
4613    }
4614
4615    fn apply_binop(&self, op: &BinOp, l: Value, r: Value) -> EvalResult {
4616        match op {
4617            BinOp::Add => match (l, r) {
4618                (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
4619                (Value::Str(a), Value::Str(b))       => Ok(Value::Str(a + &b)),
4620                (Value::Str(a), b)                   => Ok(Value::Str(a + &b.to_string())),
4621                (a, Value::Str(b))                   => Ok(Value::Str(a.to_string() + &b)),
4622                (a, b) => Err(EvalErr::from(format!("cannot add {:?} and {:?}", a, b))),
4623            },
4624            BinOp::Sub => Ok(Value::Number(self.to_number(&l)? - self.to_number(&r)?)),
4625            BinOp::Mul => Ok(Value::Number(self.to_number(&l)? * self.to_number(&r)?)),
4626            BinOp::Div => Ok(Value::Number(self.to_number(&l)? / self.to_number(&r)?)),
4627            BinOp::Rem => Ok(Value::Number(self.to_number(&l)? % self.to_number(&r)?)),
4628            BinOp::Eq  => Ok(Value::Bool(values_equal(&l, &r))),
4629            BinOp::Ne  => Ok(Value::Bool(!values_equal(&l, &r))),
4630            BinOp::Lt  => Ok(Value::Bool(self.to_number(&l)? < self.to_number(&r)?)),
4631            BinOp::Gt  => Ok(Value::Bool(self.to_number(&l)? > self.to_number(&r)?)),
4632            BinOp::Le  => Ok(Value::Bool(self.to_number(&l)? <= self.to_number(&r)?)),
4633            BinOp::Ge  => Ok(Value::Bool(self.to_number(&l)? >= self.to_number(&r)?)),
4634            BinOp::And => Ok(Value::Bool(self.is_truthy(&l) && self.is_truthy(&r))),
4635            BinOp::Or  => Ok(Value::Bool(self.is_truthy(&l) || self.is_truthy(&r))),
4636        }
4637    }
4638
4639    fn builtin_format(&self, args: &[Value]) -> Result<String, EvalErr> {
4640        if args.is_empty() { return Ok(String::new()); }
4641        let fmt = match &args[0] {
4642            Value::Str(s) => s.clone(),
4643            other => return Ok(other.to_string()),
4644        };
4645
4646        let mut result = String::new();
4647        let mut arg_idx = 1usize;
4648        let mut chars = fmt.chars().peekable();
4649        while let Some(c) = chars.next() {
4650            if c == '{' {
4651                if chars.peek() == Some(&'}') {
4652                    chars.next();
4653                    if arg_idx < args.len() {
4654                        result.push_str(&args[arg_idx].to_string());
4655                        arg_idx += 1;
4656                    }
4657                } else {
4658                    let mut spec = String::new();
4659                    for ch in chars.by_ref() {
4660                        if ch == '}' { break; }
4661                        spec.push(ch);
4662                    }
4663                    if arg_idx < args.len() {
4664                        if spec.starts_with(":.") {
4665                            if let Value::Number(n) = &args[arg_idx] {
4666                                let prec: usize = spec[2..].trim_end_matches('f')
4667                                    .parse().unwrap_or(2);
4668                                result.push_str(&format!("{:.prec$}", n));
4669                                arg_idx += 1;
4670                                continue;
4671                            }
4672                        }
4673                        result.push_str(&args[arg_idx].to_string());
4674                        arg_idx += 1;
4675                    }
4676                }
4677            } else {
4678                result.push(c);
4679            }
4680        }
4681        Ok(result)
4682    }
4683}
4684
4685#[cfg(not(target_arch = "wasm32"))]
4686fn str_to_minifb_key(name: &str) -> Option<minifb::Key> {
4687    use minifb::Key;
4688    Some(match name {
4689        "numpad0" | "kp0" => Key::NumPad0,
4690        "numpad1" | "kp1" => Key::NumPad1,
4691        "numpad2" | "kp2" => Key::NumPad2,
4692        "numpad3" | "kp3" => Key::NumPad3,
4693        "numpad4" | "kp4" => Key::NumPad4,
4694        "numpad5" | "kp5" => Key::NumPad5,
4695        "numpad6" | "kp6" => Key::NumPad6,
4696        "numpad7" | "kp7" => Key::NumPad7,
4697        "numpad8" | "kp8" => Key::NumPad8,
4698        "numpad9" | "kp9" => Key::NumPad9,
4699        "numpad+" | "kp+" => Key::NumPadPlus,
4700        "numpad-" | "kp-" => Key::NumPadMinus,
4701        "numpad*" | "kp*" => Key::NumPadAsterisk,
4702        "numpad/" | "kp/" => Key::NumPadSlash,
4703        "left"   => Key::Left,
4704        "right"  => Key::Right,
4705        "up"     => Key::Up,
4706        "down"   => Key::Down,
4707        "space"  => Key::Space,
4708        "enter"  => Key::Enter,
4709        "escape" => Key::Escape,
4710        "pageup" => Key::PageUp,
4711        "pagedown" => Key::PageDown,
4712        "lshift" | "leftshift"  => Key::LeftShift,
4713        "rshift" | "rightshift" => Key::RightShift,
4714        "lctrl"  | "leftctrl"   => Key::LeftCtrl,
4715        "rctrl"  | "rightctrl"  => Key::RightCtrl,
4716        "tab"    => Key::Tab,
4717        "backspace" => Key::Backspace,
4718        "delete" => Key::Delete,
4719        "insert" => Key::Insert,
4720        "home"   => Key::Home,
4721        "end"    => Key::End,
4722        "a" => Key::A, "b" => Key::B, "c" => Key::C, "d" => Key::D,
4723        "e" => Key::E, "f" => Key::F, "g" => Key::G, "h" => Key::H,
4724        "i" => Key::I, "j" => Key::J, "k" => Key::K, "l" => Key::L,
4725        "m" => Key::M, "n" => Key::N, "o" => Key::O, "p" => Key::P,
4726        "q" => Key::Q, "r" => Key::R, "s" => Key::S, "t" => Key::T,
4727        "u" => Key::U, "v" => Key::V, "w" => Key::W, "x" => Key::X,
4728        "y" => Key::Y, "z" => Key::Z,
4729        "0" => Key::Key0, "1" => Key::Key1, "2" => Key::Key2,
4730        "3" => Key::Key3, "4" => Key::Key4, "5" => Key::Key5,
4731        "6" => Key::Key6, "7" => Key::Key7, "8" => Key::Key8,
4732        "9" => Key::Key9,
4733        _ => return None,
4734    })
4735}
4736
4737fn values_equal(a: &Value, b: &Value) -> bool {
4738    match (a, b) {
4739        (Value::Number(x), Value::Number(y)) => (x - y).abs() < 1e-12,
4740        (Value::Str(x), Value::Str(y))       => x == y,
4741        (Value::Bool(x), Value::Bool(y))     => x == y,
4742        (Value::Unit, Value::Unit)            => true,
4743        _ => false,
4744    }
4745}
4746
4747// Rasteriser functions live in crate::gfx::raster — imported at top of file.
4748
4749// ── Window platform helpers ────────────────────────────────────────────────────
4750
4751/// Hide the console window that the OS auto-attaches to console-subsystem
4752/// processes. No-op on non-Windows and when no console is present.
4753#[cfg(not(target_arch = "wasm32"))]
4754fn hide_console_window() {
4755    #[cfg(windows)]
4756    unsafe {
4757        extern "system" {
4758            fn GetConsoleWindow() -> isize;
4759            fn ShowWindow(hwnd: isize, nCmdShow: i32) -> i32;
4760        }
4761        let hwnd = GetConsoleWindow();
4762        if hwnd != 0 {
4763            ShowWindow(hwnd, 0); // SW_HIDE = 0
4764        }
4765    }
4766}
4767
4768/// Move and resize the foreground window so it fills the primary monitor
4769/// (0,0 → screen_w × screen_h) and sits above the taskbar (HWND_TOPMOST).
4770#[cfg(all(not(target_arch = "wasm32"), windows))]
4771fn reposition_fullscreen(screen_w: i32, screen_h: i32) {
4772    unsafe {
4773        extern "system" {
4774            fn GetForegroundWindow() -> isize;
4775            fn SetWindowPos(hwnd: isize, insert_after: isize,
4776                            x: i32, y: i32, cx: i32, cy: i32,
4777                            flags: u32) -> i32;
4778        }
4779        let hwnd = GetForegroundWindow();
4780        if hwnd != 0 {
4781            // HWND_TOPMOST = -1, SWP_SHOWWINDOW = 0x0040
4782            SetWindowPos(hwnd, -1isize, 0, 0, screen_w, screen_h, 0x0040);
4783        }
4784    }
4785}
4786
4787/// Query the primary display resolution on non-Windows platforms.
4788/// Falls back to 1920×1080 if the size cannot be determined.
4789#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
4790fn native_screen_size() -> (f64, f64) {
4791    // On Linux/macOS we don't have an easy dependency-free call; return a
4792    // sensible default. Callers can always pass explicit dimensions.
4793    (1920.0, 1080.0)
4794}