authoravatarclover caruso<git@paperclover.net>2026-12-01 14:24:03-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 14:35:36-08:00
logb6e8338c7db97497095cf5de5e4c4223db443428
tree38c26911849a0d348ffed5086350b94e5059404b
parent0d06255b2ac49ce8492948def1d13109fbe6e99a
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(model,engine): harden Lua bytecode cache, downstream RoI, Text3D offscreen scale, and PolylineMask clamp


5 files changed, 726 insertions(+), 128 deletions(-)

crates/engine/src/eval/composite.rs+216-38
......@@ -60,6 +60,8 @@ fn infer_node_canvas_size(
6060 time: f64,
6161 expr: &ExprEngine,
6262 comp_dims: [u32; 2],
63 proxy_scale: u32,
64 hiq: bool,
6365 depth: usize,
6466) -> Option<[u32; 2]> {
6567 let mut cur_id = start_id;
......@@ -116,13 +118,23 @@ fn infer_node_canvas_size(
116118 {
117119 return None;
118120 }
119 let w = comp.eval_number(n, "Width", time, comp_dims[0] as f64, expr).max(1.0) as u32;
120 let h = comp.eval_number(n, "Height", time, comp_dims[1] as f64, expr).max(1.0) as u32;
121 // Only unambiguous when explicit dimensions aren't additionally proxy-scaled differently.
122121 if !n.inputs.contains_key("Width") && !n.inputs.contains_key("Height") {
123122 return Some(comp_dims);
124123 }
125 return Some([w, h]);
124 let w = comp.eval_number(n, "Width", time, comp.width as f64, expr).round().max(1.0) as u32;
125 let h = comp.eval_number(n, "Height", time, comp.height as f64, expr).round().max(1.0) as u32;
126 if matches!(n.kind.as_str(), "Background" | "FastNoise") && (w < 16 || h < 16) {
127 return Some(comp_dims);
128 }
129 let s = proxy_scale.max(1);
130 let scaled = [(w / s).max(1), (h / s).max(1)];
131 if n.kind == "FastNoise" {
132 let cap = if hiq { 8192 } else { 4096 };
133 if scaled[0].max(scaled[1]) > cap {
134 return None;
135 }
136 }
137 return Some(scaled);
126138 }
127139 _ => return None,
128140 }
......@@ -353,6 +365,7 @@ fn roi_for_node(
353365 node_id: NodeId,
354366 canvas_size: [u32; 2],
355367 comp_dims: [u32; 2],
368 proxy_scale: u32,
356369 time: f64,
357370 time_key: i64,
358371 hiq: bool,
......@@ -365,7 +378,11 @@ fn roi_for_node(
365378 if depth == 0 {
366379 return None;
367380 }
368 if let Some(&cached) = memo.get(&(node_id, time_key)) {
381 let mut mh = DefaultHasher::new();
382 time_key.hash(&mut mh);
383 canvas_size.hash(&mut mh);
384 let memo_key = mh.finish() as i64;
385 if let Some(&cached) = memo.get(&(node_id, memo_key)) {
369386 return cached;
370387 }
371388 if !visiting.insert(node_id) {
......@@ -385,6 +402,7 @@ fn roi_for_node(
385402 port,
386403 canvas_size,
387404 comp_dims,
405 proxy_scale,
388406 time,
389407 time_key,
390408 hiq,
......@@ -404,7 +422,7 @@ fn roi_for_node(
404422 };
405423
406424 visiting.remove(&node_id);
407 memo.insert((node_id, time_key), res);
425 memo.insert((node_id, memo_key), res);
408426 res
409427}
410428
......@@ -415,6 +433,7 @@ fn roi_from_consumer(
415433 port: &str,
416434 canvas_size: [u32; 2],
417435 comp_dims: [u32; 2],
436 proxy_scale: u32,
418437 time: f64,
419438 time_key: i64,
420439 hiq: bool,
......@@ -432,7 +451,7 @@ fn roi_from_consumer(
432451 }
433452 let n = comp.node(cid);
434453 if port == "__macro_output" {
435 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
454 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
436455 }
437456 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
438457 return None;
......@@ -444,7 +463,7 @@ fn roi_from_consumer(
444463 )
445464 {
446465 if port == default_main_input_port(&n.kind) {
447 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
466 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
448467 }
449468 return None;
450469 }
......@@ -461,12 +480,12 @@ fn roi_from_consumer(
461480 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
462481 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
463482 if blend <= 1e-6 && !mbm {
464 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
483 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
465484 }
466485 if has_mask {
467486 return Some(RoiBox::canvas(canvas_size));
468487 }
469 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
488 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
470489 }
471490 "Fuse.Colorize" => {
472491 if port != "Image" && port != "Input" {
......@@ -475,7 +494,7 @@ fn roi_from_consumer(
475494 if Engine::resolve_effect_mask_id(comp, n).is_some() {
476495 return Some(RoiBox::canvas(canvas_size));
477496 }
478 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
497 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
479498 }
480499 "ChannelBoolean" => {
481500 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
......@@ -483,13 +502,13 @@ fn roi_from_consumer(
483502 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
484503 if blend <= 1e-6 && !mbm {
485504 return match port {
486 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
505 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
487506 "Foreground" => Some(RoiBox::Empty),
488507 _ => None,
489508 };
490509 }
491510 if port == "Background" || port == "Foreground" {
492 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
511 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
493512 } else {
494513 None
495514 }
......@@ -502,7 +521,7 @@ fn roi_from_consumer(
502521 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
503522 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
504523 if blend <= 1e-6 && !mbm {
505 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
524 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
506525 }
507526 if n.static_str("ClippingMode").unwrap_or("Frame") != "None" || has_mask {
508527 Some(RoiBox::canvas(canvas_size))
......@@ -513,18 +532,18 @@ fn roi_from_consumer(
513532 "Dissolve" => {
514533 let mix_v = comp.eval_number(n, "Mix", time, 1.0, expr).clamp(0.0, 1.0);
515534 let blend = comp.eval_number(n, "Blend", time, 1.0, expr);
516 let has_mask = n.connected_node("EffectMask").is_some();
535 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
517536 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
518537 if (blend <= 1e-6 || mix_v <= 1e-6) && !mbm {
519538 return match port {
520 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
539 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
521540 "Foreground" => Some(RoiBox::Empty),
522541 _ => None,
523542 };
524543 }
525544 if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask {
526545 return match port {
527 "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
546 "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
528547 "Background" => Some(RoiBox::Empty),
529548 _ => None,
530549 };
......@@ -541,7 +560,7 @@ fn roi_from_consumer(
541560 }
542561 let hiq_only = comp.eval_number(n, "HiQOnly", time, 0.0, expr) > 0.5;
543562 if n.kind == "Scale" && !hiq && hiq_only {
544 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
563 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
545564 } else {
546565 Some(RoiBox::canvas(canvas_size))
547566 }
......@@ -552,10 +571,10 @@ fn roi_from_consumer(
552571 }
553572 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
554573 let mbm = n.kind != "Fuse.XGlow"
555 && n.connected_node("EffectMask").is_some()
574 && Engine::resolve_effect_mask_id(comp, n).is_some()
556575 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
557576 if blend <= 1e-6 && !mbm {
558 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
577 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
559578 } else {
560579 Some(RoiBox::canvas(canvas_size))
561580 }
......@@ -565,23 +584,58 @@ fn roi_from_consumer(
565584 return None;
566585 }
567586 let fg_none = n.connected_node("Foreground").and_then(|s| comp.find_node(s)).is_none();
568 let mbm = n.connected_node("EffectMask").is_some()
587 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
569588 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
570589 if fg_none && !mbm {
571 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
590 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
572591 } else {
573592 Some(RoiBox::canvas(canvas_size))
574593 }
575594 }
576 "CameraShake" | "DVE" | "Vortex" | "Drip" | "Dent" | "GridWarp" | "VariBlur"
577 | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Fuse.XfChroma"
578 | "Paint" => {
595 "CameraShake" => {
596 if port != "Input" {
597 return None;
598 }
599 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
600 let strength = comp.eval_number(n, "OverallStrength", time, 1.0, expr);
601 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
602 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
603 if (blend <= 1e-6 || strength.abs() <= 1e-6) && !mbm {
604 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
605 } else {
606 None
607 }
608 }
609 "GridWarp" => {
610 if port != "Input" {
611 return None;
612 }
613 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
614 if blend <= 1e-6 {
615 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
616 } else {
617 None
618 }
619 }
620 "Fuse.XfChroma" => {
621 if port != "Input" && port != "Image" {
622 return None;
623 }
624 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
625 if blend <= 1e-6 {
626 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
627 } else {
628 None
629 }
630 }
631 "DVE" | "Vortex" | "Drip" | "Dent" | "VariBlur"
632 | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Paint" => {
579633 if port != default_main_input_port(&n.kind) && port != "Input" && port != "Image" {
580634 return None;
581635 }
582636 // Conservatively union canvas crop with downstream RoI in case the node short-circuits
583637 // on an idle parameter (e.g. Blend = 0, radius = 0, etc.).
584 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
638 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
585639 Some(RoiBox::canvas(canvas_size).union(down))
586640 }
587641 "Blur" => {
......@@ -606,7 +660,7 @@ fn roi_from_consumer(
606660 let ry = y_raw * scale_ref * gauss_k;
607661 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
608662 if rx.max(ry) < 0.25 || blend <= 1e-6 {
609 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
663 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
610664 }
611665 if Engine::resolve_effect_mask_id(comp, n).is_some() {
612666 return Some(RoiBox::canvas(canvas_size));
......@@ -614,7 +668,7 @@ fn roi_from_consumer(
614668 if !rx.is_finite() || !ry.is_finite() || rx.abs() * 1.6 > 2048.0 || ry.abs() * 1.6 > 2048.0 {
615669 return None;
616670 }
617 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
671 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
618672 let RoiBox::Rect { x0, y0, x1, y1 } = down else {
619673 return Some(RoiBox::Empty);
620674 };
......@@ -633,7 +687,7 @@ fn roi_from_consumer(
633687 }
634688 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
635689 if blend <= 1e-6 {
636 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
690 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
637691 }
638692 if comp.eval_number(n, "InvertTransform", time, 0.0, expr) > 0.5 {
639693 return None;
......@@ -643,31 +697,39 @@ fn roi_from_consumer(
643697 return None;
644698 }
645699 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
646 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
700 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
647701 inverse_transform_box(comp, n, time, expr, canvas_size, has_mask, blend, down)
648702 }
649703 "Merge" => {
650704 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
651 let mbm = n.connected_node("EffectMask").is_some()
705 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
652706 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
653707 if blend <= 1e-6 && !mbm {
654708 return match port {
655 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
709 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
656710 "Foreground" => Some(RoiBox::Empty),
657711 _ => None,
658712 };
659713 }
660714 if port == "Background" {
661 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
715 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
662716 }
663717 if port == "Foreground" {
664 let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32;
665 if edges != 0 {
718 let raw_edges = comp.eval_number(n, "Edges", time, 0.0, expr) as f32;
719 let fg_id = n.connected_node("Foreground").and_then(|s| comp.find_node(s));
720 let edges = if raw_edges < 0.5 {
721 fg_id
722 .and_then(|fid| Engine::flattened_fg_edge_mode(comp, fid, time, expr))
723 .unwrap_or(raw_edges)
724 } else {
725 raw_edges
726 };
727 if edges.round() as i32 != 0 {
666728 return None;
667729 }
668730 let bg_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?;
669 let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, 16)?;
670 let down = roi_for_node(comp, cid, bg_canvas, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
731 let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, proxy_scale, hiq, 16)?;
732 let down = roi_for_node(comp, cid, bg_canvas, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
671733 return inverse_merge_fg_box(comp, n, time, expr, bg_canvas, canvas_size, down);
672734 }
673735 None
......@@ -725,6 +787,7 @@ impl Engine {
725787 merge_id,
726788 canvas_size,
727789 comp_dims,
790 self.proxy_scale,
728791 time,
729792 time_key,
730793 self.hiq,
......@@ -865,7 +928,18 @@ impl Engine {
865928 let mut dst_size = bg.size;
866929
867930 let roi_bounds = if bg.tex_scale >= 0.99 && fg.tex_scale >= 0.99 {
868 self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time)
931 self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time).map(|(rx0, ry0, rx1, ry1)| {
932 if visiting.len() == 1 {
933 (
934 rx0.min(0),
935 ry0.min(0),
936 rx1.max(bg.canvas_size[0].max(1) as i32),
937 ry1.max(bg.canvas_size[1].max(1) as i32),
938 )
939 } else {
940 (rx0, ry0, rx1, ry1)
941 }
942 })
869943 } else {
870944 None
871945 };
......@@ -2060,4 +2134,108 @@ mod tests {
20602134 let cr_px = eng.readback_rgba(&cr_tex).unwrap();
20612135 assert!(px_at(&cr_px, cr_tex.size[0], 8, 8)[0] > 200, "Crop at negative offset must sample expanded DoD");
20622136 }
2137
2138 #[test]
2139 fn directly_evaluated_merge_upstream_of_zoomed_in_transform_renders_full_canvas() {
2140 let comp_src = r#"{
2141 Tools = ordered() {
2142 Bg = Background {
2143 Inputs = {
2144 Width = Input { Value = 64, },
2145 Height = Input { Value = 64, },
2146 TopLeftRed = Input { Value = 1.0, },
2147 TopLeftAlpha = Input { Value = 1.0, },
2148 },
2149 },
2150 Fg = Background {
2151 Inputs = {
2152 Width = Input { Value = 64, },
2153 Height = Input { Value = 64, },
2154 TopLeftGreen = Input { Value = 1.0, },
2155 TopLeftAlpha = Input { Value = 1.0, },
2156 },
2157 },
2158 M = Merge {
2159 Inputs = {
2160 Background = Input { SourceOp = "Bg", Source = "Output", },
2161 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2162 },
2163 },
2164 ZoomIn = Transform {
2165 Inputs = {
2166 Size = Input { Value = 2.0, },
2167 Input = Input { SourceOp = "M", Source = "Output", },
2168 },
2169 },
2170 }
2171 }"#;
2172 let comp = Comp::from_fusion_str(comp_src).expect("parse zoom-in comp");
2173 let mut eng = Engine::new_headless().expect("headless engine");
2174 let (m_tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
2175 assert_eq!(m_tex.size, [64, 64]);
2176 let m_px = eng.readback_rgba(&m_tex).unwrap();
2177 assert_eq!(px_at(&m_px, 64, 2, 2), [0, 255, 0, 255], "corner of directly-evaluated Merge must not be cropped by downstream ZoomIn");
2178 assert_eq!(px_at(&m_px, 64, 61, 61), [0, 255, 0, 255]);
2179
2180 let (z_tex, _) = eng.evaluate(&comp, comp.find_node("ZoomIn").unwrap(), 0.0);
2181 assert_eq!(z_tex.size, [64, 64]);
2182 let z_px = eng.readback_rgba(&z_tex).unwrap();
2183 assert_eq!(px_at(&z_px, 64, 32, 32), [0, 255, 0, 255]);
2184 }
2185
2186 #[test]
2187 fn camera_shake_and_xf_chroma_preserve_upstream_dod_when_active() {
2188 let comp_src = r#"{
2189 Tools = ordered() {
2190 Bg = Background {
2191 Inputs = {
2192 Width = Input { Value = 64, },
2193 Height = Input { Value = 64, },
2194 TopLeftAlpha = Input { Value = 1.0, },
2195 },
2196 },
2197 HugeFg = Background {
2198 Inputs = {
2199 Width = Input { Value = 256, },
2200 Height = Input { Value = 256, },
2201 TopLeftRed = Input { Value = 1.0, },
2202 TopLeftAlpha = Input { Value = 1.0, },
2203 },
2204 },
2205 MShake = Merge {
2206 Inputs = {
2207 Background = Input { SourceOp = "Bg", Source = "Output", },
2208 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2209 },
2210 },
2211 Shake = CameraShake {
2212 Inputs = {
2213 Input = Input { SourceOp = "MShake", Source = "Output", },
2214 },
2215 },
2216 MChroma = Merge {
2217 Inputs = {
2218 Background = Input { SourceOp = "Bg", Source = "Output", },
2219 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2220 },
2221 },
2222 Chroma = Fuse.XfChroma {
2223 Inputs = {
2224 Input = Input { SourceOp = "MChroma", Source = "Output", },
2225 },
2226 },
2227 }
2228 }"#;
2229 let comp = Comp::from_fusion_str(comp_src).expect("parse dod consumers comp");
2230 let mut eng = Engine::new_headless().expect("headless engine");
2231 let mut enc = eng.device.create_command_encoder(&Default::default());
2232 let mut visiting = std::collections::HashSet::new();
2233 let mut stats = super::EvalStats::default();
2234
2235 let ms_tex = eng.eval_node(&comp, comp.find_node("MShake").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
2236 assert_eq!(ms_tex.size, [260, 260], "CameraShake must preserve full upstream DoD");
2237 let mc_tex = eng.eval_node(&comp, comp.find_node("MChroma").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
2238 assert_eq!(mc_tex.size, [260, 260], "Fuse.XfChroma must preserve full upstream DoD");
2239 eng.queue.submit(Some(enc.finish()));
2240 }
20632241}
crates/engine/src/eval/masks.rs+39-3
......@@ -254,9 +254,10 @@ impl Engine {
254254 let soft_px = soft * size[0] as f32;
255255 let need_post = soft_px >= 0.5 || invert || (level - 1.0).abs() > 1e-4 || prev_mask.is_some();
256256 let raw_tex = self.alloc_tex(size, BitDepth::Int8, if need_post { 0 } else { key });
257 let soft_px = soft * raw_tex.size[0] as f32;
257258
258 let has_coverage = match polyline_tight_commands(size, &points, [center[0] as f32, center[1] as f32], angle) {
259 Some(([bx0, by0, bx1, by1], cmds)) if raw_tex.size == size => {
259 let has_coverage = match polyline_tight_commands(raw_tex.size, &points, [center[0] as f32, center[1] as f32], angle) {
260 Some(([bx0, by0, bx1, by1], cmds)) => {
260261 let bw = (bx1 - bx0) as u32;
261262 let bh = (by1 - by0) as u32;
262263 let mut cov_buf = vec![0u8; (bw as usize) * (bh as usize)];
......@@ -279,7 +280,7 @@ impl Engine {
279280 }
280281 }
281282
282 if bw == size[0] && bh == size[1] {
283 if bw == raw_tex.size[0] && bh == raw_tex.size[1] {
283284 self.queue.write_texture(
284285 raw_tex.texture.as_image_copy(),
285286 &rgba,
......@@ -1316,4 +1317,39 @@ mod tests {
13161317 let soft_px = eng.readback_rgba(&soft_tex).unwrap();
13171318 assert_eq!(soft_px, ref_px, "SoftEdge PolylineMask must match full-canvas pixel-for-pixel");
13181319 }
1320
1321 #[test]
1322 fn polyline_mask_larger_than_max_texture_dimension_rasterizes_into_clamped_size() {
1323 let Ok(mut eng) = Engine::new_headless() else { return };
1324 let max_dim = eng.device.limits().max_texture_dimension_2d.max(1);
1325 let req_w = max_dim * 2;
1326 let comp_src = format!(
1327 r#"{{
1328 Tools = ordered() {{
1329 BigPoly = PolylineMask {{
1330 Inputs = {{
1331 MaskWidth = Input {{ Value = {req_w}, }},
1332 MaskHeight = Input {{ Value = 32, }},
1333 Polyline = Input {{
1334 Value = Polyline {{
1335 Closed = true,
1336 Points = {{
1337 {{ Linear = true, X = -0.25, Y = -0.25 }},
1338 {{ Linear = true, X = 0.25, Y = -0.25 }},
1339 {{ Linear = true, X = 0.25, Y = 0.25 }},
1340 {{ Linear = true, X = -0.25, Y = 0.25 }},
1341 }}
1342 }},
1343 }},
1344 }},
1345 }},
1346 }}
1347 }}"#
1348 );
1349 let comp = Comp::from_fusion_str(&comp_src).expect("parse clamped polyline comp");
1350 let (tex, _) = eng.evaluate(&comp, comp.find_node("BigPoly").unwrap(), 0.0);
1351 assert_eq!(tex.size, [max_dim, 16]);
1352 let px = eng.readback_rgba(&tex).unwrap();
1353 assert!(px.chunks_exact(4).any(|c| c[3] > 200), "clamped PolylineMask must rasterize cleanly instead of clearing to transparent");
1354 }
13191355}
crates/engine/src/eval/text_3d.rs+127-41
......@@ -265,7 +265,10 @@ fn scale_text_chars_x(
265265 out_x0 = out_x0.min((cx - hw).floor() as i32);
266266 out_x1 = out_x1.max((cx + hw).ceil() as i32);
267267 }
268 out_x0 = out_x0.clamp(0, cw);
268 if cw <= 0 || out_x0 >= cw || out_x1 <= 0 {
269 return ([1, 1], [0, 0], vec![0; 4]);
270 }
271 out_x0 = out_x0.clamp(0, cw - 1);
269272 out_x1 = out_x1.clamp(out_x0 + 1, cw);
270273 let out_w = (out_x1 - out_x0) as usize;
271274 let mut out = vec![0u8; out_w * th * 4];
......@@ -306,52 +309,74 @@ fn scale_text_chars_x(
306309const _: fn([u32; 2], &TextPlusParams<'_>, i32) -> ([u32; 2], [i32; 2], Vec<u8>) = rasterize_text_plus;
307310
308311fn needs_canvas_aligned_text_output(comp: &Comp, node: &Node) -> bool {
309 let mut target_names: Vec<&str> = vec![node.name.as_str()];
312 let mut queue = std::collections::VecDeque::new();
310313 let mut seen = HashSet::new();
314 queue.push_back(node.id);
311315 seen.insert(node.id);
312 for _ in 0..4 {
313 let mut added = false;
316 while let Some(cur_id) = queue.pop_front() {
317 let cur_name = comp.node(cur_id).name.as_str();
314318 for other in &comp.nodes {
315 if seen.contains(&other.id) {
316 continue;
317 }
318 let reads_target = other
319 .inputs
320 .values()
321 .any(|b| b.source_op.as_deref().is_some_and(|s| target_names.contains(&s)));
322 if !reads_target {
323 continue;
324 }
325 if other.bypassed || matches!(other.kind.as_str(), "PipeRouter" | "Fuse.Wireless") {
326 seen.insert(other.id);
327 target_names.push(other.name.as_str());
328 added = true;
329 continue;
319 let mut is_passthrough = matches!(other.kind.as_str(), "MacroOperator" | "GroupOperator")
320 && other.macro_output == Some(cur_id);
321 for (port, b) in &other.inputs {
322 if b.source_op.as_deref() != Some(cur_name) {
323 continue;
324 }
325 if other.bypassed
326 || matches!(
327 other.kind.as_str(),
328 "PipeRouter"
329 | "Fuse.Wireless"
330 | "Wireless"
331 | "Switch"
332 | "Fuse.Switch"
333 | "Fuse.SwitchElse"
334 | "MacroOperator"
335 | "GroupOperator"
336 )
337 {
338 is_passthrough = true;
339 continue;
340 }
341 if (other.kind == "Merge" && port == "Background")
342 || matches!(
343 other.kind.as_str(),
344 "pEmitter"
345 | "Renderer3D"
346 | "Displace3D"
347 | "Texture2DOperator"
348 | "TextureTransformOperator"
349 | "BumpMap"
350 | "Shape3D"
351 | "ImagePlane3D"
352 | "ReplaceMaterial3D"
353 | "TimeStretcher"
354 | "TimeSpeed"
355 | "Fuse.Outline"
356 | "ErodeDilate"
357 | "Blur"
358 | "Glow"
359 | "SoftGlow"
360 | "InvertColor"
361 | "BrightnessContrast"
362 | "ColorCorrector"
363 | "Fuse.Colorize"
364 | "VariBlur"
365 | "Filter"
366 | "ColorCurves"
367 | "HueCurves"
368 | "ColorGain"
369 | "Custom"
370 )
371 || other.kind.starts_with("Mtl")
372 {
373 return true;
374 }
330375 }
331 if matches!(
332 other.kind.as_str(),
333 "Fuse.Outline"
334 | "ErodeDilate"
335 | "Blur"
336 | "Glow"
337 | "SoftGlow"
338 | "InvertColor"
339 | "BrightnessContrast"
340 | "ColorCorrector"
341 | "Fuse.Colorize"
342 | "VariBlur"
343 | "Filter"
344 | "ColorCurves"
345 | "HueCurves"
346 | "ColorGain"
347 | "Custom"
348 ) {
349 return true;
376 if is_passthrough && seen.insert(other.id) {
377 queue.push_back(other.id);
350378 }
351379 }
352 if !added {
353 break;
354 }
355380 }
356381 false
357382}
......@@ -1494,4 +1519,65 @@ Composition {
14941519 let cov_tm = px_tm.chunks_exact(4).filter(|c| c[3] > 200).count();
14951520 assert!(cov_ed > cov_tm + 50, "ErodeDilate downstream of TextPlus must dilate using canvas width: {cov_ed} vs {cov_tm}");
14961521 }
1522
1523 #[test]
1524 fn offscreen_right_text3d_with_char_size_x_does_not_panic() {
1525 let (sz, orig, px) = super::scale_text_chars_x([8, 8], [150, 10], [128, 128], vec![255; 8 * 8 * 4], 1.5);
1526 assert_eq!(sz, [1, 1]);
1527 assert_eq!(orig, [0, 0]);
1528 assert_eq!(px, vec![0; 4]);
1529
1530 let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() {
1531 T = Text3D { Inputs = {
1532 StyledText = Input { Value = "OFF", },
1533 Size = Input { Value = 0.25, },
1534 Center = Input { Value = { 1.5, 0.5 }, },
1535 CharacterSizeX = Input { Value = 1.5, },
1536 }, },
1537 Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, }, },
1538 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "T", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },
1539 R = Renderer3D { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, SceneInput = Input { SourceOp = "M", Source = "Output", }, }, },
1540 } }"#;
1541 let comp = Comp::from_fusion_str(src).unwrap();
1542 let Ok(mut eng) = Engine::new_headless() else { return };
1543 let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0);
1544 assert_eq!(tex.size, [128, 128]);
1545 }
1546
1547 #[test]
1548 fn text_plus_feeding_merge_background_and_time_speed_gets_canvas_aligned_output() {
1549 let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 5 }, GlobalRange = { 0, 5 }, Tools = ordered() {
1550 TxtBg = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "BG", }, Size = Input { Value = 0.2, }, }, },
1551 TxtFg = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "FG", }, Size = Input { Value = 0.2, }, }, },
1552 M = Merge { Inputs = {
1553 Background = Input { SourceOp = "TxtBg", Source = "Output", },
1554 Foreground = Input { SourceOp = "TxtFg", Source = "Output", },
1555 }, },
1556 TxtTime = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "TM", }, Size = Input { Value = 0.2, }, }, },
1557 P1 = PipeRouter { Inputs = { Input = Input { SourceOp = "TxtTime", Source = "Output", }, }, },
1558 P2 = PipeRouter { Inputs = { Input = Input { SourceOp = "P1", Source = "Output", }, }, },
1559 P3 = PipeRouter { Inputs = { Input = Input { SourceOp = "P2", Source = "Output", }, }, },
1560 P4 = PipeRouter { Inputs = { Input = Input { SourceOp = "P3", Source = "Output", }, }, },
1561 Sw = Fuse.Switch { Inputs = { Input1 = Input { SourceOp = "P4", Source = "Output", }, }, },
1562 TS = TimeSpeed { Inputs = { Speed = Input { Value = 1.0, }, Input = Input { SourceOp = "Sw", Source = "Output", }, }, },
1563 } }"#;
1564 let comp = Comp::from_fusion_str(src).unwrap();
1565 assert!(super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtBg").unwrap())));
1566 assert!(!super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtFg").unwrap())));
1567 assert!(super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtTime").unwrap())));
1568
1569 let Ok(mut eng) = Engine::new_headless() else { return };
1570 let mut enc = eng.device.create_command_encoder(&Default::default());
1571 let mut visiting = std::collections::HashSet::new();
1572 let mut stats = super::EvalStats::default();
1573 let t_bg = eng.eval_node(&comp, comp.find_node("TxtBg").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
1574 assert_eq!(t_bg.origin, [0, 0]);
1575 assert_eq!(t_bg.size, [128, 64]);
1576 let t_fg = eng.eval_node(&comp, comp.find_node("TxtFg").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
1577 assert!(t_fg.has_dod(), "TextPlus feeding only Merge.Foreground keeps tight DoD");
1578 let t_time = eng.eval_node(&comp, comp.find_node("TxtTime").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
1579 assert_eq!(t_time.origin, [0, 0]);
1580 assert_eq!(t_time.size, [128, 64]);
1581 eng.queue.submit(Some(enc.finish()));
1582 }
14971583}
crates/model/src/comp/eval.rs+77-18
......@@ -13,6 +13,13 @@ thread_local! {
1313 RefCell::new((0, HashMap::new()));
1414}
1515
16/// Parses a bare `NodeName.ParamName` reference where both segments are identifier characters.
17fn parse_bare_node_param_ref(expr: &str) -> Option<(&str, &str)> {
18 let (n, p) = expr.trim().split_once('.')?;
19 let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
20 (ident(n) && ident(p)).then_some((n, p))
21}
22
1623fn is_lua_keyword(tok: &str) -> bool {
1724 matches!(
1825 tok,
......@@ -153,11 +160,9 @@ impl Comp {
153160 }
154161 if let Some(expr) = &binding.expression {
155162 // A bare `Node.Param` follows that input's own expression/animation instead of its baked value.
156 let referenced = expr.trim().split_once('.').and_then(|(n, p)| {
157 let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
158 (ident(n) && ident(p)).then_some((n, p))
159 });
160 let v = match referenced.and_then(|(n, p)| Some((self.node(self.find_node(n)?), p))) {
163 let v = match parse_bare_node_param_ref(expr)
164 .and_then(|(n, p)| Some((self.node(self.find_node(n)?), p)))
165 {
161166 Some((other, p)) if other.inputs.contains_key(p) && other.id != node.id => {
162167 Some(self.eval_number_at(other, p, time, f64::NAN, expr_engine, depth + 1))
163168 }
......@@ -429,10 +434,10 @@ impl Comp {
429434 if let Some(expr) = &b.expression {
430435 let trimmed = expr.trim();
431436 // Direct `NodeName.ParamName` reference to a Point input on another flow node.
432 if let Some((node_name, param_name)) = trimmed.split_once('.') {
433 if !param_name.contains('.') && !param_name.contains(' ') {
434 if let Some(nid) = self.find_node(node_name.trim()) {
435 return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1);
437 if let Some((node_name, param_name)) = parse_bare_node_param_ref(trimmed) {
438 if let Some(other) = self.find_node(node_name).map(|nid| self.node(nid)) {
439 if other.inputs.contains_key(param_name) {
440 return self.eval_point_at(other, param_name, time, default, expr_engine, depth + 1);
436441 }
437442 }
438443 }
......@@ -479,12 +484,12 @@ impl Comp {
479484 depth: usize,
480485 ) -> Option<f64> {
481486 let trimmed = expr.trim();
482 if let Some((node_name, param_name)) = trimmed.split_once('.') {
483 if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') {
484 if let Some(nid) = self.find_node(node_name.trim()) {
487 if let Some((node_name, param_name)) = parse_bare_node_param_ref(trimmed) {
488 if let Some(other) = self.find_node(node_name).map(|nid| self.node(nid)) {
489 if other.inputs.contains_key(param_name) {
485490 return Some(self.eval_number_at(
486 self.node(nid),
487 param_name.trim(),
491 other,
492 param_name,
488493 time,
489494 0.0,
490495 expr_engine,
......@@ -497,7 +502,7 @@ impl Comp {
497502 expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en)
498503 }
499504
500 /// `node name -> numeric/text inputs` for the nodes `expr` can reach; every other node is skipped.
505 /// `node name -> numeric/text/point inputs` for the nodes `expr` can reach; every other node is skipped.
501506 fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, ExprValue>> {
502507 let mut env = HashMap::new();
503508 for tok in expr
......@@ -511,7 +516,7 @@ impl Comp {
511516 .map(|n| (n.name.clone(), self.node_expr_vars(n, time)))
512517 .collect();
513518 }
514 if tok == "self" || is_lua_keyword(tok) || env.contains_key(tok) {
519 if is_lua_keyword(tok) || env.contains_key(tok) {
515520 continue;
516521 }
517522 if let Some(nid) = self.find_node(tok) {
......@@ -534,10 +539,24 @@ impl Comp {
534539 vars.insert(k.clone(), ExprValue::Text(t.clone()));
535540 continue;
536541 }
542 Some(ParamValue::Point(pt)) => {
543 vars.insert(k.clone(), ExprValue::Point(*pt));
544 continue;
545 }
537546 _ => {}
538547 }
539 if let Some(sp) = b.source_op.as_ref().and_then(|src| self.splines.get(src)) {
540 vars.insert(k.clone(), ExprValue::Number(sp.eval(time)));
548 if let Some(src) = b.source_op.as_deref() {
549 if let Some(sp) = self.splines.get(src) {
550 vars.insert(k.clone(), ExprValue::Number(sp.eval(time)));
551 } else if let Some(pp) = self.poly_paths.get(src) {
552 let disp = pp
553 .displacement_op
554 .as_deref()
555 .and_then(|d| self.splines.get(d))
556 .map(|sp| sp.eval(time))
557 .unwrap_or(pp.displacement_value);
558 vars.insert(k.clone(), ExprValue::Point(pp.eval_center(disp)));
559 }
541560 }
542561 }
543562 vars
......@@ -998,4 +1017,44 @@ mod tests {
9981017 assert_eq!(comp.checker_piece_metrics(node("Tiny"), 0.0, &engine), (2, 0.2));
9991018 assert_eq!(comp.eval_number(m, "Angle", 0.0, 7.0, &engine), 7.0, "non-ExtraScale outputs stay unresolved");
10001019 }
1020
1021 #[test]
1022 fn expression_modifier_spaceless_arithmetic_and_self_named_node() {
1023 let src = r#"Composition {
1024 Tools = ordered() {
1025 BG1 = Background { Inputs = {
1026 Width = Input { Value = 320, },
1027 Center = Input { Value = { 0.25, 0.5 }, },
1028 }, },
1029 self = Background { Inputs = {
1030 Width = Input { Value = 100, },
1031 }, },
1032 Out = Transform { Inputs = {
1033 Size = Input { SourceOp = "NumMod", Source = "NumberResult", },
1034 Center = Input { SourceOp = "PtMod", Source = "PointResult", },
1035 Angle = Input { SourceOp = "SelfMod", Source = "NumberResult", },
1036 }, },
1037 NumMod = Expression { Inputs = {
1038 n1 = Input { Expression = "BG1.Width*2", },
1039 NumberExpression = Input { Value = "n1", },
1040 }, },
1041 PtMod = Expression { Inputs = {
1042 p1 = Input { Expression = "BG1.Center+Point(0.1,0)", },
1043 PointExpressionX = Input { Value = "p1x", },
1044 PointExpressionY = Input { Value = "p1y", },
1045 }, },
1046 SelfMod = Expression { Inputs = {
1047 n1 = Input { Expression = "self.Width*3", },
1048 NumberExpression = Input { Value = "n1", },
1049 }, },
1050 }
1051 }"#;
1052 let comp = Comp::from_fusion_str(src).unwrap();
1053 let engine = ExprEngine::new();
1054 let out = comp.node(comp.find_node("Out").unwrap());
1055 assert_eq!(comp.eval_number(out, "Size", 0.0, -1.0, &engine), 640.0);
1056 let c = comp.eval_point(out, "Center", 0.0, [0.0, 0.0], &engine);
1057 assert!((c[0] - 0.35).abs() < 1e-12 && (c[1] - 0.5).abs() < 1e-12, "got {c:?}");
1058 assert_eq!(comp.eval_number(out, "Angle", 0.0, -1.0, &engine), 300.0);
1059 }
10011060}
crates/model/src/expr.rs+267-28
......@@ -9,6 +9,7 @@
99pub enum ExprValue {
1010 Number(f64),
1111 Text(String),
12 Point([f64; 2]),
1213}
1314
1415/// Lua's `tostring` for a float: C `%.14g`, so `0.1 + 0.2` reads `0.3` and `3.0` reads `3`.
......@@ -54,6 +55,56 @@ mod lua {
5455 /// Max compiled expression bytecodes cached per `ExprEngine`.
5556 const CHUNK_CACHE_CAP: usize = 512;
5657
58 /// Bounded LRU cache of compiled Lua chunk bytecodes (`None` for cached syntax errors).
59 struct ChunkCache {
60 entries: HashMap<String, (Option<Vec<u8>>, u64)>,
61 tick: u64,
62 }
63
64 impl ChunkCache {
65 fn new() -> Self {
66 Self {
67 entries: HashMap::new(),
68 tick: 0,
69 }
70 }
71
72 #[cfg(test)]
73 fn len(&self) -> usize {
74 self.entries.len()
75 }
76
77 #[cfg(test)]
78 fn get(&self, key: &str) -> Option<&Option<Vec<u8>>> {
79 self.entries.get(key).map(|(v, _)| v)
80 }
81
82 fn touch(&mut self, key: &str) -> Option<&Option<Vec<u8>>> {
83 let next = self.tick.wrapping_add(1);
84 self.tick = next;
85 self.entries.get_mut(key).map(|(v, t)| {
86 *t = next;
87 &*v
88 })
89 }
90
91 fn insert(&mut self, key: String, val: Option<Vec<u8>>) {
92 let next = self.tick.wrapping_add(1);
93 self.tick = next;
94 if !self.entries.contains_key(&key) && self.entries.len() >= CHUNK_CACHE_CAP {
95 if let Some(oldest) = self
96 .entries
97 .iter()
98 .min_by_key(|(_, (_, t))| *t)
99 .map(|(k, _)| k.clone())
100 {
101 self.entries.remove(&oldest);
102 }
103 }
104 self.entries.insert(key, (val, next));
105 }
106 }
107
57108 /// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`,
58109 /// no code loading, and bounded instructions and memory per evaluation.
59110 pub struct ExprEngine {
......@@ -64,7 +115,8 @@ mod lua {
64115 env_mt: Table,
65116 zero_mt: Table,
66117 text_mt: Table,
67 chunk_cache: RefCell<HashMap<String, Option<Vec<u8>>>>,
118 point_mt: Table,
119 chunk_cache: RefCell<ChunkCache>,
68120 }
69121
70122 impl Default for ExprEngine {
......@@ -105,7 +157,6 @@ mod lua {
105157 tan = math.tan
106158 tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end
107159 iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end
108 Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end
109160 local lua_tostring = tostring
110161 tostring = function(v) if type(v) == "number" then return string.format("%.14g", v) end return lua_tostring(v) end
111162 Text = function(s) return tostring(s or "") end
......@@ -115,6 +166,108 @@ mod lua {
115166 let _ = lua.load(init).exec();
116167
117168 let globals = lua.globals();
169 let point_mt = lua.create_table().expect("table creates");
170 let make_pt = |lua: &Lua, mt: &Table, x: f64, y: f64| -> mlua::Result<Table> {
171 let pt = lua.create_table()?;
172 pt.set("X", x)?;
173 pt.set("Y", y)?;
174 pt.set(1, x)?;
175 pt.set(2, y)?;
176 pt.set_metatable(Some(mt.clone()));
177 Ok(pt)
178 };
179 let read_pt = |v: &Value| -> Option<[f64; 2]> {
180 let Value::Table(t) = v else { return None };
181 let x = t.get::<f64>("X").or_else(|_| t.get::<f64>(1)).ok()?;
182 let y = t.get::<f64>("Y").or_else(|_| t.get::<f64>(2)).ok()?;
183 Some([x, y])
184 };
185 let read_num = |v: &Value| -> Option<f64> {
186 match v {
187 Value::Number(n) => Some(*n),
188 Value::Integer(i) => Some(*i as f64),
189 _ => None,
190 }
191 };
192 let mt_ref = point_mt.clone();
193 point_mt
194 .set(
195 "__add",
196 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
197 let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else {
198 return Err(mlua::Error::runtime("Point addition requires two Points"));
199 };
200 make_pt(lua, &mt_ref, ax + bx, ay + by)
201 })
202 .expect("function creates"),
203 )
204 .expect("table sets");
205 let mt_ref = point_mt.clone();
206 point_mt
207 .set(
208 "__sub",
209 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
210 let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else {
211 return Err(mlua::Error::runtime("Point subtraction requires two Points"));
212 };
213 make_pt(lua, &mt_ref, ax - bx, ay - by)
214 })
215 .expect("function creates"),
216 )
217 .expect("table sets");
218 let mt_ref = point_mt.clone();
219 point_mt
220 .set(
221 "__mul",
222 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
223 match (read_pt(&a), read_pt(&b), read_num(&a), read_num(&b)) {
224 (Some([ax, ay]), Some([bx, by]), _, _) => make_pt(lua, &mt_ref, ax * bx, ay * by),
225 (Some([ax, ay]), None, _, Some(s)) | (None, Some([ax, ay]), Some(s), _) => {
226 make_pt(lua, &mt_ref, ax * s, ay * s)
227 }
228 _ => Err(mlua::Error::runtime("invalid Point multiplication")),
229 }
230 })
231 .expect("function creates"),
232 )
233 .expect("table sets");
234 let mt_ref = point_mt.clone();
235 point_mt
236 .set(
237 "__div",
238 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
239 match (read_pt(&a), read_pt(&b), read_num(&b)) {
240 (Some([ax, ay]), Some([bx, by]), _) => make_pt(lua, &mt_ref, ax / bx, ay / by),
241 (Some([ax, ay]), None, Some(s)) => make_pt(lua, &mt_ref, ax / s, ay / s),
242 _ => Err(mlua::Error::runtime("invalid Point division")),
243 }
244 })
245 .expect("function creates"),
246 )
247 .expect("table sets");
248 let mt_ref = point_mt.clone();
249 point_mt
250 .set(
251 "__unm",
252 lua.create_function(move |lua, a: Value| -> mlua::Result<Table> {
253 let Some([ax, ay]) = read_pt(&a) else {
254 return Err(mlua::Error::runtime("invalid Point negation"));
255 };
256 make_pt(lua, &mt_ref, -ax, -ay)
257 })
258 .expect("function creates"),
259 )
260 .expect("table sets");
261 let mt_ref = point_mt.clone();
262 globals
263 .set(
264 "Point",
265 lua.create_function(move |lua, (x, y): (Option<f64>, Option<f64>)| {
266 make_pt(lua, &mt_ref, x.unwrap_or(0.0), y.unwrap_or(0.0))
267 })
268 .expect("function creates"),
269 )
270 .expect("global sets");
118271 // Stdlib tables become write-protected proxies so no evaluation can alter them for the next.
119272 let read_only = lua
120273 .create_function(|_, _: MultiValue| -> mlua::Result<()> {
......@@ -180,14 +333,15 @@ mod lua {
180333 env_mt,
181334 zero_mt,
182335 text_mt,
183 chunk_cache: RefCell::new(HashMap::new()),
336 point_mt,
337 chunk_cache: RefCell::new(ChunkCache::new()),
184338 }
185339 }
186340
187341 fn load_cached(&self, expr: &str, env: Table) -> Option<Function> {
188342 {
189 let cache = self.chunk_cache.borrow();
190 if let Some(hit) = cache.get(expr) {
343 let mut cache = self.chunk_cache.borrow_mut();
344 if let Some(hit) = cache.touch(expr) {
191345 let bytes = hit.as_ref()?;
192346 return self
193347 .lua
......@@ -199,26 +353,24 @@ mod lua {
199353 }
200354 }
201355 let chunk_src = Self::expr_chunk(expr);
202 let compiled = self
356 match self
203357 .lua
204358 .load(&chunk_src)
359 .set_mode(ChunkMode::Text)
360 .set_environment(env)
205361 .into_function()
206 .ok()
207 .map(|f| f.dump(true));
208 let func = compiled.as_ref().and_then(|bytes| {
209 self.lua
210 .load(bytes.as_slice())
211 .set_mode(ChunkMode::Binary)
212 .set_environment(env)
213 .into_function()
214 .ok()
215 });
216 let mut cache = self.chunk_cache.borrow_mut();
217 if cache.len() >= CHUNK_CACHE_CAP {
218 cache.clear();
362 {
363 Ok(func) => {
364 let bytes = func.dump(true);
365 self.chunk_cache.borrow_mut().insert(expr.to_owned(), Some(bytes));
366 Some(func)
367 }
368 Err(mlua::Error::SyntaxError { .. }) => {
369 self.chunk_cache.borrow_mut().insert(expr.to_owned(), None);
370 None
371 }
372 Err(_) => None,
219373 }
220 cache.insert(expr.to_owned(), compiled);
221 func
222374 }
223375
224376 /// Evaluates `expr` in a fresh environment with a fresh instruction budget.
......@@ -304,6 +456,16 @@ mod lua {
304456 }
305457 }
306458
459 fn make_point(&self, p: [f64; 2]) -> mlua::Result<Table> {
460 let pt = self.lua.create_table()?;
461 pt.set("X", p[0])?;
462 pt.set("Y", p[1])?;
463 pt.set(1, p[0])?;
464 pt.set(2, p[1])?;
465 pt.set_metatable(Some(self.point_mt.clone()));
466 Ok(pt)
467 }
468
307469 fn build_env(
308470 &self,
309471 time: f64,
......@@ -319,12 +481,7 @@ mod lua {
319481 env.set(k.as_str(), *v)?;
320482 }
321483 for (k, p) in self_points {
322 let pt = self.lua.create_table()?;
323 pt.set("X", p[0])?;
324 pt.set("Y", p[1])?;
325 pt.set(1, p[0])?;
326 pt.set(2, p[1])?;
327 env.set(k.as_str(), pt)?;
484 env.set(k.as_str(), self.make_point(*p)?)?;
328485 }
329486 // Missing node fields default to 0 so expressions don't nil-crash.
330487 for (node_name, params) in env_nodes {
......@@ -338,6 +495,7 @@ mod lua {
338495 text.set_metatable(Some(self.text_mt.clone()));
339496 nt.set(pk.as_str(), text)?;
340497 }
498 ExprValue::Point(p) => nt.set(pk.as_str(), self.make_point(*p)?)?,
341499 }
342500 }
343501 nt.set_metatable(Some(self.zero_mt.clone()));
......@@ -453,6 +611,66 @@ mod lua {
453611 assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &HashMap::new()), None);
454612 assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None));
455613 }
614
615 #[test]
616 fn binary_bytecode_prefix_is_rejected_in_text_mode() {
617 let engine = ExprEngine::new();
618 let empty = HashMap::new();
619 // Even with a Lua binary signature `\x1bLua...`, ChunkMode::Text rejects it safely.
620 for bad in [":\x1bLua", ":\x1bLuaT\0\x19\x0d\x0a\x1a\x0a", "\x1bLua"] {
621 assert_eq!(engine.eval_number(bad, 0.0, &HashMap::new(), &HashMap::new(), &empty), None);
622 assert_eq!(engine.chunk_cache.borrow().get(bad), Some(&None));
623 }
624 // Valid expressions continue to evaluate cleanly afterwards.
625 assert_eq!(engine.eval_number("2 + 3", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(5.0));
626 }
627
628 #[test]
629 fn syntax_vs_runtime_and_memory_error_caching_and_lru() {
630 let engine = ExprEngine::new();
631 let empty = HashMap::new();
632
633 // SyntaxError is negative-cached as None.
634 assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &empty), None);
635 assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None));
636
637 // Runtime error compiles cleanly (cached as Some(bytecode)), fails on call, and doesn't poison valid runs.
638 assert_eq!(
639 engine.eval_number("1 + nil", 0.0, &HashMap::new(), &HashMap::new(), &empty),
640 None
641 );
642 assert!(matches!(engine.chunk_cache.borrow().get("1 + nil"), Some(Some(_))));
643
644 // MemoryError during compilation is NOT negative-cached.
645 engine.lua.set_memory_limit(1).expect("tight limit applies");
646 let mem_expr = format!("1{}", " + 1".repeat(200));
647 assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), None);
648 assert_eq!(engine.chunk_cache.borrow().get(&mem_expr), None);
649 engine.lua.set_memory_limit(MEMORY_LIMIT).expect("restore memory limit");
650 assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(201.0));
651 assert!(matches!(engine.chunk_cache.borrow().get(&mem_expr), Some(Some(_))));
652
653 // LRU eviction keeps hot entries when exceeding CHUNK_CACHE_CAP.
654 let lru_engine = ExprEngine::new();
655 for i in 0..CHUNK_CACHE_CAP {
656 let expr = format!("{i} + 1");
657 assert_eq!(
658 lru_engine.eval_number(&expr, 0.0, &HashMap::new(), &HashMap::new(), &empty),
659 Some((i + 1) as f64)
660 );
661 }
662 assert_eq!(lru_engine.chunk_cache.borrow().len(), CHUNK_CACHE_CAP);
663 // Touch entry 0 so entry 1 becomes the least recently used.
664 assert_eq!(lru_engine.eval_number("0 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(1.0));
665 assert_eq!(
666 lru_engine.eval_number("9999 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty),
667 Some(10000.0)
668 );
669 let cache = lru_engine.chunk_cache.borrow();
670 assert_eq!(cache.len(), CHUNK_CACHE_CAP);
671 assert!(cache.get("0 + 1").is_some(), "hot entry 0 must stay in LRU cache");
672 assert!(cache.get("1 + 1").is_none(), "cold entry 1 must be evicted");
673 }
456674 }
457675}
458676
......@@ -809,7 +1027,10 @@ mod pure {
8091027 Ast::Num(n) | Ast::Int(n) => Val::Num(*n),
8101028 Ast::Str(s) => Val::Str(s.clone()),
8111029 Ast::Name(n) => self.name(n),
812 Ast::Neg(a) => Val::Num(-self.eval(a)?.num()?),
1030 Ast::Neg(a) => match self.eval(a)? {
1031 Val::Point([x, y]) => Val::Point([-x, -y]),
1032 v => Val::Num(-v.num()?),
1033 },
8131034 Ast::Not(a) => Val::Bool(!self.eval(a)?.truthy()),
8141035 Ast::Index(base, key) => index(self.eval(base)?, self.eval(key)?)?,
8151036 Ast::Call(callee, args) => {
......@@ -853,6 +1074,7 @@ mod pure {
8531074 Val::Str(k) => match fields.get(&k) {
8541075 Some(ExprValue::Number(n)) => Val::Num(*n),
8551076 Some(ExprValue::Text(s)) => Val::Text(s.clone()),
1077 Some(ExprValue::Point(p)) => Val::Point(*p),
8561078 None => Val::Num(0.0),
8571079 },
8581080 _ => Val::Num(0.0),
......@@ -888,6 +1110,23 @@ mod pure {
8881110 ">" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o == Ordering::Greater)),
8891111 ">=" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o != Ordering::Less)),
8901112 ".." => Val::Str(a.text()? + &b.text()?),
1113 "+" | "-" | "*" | "/" if matches!((&a, &b), (Val::Point(_), _) | (_, Val::Point(_))) => {
1114 match (op, a, b) {
1115 ("+", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax + bx, ay + by]),
1116 ("-", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax - bx, ay - by]),
1117 ("*", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax * bx, ay * by]),
1118 ("/", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax / bx, ay / by]),
1119 ("*", Val::Point([ax, ay]), other) | ("*", other, Val::Point([ax, ay])) => {
1120 let s = other.num()?;
1121 Val::Point([ax * s, ay * s])
1122 }
1123 ("/", Val::Point([ax, ay]), other) => {
1124 let s = other.num()?;
1125 Val::Point([ax / s, ay / s])
1126 }
1127 _ => return None,
1128 }
1129 }
8911130 _ => {
8921131 let (a, b) = (a.num()?, b.num()?);
8931132 Val::Num(match op {