| author | |
| committer | |
| log | f67c492be699a101af979c04841a9dc40a8faf58 |
| tree | 811424034e408c9384652c916c0dada83e7592d0 |
| parent | 24841f6551d2b6b4acea25c5b794813845c8bb30 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
4 files changed, 413 insertions(+), 123 deletions(-)
crates/engine/src/eval/mod.rs+82-20| ... | ... | @@ -81,10 +81,14 @@ pub struct Engine { |
| 81 | 81 | pub expr: ExprEngine, |
| 82 | 82 | /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. |
| 83 | 83 | frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, |
| 84 | /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current frame. | |
| 84 | /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current comp revision. | |
| 85 | 85 | frame_consumers: Vec<Vec<(NodeId, String)>>, |
| 86 | /// Comp revision for which `frame_consumers` was built, so steady-state frames skip rebuilding it. | |
| 87 | frame_consumers_rev: Option<u64>, | |
| 86 | 88 | /// Per-evaluation memo of conservative downstream RoI bounds `(node_id, time_bits)`. |
| 87 | 89 | frame_roi_memo: HashMap<(NodeId, i64), Option<composite::RoiBox>>, |
| 90 | /// Reusable cycle-detection set for `eval_node` across frames. | |
| 91 | frame_visiting: HashSet<(NodeId, i64)>, | |
| 88 | 92 | output_cache: OutputCache, |
| 89 | 93 | /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default |
| 90 | 94 | /// to matching the dimensions & aspect ratio of the node they mask!). |
| ... | ... | @@ -136,7 +140,9 @@ impl Engine { |
| 136 | 140 | expr: ExprEngine::new(), |
| 137 | 141 | frame_memo: HashMap::new(), |
| 138 | 142 | frame_consumers: Vec::new(), |
| 143 | frame_consumers_rev: None, | |
| 139 | 144 | frame_roi_memo: HashMap::new(), |
| 145 | frame_visiting: HashSet::new(), | |
| 140 | 146 | output_cache: OutputCache::new(), |
| 141 | 147 | mask_target_size: None, |
| 142 | 148 | proxy_scale: 1, |
| ... | ... | @@ -242,6 +248,8 @@ impl Engine { |
| 242 | 248 | self.particles.clear(); |
| 243 | 249 | self.sprite_cache.clear(); |
| 244 | 250 | self.scene3d.clear_shadow_targets(); |
| 251 | self.frame_consumers.clear(); | |
| 252 | self.frame_consumers_rev = None; | |
| 245 | 253 | *self.ram_upload_tex.borrow_mut() = None; |
| 246 | 254 | io::clear_dims_cache(); |
| 247 | 255 | } |
| ... | ... | @@ -267,6 +275,27 @@ impl Engine { |
| 267 | 275 | self.cache.bust_subtree(node) |
| 268 | 276 | } |
| 269 | 277 | |
| 278 | fn prepare_frame_scratch(&mut self, comp: &Comp) -> HashSet<(NodeId, i64)> { | |
| 279 | self.frame_memo.clear(); | |
| 280 | self.frame_roi_memo.clear(); | |
| 281 | if self.frame_consumers_rev != Some(comp.revision) | |
| 282 | || self.frame_consumers.len() != comp.nodes.len() | |
| 283 | { | |
| 284 | self.frame_consumers.clear(); | |
| 285 | self.frame_consumers_rev = Some(comp.revision); | |
| 286 | } | |
| 287 | let mut visiting = std::mem::take(&mut self.frame_visiting); | |
| 288 | visiting.clear(); | |
| 289 | visiting | |
| 290 | } | |
| 291 | ||
| 292 | fn finish_frame_scratch(&mut self, mut visiting: HashSet<(NodeId, i64)>) { | |
| 293 | self.frame_memo.clear(); | |
| 294 | self.frame_roi_memo.clear(); | |
| 295 | visiting.clear(); | |
| 296 | self.frame_visiting = visiting; | |
| 297 | } | |
| 298 | ||
| 270 | 299 | /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. |
| 271 | 300 | pub fn evaluate( |
| 272 | 301 | &mut self, |
| ... | ... | @@ -292,10 +321,7 @@ impl Engine { |
| 292 | 321 | let mut stats = EvalStats::default(); |
| 293 | 322 | self.media |
| 294 | 323 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 295 | let mut visiting = HashSet::with_capacity(comp.nodes.len().min(64)); | |
| 296 | self.frame_memo.clear(); | |
| 297 | self.frame_consumers.clear(); | |
| 298 | self.frame_roi_memo.clear(); | |
| 324 | let mut visiting = self.prepare_frame_scratch(comp); | |
| 299 | 325 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 300 | 326 | label: Some("comp-eval"), |
| 301 | 327 | }); |
| ... | ... | @@ -306,9 +332,7 @@ impl Engine { |
| 306 | 332 | tex = self.crop_to_canvas(&mut encoder, tex); |
| 307 | 333 | } |
| 308 | 334 | self.queue.submit(Some(encoder.finish())); |
| 309 | self.frame_memo.clear(); | |
| 310 | self.frame_consumers.clear(); | |
| 311 | self.frame_roi_memo.clear(); | |
| 335 | self.finish_frame_scratch(visiting); | |
| 312 | 336 | self.cache.flush_pending_pool(); |
| 313 | 337 | self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); |
| 314 | 338 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| ... | ... | @@ -335,19 +359,16 @@ impl Engine { |
| 335 | 359 | label: Some("comp-viewer-eval"), |
| 336 | 360 | }); |
| 337 | 361 | |
| 338 | let (tex, need_output_insert) = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { | |
| 362 | let (tex, visiting_opt) = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { | |
| 339 | 363 | stats.cache_hits = 1; |
| 340 | 364 | stats.unsupported_nodes = unsupported; |
| 341 | (cached, false) | |
| 365 | (cached, None) | |
| 342 | 366 | } else { |
| 343 | 367 | self.media |
| 344 | 368 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 345 | let mut visiting = HashSet::with_capacity(comp.nodes.len().min(64)); | |
| 346 | self.frame_memo.clear(); | |
| 347 | self.frame_consumers.clear(); | |
| 348 | self.frame_roi_memo.clear(); | |
| 369 | let mut visiting = self.prepare_frame_scratch(comp); | |
| 349 | 370 | let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 350 | (t, true) | |
| 371 | (t, Some(visiting)) | |
| 351 | 372 | }; |
| 352 | 373 | |
| 353 | 374 | let dst_size = [dst_texture.width(), dst_texture.height()]; |
| ... | ... | @@ -381,13 +402,11 @@ impl Engine { |
| 381 | 402 | ); |
| 382 | 403 | |
| 383 | 404 | self.queue.submit(Some(encoder.finish())); |
| 384 | self.frame_memo.clear(); | |
| 385 | self.frame_consumers.clear(); | |
| 386 | self.frame_roi_memo.clear(); | |
| 387 | self.cache.flush_pending_pool(); | |
| 388 | if need_output_insert { | |
| 405 | if let Some(visiting) = visiting_opt { | |
| 406 | self.finish_frame_scratch(visiting); | |
| 389 | 407 | self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); |
| 390 | 408 | } |
| 409 | self.cache.flush_pending_pool(); | |
| 391 | 410 | |
| 392 | 411 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 393 | 412 | stats.cached_entries = self.cache.entry_count(); |
| ... | ... | @@ -1389,4 +1408,47 @@ Composition { |
| 1389 | 1408 | // InterpolateBetweenFrames=0 rounds half-up via floor(x + 0.5): 13.5 -> 14 -> (14 - (-10))/50 = 0.48 -> 122 |
| 1390 | 1409 | assert!((red_at(&mut eng, "StrSnap", 0.0) as i32 - 122).abs() <= 2); |
| 1391 | 1410 | } |
| 1411 | ||
| 1412 | #[test] | |
| 1413 | fn frame_consumers_persist_within_revision_and_rebuild_on_edit() { | |
| 1414 | let src = r#" | |
| 1415 | Composition { | |
| 1416 | CurrentTime = 0, | |
| 1417 | RenderRange = { 0, 2 }, | |
| 1418 | GlobalRange = { 0, 2 }, | |
| 1419 | Tools = ordered() { | |
| 1420 | BG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, | |
| 1421 | FG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 1.0, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, | |
| 1422 | FG2 = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, | |
| 1423 | M = Merge { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Foreground = Input { SourceOp = "FG", Source = "Output", }, }, }, | |
| 1424 | }, | |
| 1425 | } | |
| 1426 | "#; | |
| 1427 | let mut comp = Comp::from_fusion_str(src).expect("parse merge comp"); | |
| 1428 | let Ok(mut eng) = Engine::new_headless() else { | |
| 1429 | return; | |
| 1430 | }; | |
| 1431 | let m_id = comp.find_node("M").unwrap(); | |
| 1432 | let fg_id = comp.find_node("FG").unwrap(); | |
| 1433 | let fg2_id = comp.find_node("FG2").unwrap(); | |
| 1434 | ||
| 1435 | let _ = eng.evaluate(&comp, m_id, 0.0); | |
| 1436 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); | |
| 1437 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); | |
| 1438 | assert!(eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); | |
| 1439 | ||
| 1440 | // Second frame at same revision keeps the cached adjacency table instead of clearing it. | |
| 1441 | let _ = eng.evaluate(&comp, m_id, 1.0); | |
| 1442 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); | |
| 1443 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); | |
| 1444 | assert!(eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); | |
| 1445 | ||
| 1446 | // Mutating the comp increments comp.revision and refreshes frame_consumers on next eval. | |
| 1447 | comp.connect_output(fg2_id, "Output", m_id, "Foreground").unwrap(); | |
| 1448 | let _ = eng.evaluate(&comp, m_id, 1.0); | |
| 1449 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); | |
| 1450 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); | |
| 1451 | assert!(!eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); | |
| 1452 | assert!(eng.frame_consumers[fg2_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); | |
| 1453 | } | |
| 1392 | 1454 | } |
crates/model/src/comp/eval.rs+183-63| ... | ... | @@ -1,44 +1,65 @@ |
| 1 | 1 | use super::math::eval_fusion_math_expr; |
| 2 | use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier}; | |
| 2 | use super::{ClsEntry, Comp, ExpressionModifier, InputBinding, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier}; | |
| 3 | 3 | use crate::expr::{ExprEngine, ExprValue}; |
| 4 | 4 | use crate::spline::Gradient; |
| 5 | 5 | use std::cell::RefCell; |
| 6 | use std::collections::{HashMap, HashSet}; | |
| 6 | use std::collections::HashMap; | |
| 7 | 7 | |
| 8 | 8 | /// `(modifier address, output tag, time bits)`. |
| 9 | 9 | type ModMemoKey = (usize, u8, u64); |
| 10 | 10 | |
| 11 | 11 | thread_local! { |
| 12 | static EXPR_MOD_MEMO: RefCell<Option<HashMap<ModMemoKey, Option<[f64; 2]>>>> = const { RefCell::new(None) }; | |
| 12 | static EXPR_MOD_MEMO: RefCell<(usize, HashMap<ModMemoKey, Option<[f64; 2]>>)> = | |
| 13 | RefCell::new((0, HashMap::new())); | |
| 13 | 14 | } |
| 14 | 15 | |
| 15 | /// Identifiers `expr` can look up, or `None` when `_ENV`/`_G` allow lookups by computed name. | |
| 16 | fn referenced_names(expr: &str) -> Option<HashSet<&str>> { | |
| 17 | let names: HashSet<&str> = | |
| 18 | expr.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').filter(|t| !t.is_empty()).collect(); | |
| 19 | (!names.contains("_ENV") && !names.contains("_G")).then_some(names) | |
| 16 | fn is_lua_keyword(tok: &str) -> bool { | |
| 17 | matches!( | |
| 18 | tok, | |
| 19 | "and" | |
| 20 | | "break" | |
| 21 | | "do" | |
| 22 | | "else" | |
| 23 | | "elseif" | |
| 24 | | "end" | |
| 25 | | "false" | |
| 26 | | "for" | |
| 27 | | "function" | |
| 28 | | "goto" | |
| 29 | | "if" | |
| 30 | | "in" | |
| 31 | | "local" | |
| 32 | | "nil" | |
| 33 | | "not" | |
| 34 | | "or" | |
| 35 | | "repeat" | |
| 36 | | "return" | |
| 37 | | "then" | |
| 38 | | "true" | |
| 39 | | "until" | |
| 40 | | "while" | |
| 41 | ) | |
| 20 | 42 | } |
| 21 | 43 | |
| 22 | struct ModMemoScope(bool); | |
| 44 | struct ModMemoScope; | |
| 23 | 45 | |
| 24 | 46 | impl Drop for ModMemoScope { |
| 25 | 47 | fn drop(&mut self) { |
| 26 | if self.0 { | |
| 27 | EXPR_MOD_MEMO.with_borrow_mut(|m| *m = None); | |
| 28 | } | |
| 48 | EXPR_MOD_MEMO.with_borrow_mut(|(depth, map)| { | |
| 49 | *depth = depth.saturating_sub(1); | |
| 50 | if *depth == 0 { | |
| 51 | map.clear(); | |
| 52 | } | |
| 53 | }); | |
| 29 | 54 | } |
| 30 | 55 | } |
| 31 | 56 | |
| 32 | 57 | /// Runs `compute` once per key within the outermost modifier evaluation on this thread, which |
| 33 | 58 | /// keeps fanned-out modifier chains linear. Re-entering an unfinished key (a cycle) yields `None`. |
| 34 | 59 | fn memoized_modifier(key: ModMemoKey, compute: impl FnOnce() -> Option<[f64; 2]>) -> Option<[f64; 2]> { |
| 35 | let _scope = ModMemoScope(EXPR_MOD_MEMO.with_borrow_mut(|m| { | |
| 36 | let outermost = m.is_none(); | |
| 37 | m.get_or_insert_default(); | |
| 38 | outermost | |
| 39 | })); | |
| 40 | let hit = EXPR_MOD_MEMO.with_borrow_mut(|m| { | |
| 41 | let m = m.as_mut().expect("scope installs the memo"); | |
| 60 | EXPR_MOD_MEMO.with_borrow_mut(|(depth, _)| *depth += 1); | |
| 61 | let _scope = ModMemoScope; | |
| 62 | let hit = EXPR_MOD_MEMO.with_borrow_mut(|(_, m)| { | |
| 42 | 63 | let hit = m.get(&key).copied(); |
| 43 | 64 | if hit.is_none() { |
| 44 | 65 | m.insert(key, None); |
| ... | ... | @@ -49,7 +70,7 @@ fn memoized_modifier(key: ModMemoKey, compute: impl FnOnce() -> Option<[f64; 2]> |
| 49 | 70 | return done; |
| 50 | 71 | } |
| 51 | 72 | let value = compute(); |
| 52 | EXPR_MOD_MEMO.with_borrow_mut(|m| m.as_mut().expect("scope installs the memo").insert(key, value)); | |
| 73 | EXPR_MOD_MEMO.with_borrow_mut(|(_, m)| m.insert(key, value)); | |
| 53 | 74 | value |
| 54 | 75 | } |
| 55 | 76 | |
| ... | ... | @@ -96,6 +117,7 @@ impl Comp { |
| 96 | 117 | } |
| 97 | 118 | |
| 98 | 119 | /// Evaluates a numeric input on `node` at continuous `time`, checking Expression -> Spline -> Static -> `default`. |
| 120 | #[inline] | |
| 99 | 121 | pub fn eval_number( |
| 100 | 122 | &self, |
| 101 | 123 | node: &Node, |
| ... | ... | @@ -122,6 +144,13 @@ impl Comp { |
| 122 | 144 | let Some(binding) = node.inputs.get(param) else { |
| 123 | 145 | return default; |
| 124 | 146 | }; |
| 147 | if binding.expression.is_none() && binding.source_op.is_none() { | |
| 148 | return binding | |
| 149 | .value | |
| 150 | .as_ref() | |
| 151 | .and_then(ParamValue::as_f64) | |
| 152 | .unwrap_or(default); | |
| 153 | } | |
| 125 | 154 | if let Some(expr) = &binding.expression { |
| 126 | 155 | // A bare `Node.Param` follows that input's own expression/animation instead of its baked value. |
| 127 | 156 | let referenced = expr.trim().split_once('.').and_then(|(n, p)| { |
| ... | ... | @@ -191,6 +220,7 @@ impl Comp { |
| 191 | 220 | } |
| 192 | 221 | |
| 193 | 222 | /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`. |
| 223 | #[inline] | |
| 194 | 224 | pub fn eval_point( |
| 195 | 225 | &self, |
| 196 | 226 | node: &Node, |
| ... | ... | @@ -217,6 +247,13 @@ impl Comp { |
| 217 | 247 | let Some(binding) = node.inputs.get(param) else { |
| 218 | 248 | return default; |
| 219 | 249 | }; |
| 250 | if binding.expression.is_none() && binding.source_op.is_none() { | |
| 251 | return binding | |
| 252 | .value | |
| 253 | .as_ref() | |
| 254 | .and_then(ParamValue::as_point) | |
| 255 | .unwrap_or(default); | |
| 256 | } | |
| 220 | 257 | if let Some(expr) = &binding.expression { |
| 221 | 258 | if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) { |
| 222 | 259 | return p; |
| ... | ... | @@ -462,12 +499,27 @@ impl Comp { |
| 462 | 499 | |
| 463 | 500 | /// `node name -> numeric/text inputs` for the nodes `expr` can reach; every other node is skipped. |
| 464 | 501 | fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, ExprValue>> { |
| 465 | let names = referenced_names(expr); | |
| 466 | self.nodes | |
| 467 | .iter() | |
| 468 | .filter(|n| names.as_ref().is_none_or(|s| s.contains(n.name.as_str()))) | |
| 469 | .map(|n| (n.name.clone(), self.node_expr_vars(n, time))) | |
| 470 | .collect() | |
| 502 | let mut env = HashMap::new(); | |
| 503 | for tok in expr | |
| 504 | .split(|c: char| !c.is_ascii_alphanumeric() && c != '_') | |
| 505 | .filter(|t| !t.is_empty() && !t.as_bytes()[0].is_ascii_digit()) | |
| 506 | { | |
| 507 | if tok == "_ENV" || tok == "_G" { | |
| 508 | return self | |
| 509 | .nodes | |
| 510 | .iter() | |
| 511 | .map(|n| (n.name.clone(), self.node_expr_vars(n, time))) | |
| 512 | .collect(); | |
| 513 | } | |
| 514 | if tok == "self" || is_lua_keyword(tok) || env.contains_key(tok) { | |
| 515 | continue; | |
| 516 | } | |
| 517 | if let Some(nid) = self.find_node(tok) { | |
| 518 | let n = self.node(nid); | |
| 519 | env.insert(n.name.clone(), self.node_expr_vars(n, time)); | |
| 520 | } | |
| 521 | } | |
| 522 | env | |
| 471 | 523 | } |
| 472 | 524 | |
| 473 | 525 | fn node_expr_vars(&self, node: &Node, time: f64) -> HashMap<String, ExprValue> { |
| ... | ... | @@ -498,41 +550,59 @@ impl Comp { |
| 498 | 550 | expr_engine: &ExprEngine, |
| 499 | 551 | depth: usize, |
| 500 | 552 | ) -> (HashMap<String, f64>, HashMap<String, [f64; 2]>) { |
| 501 | let mut vars = HashMap::with_capacity(32); | |
| 553 | const N_KEYS: [(&str, &str); 9] = [ | |
| 554 | ("n1", "NumberIn1"), | |
| 555 | ("n2", "NumberIn2"), | |
| 556 | ("n3", "NumberIn3"), | |
| 557 | ("n4", "NumberIn4"), | |
| 558 | ("n5", "NumberIn5"), | |
| 559 | ("n6", "NumberIn6"), | |
| 560 | ("n7", "NumberIn7"), | |
| 561 | ("n8", "NumberIn8"), | |
| 562 | ("n9", "NumberIn9"), | |
| 563 | ]; | |
| 564 | const P_KEYS: [(&str, &str, &str, &str); 9] = [ | |
| 565 | ("p1", "PointIn1", "p1x", "p1y"), | |
| 566 | ("p2", "PointIn2", "p2x", "p2y"), | |
| 567 | ("p3", "PointIn3", "p3x", "p3y"), | |
| 568 | ("p4", "PointIn4", "p4x", "p4y"), | |
| 569 | ("p5", "PointIn5", "p5x", "p5y"), | |
| 570 | ("p6", "PointIn6", "p6x", "p6y"), | |
| 571 | ("p7", "PointIn7", "p7x", "p7y"), | |
| 572 | ("p8", "PointIn8", "p8x", "p8y"), | |
| 573 | ("p9", "PointIn9", "p9x", "p9y"), | |
| 574 | ]; | |
| 575 | let mut vars = HashMap::with_capacity(42); | |
| 502 | 576 | let mut pts = HashMap::with_capacity(18); |
| 503 | 577 | vars.insert("time".to_owned(), time); |
| 504 | 578 | vars.insert("pi".to_owned(), std::f64::consts::PI); |
| 505 | 579 | vars.insert("e".to_owned(), std::f64::consts::E); |
| 506 | 580 | |
| 507 | for i in 1..=9 { | |
| 508 | let short = format!("n{i}"); | |
| 509 | let long = format!("NumberIn{i}"); | |
| 581 | for &(short, long) in &N_KEYS { | |
| 510 | 582 | let v = self.eval_expr_mod_input_number( |
| 511 | 583 | em, |
| 512 | &[short.as_str(), long.as_str()], | |
| 584 | &[short, long], | |
| 513 | 585 | time, |
| 514 | 586 | 0.0, |
| 515 | 587 | expr_engine, |
| 516 | 588 | depth, |
| 517 | 589 | ); |
| 518 | vars.insert(short, v); | |
| 519 | vars.insert(long, v); | |
| 590 | vars.insert(short.to_owned(), v); | |
| 591 | vars.insert(long.to_owned(), v); | |
| 520 | 592 | } |
| 521 | for i in 1..=9 { | |
| 522 | let short = format!("p{i}"); | |
| 523 | let long = format!("PointIn{i}"); | |
| 593 | for &(short, long, px, py) in &P_KEYS { | |
| 524 | 594 | let pt = self.eval_expr_mod_input_point( |
| 525 | 595 | em, |
| 526 | &[short.as_str(), long.as_str()], | |
| 596 | &[short, long], | |
| 527 | 597 | time, |
| 528 | 598 | [0.5, 0.5], |
| 529 | 599 | expr_engine, |
| 530 | 600 | depth, |
| 531 | 601 | ); |
| 532 | vars.insert(format!("p{i}x"), pt[0]); | |
| 533 | vars.insert(format!("p{i}y"), pt[1]); | |
| 534 | pts.insert(short, pt); | |
| 535 | pts.insert(long, pt); | |
| 602 | vars.insert(px.to_owned(), pt[0]); | |
| 603 | vars.insert(py.to_owned(), pt[1]); | |
| 604 | pts.insert(short.to_owned(), pt); | |
| 605 | pts.insert(long.to_owned(), pt); | |
| 536 | 606 | } |
| 537 | 607 | for (k, b) in &em.inputs { |
| 538 | 608 | if !vars.contains_key(k) { |
| ... | ... | @@ -638,6 +708,7 @@ impl Comp { |
| 638 | 708 | }) |
| 639 | 709 | } |
| 640 | 710 | |
| 711 | #[inline] | |
| 641 | 712 | pub fn eval_text( |
| 642 | 713 | &self, |
| 643 | 714 | node: &Node, |
| ... | ... | @@ -649,6 +720,14 @@ impl Comp { |
| 649 | 720 | let Some(binding) = node.inputs.get(param) else { |
| 650 | 721 | return default.to_owned(); |
| 651 | 722 | }; |
| 723 | if binding.expression.is_none() && binding.source_op.is_none() { | |
| 724 | return binding | |
| 725 | .value | |
| 726 | .as_ref() | |
| 727 | .and_then(ParamValue::as_str) | |
| 728 | .unwrap_or(default) | |
| 729 | .to_owned(); | |
| 730 | } | |
| 652 | 731 | if let Some(expr) = &binding.expression { |
| 653 | 732 | let (sp, spts, en) = self.collect_expr_env(node, expr, time); |
| 654 | 733 | if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) { |
| ... | ... | @@ -726,6 +805,33 @@ impl Comp { |
| 726 | 805 | None |
| 727 | 806 | } |
| 728 | 807 | |
| 808 | fn insert_self_binding( | |
| 809 | &self, | |
| 810 | key: &str, | |
| 811 | binding: &InputBinding, | |
| 812 | time: f64, | |
| 813 | self_params: &mut HashMap<String, f64>, | |
| 814 | self_points: &mut HashMap<String, [f64; 2]>, | |
| 815 | ) { | |
| 816 | if let Some(v) = binding.value.as_ref().and_then(ParamValue::as_f64) { | |
| 817 | self_params.insert(key.to_owned(), v); | |
| 818 | } else if let Some(pt) = binding.value.as_ref().and_then(ParamValue::as_point) { | |
| 819 | self_points.insert(key.to_owned(), pt); | |
| 820 | } else if let Some(src) = &binding.source_op { | |
| 821 | if let Some(sp) = self.splines.get(src) { | |
| 822 | self_params.insert(key.to_owned(), sp.eval(time)); | |
| 823 | } else if let Some(pp) = self.poly_paths.get(src) { | |
| 824 | let disp = pp | |
| 825 | .displacement_op | |
| 826 | .as_deref() | |
| 827 | .and_then(|d| self.splines.get(d)) | |
| 828 | .map(|sp| sp.eval(time)) | |
| 829 | .unwrap_or(pp.displacement_value); | |
| 830 | self_points.insert(key.to_owned(), pp.eval_center(disp)); | |
| 831 | } | |
| 832 | } | |
| 833 | } | |
| 834 | ||
| 729 | 835 | fn collect_expr_env( |
| 730 | 836 | &self, |
| 731 | 837 | node: &Node, |
| ... | ... | @@ -736,34 +842,47 @@ impl Comp { |
| 736 | 842 | HashMap<String, [f64; 2]>, |
| 737 | 843 | HashMap<String, HashMap<String, ExprValue>>, |
| 738 | 844 | ) { |
| 739 | let names = referenced_names(expr); | |
| 740 | 845 | let mut self_params = HashMap::new(); |
| 741 | 846 | let mut self_points = HashMap::new(); |
| 742 | for (k, b) in &node.inputs { | |
| 743 | if !names.as_ref().is_none_or(|s| s.contains(k.as_str())) { | |
| 847 | let mut env_nodes = HashMap::new(); | |
| 848 | for tok in expr | |
| 849 | .split(|c: char| !c.is_ascii_alphanumeric() && c != '_') | |
| 850 | .filter(|t| !t.is_empty() && !t.as_bytes()[0].is_ascii_digit()) | |
| 851 | { | |
| 852 | if tok == "_ENV" || tok == "_G" { | |
| 853 | self_params.clear(); | |
| 854 | self_points.clear(); | |
| 855 | for (k, b) in &node.inputs { | |
| 856 | self.insert_self_binding(k, b, time, &mut self_params, &mut self_points); | |
| 857 | } | |
| 858 | let mut all_nodes: HashMap<String, HashMap<String, ExprValue>> = self | |
| 859 | .nodes | |
| 860 | .iter() | |
| 861 | .map(|n| (n.name.clone(), self.node_expr_vars(n, time))) | |
| 862 | .collect(); | |
| 863 | all_nodes.insert("self".to_owned(), self.node_expr_vars(node, time)); | |
| 864 | return (self_params, self_points, all_nodes); | |
| 865 | } | |
| 866 | if is_lua_keyword(tok) { | |
| 744 | 867 | continue; |
| 745 | 868 | } |
| 746 | if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { | |
| 747 | self_params.insert(k.clone(), v); | |
| 748 | } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) { | |
| 749 | self_points.insert(k.clone(), pt); | |
| 750 | } else if let Some(src) = &b.source_op { | |
| 751 | if let Some(sp) = self.splines.get(src) { | |
| 752 | self_params.insert(k.clone(), sp.eval(time)); | |
| 753 | } else if let Some(pp) = self.poly_paths.get(src) { | |
| 754 | let disp = pp | |
| 755 | .displacement_op | |
| 756 | .as_deref() | |
| 757 | .and_then(|d| self.splines.get(d)) | |
| 758 | .map(|sp| sp.eval(time)) | |
| 759 | .unwrap_or(pp.displacement_value); | |
| 760 | self_points.insert(k.clone(), pp.eval_center(disp)); | |
| 869 | if tok == "self" { | |
| 870 | if !env_nodes.contains_key("self") { | |
| 871 | env_nodes.insert("self".to_owned(), self.node_expr_vars(node, time)); | |
| 872 | } | |
| 873 | continue; | |
| 874 | } | |
| 875 | if let Some(b) = node.inputs.get(tok) { | |
| 876 | if !self_params.contains_key(tok) && !self_points.contains_key(tok) { | |
| 877 | self.insert_self_binding(tok, b, time, &mut self_params, &mut self_points); | |
| 878 | } | |
| 879 | } | |
| 880 | if !env_nodes.contains_key(tok) { | |
| 881 | if let Some(nid) = self.find_node(tok) { | |
| 882 | let n = self.node(nid); | |
| 883 | env_nodes.insert(n.name.clone(), self.node_expr_vars(n, time)); | |
| 761 | 884 | } |
| 762 | 885 | } |
| 763 | } | |
| 764 | let mut env_nodes = self.collect_node_env(expr, time); | |
| 765 | if names.as_ref().is_none_or(|s| s.contains("self")) { | |
| 766 | env_nodes.insert("self".to_owned(), self.node_expr_vars(node, time)); | |
| 767 | 886 | } |
| 768 | 887 | (self_params, self_points, env_nodes) |
| 769 | 888 | } |
| ... | ... | @@ -798,6 +917,7 @@ mod tests { |
| 798 | 917 | |
| 799 | 918 | #[test] |
| 800 | 919 | fn expressions_see_only_referenced_nodes_in_a_large_comp() { |
| 920 | use std::collections::HashSet; | |
| 801 | 921 | let mut src = String::from("Composition { Tools = ordered() {\n"); |
| 802 | 922 | for i in 0..100 { |
| 803 | 923 | src += &format!("N{i} = Transform {{ Inputs = {{ Size = Input {{ Value = {i}, }}, Angle = Input {{ Value = 1, }}, }}, }},\n"); |
crates/model/src/comp/load.rs+47-27| ... | ... | @@ -82,7 +82,6 @@ impl Comp { |
| 82 | 82 | let mut shakes = HashMap::new(); |
| 83 | 83 | let mut expression_modifiers = HashMap::new(); |
| 84 | 84 | let mut tracker_aliases: Vec<(String, String)> = Vec::new(); |
| 85 | let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new(); | |
| 86 | 85 | let mut instanced_from: Vec<(NodeId, String)> = Vec::new(); |
| 87 | 86 | let mut macro_owner: HashMap<NodeId, NodeId> = HashMap::new(); |
| 88 | 87 | |
| ... | ... | @@ -102,7 +101,6 @@ impl Comp { |
| 102 | 101 | &mut shakes, |
| 103 | 102 | &mut expression_modifiers, |
| 104 | 103 | &mut tracker_aliases, |
| 105 | &mut macro_defaults, | |
| 106 | 104 | &mut instanced_from, |
| 107 | 105 | &mut macro_owner, |
| 108 | 106 | ); |
| ... | ... | @@ -117,21 +115,6 @@ impl Comp { |
| 117 | 115 | |
| 118 | 116 | let cross_macro_wires = clear_cross_macro_wires(&mut nodes, &macro_owner); |
| 119 | 117 | |
| 120 | // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools. | |
| 121 | for (target_op, target_param, val) in macro_defaults { | |
| 122 | if let Some(&nid) = node_by_name.get(&target_op) { | |
| 123 | let entry = nodes[nid.0].inputs.entry(target_param).or_insert(InputBinding { | |
| 124 | value: None, | |
| 125 | source_op: None, | |
| 126 | source_output: None, | |
| 127 | expression: None, | |
| 128 | }); | |
| 129 | if entry.value.is_none() && entry.source_op.is_none() && entry.expression.is_none() { | |
| 130 | entry.value = Some(val); | |
| 131 | } | |
| 132 | } | |
| 133 | } | |
| 134 | ||
| 135 | 118 | // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets |
| 136 | 119 | // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`. |
| 137 | 120 | let node_inputs_snapshot: Vec<(String, HashMap<String, InputBinding>)> = nodes |
| ... | ... | @@ -516,7 +499,6 @@ fn parse_tools_table( |
| 516 | 499 | shakes: &mut HashMap<String, ShakeModifier>, |
| 517 | 500 | expression_modifiers: &mut HashMap<String, ExpressionModifier>, |
| 518 | 501 | tracker_aliases: &mut Vec<(String, String)>, |
| 519 | macro_defaults: &mut Vec<(String, String, ParamValue)>, | |
| 520 | 502 | instanced_from: &mut Vec<(NodeId, String)>, |
| 521 | 503 | macro_owner: &mut HashMap<NodeId, NodeId>, |
| 522 | 504 | ) { |
| ... | ... | @@ -692,13 +674,6 @@ fn parse_tools_table( |
| 692 | 674 | let LuaKey::Str(in_name) = ik else { continue }; |
| 693 | 675 | let Some(it) = iv.as_table() else { continue }; |
| 694 | 676 | let binding = parse_input_binding(it); |
| 695 | if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { | |
| 696 | if let (Some(src_op), Some(src_param)) = (&binding.source_op, &binding.source_output) { | |
| 697 | if let Some(def_v) = it.get("Default") { | |
| 698 | macro_defaults.push((src_op.clone(), src_param.clone(), parse_param_value(def_v))); | |
| 699 | } | |
| 700 | } | |
| 701 | } | |
| 702 | 677 | inputs.insert(in_name.clone(), binding); |
| 703 | 678 | } |
| 704 | 679 | } |
| ... | ... | @@ -805,7 +780,6 @@ fn parse_tools_table( |
| 805 | 780 | shakes, |
| 806 | 781 | expression_modifiers, |
| 807 | 782 | tracker_aliases, |
| 808 | macro_defaults, | |
| 809 | 783 | instanced_from, |
| 810 | 784 | macro_owner, |
| 811 | 785 | ); |
| ... | ... | @@ -844,7 +818,6 @@ fn parse_tools_table( |
| 844 | 818 | shakes, |
| 845 | 819 | expression_modifiers, |
| 846 | 820 | tracker_aliases, |
| 847 | macro_defaults, | |
| 848 | 821 | instanced_from, |
| 849 | 822 | macro_owner, |
| 850 | 823 | ); |
| ... | ... | @@ -980,4 +953,51 @@ Composition { |
| 980 | 953 | assert_eq!(out_a.connected_node("Foreground"), None, "OutA -> OnlyInB must be cleared"); |
| 981 | 954 | assert_eq!(out_b.connected_node("Foreground"), None, "OutB -> OnlyInA must be cleared"); |
| 982 | 955 | } |
| 956 | ||
| 957 | #[test] | |
| 958 | fn macro_instance_input_default_does_not_overwrite_omitted_inner_input() { | |
| 959 | let src = r#" | |
| 960 | Composition { | |
| 961 | Tools = ordered() { | |
| 962 | Colorize1 = MacroOperator { | |
| 963 | Inputs = ordered() { | |
| 964 | Input11 = InstanceInput { | |
| 965 | SourceOp = "Color", | |
| 966 | Source = "NumberIn1", | |
| 967 | Default = 0, | |
| 968 | }, | |
| 969 | Input12 = InstanceInput { | |
| 970 | SourceOp = "Color", | |
| 971 | Source = "NumberIn2", | |
| 972 | Default = 0.3, | |
| 973 | }, | |
| 974 | Input13 = InstanceInput { | |
| 975 | SourceOp = "Color", | |
| 976 | Source = "NumberIn3", | |
| 977 | Default = 0.5, | |
| 978 | }, | |
| 979 | }, | |
| 980 | Outputs = ordered() { | |
| 981 | MainOutput1 = InstanceOutput { SourceOp = "Color", Source = "Output", }, | |
| 982 | }, | |
| 983 | Tools = ordered() { | |
| 984 | Color = Custom { | |
| 985 | Inputs = { | |
| 986 | NumberIn1 = Input { Value = 0.02, }, | |
| 987 | NumberIn3 = Input { Value = 0.607, }, | |
| 988 | }, | |
| 989 | }, | |
| 990 | }, | |
| 991 | }, | |
| 992 | }, | |
| 993 | } | |
| 994 | "#; | |
| 995 | let comp = Comp::from_fusion_str(src).expect("parse macro InstanceInput Default"); | |
| 996 | let color = comp.nodes.iter().find(|n| n.name == "Color").expect("Color"); | |
| 997 | let expr = crate::expr::ExprEngine::new(); | |
| 998 | assert!((comp.eval_number(color, "NumberIn1", 0.0, 0.0, &expr) - 0.02).abs() < 1e-9); | |
| 999 | assert_eq!(color.static_number("NumberIn2"), None); | |
| 1000 | assert!((comp.eval_number(color, "NumberIn2", 0.0, 0.0, &expr) - 0.0).abs() < 1e-9); | |
| 1001 | assert!((comp.eval_number(color, "NumberIn3", 0.0, 0.0, &expr) - 0.607).abs() < 1e-9); | |
| 1002 | } | |
| 983 | 1003 | } |
crates/model/src/expr.rs+101-13| ... | ... | @@ -40,7 +40,8 @@ fn format_number(n: f64) -> String { |
| 40 | 40 | #[cfg(not(target_arch = "wasm32"))] |
| 41 | 41 | mod lua { |
| 42 | 42 | use super::ExprValue; |
| 43 | use mlua::{HookTriggers, Lua, LuaOptions, MultiValue, StdLib, Value, VmState}; | |
| 43 | use mlua::{ChunkMode, Function, HookTriggers, Lua, LuaOptions, MultiValue, StdLib, Table, Value, VmState}; | |
| 44 | use std::cell::RefCell; | |
| 44 | 45 | use std::collections::HashMap; |
| 45 | 46 | use std::sync::Arc; |
| 46 | 47 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| ... | ... | @@ -50,6 +51,8 @@ mod lua { |
| 50 | 51 | /// Hook granularity; the budget is enforced in steps of this many instructions. |
| 51 | 52 | const HOOK_STEP: u32 = 1000; |
| 52 | 53 | const MEMORY_LIMIT: usize = 16 * 1024 * 1024; |
| 54 | /// Max compiled expression bytecodes cached per `ExprEngine`. | |
| 55 | const CHUNK_CACHE_CAP: usize = 512; | |
| 53 | 56 | |
| 54 | 57 | /// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`, |
| 55 | 58 | /// no code loading, and bounded instructions and memory per evaluation. |
| ... | ... | @@ -58,6 +61,10 @@ mod lua { |
| 58 | 61 | instructions_used: Arc<AtomicU64>, |
| 59 | 62 | /// Latched once the budget is exceeded so every later hook call also errors. |
| 60 | 63 | aborted: Arc<AtomicBool>, |
| 64 | env_mt: Table, | |
| 65 | zero_mt: Table, | |
| 66 | text_mt: Table, | |
| 67 | chunk_cache: RefCell<HashMap<String, Option<Vec<u8>>>>, | |
| 61 | 68 | } |
| 62 | 69 | |
| 63 | 70 | impl Default for ExprEngine { |
| ... | ... | @@ -147,7 +154,71 @@ mod lua { |
| 147 | 154 | }); |
| 148 | 155 | lua.set_memory_limit(MEMORY_LIMIT).expect("memory limit applies"); |
| 149 | 156 | |
| 150 | Self { lua, instructions_used, aborted } | |
| 157 | let env_mt = lua.create_table().expect("table creates"); | |
| 158 | env_mt.set("__index", globals).expect("table sets"); | |
| 159 | let zero_mt = lua.create_table().expect("table creates"); | |
| 160 | zero_mt | |
| 161 | .set( | |
| 162 | "__index", | |
| 163 | lua.create_function(|_, _args: MultiValue| Ok(0.0_f64)) | |
| 164 | .expect("function creates"), | |
| 165 | ) | |
| 166 | .expect("table sets"); | |
| 167 | let text_mt = lua.create_table().expect("table creates"); | |
| 168 | text_mt | |
| 169 | .set( | |
| 170 | "__tostring", | |
| 171 | lua.create_function(|_, this: Table| this.get::<String>("Value")) | |
| 172 | .expect("function creates"), | |
| 173 | ) | |
| 174 | .expect("table sets"); | |
| 175 | ||
| 176 | Self { | |
| 177 | lua, | |
| 178 | instructions_used, | |
| 179 | aborted, | |
| 180 | env_mt, | |
| 181 | zero_mt, | |
| 182 | text_mt, | |
| 183 | chunk_cache: RefCell::new(HashMap::new()), | |
| 184 | } | |
| 185 | } | |
| 186 | ||
| 187 | fn load_cached(&self, expr: &str, env: Table) -> Option<Function> { | |
| 188 | { | |
| 189 | let cache = self.chunk_cache.borrow(); | |
| 190 | if let Some(hit) = cache.get(expr) { | |
| 191 | let bytes = hit.as_ref()?; | |
| 192 | return self | |
| 193 | .lua | |
| 194 | .load(bytes.as_slice()) | |
| 195 | .set_mode(ChunkMode::Binary) | |
| 196 | .set_environment(env) | |
| 197 | .into_function() | |
| 198 | .ok(); | |
| 199 | } | |
| 200 | } | |
| 201 | let chunk_src = Self::expr_chunk(expr); | |
| 202 | let compiled = self | |
| 203 | .lua | |
| 204 | .load(&chunk_src) | |
| 205 | .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(); | |
| 219 | } | |
| 220 | cache.insert(expr.to_owned(), compiled); | |
| 221 | func | |
| 151 | 222 | } |
| 152 | 223 | |
| 153 | 224 | /// Evaluates `expr` in a fresh environment with a fresh instruction budget. |
| ... | ... | @@ -160,9 +231,10 @@ mod lua { |
| 160 | 231 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 161 | 232 | ) -> Option<Value> { |
| 162 | 233 | let env = self.build_env(time, self_params, self_points, env_nodes).ok()?; |
| 234 | let func = self.load_cached(expr, env)?; | |
| 163 | 235 | self.instructions_used.store(0, Ordering::Relaxed); |
| 164 | 236 | self.aborted.store(false, Ordering::Relaxed); |
| 165 | self.lua.load(&Self::expr_chunk(expr)).set_environment(env).eval().ok() | |
| 237 | func.call::<Value>(()).ok() | |
| 166 | 238 | } |
| 167 | 239 | |
| 168 | 240 | fn expr_chunk(expr: &str) -> String { |
| ... | ... | @@ -238,11 +310,9 @@ mod lua { |
| 238 | 310 | self_params: &HashMap<String, f64>, |
| 239 | 311 | self_points: &HashMap<String, [f64; 2]>, |
| 240 | 312 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 241 | ) -> mlua::Result<mlua::Table> { | |
| 313 | ) -> mlua::Result<Table> { | |
| 242 | 314 | let env = self.lua.create_table()?; |
| 243 | let mt = self.lua.create_table()?; | |
| 244 | mt.set("__index", self.lua.globals())?; | |
| 245 | env.set_metatable(Some(mt)); | |
| 315 | env.set_metatable(Some(self.env_mt.clone())); | |
| 246 | 316 | env.set("time", time)?; |
| 247 | 317 | env.set("comp", self.lua.create_table()?)?; |
| 248 | 318 | for (k, v) in self_params { |
| ... | ... | @@ -257,10 +327,6 @@ mod lua { |
| 257 | 327 | env.set(k.as_str(), pt)?; |
| 258 | 328 | } |
| 259 | 329 | // Missing node fields default to 0 so expressions don't nil-crash. |
| 260 | let zero_mt = self.lua.create_table()?; | |
| 261 | zero_mt.set("__index", self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?)?; | |
| 262 | let text_mt = self.lua.create_table()?; | |
| 263 | text_mt.set("__tostring", self.lua.create_function(|_, this: mlua::Table| this.get::<String>("Value"))?)?; | |
| 264 | 330 | for (node_name, params) in env_nodes { |
| 265 | 331 | let nt = self.lua.create_table()?; |
| 266 | 332 | for (pk, pv) in params { |
| ... | ... | @@ -269,12 +335,12 @@ mod lua { |
| 269 | 335 | ExprValue::Text(s) => { |
| 270 | 336 | let text = self.lua.create_table()?; |
| 271 | 337 | text.set("Value", s.as_str())?; |
| 272 | text.set_metatable(Some(text_mt.clone())); | |
| 338 | text.set_metatable(Some(self.text_mt.clone())); | |
| 273 | 339 | nt.set(pk.as_str(), text)?; |
| 274 | 340 | } |
| 275 | 341 | } |
| 276 | 342 | } |
| 277 | nt.set_metatable(Some(zero_mt.clone())); | |
| 343 | nt.set_metatable(Some(self.zero_mt.clone())); | |
| 278 | 344 | env.set(node_name.as_str(), nt)?; |
| 279 | 345 | } |
| 280 | 346 | Ok(env) |
| ... | ... | @@ -365,6 +431,28 @@ mod lua { |
| 365 | 431 | assert_eq!(upper.as_deref(), Some("A")); |
| 366 | 432 | assert_eq!(eval("string.len('abc') + select('#', table.unpack({1, 2}))"), Some(5.0)); |
| 367 | 433 | } |
| 434 | ||
| 435 | #[test] | |
| 436 | fn chunk_cache_reuses_compiled_bytecode_with_isolated_envs() { | |
| 437 | let engine = ExprEngine::new(); | |
| 438 | let expr = "time + x + N1.Gain"; | |
| 439 | let mut sp = HashMap::from([("x".to_owned(), 10.0)]); | |
| 440 | let mut n1 = HashMap::from([("Gain".to_owned(), ExprValue::Number(2.0))]); | |
| 441 | let mut env = HashMap::from([("N1".to_owned(), n1.clone())]); | |
| 442 | ||
| 443 | assert_eq!(engine.eval_number(expr, 1.0, &sp, &HashMap::new(), &env), Some(13.0)); | |
| 444 | assert_eq!(engine.chunk_cache.borrow().len(), 1); | |
| 445 | ||
| 446 | sp.insert("x".to_owned(), 20.0); | |
| 447 | n1.insert("Gain".to_owned(), ExprValue::Number(5.0)); | |
| 448 | env.insert("N1".to_owned(), n1); | |
| 449 | assert_eq!(engine.eval_number(expr, 3.0, &sp, &HashMap::new(), &env), Some(28.0)); | |
| 450 | assert_eq!(engine.chunk_cache.borrow().len(), 1); | |
| 451 | ||
| 452 | // Cached compilation error stays cached as None and does not pollute valid runs. | |
| 453 | assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &HashMap::new()), None); | |
| 454 | assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None)); | |
| 455 | } | |
| 368 | 456 | } |
| 369 | 457 | } |
| 370 | 458 |