authoravatarclover caruso<git@paperclover.net>2026-12-01 16:41:43-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 16:47:41-08:00
log58f0a438503070b75389125a5d64ee6e27cf4cd9
treed69a7313ebf35fdbcd73098873fe4a5e75cbc39e
parentad4bb44659c9b2a8780f96640438f8cfcb0464e4
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(model): optimize .comp Lua parser, loader, and lossless writer


3 files changed, 1915 insertions(+), 452 deletions(-)

crates/model/src/comp/load.rs+274-133
......@@ -22,10 +22,13 @@ impl Comp {
2222 }
2323
2424 pub fn from_fusion_str(text: &str) -> Result<Self, ParseError> {
25 let root_val = parse_lua(text)?;
26 let root = root_val
27 .as_table()
28 .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?;
25 let LuaValue::Table(root) = parse_lua(text)? else {
26 return Err(ParseError {
27 offset: 0,
28 line: 1,
29 message: "comp root is not a table".into(),
30 });
31 };
2932
3033 let current_time = root.get_f64("CurrentTime").unwrap_or(0.0);
3134 let global_range = root
......@@ -70,9 +73,11 @@ impl Comp {
7073 }
7174 }
7275
73 let mut nodes = Vec::new();
74 let mut node_by_name = HashMap::new();
75 let mut splines = HashMap::new();
76 let tools_len = root.get_table("Tools").map_or(0, |t| t.entries.len());
77 let approx_nodes = tools_len / 2;
78 let mut nodes = Vec::with_capacity(approx_nodes);
79 let mut node_by_name = HashMap::with_capacity(approx_nodes);
80 let mut splines = HashMap::with_capacity(tools_len - approx_nodes);
7681 let mut poly_paths = HashMap::new();
7782 let mut gradient_modifiers = HashMap::new();
7883 let mut text_modifiers = HashMap::new();
......@@ -117,35 +122,45 @@ impl Comp {
117122
118123 // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets
119124 // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`.
120 let node_inputs_snapshot: Vec<(String, HashMap<String, InputBinding>)> = nodes
121 .iter()
122 .map(|n| (n.name.clone(), n.inputs.clone()))
123 .collect();
124 let snap_map: HashMap<String, HashMap<String, InputBinding>> = node_inputs_snapshot.into_iter().collect();
125 for n in &mut nodes {
126 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
127 let mut flow_wires = HashMap::new();
125 if nodes.iter().any(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) {
126 let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(nodes.len());
127 for (idx, n) in nodes.iter().enumerate() {
128 name_to_idx.insert(n.name.as_str(), idx);
129 }
130 let mut group_wires: Vec<(usize, Vec<(String, InputBinding)>)> = Vec::new();
131 for (idx, n) in nodes.iter().enumerate() {
132 if !matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
133 continue;
134 }
135 let mut flow_wires = Vec::new();
128136 for (in_name, b) in &n.inputs {
129137 if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) {
130 if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) {
131 if let Some(ext_src) = &inner_in.source_op {
132 // Only connect if ext_src is a visible (non-internal) flow node
133 if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) {
134 flow_wires.insert(
135 in_name.clone(),
136 InputBinding {
137 value: None,
138 source_op: Some(ext_src.clone()),
139 source_output: inner_in.source_output.clone(),
140 expression: None,
141 },
142 );
138 if let Some(&inner_idx) = name_to_idx.get(inner_op.as_str()) {
139 if let Some(inner_in) = nodes[inner_idx].inputs.get(inner_port) {
140 if let Some(ext_src) = &inner_in.source_op {
141 // Only connect if ext_src is a visible (non-internal) flow node
142 if node_by_name.get(ext_src).is_some_and(|&id| id != n.id) {
143 flow_wires.push((
144 in_name.clone(),
145 InputBinding {
146 value: None,
147 source_op: Some(ext_src.clone()),
148 source_output: inner_in.source_output.clone(),
149 expression: None,
150 },
151 ));
152 }
143153 }
144154 }
145155 }
146156 }
147157 }
148 n.inputs.extend(flow_wires);
158 if !flow_wires.is_empty() {
159 group_wires.push((idx, flow_wires));
160 }
161 }
162 for (idx, wires) in group_wires {
163 nodes[idx].inputs.extend(wires);
149164 }
150165 }
151166
......@@ -163,13 +178,20 @@ impl Comp {
163178 .map(|mid| (*nid, mid))
164179 })
165180 .collect();
166 let orig_inputs: Vec<HashMap<String, InputBinding>> =
167 nodes.iter().map(|n| n.inputs.clone()).collect();
181 let mut orig_inputs: HashMap<NodeId, HashMap<String, InputBinding>> =
182 HashMap::with_capacity(parent_of.len());
183 for &pid in parent_of.values() {
184 orig_inputs
185 .entry(pid)
186 .or_insert_with(|| nodes[pid.0].inputs.clone());
187 }
168188
189 let mut visited = HashSet::new();
190 let mut blocked: HashSet<String> = HashSet::new();
169191 for &(nid, _) in &instanced_from {
170 let mut visited = HashSet::new();
192 visited.clear();
171193 visited.insert(nid);
172 let mut blocked: HashSet<String> = HashSet::new();
194 blocked.clear();
173195 let mut cur = nid;
174196 for _depth in 0..8 {
175197 let Some(&pid) = parent_of.get(&cur) else {
......@@ -179,25 +201,26 @@ impl Comp {
179201 break;
180202 }
181203 let inst_inputs = &mut nodes[nid.0].inputs;
182 for (inp_name, parent_binding) in &orig_inputs[pid.0] {
183 if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name)
184 {
185 continue;
186 }
187 if blocked.contains(inp_name) {
188 continue;
189 }
190 if parent_binding.value.is_none()
191 && parent_binding.source_op.is_none()
192 && parent_binding.expression.is_none()
193 {
194 // An empty `Param = Input {}` on an ancestor marks a de-instanced
195 // override to default and stops further inheritance up the chain.
196 blocked.insert(inp_name.clone());
197 continue;
198 }
199 if !inst_inputs.contains_key(inp_name) {
200 inst_inputs.insert(inp_name.clone(), parent_binding.clone());
204 if let Some(parent_map) = orig_inputs.get(&pid) {
205 for (inp_name, parent_binding) in parent_map {
206 if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) {
207 continue;
208 }
209 if blocked.contains(inp_name) {
210 continue;
211 }
212 if parent_binding.value.is_none()
213 && parent_binding.source_op.is_none()
214 && parent_binding.expression.is_none()
215 {
216 // An empty `Param = Input {}` on an ancestor marks a de-instanced
217 // override to default and stops further inheritance up the chain.
218 blocked.insert(inp_name.clone());
219 continue;
220 }
221 if !inst_inputs.contains_key(inp_name) {
222 inst_inputs.insert(inp_name.clone(), parent_binding.clone());
223 }
201224 }
202225 }
203226 cur = pid;
......@@ -217,19 +240,21 @@ impl Comp {
217240 "GreenSuppress",
218241 "BlueSuppress",
219242 ];
220 let mut hue_spline_names: HashSet<String> = HashSet::new();
221 for n in &nodes {
222 if n.kind == "HueCurves" {
223 for &port in HUE_CURVE_PORTS {
224 if let Some(sp_name) = n.connected_node(port) {
225 hue_spline_names.insert(sp_name.to_owned());
243 if !splines.is_empty() && nodes.iter().any(|n| n.kind == "HueCurves") {
244 let mut hue_spline_names: HashSet<String> = HashSet::new();
245 for n in &nodes {
246 if n.kind == "HueCurves" {
247 for &port in HUE_CURVE_PORTS {
248 if let Some(sp_name) = n.connected_node(port) {
249 hue_spline_names.insert(sp_name.to_owned());
250 }
226251 }
227252 }
228253 }
229 }
230 for sp_name in hue_spline_names {
231 if let Some(sp) = splines.get_mut(&sp_name) {
232 sp.apply_hue_curves_cyclic_ends();
254 for sp_name in hue_spline_names {
255 if let Some(sp) = splines.get_mut(&sp_name) {
256 sp.apply_hue_curves_cyclic_ends();
257 }
233258 }
234259 }
235260
......@@ -272,7 +297,7 @@ impl Comp {
272297 shakes,
273298 expression_modifiers,
274299 cross_macro_wires,
275 raw_root: Some(root.clone()),
300 raw_root: Some(root),
276301 revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed),
277302 })
278303 }
......@@ -284,9 +309,25 @@ impl Comp {
284309/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was
285310/// cleared here so saving keeps the original text.
286311fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap<NodeId, NodeId>) -> HashSet<(String, String)> {
287 let mut by_name: HashMap<&str, Vec<NodeId>> = HashMap::new();
312 if owner.is_empty() {
313 return HashSet::new();
314 }
315 enum NameMatches {
316 One(NodeId),
317 Many(Vec<NodeId>),
318 }
319 let mut by_name: HashMap<&str, NameMatches> = HashMap::with_capacity(nodes.len());
288320 for n in nodes.iter() {
289 by_name.entry(n.name.as_str()).or_default().push(n.id);
321 match by_name.get_mut(n.name.as_str()) {
322 None => {
323 by_name.insert(n.name.as_str(), NameMatches::One(n.id));
324 }
325 Some(NameMatches::One(first)) => {
326 let first = *first;
327 by_name.insert(n.name.as_str(), NameMatches::Many(vec![first, n.id]));
328 }
329 Some(NameMatches::Many(v)) => v.push(n.id),
330 }
290331 }
291332 let encloses = |outer: NodeId, mut inner: NodeId| {
292333 loop {
......@@ -314,7 +355,11 @@ fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap<NodeId, NodeId>)
314355 let Some(candidates) = b.source_op.as_deref().and_then(|s| by_name.get(s)) else {
315356 continue;
316357 };
317 if !candidates.iter().any(|&t| in_scope(n_scope, t)) {
358 let any_in_scope = match candidates {
359 NameMatches::One(t) => in_scope(n_scope, *t),
360 NameMatches::Many(vec) => vec.iter().any(|&t| in_scope(n_scope, t)),
361 };
362 if !any_in_scope {
318363 cleared.push((n.id, port.clone()));
319364 }
320365 }
......@@ -368,11 +413,34 @@ fn is_non_inheritable_instance_port(
368413}
369414
370415pub(super) fn parse_input_binding(t: &LuaTable) -> InputBinding {
371 let source_op = t.get_str("SourceOp").map(str::to_owned);
372 let source_output = t.get_str("Source").map(str::to_owned);
373 let expression = t.get_str("Expression").map(str::to_owned);
374
375 let value = t.get("Value").map(parse_param_value);
416 let mut source_op = None;
417 let mut source_output = None;
418 let mut expression = None;
419 let mut value = None;
420 for (k, v) in &t.entries {
421 let LuaKey::Str(s) = k else { continue };
422 match s.as_str() {
423 "SourceOp" => {
424 if let Some(sv) = v.as_str() {
425 source_op = Some(sv.to_owned());
426 }
427 }
428 "Source" => {
429 if let Some(sv) = v.as_str() {
430 source_output = Some(sv.to_owned());
431 }
432 }
433 "Expression" => {
434 if let Some(sv) = v.as_str() {
435 expression = Some(sv.to_owned());
436 }
437 }
438 "Value" => {
439 value = Some(parse_param_value(v));
440 }
441 _ => {}
442 }
443 }
376444 InputBinding {
377445 value,
378446 source_op,
......@@ -407,9 +475,8 @@ pub(super) fn parse_param_value(v: &LuaValue) -> ParamValue {
407475 }
408476}
409477
410fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)>> {
411 let kfs = table.get_table("KeyFrames")?;
412 let mut grads = Vec::new();
478fn try_parse_gradient_keyframes(kfs: &LuaTable) -> Option<Vec<(f64, Gradient)>> {
479 let mut grads = Vec::with_capacity(kfs.entries.len());
413480 for (k, v) in &kfs.entries {
414481 let time = match k {
415482 LuaKey::Index(i) => *i as f64,
......@@ -433,9 +500,8 @@ fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)>
433500 Some(grads)
434501}
435502
436fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> {
437 let kfs = table.get_table("KeyFrames")?;
438 let mut texts = Vec::new();
503fn try_parse_text_keyframes(kfs: &LuaTable) -> Option<Vec<(f64, String)>> {
504 let mut texts = Vec::with_capacity(kfs.entries.len());
439505 for (k, v) in &kfs.entries {
440506 let time = match k {
441507 LuaKey::Index(i) => *i as f64,
......@@ -458,9 +524,8 @@ fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> {
458524 Some(texts)
459525}
460526
461fn try_parse_polyline_keyframes(table: &LuaTable) -> Option<Vec<(f64, Vec<crate::spline::PolyPoint>)>> {
462 let kfs = table.get_table("KeyFrames")?;
463 let mut shapes = Vec::new();
527fn try_parse_polyline_keyframes(kfs: &LuaTable) -> Option<Vec<(f64, Vec<crate::spline::PolyPoint>)>> {
528 let mut shapes = Vec::with_capacity(kfs.entries.len());
464529 for (k, v) in &kfs.entries {
465530 let time = match k {
466531 LuaKey::Index(i) => *i as f64,
......@@ -505,25 +570,43 @@ fn parse_tools_table(
505570 for (key, val) in &tools.entries {
506571 let LuaKey::Str(name) = key else { continue };
507572 let Some(tbl) = val.as_table() else { continue };
508 let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned());
509
510 if kind == "BezierSpline" || kind == "LUTBezier" {
511 if let Some(grads) = try_parse_gradient_keyframes(tbl) {
512 gradient_modifiers.insert(name.clone(), grads);
513 } else if let Some(txts) = try_parse_text_keyframes(tbl) {
514 text_splines.insert(name.clone(), txts);
515 } else if let Some(polys) = try_parse_polyline_keyframes(tbl) {
516 polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys));
517 } else {
518 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
573 let kind_ref = tbl.tag.as_deref().unwrap_or("Unknown");
574
575 if kind_ref == "BezierSpline" || kind_ref == "LUTBezier" {
576 if let Some(kfs) = tbl.get_table("KeyFrames") {
577 let first_val_tag = kfs.entries.iter().find_map(|(k, v)| {
578 if !matches!(k, LuaKey::Index(_) | LuaKey::Number(_)) {
579 return None;
580 }
581 let kt = v.as_table()?;
582 kt.get_table("Value")
583 .or_else(|| kt.get_index(1).and_then(LuaValue::as_table))
584 .and_then(|t| t.tag.as_deref())
585 });
586 match first_val_tag {
587 Some("Gradient") if try_parse_gradient_keyframes(kfs).is_some_and(|g| { gradient_modifiers.insert(name.clone(), g); true }) => {
588 continue;
589 }
590 Some("Text" | "StyledText") if try_parse_text_keyframes(kfs).is_some_and(|t| { text_splines.insert(name.clone(), t); true }) => {
591 continue;
592 }
593 Some("Polyline") if try_parse_polyline_keyframes(kfs).is_some_and(|p| {
594 polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), p));
595 true
596 }) => {
597 continue;
598 }
599 _ => {}
600 }
519601 }
602 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
520603 continue;
521604 }
522 if kind == "PolyPath" || kind == "Path" {
605 if kind_ref == "PolyPath" || kind_ref == "Path" {
523606 poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl));
524607 continue;
525608 }
526 if kind == "TrackerModifier" {
609 if kind_ref == "TrackerModifier" {
527610 if let Some(in_tbl) = tbl.get_table("Inputs") {
528611 if let Some(src_op) = in_tbl
529612 .get_table("TrackedCenter0")
......@@ -557,7 +640,7 @@ fn parse_tools_table(
557640 }
558641 continue;
559642 }
560 if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" {
643 if kind_ref == "StyledTextCLS" || kind_ref == "CharacterLevelStyling" {
561644 if let Some(in_tbl) = tbl.get_table("Inputs") {
562645 if let Some(txt_in) = in_tbl.get_table("Text").or_else(|| in_tbl.get_table("StyledText")) {
563646 if let Some(txt) = txt_in
......@@ -607,9 +690,10 @@ fn parse_tools_table(
607690 }
608691 continue;
609692 }
610 if kind == "Shake" {
693 if kind_ref == "Shake" {
611694 let mut inputs = HashMap::new();
612695 if let Some(in_tbl) = tbl.get_table("Inputs") {
696 inputs.reserve(in_tbl.entries.len());
613697 for (ik, iv) in &in_tbl.entries {
614698 let LuaKey::Str(in_name) = ik else { continue };
615699 let Some(it) = iv.as_table() else { continue };
......@@ -619,9 +703,10 @@ fn parse_tools_table(
619703 shakes.insert(name.clone(), ShakeModifier { inputs });
620704 continue;
621705 }
622 if kind == "Expression" {
706 if kind_ref == "Expression" {
623707 let mut inputs = HashMap::new();
624708 if let Some(in_tbl) = tbl.get_table("Inputs") {
709 inputs.reserve(in_tbl.entries.len());
625710 for (ik, iv) in &in_tbl.entries {
626711 let LuaKey::Str(in_name) = ik else { continue };
627712 let Some(it) = iv.as_table() else { continue };
......@@ -653,23 +738,45 @@ fn parse_tools_table(
653738 expression_modifiers.insert(name.clone(), ExpressionModifier { inputs });
654739 continue;
655740 }
656 if is_modifier_type(&kind) {
741 if is_modifier_type(kind_ref) {
657742 if tbl.get_table("KeyFrames").is_some() {
658743 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
659744 }
660745 continue;
661746 }
662747
663 let pos = tbl
664 .get_table("ViewInfo")
748 let mut view_info_tbl: Option<&LuaTable> = None;
749 let mut bypassed = false;
750 let mut inputs_tbl: Option<&LuaTable> = None;
751 let mut user_controls_tbl: Option<&LuaTable> = None;
752 let mut clips_tbl: Option<&LuaTable> = None;
753 let mut inner_tools_tbl: Option<&LuaTable> = None;
754 let mut outputs_tbl: Option<&LuaTable> = None;
755 let mut source_op_str: Option<&str> = None;
756 for (tk, tv) in &tbl.entries {
757 let LuaKey::Str(s) = tk else { continue };
758 match s.as_str() {
759 "ViewInfo" => view_info_tbl = tv.as_table(),
760 "PassThrough" => if let Some(b) = tv.as_bool() { bypassed = b; },
761 "Inputs" => inputs_tbl = tv.as_table(),
762 "UserControls" => user_controls_tbl = tv.as_table(),
763 "Clips" => clips_tbl = tv.as_table(),
764 "Tools" => inner_tools_tbl = tv.as_table(),
765 "Outputs" => outputs_tbl = tv.as_table(),
766 "SourceOp" => source_op_str = tv.as_str(),
767 _ => {}
768 }
769 }
770
771 let pos = view_info_tbl
665772 .and_then(|vi| vi.get_table("Pos"))
666773 .and_then(read_vec2)
667774 .map(|[x, y]| [x as f32, y as f32])
668775 .unwrap_or([0.0, 0.0]);
669 let bypassed = tbl.get_bool("PassThrough").unwrap_or(false);
670776
671777 let mut inputs = HashMap::new();
672 if let Some(in_tbl) = tbl.get_table("Inputs") {
778 if let Some(in_tbl) = inputs_tbl {
779 inputs.reserve(in_tbl.entries.len());
673780 for (ik, iv) in &in_tbl.entries {
674781 let LuaKey::Str(in_name) = ik else { continue };
675782 let Some(it) = iv.as_table() else { continue };
......@@ -679,7 +786,7 @@ fn parse_tools_table(
679786 }
680787
681788 // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.)
682 if let Some(uc) = tbl.get_table("UserControls") {
789 if let Some(uc) = user_controls_tbl {
683790 for (uk, uv) in &uc.entries {
684791 let LuaKey::Str(uname) = uk else { continue };
685792 let Some(ut) = uv.as_table() else { continue };
......@@ -712,34 +819,18 @@ fn parse_tools_table(
712819 }
713820
714821 let mut clips = Vec::new();
715 if let Some(clips_tbl) = tbl.get_table("Clips") {
822 if let Some(clips_tbl) = clips_tbl {
716823 for (_, cv) in &clips_tbl.entries {
717824 if let Some(ct) = cv.as_table() {
718 if let Some(filename) = ct.get_str("Filename") {
719 clips.push(ClipSpec {
720 filename: filename.to_owned(),
721 alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned),
722 start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64,
723 length: ct.get_f64("Length").map(|v| v as i64),
724 trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64,
725 trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64,
726 global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64,
727 global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64,
728 extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64,
729 extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64,
730 // Fusion `Clip.Loop` is a loop count: 0 = infinite loop (Loop ON),
731 // 1 (or omitted) = play once (Loop OFF).
732 loop_clip: ct.get_f64("Loop").is_some_and(|v| v == 0.0),
733 reverse: ct.get_bool("Reverse").unwrap_or(false),
734 });
825 if let Some(clip) = parse_clip_spec(ct) {
826 clips.push(clip);
735827 }
736828 }
737829 }
738830 }
739831
740 if kind == "Saver" && clips.is_empty() {
741 if let Some(c) = tbl
742 .get_table("Inputs")
832 if kind_ref == "Saver" && clips.is_empty() {
833 if let Some(c) = inputs_tbl
743834 .and_then(|i| i.get_table("Clip"))
744835 .and_then(|c| c.get_table("Value"))
745836 {
......@@ -763,8 +854,8 @@ fn parse_tools_table(
763854 }
764855
765856 // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table!
766 if kind == "ColorCurves" || kind == "HueCurves" {
767 if let Some(inner_tools) = tbl.get_table("Tools") {
857 if kind_ref == "ColorCurves" || kind_ref == "HueCurves" {
858 if let Some(inner_tools) = inner_tools_tbl {
768859 parse_tools_table(
769860 inner_tools,
770861 true,
......@@ -788,13 +879,13 @@ fn parse_tools_table(
788879
789880 let mut macro_output = None;
790881 let mut macro_inner_start = None;
791 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
792 let mut out_name: Option<String> = None;
793 if let Some(outs) = tbl.get_table("Outputs") {
882 if matches!(kind_ref, "MacroOperator" | "GroupOperator") {
883 let mut out_name: Option<&str> = None;
884 if let Some(outs) = outputs_tbl {
794885 for (_, ov) in &outs.entries {
795886 if let Some(ot) = ov.as_table() {
796887 if let Some(src_op) = ot.get_str("SourceOp") {
797 out_name = Some(src_op.to_owned());
888 out_name = Some(src_op);
798889 break;
799890 }
800891 }
......@@ -802,7 +893,7 @@ fn parse_tools_table(
802893 }
803894 let inner_start = nodes.len();
804895 macro_inner_start = Some(inner_start);
805 if let Some(inner_tools) = tbl.get_table("Tools") {
896 if let Some(inner_tools) = inner_tools_tbl {
806897 parse_tools_table(
807898 inner_tools,
808899 true,
......@@ -827,7 +918,7 @@ fn parse_tools_table(
827918 .iter()
828919 .find(|n| n.name == oname)
829920 .map(|n| n.id)
830 .or_else(|| node_by_name.get(&oname).copied());
921 .or_else(|| node_by_name.get(oname).copied());
831922 }
832923 }
833924
......@@ -841,13 +932,13 @@ fn parse_tools_table(
841932 if !is_internal || !node_by_name.contains_key(name) {
842933 node_by_name.insert(name.clone(), id);
843934 }
844 if let Some(master) = tbl.get_str("SourceOp") {
935 if let Some(master) = source_op_str {
845936 instanced_from.push((id, master.to_owned()));
846937 }
847938 nodes.push(Node {
848939 id,
849940 name: name.clone(),
850 kind,
941 kind: kind_ref.to_owned(),
851942 pos,
852943 bypassed,
853944 internal: is_internal,
......@@ -859,6 +950,56 @@ fn parse_tools_table(
859950 }
860951}
861952
953fn parse_clip_spec(ct: &LuaTable) -> Option<ClipSpec> {
954 let mut filename: Option<&str> = None;
955 let mut alternate_filename: Option<&str> = None;
956 let mut start_frame: i64 = -1;
957 let mut length: Option<i64> = None;
958 let mut trim_in: i64 = 0;
959 let mut trim_out: i64 = 0;
960 let mut global_start: i64 = 0;
961 let mut global_end: i64 = 0;
962 let mut extend_first: i64 = 0;
963 let mut extend_last: i64 = 0;
964 let mut loop_clip = false;
965 let mut reverse = false;
966
967 for (k, v) in &ct.entries {
968 let LuaKey::Str(s) = k else { continue };
969 match s.as_str() {
970 "Filename" => filename = v.as_str(),
971 "AlternateFilename" => alternate_filename = v.as_str(),
972 "StartFrame" => if let Some(n) = v.as_f64() { start_frame = n as i64; },
973 "Length" => if let Some(n) = v.as_f64() { length = Some(n as i64); },
974 "TrimIn" => if let Some(n) = v.as_f64() { trim_in = n as i64; },
975 "TrimOut" => if let Some(n) = v.as_f64() { trim_out = n as i64; },
976 "GlobalStart" => if let Some(n) = v.as_f64() { global_start = n as i64; },
977 "GlobalEnd" => if let Some(n) = v.as_f64() { global_end = n as i64; },
978 "ExtendFirst" => if let Some(n) = v.as_f64() { extend_first = n as i64; },
979 "ExtendLast" => if let Some(n) = v.as_f64() { extend_last = n as i64; },
980 "Loop" => if let Some(n) = v.as_f64() { loop_clip = n == 0.0; },
981 "Reverse" => if let Some(b) = v.as_bool() { reverse = b; },
982 _ => {}
983 }
984 }
985
986 let filename = filename?;
987 Some(ClipSpec {
988 filename: filename.to_owned(),
989 alternate_filename: alternate_filename.map(str::to_owned),
990 start_frame,
991 length,
992 trim_in,
993 trim_out,
994 global_start,
995 global_end,
996 extend_first,
997 extend_last,
998 loop_clip,
999 reverse,
1000 })
1001}
1002
8621003#[cfg(test)]
8631004mod tests {
8641005 use super::*;
crates/model/src/comp/save.rs+1168-55
......@@ -1,13 +1,61 @@
11use super::load::{parse_input_binding, parse_param_value};
22use super::math::find_raw_tool_mut;
33use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};
4use crate::lua_value::{LuaKey, LuaTable, LuaValue};
5use crate::spline::{BezierSpline, read_vec2};
6use std::collections::{HashMap, HashSet, VecDeque};
4use crate::lua_value::{
5 LuaKey, LuaTable, LuaValue, can_use_positional, has_call_args, write_entry_key, write_indent,
6 write_table, write_table_prefix, write_value,
7};
8use crate::spline::{BezierSpline, Gradient, HandleMode, KeyFlags, read_vec2};
9use std::collections::{HashMap, HashSet};
710use std::io::Write;
811use std::path::{Path, PathBuf};
912use std::sync::atomic::{AtomicU64, Ordering};
1013
14enum NodePool<'a> {
15 One(&'a Node),
16 Many(Vec<&'a Node>, usize),
17}
18
19impl<'a> NodePool<'a> {
20 fn push(&mut self, node: &'a Node) {
21 match self {
22 NodePool::One(first) => {
23 *self = NodePool::Many(vec![*first, node], 0);
24 }
25 NodePool::Many(v, _) => v.push(node),
26 }
27 }
28
29 fn is_non_empty(&self) -> bool {
30 match self {
31 NodePool::One(_) => true,
32 NodePool::Many(v, idx) => *idx < v.len(),
33 }
34 }
35
36 fn peek_at(&self, offset: usize) -> Option<&'a Node> {
37 match self {
38 NodePool::One(n) => (offset == 0).then_some(*n),
39 NodePool::Many(v, idx) => v.get(*idx + offset).copied(),
40 }
41 }
42}
43
44fn pop_pool<'a>(pool: &mut HashMap<&'a str, NodePool<'a>>, name: &str) -> Option<&'a Node> {
45 match pool.get_mut(name)? {
46 NodePool::One(n) => {
47 let n = *n;
48 pool.remove(name);
49 Some(n)
50 }
51 NodePool::Many(v, idx) => {
52 let n = v.get(*idx).copied()?;
53 *idx += 1;
54 Some(n)
55 }
56 }
57}
58
1159impl Comp {
1260 /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits,
1361 /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST,
......@@ -87,10 +135,17 @@ impl Comp {
87135 tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl));
88136 }
89137
90 let mut pool: HashMap<(bool, String), VecDeque<&Node>> = HashMap::new();
138 let mut top_pool: HashMap<&str, NodePool<'_>> = HashMap::with_capacity(self.nodes.len());
139 let mut inner_pool: HashMap<&str, NodePool<'_>> = HashMap::new();
91140 let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new();
92141 for node in &self.nodes {
93 pool.entry((node.internal, node.name.clone())).or_default().push_back(node);
142 let pool = if node.internal { &mut inner_pool } else { &mut top_pool };
143 let key = node.name.as_str();
144 if let Some(entry) = pool.get_mut(key) {
145 entry.push(node);
146 } else {
147 pool.insert(key, NodePool::One(node));
148 }
94149 if !is_group_kind(&node.kind) {
95150 continue;
96151 }
......@@ -100,30 +155,33 @@ impl Comp {
100155 }
101156 }
102157 }
103 self.sync_tools_level(tools, false, &mut pool, &instance_defaults);
158 self.sync_tools_level(tools, false, &mut top_pool, &mut inner_pool, &instance_defaults);
104159
105 // Sync BezierSpline edits (only touch splines that actually differ from the raw AST)
106 let mut spline_names: Vec<&String> = self.splines.keys().collect();
107 spline_names.sort();
108 for spline_name in spline_names {
109 let spline = &self.splines[spline_name];
110 if let Some(tbl) = find_raw_tool_mut(tools, spline_name) {
111 sync_spline_table(spline_name, spline, tbl);
112 continue;
160 // Sync BezierSpline edits (walk `Tools` once in top-level-then-nested order -> O(T), not O(S * T))
161 if !self.splines.is_empty() {
162 let mut remaining: HashMap<&str, &BezierSpline> =
163 self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect();
164 sync_existing_splines_in_tools(tools, &mut remaining);
165 if !remaining.is_empty() {
166 let mut new_names: Vec<&str> = remaining.keys().copied().collect();
167 new_names.sort_unstable();
168 for spline_name in new_names {
169 let spline = remaining[spline_name];
170 let mut sp_tbl = LuaTable {
171 tag: Some("BezierSpline".to_owned()),
172 entries: Vec::with_capacity(2),
173 };
174 sp_tbl.set(
175 LuaKey::Str("SplineColor".to_owned()),
176 spline_color_lua(spline.color),
177 );
178 sp_tbl.set(
179 LuaKey::Str("KeyFrames".to_owned()),
180 LuaValue::Table(build_keyframes_table(spline)),
181 );
182 tools.set(LuaKey::Str(spline_name.to_owned()), LuaValue::Table(sp_tbl));
183 }
113184 }
114 let mut sp_tbl = LuaTable {
115 tag: Some("BezierSpline".to_owned()),
116 entries: Vec::new(),
117 };
118 sp_tbl.set(
119 LuaKey::Str("SplineColor".to_owned()),
120 spline_color_lua(spline.color),
121 );
122 sp_tbl.set(
123 LuaKey::Str("KeyFrames".to_owned()),
124 LuaValue::Table(build_keyframes_table(spline)),
125 );
126 tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl));
127185 }
128186
129187 root
......@@ -135,27 +193,35 @@ impl Comp {
135193 &'a self,
136194 tools: &mut LuaTable,
137195 internal: bool,
138 pool: &mut HashMap<(bool, String), VecDeque<&'a Node>>,
196 top_pool: &mut HashMap<&'a str, NodePool<'a>>,
197 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
139198 instance_defaults: &HashMap<(&str, &str), ParamValue>,
140199 ) {
141 tools.entries.retain(|(k, v)| {
142 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true };
143 is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown"))
144 || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty())
145 });
200 {
201 let pool = if internal { &*inner_pool } else { &*top_pool };
202 tools.entries.retain(|(k, v)| {
203 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true };
204 is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown"))
205 || pool.get(name.as_str()).is_some_and(NodePool::is_non_empty)
206 });
207 }
146208
147209 for (k, v) in &mut tools.entries {
148210 let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue };
149211 if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) {
150212 continue;
151213 }
152 let Some(node) = pool.get_mut(&(internal, name.clone())).and_then(VecDeque::pop_front) else {
214 let node = {
215 let pool = if internal { &mut *inner_pool } else { &mut *top_pool };
216 pop_pool(pool, name.as_str())
217 };
218 let Some(node) = node else {
153219 continue;
154220 };
155221 self.sync_node_tool(node, tool_tbl, instance_defaults);
156222 if is_group_kind(&node.kind) {
157223 if let Some(inner) = tool_tbl.get_table_mut("Tools") {
158 self.sync_tools_level(inner, true, pool, instance_defaults);
224 self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults);
159225 }
160226 sync_group_wiring(node, tool_tbl);
161227 }
......@@ -205,8 +271,12 @@ impl Comp {
205271 if node.kind == "Loader" {
206272 let edited = |port: &str| {
207273 let now = node.static_number(port)?;
208 let before = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port)).map(parse_input_binding);
209 (before.and_then(|b| b.value?.as_f64()) != Some(now)).then_some(now)
274 let before = tool_tbl
275 .get_table("Inputs")
276 .and_then(|i| i.get_table(port))
277 .and_then(|t| t.get("Value"))
278 .and_then(lua_value_as_number);
279 (before != Some(now)).then_some(now)
210280 };
211281 let updates = [
212282 ("GlobalStart", edited("GlobalIn").map(LuaValue::Number)),
......@@ -240,6 +310,9 @@ impl Comp {
240310
241311 /// Serializes this composition back to a Blackmagic Fusion `.comp` string.
242312 pub fn to_fusion_string(&self) -> String {
313 if let Some(s) = self.try_to_fusion_string_streaming() {
314 return s;
315 }
243316 let mut s = self.sync_to_raw_ast().to_fusion_string();
244317 if !s.ends_with('\n') {
245318 s.push('\n');
......@@ -247,6 +320,631 @@ impl Comp {
247320 s
248321 }
249322
323 fn try_to_fusion_string_streaming(&self) -> Option<String> {
324 let root = self.raw_root.as_ref()?;
325 if has_call_args(root) {
326 return None;
327 }
328 let tools = root.get_table("Tools")?;
329 if (tools.tag.as_deref() != Some("ordered") && tools.entries.len() <= 4)
330 || has_call_args(tools)
331 || !tools.entries.iter().all(|(k, _)| matches!(k, LuaKey::Str(_)))
332 {
333 return None;
334 }
335
336 let cap = tools
337 .entries
338 .len()
339 .saturating_mul(1024)
340 .saturating_add(4096);
341 let mut out = String::with_capacity(cap);
342
343 let mut top_pool: HashMap<&str, NodePool<'_>> = HashMap::with_capacity(self.nodes.len());
344 let mut inner_pool: HashMap<&str, NodePool<'_>> = HashMap::new();
345 let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new();
346 for node in &self.nodes {
347 let pool = if node.internal { &mut inner_pool } else { &mut top_pool };
348 let key = node.name.as_str();
349 if let Some(entry) = pool.get_mut(key) {
350 entry.push(node);
351 } else {
352 pool.insert(key, NodePool::One(node));
353 }
354 if !is_group_kind(&node.kind) {
355 continue;
356 }
357 for (inner_op, inner_port, default) in instance_inputs(&node.raw) {
358 if let Some(d) = default {
359 instance_defaults.insert((inner_op, inner_port), d);
360 }
361 }
362 }
363
364 let positional = can_use_positional(root.entries.iter());
365 write_table_prefix(root.tag.as_deref(), &[], 0, &mut out);
366 out.push_str("{\n");
367
368 let mut seen_current_time = false;
369 let mut seen_global_range = false;
370 let mut seen_render_range = false;
371 let mut seen_audio_filename = false;
372 let mut seen_audio_offset = false;
373 let mut seen_prefs = false;
374 let mut seen_tools = false;
375
376 for (k, v) in &root.entries {
377 if let LuaKey::Str(name) = k {
378 match name.as_str() {
379 "CurrentTime" => {
380 seen_current_time = true;
381 write_indent(&mut out, 1);
382 write_entry_key(k, positional, &mut out);
383 write_value(&LuaValue::Number(self.current_time), 1, &mut out);
384 out.push_str(",\n");
385 continue;
386 }
387 "GlobalRange" => {
388 seen_global_range = true;
389 write_indent(&mut out, 1);
390 write_entry_key(k, positional, &mut out);
391 let gr = vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64);
392 write_value(&gr, 1, &mut out);
393 out.push_str(",\n");
394 continue;
395 }
396 "RenderRange" => {
397 seen_render_range = true;
398 write_indent(&mut out, 1);
399 write_entry_key(k, positional, &mut out);
400 let rr = vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64);
401 write_value(&rr, 1, &mut out);
402 out.push_str(",\n");
403 continue;
404 }
405 "AudioFilename" => {
406 seen_audio_filename = true;
407 write_indent(&mut out, 1);
408 write_entry_key(k, positional, &mut out);
409 if let Some(ref af) = self.audio_filename {
410 write_value(&LuaValue::String(af.clone()), 1, &mut out);
411 } else {
412 write_value(v, 1, &mut out);
413 }
414 out.push_str(",\n");
415 continue;
416 }
417 "AudioOffset" => {
418 seen_audio_offset = true;
419 write_indent(&mut out, 1);
420 write_entry_key(k, positional, &mut out);
421 write_value(&LuaValue::Number(self.audio_offset), 1, &mut out);
422 out.push_str(",\n");
423 continue;
424 }
425 "Prefs" => {
426 seen_prefs = true;
427 write_indent(&mut out, 1);
428 write_entry_key(k, positional, &mut out);
429 if self.prefs_needs_sync(v) {
430 let mut prefs_val = v.clone();
431 let prefs_tbl = match prefs_val.as_table_mut() {
432 Some(t) => t,
433 None => {
434 prefs_val = LuaValue::Table(LuaTable::default());
435 prefs_val.as_table_mut().unwrap()
436 }
437 };
438 self.patch_prefs_table(prefs_tbl);
439 write_value(&prefs_val, 1, &mut out);
440 } else {
441 write_value(v, 1, &mut out);
442 }
443 out.push_str(",\n");
444 continue;
445 }
446 "Tools" => {
447 seen_tools = true;
448 write_indent(&mut out, 1);
449 write_entry_key(k, positional, &mut out);
450 self.write_tools_streaming(
451 tools,
452 &mut top_pool,
453 &mut inner_pool,
454 &instance_defaults,
455 &mut out,
456 );
457 out.push_str(",\n");
458 continue;
459 }
460 _ => {}
461 }
462 }
463 write_indent(&mut out, 1);
464 write_entry_key(k, positional, &mut out);
465 write_value(v, 1, &mut out);
466 out.push_str(",\n");
467 }
468
469 if !seen_current_time {
470 write_root_kv("CurrentTime", &LuaValue::Number(self.current_time), &mut out);
471 }
472 if !seen_global_range {
473 let gr = vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64);
474 write_root_kv("GlobalRange", &gr, &mut out);
475 }
476 if !seen_render_range {
477 let rr = vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64);
478 write_root_kv("RenderRange", &rr, &mut out);
479 }
480 if !seen_audio_filename {
481 if let Some(ref af) = self.audio_filename {
482 write_root_kv("AudioFilename", &LuaValue::String(af.clone()), &mut out);
483 }
484 }
485 if !seen_audio_offset && self.audio_offset != 0.0 {
486 write_root_kv("AudioOffset", &LuaValue::Number(self.audio_offset), &mut out);
487 }
488 if !seen_prefs {
489 let mut prefs_tbl = LuaTable::default();
490 self.patch_prefs_table(&mut prefs_tbl);
491 write_root_kv("Prefs", &LuaValue::Table(prefs_tbl), &mut out);
492 }
493 if !seen_tools {
494 unreachable!("checked root.get_table(\"Tools\")");
495 }
496
497 out.push_str("}\n");
498 Some(out)
499 }
500
501 fn prefs_needs_sync(&self, prefs_val: &LuaValue) -> bool {
502 let Some(ff) = prefs_val
503 .as_table()
504 .and_then(|p| p.get_table("Comp"))
505 .and_then(|c| c.get_table("FrameFormat"))
506 else {
507 return true;
508 };
509 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
510 return true;
511 }
512 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
513 return true;
514 }
515 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
516 return true;
517 }
518 let existing_depth = ff
519 .get_f64("DepthFull")
520 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
521 .unwrap_or(BitDepth::Int8);
522 existing_depth != self.depth_full
523 }
524
525 fn patch_prefs_table(&self, prefs: &mut LuaTable) {
526 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
527 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
528 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
529 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
530 }
531 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
532 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
533 }
534 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
535 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
536 }
537 let existing_depth = ff
538 .get_f64("DepthFull")
539 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
540 .unwrap_or(BitDepth::Int8);
541 if existing_depth != self.depth_full {
542 ff.set(
543 LuaKey::Str("DepthFull".to_owned()),
544 LuaValue::Number((self.depth_full as i32) as f64),
545 );
546 }
547 }
548
549 fn write_tools_streaming<'a>(
550 &'a self,
551 tools: &LuaTable,
552 top_pool: &mut HashMap<&'a str, NodePool<'a>>,
553 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
554 instance_defaults: &HashMap<(&str, &str), ParamValue>,
555 out: &mut String,
556 ) {
557 let mut remaining_splines: HashMap<&str, &BezierSpline> =
558 self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect();
559
560 // Record top-level spline names first so nested `Tools` matches `sync_existing_splines_in_tools`
561 // priority order even if a duplicate modifier name appears at both levels.
562 let mut top_level_spline_names: HashSet<&str> = HashSet::new();
563 if !remaining_splines.is_empty() {
564 for (k, v) in &tools.entries {
565 if let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) {
566 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
567 if is_modifier_type(tag) && remaining_splines.contains_key(name.as_str()) {
568 top_level_spline_names.insert(name.as_str());
569 }
570 }
571 }
572 }
573
574 let mut seen_in_tools: HashSet<&str> = HashSet::with_capacity(tools.entries.len());
575
576 write_table_prefix(tools.tag.as_deref(), &[], 1, out);
577 out.push_str("{\n");
578
579 for (k, v) in &tools.entries {
580 let LuaKey::Str(name) = k else {
581 write_indent(out, 2);
582 write_entry_key(k, true, out);
583 write_value(v, 2, out);
584 out.push_str(",\n");
585 continue;
586 };
587 let Some(tbl) = v.as_table() else {
588 seen_in_tools.insert(name.as_str());
589 write_indent(out, 2);
590 write_entry_key(k, true, out);
591 write_value(v, 2, out);
592 out.push_str(",\n");
593 continue;
594 };
595
596 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
597 if is_modifier_type(tag) {
598 seen_in_tools.insert(name.as_str());
599 write_indent(out, 2);
600 write_entry_key(k, true, out);
601 if let Some(spline) = remaining_splines.remove(name.as_str()) {
602 if !spline_needs_sync(name, spline, tbl) {
603 write_table(tbl, 2, out);
604 } else {
605 let mut cloned = tbl.clone();
606 sync_spline_table(name, spline, &mut cloned);
607 write_table(&cloned, 2, out);
608 }
609 } else {
610 write_table(tbl, 2, out);
611 }
612 out.push_str(",\n");
613 continue;
614 }
615
616 let Some(node) = pop_pool(top_pool, name.as_str()) else {
617 // Deleted flow node.
618 continue;
619 };
620 seen_in_tools.insert(name.as_str());
621
622 write_indent(out, 2);
623 write_entry_key(k, true, out);
624
625 if is_group_kind(&node.kind) {
626 if self.group_can_stream_verbatim(
627 node,
628 tbl,
629 inner_pool,
630 instance_defaults,
631 &mut remaining_splines,
632 &top_level_spline_names,
633 ) {
634 write_table(tbl, 2, out);
635 } else {
636 let mut cloned = tbl.clone();
637 self.sync_node_tool(node, &mut cloned, instance_defaults);
638 if let Some(inner) = cloned.get_table_mut("Tools") {
639 self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults);
640 }
641 sync_group_wiring(node, &mut cloned);
642 if !remaining_splines.is_empty() {
643 if let Some(inner) = cloned.get_table_mut("Tools") {
644 sync_existing_splines_in_tools_excluding(
645 inner,
646 &mut remaining_splines,
647 &top_level_spline_names,
648 );
649 }
650 }
651 write_table(&cloned, 2, out);
652 }
653 } else if self.node_can_stream_verbatim(
654 node,
655 tbl,
656 instance_defaults,
657 &mut remaining_splines,
658 &top_level_spline_names,
659 ) {
660 write_table(tbl, 2, out);
661 } else {
662 let mut cloned = tbl.clone();
663 self.sync_node_tool(node, &mut cloned, instance_defaults);
664 if !remaining_splines.is_empty() {
665 if let Some(inner) = cloned.get_table_mut("Tools") {
666 sync_existing_splines_in_tools_excluding(
667 inner,
668 &mut remaining_splines,
669 &top_level_spline_names,
670 );
671 }
672 }
673 write_table(&cloned, 2, out);
674 }
675 out.push_str(",\n");
676 }
677
678 // Newly added top-level nodes not yet present in `tools`
679 for node in self.nodes.iter().filter(|n| !n.internal) {
680 if seen_in_tools.contains(node.name.as_str()) {
681 continue;
682 }
683 seen_in_tools.insert(node.name.as_str());
684 let Some(node) = pop_pool(top_pool, node.name.as_str()) else {
685 continue;
686 };
687 let mut new_tbl = if node.raw.tag.is_some() {
688 node.raw.clone()
689 } else {
690 LuaTable { tag: None, entries: Vec::new() }
691 };
692 if new_tbl.tag.is_none() {
693 new_tbl.tag = Some(node.kind.clone());
694 }
695 self.sync_node_tool(node, &mut new_tbl, instance_defaults);
696 if is_group_kind(&node.kind) {
697 if let Some(inner) = new_tbl.get_table_mut("Tools") {
698 self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults);
699 }
700 sync_group_wiring(node, &mut new_tbl);
701 }
702 if !remaining_splines.is_empty() {
703 if let Some(inner) = new_tbl.get_table_mut("Tools") {
704 sync_existing_splines_in_tools_excluding(
705 inner,
706 &mut remaining_splines,
707 &top_level_spline_names,
708 );
709 }
710 }
711 write_indent(out, 2);
712 write_entry_key(&LuaKey::Str(node.name.clone()), true, out);
713 write_table(&new_tbl, 2, out);
714 out.push_str(",\n");
715 }
716
717 // Newly added splines not yet present in `tools`
718 if !remaining_splines.is_empty() {
719 let mut new_names: Vec<&str> = remaining_splines.keys().copied().collect();
720 new_names.sort_unstable();
721 for spline_name in new_names {
722 let spline = remaining_splines[spline_name];
723 let mut sp_tbl = LuaTable {
724 tag: Some("BezierSpline".to_owned()),
725 entries: Vec::with_capacity(2),
726 };
727 sp_tbl.set(
728 LuaKey::Str("SplineColor".to_owned()),
729 spline_color_lua(spline.color),
730 );
731 sp_tbl.set(
732 LuaKey::Str("KeyFrames".to_owned()),
733 LuaValue::Table(build_keyframes_table(spline)),
734 );
735 write_indent(out, 2);
736 write_entry_key(&LuaKey::Str(spline_name.to_owned()), true, out);
737 write_table(&sp_tbl, 2, out);
738 out.push_str(",\n");
739 }
740 }
741
742 write_indent(out, 1);
743 out.push('}');
744 }
745
746 fn node_header_needs_sync(&self, node: &Node, tool_tbl: &LuaTable) -> bool {
747 // ViewInfo.Pos
748 if let Some(vi) = tool_tbl.get_table("ViewInfo") {
749 let pos_changed = vi
750 .get_table("Pos")
751 .and_then(read_vec2)
752 .is_none_or(|[x, y]| {
753 (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4
754 });
755 if pos_changed {
756 return true;
757 }
758 } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 {
759 return true;
760 }
761
762 // PassThrough
763 if node.bypassed {
764 if tool_tbl.get_bool("PassThrough") != Some(true) {
765 return true;
766 }
767 } else if tool_tbl.get("PassThrough").is_some() {
768 return true;
769 }
770
771 // Loader clip timing
772 if node.kind == "Loader" {
773 let clip_exists = tool_tbl.get_table("Clips").is_some_and(|c| {
774 c.entries
775 .iter()
776 .any(|(_, v)| v.as_table().is_some_and(|t| t.get_str("Filename").is_some()))
777 });
778 if clip_exists {
779 let edited = |port: &str| {
780 let now = node.static_number(port)?;
781 let before = tool_tbl
782 .get_table("Inputs")
783 .and_then(|i| i.get_table(port))
784 .and_then(|t| t.get("Value"))
785 .and_then(lua_value_as_number);
786 (before != Some(now)).then_some(now)
787 };
788 if edited("GlobalIn").is_some()
789 || edited("GlobalOut").is_some()
790 || edited("Loop").is_some()
791 || edited("Reverse").is_some()
792 {
793 return true;
794 }
795 }
796 }
797
798 false
799 }
800
801 fn node_can_stream_verbatim<'a>(
802 &'a self,
803 node: &Node,
804 tool_tbl: &LuaTable,
805 instance_defaults: &HashMap<(&str, &str), ParamValue>,
806 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
807 top_level_spline_names: &HashSet<&str>,
808 ) -> bool {
809 if self.node_header_needs_sync(node, tool_tbl) {
810 return false;
811 }
812 let master_inputs = node
813 .raw
814 .get_str("SourceOp")
815 .and_then(|m| self.find_node(m))
816 .map(|mid| &self.nodes[mid.0].inputs);
817 if node_inputs_need_sync(
818 node,
819 master_inputs,
820 instance_defaults,
821 &self.cross_macro_wires,
822 tool_tbl,
823 ) {
824 return false;
825 }
826 if let Some(inner) = tool_tbl.get_table("Tools") {
827 if !nested_splines_verbatim(inner, remaining_splines, top_level_spline_names) {
828 return false;
829 }
830 consume_nested_splines(inner, remaining_splines, top_level_spline_names);
831 }
832 true
833 }
834
835 fn group_can_stream_verbatim<'a>(
836 &'a self,
837 node: &Node,
838 tool_tbl: &LuaTable,
839 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
840 instance_defaults: &HashMap<(&str, &str), ParamValue>,
841 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
842 top_level_spline_names: &HashSet<&str>,
843 ) -> bool {
844 if self.node_header_needs_sync(node, tool_tbl) {
845 return false;
846 }
847 if group_wiring_needs_sync(node, tool_tbl) {
848 return false;
849 }
850 let Some(inner_tools) = tool_tbl.get_table("Tools") else {
851 return true;
852 };
853 let mut peek_offsets: HashMap<&str, usize> = HashMap::new();
854 if !self.check_inner_tools_verbatim(
855 inner_tools,
856 inner_pool,
857 &mut peek_offsets,
858 instance_defaults,
859 remaining_splines,
860 top_level_spline_names,
861 ) {
862 return false;
863 }
864 // All checks passed: commit pops from `inner_pool` and removals from `remaining_splines`.
865 commit_inner_tools_verbatim(
866 inner_tools,
867 inner_pool,
868 remaining_splines,
869 top_level_spline_names,
870 );
871 true
872 }
873
874 fn check_inner_tools_verbatim<'a, 'b>(
875 &'a self,
876 inner_tools: &'b LuaTable,
877 inner_pool: &HashMap<&'a str, NodePool<'a>>,
878 peek_offsets: &mut HashMap<&'b str, usize>,
879 instance_defaults: &HashMap<(&str, &str), ParamValue>,
880 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,
881 top_level_spline_names: &HashSet<&str>,
882 ) -> bool {
883 // Check modifiers at this level first (matching `sync_existing_splines_in_tools` top-down order).
884 for (k, v) in &inner_tools.entries {
885 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
886 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
887 if is_modifier_type(tag) {
888 if !top_level_spline_names.contains(name.as_str()) {
889 if let Some(&spline) = remaining_splines.get(name.as_str()) {
890 if spline_needs_sync(name, spline, tbl) {
891 return false;
892 }
893 }
894 }
895 continue;
896 }
897 // Flow node: check if it survived `retain` and matches `node`
898 let offset = peek_offsets.entry(name.as_str()).or_insert(0);
899 let Some(inner_node) = inner_pool.get(name.as_str()).and_then(|p| p.peek_at(*offset)) else {
900 // Deleted inner node!
901 return false;
902 };
903 *offset += 1;
904
905 if is_group_kind(&inner_node.kind) {
906 if self.node_header_needs_sync(inner_node, tbl) || group_wiring_needs_sync(inner_node, tbl) {
907 return false;
908 }
909 if let Some(sub_tools) = tbl.get_table("Tools") {
910 if !self.check_inner_tools_verbatim(
911 sub_tools,
912 inner_pool,
913 peek_offsets,
914 instance_defaults,
915 remaining_splines,
916 top_level_spline_names,
917 ) {
918 return false;
919 }
920 }
921 } else {
922 if self.node_header_needs_sync(inner_node, tbl) {
923 return false;
924 }
925 let master_inputs = inner_node
926 .raw
927 .get_str("SourceOp")
928 .and_then(|m| self.find_node(m))
929 .map(|mid| &self.nodes[mid.0].inputs);
930 if node_inputs_need_sync(
931 inner_node,
932 master_inputs,
933 instance_defaults,
934 &self.cross_macro_wires,
935 tbl,
936 ) {
937 return false;
938 }
939 if let Some(sub_tools) = tbl.get_table("Tools") {
940 if !nested_splines_verbatim(sub_tools, remaining_splines, top_level_spline_names) {
941 return false;
942 }
943 }
944 }
945 }
946 true
947 }
250948 /// Atomically saves this composition to `path`.
251949 /// If `path` already exists, backs up the original bytes to
252950 /// `<temp_dir>/fission-backups/<stem>_<unix_millis>_<pid>_<seq>.comp.bak` and returns `Ok(Some(backup_path))`.
......@@ -325,6 +1023,239 @@ impl Comp {
3251023 }
3261024}
3271025
1026fn write_root_kv(key: &str, val: &LuaValue, out: &mut String) {
1027 write_indent(out, 1);
1028 out.push_str(key);
1029 out.push_str(" = ");
1030 write_value(val, 1, out);
1031 out.push_str(",\n");
1032}
1033
1034fn commit_inner_tools_verbatim<'a>(
1035 inner_tools: &LuaTable,
1036 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
1037 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
1038 top_level_spline_names: &HashSet<&str>,
1039) {
1040 for (k, v) in &inner_tools.entries {
1041 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1042 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
1043 if is_modifier_type(tag) {
1044 if !top_level_spline_names.contains(name.as_str()) {
1045 remaining_splines.remove(name.as_str());
1046 }
1047 continue;
1048 }
1049 let Some(inner_node) = pop_pool(inner_pool, name.as_str()) else { continue };
1050 if let Some(sub_tools) = tbl.get_table("Tools") {
1051 if is_group_kind(&inner_node.kind) {
1052 commit_inner_tools_verbatim(sub_tools, inner_pool, remaining_splines, top_level_spline_names);
1053 } else {
1054 consume_nested_splines(sub_tools, remaining_splines, top_level_spline_names);
1055 }
1056 }
1057 }
1058}
1059
1060fn nested_splines_verbatim(
1061 tools: &LuaTable,
1062 remaining_splines: &HashMap<&str, &BezierSpline>,
1063 top_level_spline_names: &HashSet<&str>,
1064) -> bool {
1065 if remaining_splines.is_empty() {
1066 return true;
1067 }
1068 for (k, v) in &tools.entries {
1069 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1070 if !top_level_spline_names.contains(name.as_str()) {
1071 if let Some(&spline) = remaining_splines.get(name.as_str()) {
1072 if spline_needs_sync(name, spline, tbl) {
1073 return false;
1074 }
1075 }
1076 }
1077 if let Some(sub) = tbl.get_table("Tools") {
1078 if !nested_splines_verbatim(sub, remaining_splines, top_level_spline_names) {
1079 return false;
1080 }
1081 }
1082 }
1083 true
1084}
1085
1086fn consume_nested_splines(
1087 tools: &LuaTable,
1088 remaining_splines: &mut HashMap<&str, &BezierSpline>,
1089 top_level_spline_names: &HashSet<&str>,
1090) {
1091 if remaining_splines.is_empty() {
1092 return;
1093 }
1094 for (k, v) in &tools.entries {
1095 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1096 if !top_level_spline_names.contains(name.as_str()) {
1097 remaining_splines.remove(name.as_str());
1098 }
1099 if let Some(sub) = tbl.get_table("Tools") {
1100 consume_nested_splines(sub, remaining_splines, top_level_spline_names);
1101 }
1102 }
1103}
1104
1105fn sync_existing_splines_in_tools_excluding(
1106 tools: &mut LuaTable,
1107 remaining: &mut HashMap<&str, &BezierSpline>,
1108 excluded: &HashSet<&str>,
1109) {
1110 if remaining.is_empty() {
1111 return;
1112 }
1113 for (k, v) in &mut tools.entries {
1114 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };
1115 if excluded.contains(name.as_str()) {
1116 continue;
1117 }
1118 if let Some(spline) = remaining.remove(name.as_str()) {
1119 sync_spline_table(name, spline, tbl);
1120 if remaining.is_empty() {
1121 return;
1122 }
1123 }
1124 }
1125 for (_, v) in &mut tools.entries {
1126 if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) {
1127 sync_existing_splines_in_tools_excluding(inner, remaining, excluded);
1128 if remaining.is_empty() {
1129 return;
1130 }
1131 }
1132 }
1133}
1134
1135fn spline_needs_sync(spline_name: &str, spline: &BezierSpline, tbl: &LuaTable) -> bool {
1136 if spline_color_from_lua(tbl) != spline.color {
1137 return true;
1138 }
1139 if keyframes_match_lua(spline, tbl) {
1140 return false;
1141 }
1142 let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl);
1143 let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && {
1144 let mut normalized = existing.clone();
1145 normalized.apply_hue_curves_cyclic_ends();
1146 normalized.keyframes == spline.keyframes
1147 };
1148 existing.keyframes != spline.keyframes && !unchanged_cyclic
1149}
1150
1151fn group_wiring_needs_sync(node: &Node, group_tbl: &LuaTable) -> bool {
1152 let Some(inputs) = group_tbl.get_table("Inputs") else {
1153 return false;
1154 };
1155 let Some(inner_tools) = group_tbl.get_table("Tools") else {
1156 return false;
1157 };
1158 for (k, v) in &inputs.entries {
1159 let LuaKey::Str(port) = k else { continue };
1160 let Some(t) = v.as_table() else { continue };
1161 let Some(inner_op) = t.get_str("SourceOp") else { continue };
1162 let Some(inner_port) = t.get_str("Source") else { continue };
1163 let desired = node.inputs.get(port);
1164 if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op)) {
1165 continue;
1166 }
1167 let Some(inner_tbl) = super::math::find_raw_tool(inner_tools, inner_op) else {
1168 continue;
1169 };
1170 let existing_it = inner_tbl
1171 .get_table("Inputs")
1172 .and_then(|i| i.get_table(inner_port));
1173 let cur_src_op = existing_it.and_then(|it| it.get_str("SourceOp"));
1174 let cur_src_out = existing_it.and_then(|it| it.get_str("Source"));
1175 match desired {
1176 Some(b) => {
1177 if existing_it.is_none()
1178 || (cur_src_op, cur_src_out) != (b.source_op.as_deref(), b.source_output.as_deref())
1179 {
1180 return true;
1181 }
1182 }
1183 None if cur_src_op.is_some() => {
1184 return true;
1185 }
1186 _ => {}
1187 }
1188 }
1189 false
1190}
1191
1192fn node_inputs_need_sync(
1193 node: &Node,
1194 master_inputs: Option<&HashMap<String, InputBinding>>,
1195 instance_defaults: &HashMap<(&str, &str), ParamValue>,
1196 cross_macro_wires: &HashSet<(String, String)>,
1197 tool_tbl: &LuaTable,
1198) -> bool {
1199 let in_tbl = tool_tbl.get_table("Inputs");
1200 if let Some(in_tbl) = in_tbl {
1201 for (k, v) in &in_tbl.entries {
1202 let LuaKey::Str(port) = k else { continue };
1203 if v.as_table().is_some() && !node.inputs.contains_key(port) {
1204 return true;
1205 }
1206 }
1207 }
1208
1209 for (port, binding) in &node.inputs {
1210 if !instance_defaults.is_empty()
1211 && binding.source_op.is_none()
1212 && binding.expression.is_none()
1213 && binding.value.is_some()
1214 && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str()))
1215 && in_tbl
1216 .and_then(|i| i.get_table(port))
1217 .is_none_or(|t| t.get("Value").is_none())
1218 {
1219 continue;
1220 }
1221
1222 if let Some(it) = in_tbl.and_then(|i| i.get_table(port)) {
1223 let clear_src = !cross_macro_wires.is_empty()
1224 && binding.source_op.is_none()
1225 && cross_macro_wires.contains(&(node.name.clone(), port.clone()));
1226 if binding_matches_lua(it, binding, clear_src) {
1227 continue;
1228 }
1229 // Check empty-stub master inheritance skip
1230 let is_empty_stub = it.get("Value").is_none()
1231 && (clear_src || it.get_str("SourceOp").is_none())
1232 && it.get_str("Expression").is_none();
1233 if is_empty_stub && master_inputs.is_some_and(|m| m.get(port) == Some(binding)) {
1234 continue;
1235 }
1236 return true;
1237 } else {
1238 if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() {
1239 continue;
1240 }
1241 if binding.source_op.is_none()
1242 && binding.expression.is_none()
1243 && binding.value.is_some()
1244 && binding.value == user_control_default(&node.raw, port)
1245 {
1246 continue;
1247 }
1248 if let Some(master) = master_inputs {
1249 if master.get(port) == Some(binding) {
1250 continue;
1251 }
1252 }
1253 return true;
1254 }
1255 }
1256 false
1257}
1258
3281259pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue {
3291260 LuaValue::Table(LuaTable {
3301261 tag: None,
......@@ -467,6 +1398,88 @@ fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) {
4671398 }
4681399}
4691400
1401fn lua_value_as_number(v: &LuaValue) -> Option<f64> {
1402 match v {
1403 LuaValue::Number(n) => Some(*n),
1404 LuaValue::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
1405 LuaValue::Table(t) if t.tag.as_deref() == Some("Number") => Some(t.get_f64("Value").unwrap_or(0.0)),
1406 _ => None,
1407 }
1408}
1409
1410fn param_matches_lua(v: &LuaValue, p: &ParamValue) -> bool {
1411 match (v, p) {
1412 (LuaValue::Number(n), ParamValue::Number(pn)) => n == pn,
1413 (LuaValue::Bool(b), ParamValue::Number(pn)) => (if *b { 1.0 } else { 0.0 }) == *pn,
1414 (LuaValue::String(s), ParamValue::Text(ps)) => s == ps,
1415 (LuaValue::Table(t), _) => match t.tag.as_deref() {
1416 Some("FuID") => {
1417 matches!(p, ParamValue::FuId(pf) if t.get_index(1).and_then(LuaValue::as_str).unwrap_or("") == pf)
1418 }
1419 Some("Number") => {
1420 matches!(p, ParamValue::Number(pn) if t.get_f64("Value").unwrap_or(0.0) == *pn)
1421 }
1422 Some("Gradient") => {
1423 matches!(p, ParamValue::Gradient(pg) if Gradient::from_lua(t) == *pg)
1424 }
1425 _ => {
1426 if let Some(pt) = read_vec2(t) {
1427 matches!(p, ParamValue::Point(pp) if pt == *pp)
1428 } else {
1429 matches!(p, ParamValue::Raw(LuaValue::Table(rt)) if rt == t)
1430 }
1431 }
1432 },
1433 (LuaValue::Nil, ParamValue::Raw(LuaValue::Nil)) => true,
1434 _ => false,
1435 }
1436}
1437
1438fn binding_matches_lua(it: &LuaTable, binding: &InputBinding, clear_source_op: bool) -> bool {
1439 let mut source_op: Option<&str> = None;
1440 let mut source_output: Option<&str> = None;
1441 let mut expression: Option<&str> = None;
1442 let mut value: Option<&LuaValue> = None;
1443 for (k, v) in &it.entries {
1444 let LuaKey::Str(s) = k else { continue };
1445 match s.as_str() {
1446 "SourceOp" => {
1447 if let Some(sv) = v.as_str() {
1448 source_op = Some(sv);
1449 }
1450 }
1451 "Source" => {
1452 if let Some(sv) = v.as_str() {
1453 source_output = Some(sv);
1454 }
1455 }
1456 "Expression" => {
1457 if let Some(sv) = v.as_str() {
1458 expression = Some(sv);
1459 }
1460 }
1461 "Value" => {
1462 value = Some(v);
1463 }
1464 _ => {}
1465 }
1466 }
1467 if clear_source_op {
1468 source_op = None;
1469 }
1470 if source_op != binding.source_op.as_deref()
1471 || source_output != binding.source_output.as_deref()
1472 || expression != binding.expression.as_deref()
1473 {
1474 return false;
1475 }
1476 match (value, &binding.value) {
1477 (None, None) => true,
1478 (Some(lv), Some(pv)) => param_matches_lua(lv, pv),
1479 _ => false,
1480 }
1481}
1482
4701483fn sync_node_inputs(
4711484 node: &Node,
4721485 master_inputs: Option<&HashMap<String, InputBinding>>,
......@@ -487,37 +1500,38 @@ fn sync_node_inputs(
4871500
4881501 // Collect sorted port names for deterministic output when appending new inputs.
4891502 let mut ports: Vec<&String> = node.inputs.keys().collect();
490 ports.sort();
1503 if ports.len() > 1 {
1504 ports.sort();
1505 }
4911506
4921507 for port in ports {
4931508 let binding = &node.inputs[port];
4941509 // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default.
495 if binding.source_op.is_none()
1510 if !instance_defaults.is_empty()
1511 && binding.source_op.is_none()
4961512 && binding.expression.is_none()
4971513 && binding.value.is_some()
4981514 && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str()))
4991515 && tool_tbl
5001516 .get_table("Inputs")
5011517 .and_then(|i| i.get_table(port))
502 .is_none_or(|t| parse_input_binding(t).value.is_none())
1518 .is_none_or(|t| t.get("Value").is_none())
5031519 {
5041520 continue;
5051521 }
506 let existing_binding = tool_tbl
507 .get_table("Inputs")
508 .and_then(|i| i.get_table(port))
509 .map(parse_input_binding)
510 .map(|mut b| {
511 if binding.source_op.is_none() && cross_macro_wires.contains(&(node.name.clone(), port.clone())) {
512 b.source_op = None;
513 }
514 b
515 });
5161522
517 if let Some(orig) = existing_binding {
518 if orig == *binding {
1523 let existing_tbl = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port));
1524 if let Some(it) = existing_tbl {
1525 let clear_src = !cross_macro_wires.is_empty()
1526 && binding.source_op.is_none()
1527 && cross_macro_wires.contains(&(node.name.clone(), port.clone()));
1528 if binding_matches_lua(it, binding, clear_src) {
5191529 continue;
5201530 }
1531 let mut orig = parse_input_binding(it);
1532 if clear_src {
1533 orig.source_op = None;
1534 }
5211535 // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools.
5221536 if orig.value.is_none()
5231537 && orig.source_op.is_none()
......@@ -591,7 +1605,7 @@ fn sync_node_inputs(
5911605
5921606 let mut it = LuaTable {
5931607 tag: Some("Input".to_owned()),
594 entries: Vec::new(),
1608 entries: Vec::with_capacity(4),
5951609 };
5961610 if let Some(op) = &binding.source_op {
5971611 it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone()));
......@@ -670,11 +1684,110 @@ fn build_keyframes_table(spline: &BezierSpline) -> LuaTable {
6701684 tbl
6711685}
6721686
1687/// Walks `tools` in top-level-before-nested order to sync all existing splines in one O(T) pass.
1688fn sync_existing_splines_in_tools(tools: &mut LuaTable, remaining: &mut HashMap<&str, &BezierSpline>) {
1689 if remaining.is_empty() {
1690 return;
1691 }
1692 for (k, v) in &mut tools.entries {
1693 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };
1694 if let Some(spline) = remaining.remove(name.as_str()) {
1695 sync_spline_table(name, spline, tbl);
1696 if remaining.is_empty() {
1697 return;
1698 }
1699 }
1700 }
1701 for (_, v) in &mut tools.entries {
1702 if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) {
1703 sync_existing_splines_in_tools(inner, remaining);
1704 if remaining.is_empty() {
1705 return;
1706 }
1707 }
1708 }
1709}
1710
1711fn spline_color_from_lua(table: &LuaTable) -> [u8; 3] {
1712 table
1713 .get_table("SplineColor")
1714 .map(|c| {
1715 [
1716 c.get_f64("Red").unwrap_or(200.0) as u8,
1717 c.get_f64("Green").unwrap_or(140.0) as u8,
1718 c.get_f64("Blue").unwrap_or(255.0) as u8,
1719 ]
1720 })
1721 .unwrap_or([210, 140, 255])
1722}
1723
1724fn keyframes_match_lua(spline: &BezierSpline, table: &LuaTable) -> bool {
1725 let kf_table = table.get_table("KeyFrames").or_else(|| {
1726 table
1727 .get_table("KeyColorSplines")
1728 .and_then(|kc| kc.get_index(0))
1729 .and_then(LuaValue::as_table)
1730 });
1731 let Some(kfs) = kf_table else {
1732 return spline.keyframes.is_empty();
1733 };
1734 let mut idx = 0usize;
1735 let mut prev_time = f64::NEG_INFINITY;
1736 for (k, v) in &kfs.entries {
1737 let time = match k {
1738 LuaKey::Index(i) => *i as f64,
1739 LuaKey::Number(n) => *n,
1740 _ => continue,
1741 };
1742 let Some(kt) = v.as_table() else { continue };
1743 // Fall back to full parse + sort if raw keyframes are not strictly ascending.
1744 if !(time > prev_time) && idx > 0 {
1745 return false;
1746 }
1747 prev_time = time;
1748 let Some(target) = spline.keyframes.get(idx) else {
1749 return false;
1750 };
1751 let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0);
1752 let lh = kt.get_table("LH").and_then(read_vec2);
1753 let rh = kt.get_table("RH").and_then(read_vec2);
1754 let mut flags = KeyFlags::default();
1755 if let Some(ft) = kt.get_table("Flags") {
1756 flags.linear = ft.get_bool("Linear").unwrap_or(false);
1757 flags.step_in = ft.get_bool("StepIn").unwrap_or(false);
1758 flags.step_out = ft.get_bool("StepOut").unwrap_or(false);
1759 flags.loop_after = ft.get_bool("Loop").unwrap_or(false);
1760 flags.loop_rel = ft.get_bool("LoopRel").unwrap_or(false);
1761 flags.ping_pong = ft.get_bool("PingPong").unwrap_or(false);
1762 flags.locked_y = ft.get_bool("LockedY").unwrap_or(false);
1763 }
1764 let handle_mode = if flags.linear {
1765 HandleMode::Vector
1766 } else {
1767 HandleMode::Free
1768 };
1769 if target.time != time
1770 || target.value != value
1771 || target.lh != lh
1772 || target.rh != rh
1773 || target.flags != flags
1774 || target.handle_mode != handle_mode
1775 {
1776 return false;
1777 }
1778 idx += 1;
1779 }
1780 idx == spline.keyframes.len()
1781}
1782
6731783fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) {
674 let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl);
675 if existing.color != spline.color {
1784 if spline_color_from_lua(tbl) != spline.color {
6761785 tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color));
6771786 }
1787 if keyframes_match_lua(spline, tbl) {
1788 return;
1789 }
1790 let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl);
6781791 let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && {
6791792 let mut normalized = existing.clone();
6801793 normalized.apply_hue_curves_cyclic_ends();
crates/model/src/lua_value.rs+473-264
......@@ -97,7 +97,10 @@ impl LuaTable {
9797
9898 /// Serializes this table using Blackmagic Fusion `.comp` Lua table syntax.
9999 pub fn to_fusion_string(&self) -> String {
100 let mut out = String::new();
100 let cap = self
101 .get_table("Tools")
102 .map_or_else(|| self.entries.len().saturating_mul(64), |t| t.entries.len().saturating_mul(1024).saturating_add(4096));
103 let mut out = String::with_capacity(cap);
101104 write_table(self, 0, &mut out);
102105 out
103106 }
......@@ -221,32 +224,53 @@ impl<'a> Parser<'a> {
221224 Some(b)
222225 }
223226
227 #[inline(always)]
224228 fn skip_ws_and_comments(&mut self) -> Result<(), ParseError> {
229 let src = self.src;
230 let len = src.len();
231 let mut p = self.pos;
232 while p < len && matches!(src[p], b' ' | b'\t' | b'\r' | b'\n') {
233 p += 1;
234 }
235 self.pos = p;
236 if p + 1 < len && src[p] == b'-' && src[p + 1] == b'-' {
237 self.skip_comments_and_ws_slow()
238 } else {
239 Ok(())
240 }
241 }
242
243 #[cold]
244 fn skip_comments_and_ws_slow(&mut self) -> Result<(), ParseError> {
245 let src = self.src;
246 let len = src.len();
247 let mut p = self.pos;
225248 loop {
226 while let Some(b) = self.peek() {
227 if matches!(b, b' ' | b'\t' | b'\r' | b'\n') {
228 self.pos += 1;
229 } else {
230 break;
231 }
249 while p < len && matches!(src[p], b' ' | b'\t' | b'\r' | b'\n') {
250 p += 1;
232251 }
233 if self.peek() == Some(b'-') && self.peek_at(1) == Some(b'-') {
234 self.pos += 2;
235 if self.peek() == Some(b'[') {
252 if p + 1 < len && src[p] == b'-' && src[p + 1] == b'-' {
253 p += 2;
254 if p < len && src[p] == b'[' {
255 self.pos = p;
236256 if let Some(level) = self.try_open_long_bracket() {
237257 self.skip_long_bracket(level)?;
258 p = self.pos;
238259 continue;
239260 }
261 p = self.pos;
240262 }
241 while let Some(b) = self.bump() {
242 if b == b'\n' {
243 break;
244 }
263 while p < len && src[p] != b'\n' {
264 p += 1;
265 }
266 if p < len {
267 p += 1;
245268 }
246269 continue;
247270 }
248271 break;
249272 }
273 self.pos = p;
250274 Ok(())
251275 }
252276
......@@ -269,22 +293,29 @@ impl<'a> Parser<'a> {
269293
270294 fn skip_long_bracket(&mut self, level: usize) -> Result<String, ParseError> {
271295 let start = self.pos;
272 while self.pos < self.src.len() {
273 if self.src[self.pos] == b']' {
274 let mut i = self.pos + 1;
275 let mut eq = 0;
276 while i < self.src.len() && self.src[i] == b'=' && eq < level {
277 i += 1;
278 eq += 1;
279 }
280 if eq == level && i < self.src.len() && self.src[i] == b']' {
281 let s = String::from_utf8_lossy(&self.src[start..self.pos]).into_owned();
282 self.pos = i + 1;
283 return Ok(s);
284 }
296 let src = self.src;
297 let len = src.len();
298 let mut p = start;
299 while let Some(rel) = src[p..].iter().position(|&b| b == b']') {
300 let close_start = p + rel;
301 let mut i = close_start + 1;
302 let mut eq = 0;
303 while i < len && src[i] == b'=' && eq < level {
304 i += 1;
305 eq += 1;
285306 }
286 self.pos += 1;
307 if eq == level && i < len && src[i] == b']' {
308 let slice = &src[start..close_start];
309 let s = match std::str::from_utf8(slice) {
310 Ok(v) => v.to_owned(),
311 Err(_) => String::from_utf8_lossy(slice).into_owned(),
312 };
313 self.pos = i + 1;
314 return Ok(s);
315 }
316 p = close_start + 1;
287317 }
318 self.pos = len;
288319 Err(self.err("unterminated long bracket string/comment"))
289320 }
290321
......@@ -318,26 +349,31 @@ impl<'a> Parser<'a> {
318349
319350 fn parse_ident_or_constructor(&mut self) -> Result<LuaValue, ParseError> {
320351 let start = self.pos;
321 while let Some(b) = self.peek() {
322 if is_ident_cont(b) || b == b'.' {
323 self.pos += 1;
324 } else {
325 break;
326 }
352 let src = self.src;
353 let len = src.len();
354 let mut p = start;
355 while p < len && (is_ident_cont(src[p]) || src[p] == b'.') {
356 p += 1;
327357 }
328 let ident = std::str::from_utf8(&self.src[start..self.pos])
329 .map_err(|_| self.err("invalid UTF-8 identifier"))?
330 .to_owned();
358 self.pos = p;
359 self.finish_ident_or_constructor(start, p)
360 }
331361
332 match ident.as_str() {
333 "true" => return Ok(LuaValue::Bool(true)),
334 "false" => return Ok(LuaValue::Bool(false)),
335 "nil" => return Ok(LuaValue::Nil),
336 "inf" | "INF" => return Ok(LuaValue::Number(f64::INFINITY)),
337 "nan" | "NaN" | "NAN" => return Ok(LuaValue::Number(f64::NAN)),
362 fn finish_ident_or_constructor(&mut self, start: usize, end: usize) -> Result<LuaValue, ParseError> {
363 let ident_bytes = &self.src[start..end];
364 match ident_bytes {
365 b"true" => return Ok(LuaValue::Bool(true)),
366 b"false" => return Ok(LuaValue::Bool(false)),
367 b"nil" => return Ok(LuaValue::Nil),
368 b"inf" | b"INF" => return Ok(LuaValue::Number(f64::INFINITY)),
369 b"nan" | b"NaN" | b"NAN" => return Ok(LuaValue::Number(f64::NAN)),
338370 _ => {}
339371 }
340372
373 let ident = std::str::from_utf8(ident_bytes)
374 .map_err(|_| self.err("invalid UTF-8 identifier"))?
375 .to_owned();
376
341377 self.skip_ws_and_comments()?;
342378
343379 // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)`
......@@ -369,7 +405,7 @@ impl<'a> Parser<'a> {
369405 return Ok(LuaValue::Table(table));
370406 }
371407 // Standalone call like `Point(0.5, 0.5)` or `FuID("Foo")`
372 let mut table = LuaTable { tag: Some(ident), entries: Vec::new() };
408 let mut table = LuaTable { tag: Some(ident), entries: Vec::with_capacity(args.len()) };
373409 for (i, arg) in args.into_iter().enumerate() {
374410 table.entries.push((LuaKey::Index((i + 1) as i64), arg));
375411 }
......@@ -397,61 +433,38 @@ impl<'a> Parser<'a> {
397433 if self.bump() != Some(b'{') {
398434 return Err(self.err("expected '{'"));
399435 }
400 let mut entries = Vec::new();
436 let mut first_entry: Option<(LuaKey, LuaValue)> = None;
437 let mut entries: Option<Vec<(LuaKey, LuaValue)>> = None;
401438 let mut next_index: i64 = 1;
402439
403440 loop {
404441 self.skip_ws_and_comments()?;
405 match self.peek() {
406 None => {
407 // Gracefully close open tables on truncated/export-clipped `.comp` files.
408 break;
409 }
410 Some(b'}') => {
442 let Some(b) = self.peek() else {
443 // Gracefully close open tables on truncated/export-clipped `.comp` files.
444 break;
445 };
446 match b {
447 b'}' => {
411448 self.pos += 1;
412449 break;
413450 }
414 Some(b',') | Some(b';') => {
451 b',' | b';' => {
415452 self.pos += 1;
416453 continue;
417454 }
418455 _ => {}
419456 }
420457
421 // Decide between `[expr] = val`, `ident = val`, or positional `val`
422 if self.peek() == Some(b'[') && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') {
423 self.pos += 1; // consume '['
424 self.skip_ws_and_comments()?;
425 let key_val = self.parse_value()?;
426 self.skip_ws_and_comments()?;
427 if self.bump() != Some(b']') {
428 return Err(self.err("expected ']' after table key"));
429 }
430 self.skip_ws_and_comments()?;
431 if self.bump() != Some(b'=') {
432 return Err(self.err("expected '=' after [key]"));
433 }
434 let val = self.parse_value()?;
435 let key = match key_val {
436 LuaValue::String(s) => LuaKey::Str(s),
437 LuaValue::Number(n) => {
438 if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) {
439 LuaKey::Index(n as i64)
440 } else {
441 LuaKey::Number(n)
442 }
443 }
444 other => LuaKey::Str(format!("{other:?}")),
445 };
446 entries.push((key, val));
447 } else if let Some((key, saved_pos)) = self.try_ident_equals() {
448 let _ = saved_pos;
449 let val = self.parse_value()?;
450 entries.push((LuaKey::Str(key), val));
458 let entry = self.parse_table_entry(b, &mut next_index)?;
459 if let Some(ref mut vec) = entries {
460 vec.push(entry);
461 } else if let Some(prev) = first_entry.take() {
462 let mut vec = Vec::with_capacity(4);
463 vec.push(prev);
464 vec.push(entry);
465 entries = Some(vec);
451466 } else {
452 let val = self.parse_value()?;
453 entries.push((LuaKey::Index(next_index), val));
454 next_index += 1;
467 first_entry = Some(entry);
455468 }
456469
457470 self.skip_ws_and_comments()?;
......@@ -460,187 +473,313 @@ impl<'a> Parser<'a> {
460473 }
461474 }
462475
476 let entries = match (entries, first_entry) {
477 (Some(vec), _) => vec,
478 (None, Some(e)) => vec![e],
479 (None, None) => Vec::new(),
480 };
463481 Ok(LuaTable { tag, entries })
464482 }
465483
466 fn try_ident_equals(&mut self) -> Option<(String, usize)> {
467 let saved = self.pos;
468 let b = self.peek()?;
469 if !is_ident_start(b) {
470 return None;
471 }
472 let start = self.pos;
473 while let Some(c) = self.peek() {
474 if is_ident_cont(c) {
475 self.pos += 1;
484 #[inline(always)]
485 fn parse_table_entry(&mut self, b: u8, next_index: &mut i64) -> Result<(LuaKey, LuaValue), ParseError> {
486 if b == b'[' && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') {
487 self.pos += 1; // consume '['
488 self.skip_ws_and_comments()?;
489 let key_val = self.parse_value()?;
490 self.skip_ws_and_comments()?;
491 if self.bump() != Some(b']') {
492 return Err(self.err("expected ']' after table key"));
493 }
494 self.skip_ws_and_comments()?;
495 if self.bump() != Some(b'=') {
496 return Err(self.err("expected '=' after [key]"));
497 }
498 let val = self.parse_value()?;
499 let key = match key_val {
500 LuaValue::String(s) => LuaKey::Str(s),
501 LuaValue::Number(n) => {
502 if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) {
503 LuaKey::Index(n as i64)
504 } else {
505 LuaKey::Number(n)
506 }
507 }
508 other => LuaKey::Str(format!("{other:?}")),
509 };
510 Ok((key, val))
511 } else if is_ident_start(b) {
512 let start = self.pos;
513 let src = self.src;
514 let len = src.len();
515 let mut p = start + 1;
516 while p < len && is_ident_cont(src[p]) {
517 p += 1;
518 }
519 if p < len && src[p] == b'.' {
520 // Dotted constructor/ident like `Fuse.Colorize { ... }`
521 p += 1;
522 while p < len && (is_ident_cont(src[p]) || src[p] == b'.') {
523 p += 1;
524 }
525 self.pos = p;
526 let val = self.finish_ident_or_constructor(start, p)?;
527 let idx = *next_index;
528 *next_index += 1;
529 Ok((LuaKey::Index(idx), val))
476530 } else {
477 break;
531 self.pos = p;
532 self.skip_ws_and_comments()?;
533 if self.peek() == Some(b'=') && self.peek_at(1) != Some(b'=') {
534 self.pos += 1;
535 let key = std::str::from_utf8(&self.src[start..p])
536 .map_err(|_| self.err("invalid UTF-8 identifier"))?
537 .to_owned();
538 let val = self.parse_value()?;
539 Ok((LuaKey::Str(key), val))
540 } else {
541 let val = self.finish_ident_or_constructor(start, p)?;
542 let idx = *next_index;
543 *next_index += 1;
544 Ok((LuaKey::Index(idx), val))
545 }
478546 }
479 }
480 let end = self.pos;
481 let _ = self.skip_ws_and_comments();
482 if self.peek() == Some(b'=') && self.peek_at(1) != Some(b'=') {
483 self.pos += 1;
484 let key = std::str::from_utf8(&self.src[start..end]).ok()?.to_owned();
485 Some((key, saved))
486547 } else {
487 self.pos = saved;
488 None
548 let val = self.parse_value()?;
549 let idx = *next_index;
550 *next_index += 1;
551 Ok((LuaKey::Index(idx), val))
489552 }
490553 }
491554
492555 fn parse_quoted_string(&mut self) -> Result<String, ParseError> {
493556 let quote = self.bump().ok_or_else(|| self.err("expected quote"))?;
494 let mut out = Vec::new();
495 while let Some(b) = self.bump() {
557 let src = self.src;
558 let len = src.len();
559 let start = self.pos;
560 let mut p = start;
561 while p < len {
562 let b = src[p];
496563 if b == quote {
497 return Ok(String::from_utf8_lossy(&out).into_owned());
564 let slice = &src[start..p];
565 self.pos = p + 1;
566 return Ok(match std::str::from_utf8(slice) {
567 Ok(s) => s.to_owned(),
568 Err(_) => String::from_utf8_lossy(slice).into_owned(),
569 });
498570 }
499571 if b == b'\\' {
500 let Some(esc) = self.bump() else {
501 return Err(self.err("unterminated escape sequence"));
502 };
503 match esc {
504 b'n' => out.push(b'\n'),
505 b'r' => out.push(b'\r'),
506 b't' => out.push(b'\t'),
507 b'\\' => out.push(b'\\'),
508 b'"' => out.push(b'"'),
509 b'\'' => out.push(b'\''),
510 b'a' => out.push(0x07),
511 b'b' => out.push(0x08),
512 b'f' => out.push(0x0C),
513 b'v' => out.push(0x0B),
514 b'\n' => out.push(b'\n'),
515 b'\r' => {
516 if self.peek() == Some(b'\n') {
517 self.pos += 1;
518 }
519 out.push(b'\n');
572 break;
573 }
574 p += 1;
575 }
576 if p >= len {
577 self.pos = len;
578 return Err(self.err("unterminated string literal"));
579 }
580
581 let mut out = Vec::with_capacity((p - start).saturating_add(16));
582 if p > start {
583 out.extend_from_slice(&src[start..p]);
584 }
585 self.pos = p;
586
587 while self.pos < len {
588 let chunk_start = self.pos;
589 let mut q = chunk_start;
590 let mut found_quote = false;
591 let mut found_esc = false;
592 while q < len {
593 let b = src[q];
594 if b == quote {
595 found_quote = true;
596 break;
597 }
598 if b == b'\\' {
599 found_esc = true;
600 break;
601 }
602 q += 1;
603 }
604 if q > chunk_start {
605 out.extend_from_slice(&src[chunk_start..q]);
606 }
607 if found_quote {
608 self.pos = q + 1;
609 return Ok(match String::from_utf8(out) {
610 Ok(s) => s,
611 Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
612 });
613 }
614 if !found_esc {
615 self.pos = q;
616 return Err(self.err("unterminated string literal"));
617 }
618 self.pos = q + 1; // consume '\\'
619 let Some(esc) = self.bump() else {
620 return Err(self.err("unterminated escape sequence"));
621 };
622 match esc {
623 b'n' => out.push(b'\n'),
624 b'r' => out.push(b'\r'),
625 b't' => out.push(b'\t'),
626 b'\\' => out.push(b'\\'),
627 b'"' => out.push(b'"'),
628 b'\'' => out.push(b'\''),
629 b'a' => out.push(0x07),
630 b'b' => out.push(0x08),
631 b'f' => out.push(0x0C),
632 b'v' => out.push(0x0B),
633 b'\n' => out.push(b'\n'),
634 b'\r' => {
635 if self.peek() == Some(b'\n') {
636 self.pos += 1;
520637 }
521 b'z' => {
522 while let Some(ws) = self.peek() {
523 if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') {
524 self.pos += 1;
525 } else {
526 break;
527 }
638 out.push(b'\n');
639 }
640 b'z' => {
641 while let Some(ws) = self.peek() {
642 if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') {
643 self.pos += 1;
644 } else {
645 break;
528646 }
529647 }
530 b'x' => {
531 let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?;
532 let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?;
533 let s = [h1, h2];
534 let byte = u8::from_str_radix(std::str::from_utf8(&s).unwrap_or("00"), 16)
535 .map_err(|_| self.err("invalid hex escape"))?;
536 out.push(byte);
537 }
538 b'0'..=b'9' => {
539 let mut val = (esc - b'0') as u32;
540 for _ in 0..2 {
541 if let Some(d @ b'0'..=b'9') = self.peek() {
542 self.pos += 1;
543 val = val * 10 + (d - b'0') as u32;
544 } else {
545 break;
546 }
648 }
649 b'x' => {
650 let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?;
651 let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?;
652 let n1 = hex_nibble(h1).ok_or_else(|| self.err("invalid hex escape"))?;
653 let n2 = hex_nibble(h2).ok_or_else(|| self.err("invalid hex escape"))?;
654 out.push((n1 << 4) | n2);
655 }
656 b'0'..=b'9' => {
657 let mut val = (esc - b'0') as u32;
658 for _ in 0..2 {
659 if let Some(d @ b'0'..=b'9') = self.peek() {
660 self.pos += 1;
661 val = val * 10 + (d - b'0') as u32;
662 } else {
663 break;
547664 }
548 out.push((val & 0xFF) as u8);
549665 }
550 other => out.push(other),
666 out.push((val & 0xFF) as u8);
551667 }
552 } else {
553 out.push(b);
668 other => out.push(other),
554669 }
555670 }
556671 Err(self.err("unterminated string literal"))
557672 }
558673
559674 fn parse_number(&mut self) -> Result<LuaValue, ParseError> {
675 let src = self.src;
676 let len = src.len();
560677 let start = self.pos;
561 if matches!(self.peek(), Some(b'-' | b'+')) {
562 self.pos += 1;
563 }
564 // Check for -inf / -nan / -1.#INF / -1.#IND (Windows MSVC Fusion files!)
565 if self.src[self.pos..].starts_with(b"inf") || self.src[self.pos..].starts_with(b"INF") {
566 self.pos += 3;
567 let neg = self.src[start] == b'-';
568 return Ok(LuaValue::Number(if neg { f64::NEG_INFINITY } else { f64::INFINITY }));
569 }
570 if self.src[self.pos..].starts_with(b"nan") || self.src[self.pos..].starts_with(b"NaN") || self.src[self.pos..].starts_with(b"NAN") {
571 self.pos += 3;
572 return Ok(LuaValue::Number(f64::NAN));
678 let mut p = start;
679 let mut neg = false;
680 if p < len {
681 if src[p] == b'-' {
682 neg = true;
683 p += 1;
684 } else if src[p] == b'+' {
685 p += 1;
686 }
573687 }
574688
575 // Hex integer / float `0x...`
576 if self.peek() == Some(b'0') && matches!(self.peek_at(1), Some(b'x' | b'X')) {
577 self.pos += 2;
578 let hex_start = self.pos;
579 while let Some(b) = self.peek() {
580 if b.is_ascii_hexdigit() {
581 self.pos += 1;
582 } else {
583 break;
689 if p < len && src[p].is_ascii_digit() {
690 // Hex integer `0x...`
691 if src[p] == b'0' && p + 1 < len && (src[p + 1] == b'x' || src[p + 1] == b'X') {
692 p += 2;
693 let hex_start = p;
694 let mut val: u64 = 0;
695 while p < len && src[p].is_ascii_hexdigit() {
696 if p - hex_start < 16 {
697 val = (val << 4) | (hex_nibble(src[p]).unwrap_or(0) as u64);
698 }
699 p += 1;
700 }
701 self.pos = p;
702 let digits = p - hex_start;
703 if digits == 0 || digits > 16 {
704 let s = std::str::from_utf8(&src[hex_start..p]).unwrap_or("0");
705 let v = u64::from_str_radix(s, 16).map_err(|_| self.err("invalid hex number"))? as f64;
706 return Ok(LuaValue::Number(if neg { -v } else { v }));
584707 }
708 let v = val as f64;
709 return Ok(LuaValue::Number(if neg { -v } else { v }));
585710 }
586 let s = std::str::from_utf8(&self.src[hex_start..self.pos]).unwrap_or("0");
587 let v = u64::from_str_radix(s, 16).map_err(|_| self.err("invalid hex number"))? as f64;
588 let neg = self.src[start] == b'-';
589 return Ok(LuaValue::Number(if neg { -v } else { v }));
590 }
591711
592 while let Some(b) = self.peek() {
593 if b.is_ascii_digit() {
594 self.pos += 1;
595 } else {
596 break;
712 let int_start = p;
713 let mut int_val: u64 = 0;
714 while p < len && src[p].is_ascii_digit() {
715 if p - int_start < 15 {
716 int_val = int_val * 10 + (src[p] - b'0') as u64;
717 }
718 p += 1;
719 }
720 let next = if p < len { src[p] } else { 0 };
721 if next != b'.' && next != b'e' && next != b'E' && (p - int_start) <= 15 {
722 self.pos = p;
723 let v = int_val as f64;
724 return Ok(LuaValue::Number(if neg { -v } else { v }));
725 }
726 } else {
727 // Check for -inf / -nan (Windows MSVC / LuaJIT Fusion files!)
728 if src[p..].starts_with(b"inf") || src[p..].starts_with(b"INF") {
729 self.pos = p + 3;
730 return Ok(LuaValue::Number(if neg { f64::NEG_INFINITY } else { f64::INFINITY }));
731 }
732 if src[p..].starts_with(b"nan") || src[p..].starts_with(b"NaN") || src[p..].starts_with(b"NAN") {
733 self.pos = p + 3;
734 return Ok(LuaValue::Number(f64::NAN));
597735 }
598736 }
599 if self.peek() == Some(b'.') {
600 self.pos += 1;
737
738 if p < len && src[p] == b'.' {
739 p += 1;
601740 // Handle Windows MSVC `1.#INF`, `1.#IND`, `1.#QNAN`
602 if self.peek() == Some(b'#') {
603 while let Some(b) = self.peek() {
604 if b.is_ascii_alphanumeric() || b == b'#' {
605 self.pos += 1;
606 } else {
607 break;
608 }
741 if p < len && src[p] == b'#' {
742 while p < len && (src[p].is_ascii_alphanumeric() || src[p] == b'#') {
743 p += 1;
609744 }
610 let raw = std::str::from_utf8(&self.src[start..self.pos]).unwrap_or("");
745 self.pos = p;
746 let raw = std::str::from_utf8(&src[start..p]).unwrap_or("");
611747 if raw.contains("INF") {
612748 return Ok(LuaValue::Number(if raw.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY }));
613749 }
614750 return Ok(LuaValue::Number(f64::NAN));
615751 }
616 while let Some(b) = self.peek() {
617 if b.is_ascii_digit() {
618 self.pos += 1;
619 } else {
620 break;
621 }
752 while p < len && src[p].is_ascii_digit() {
753 p += 1;
622754 }
623755 }
624 if matches!(self.peek(), Some(b'e' | b'E')) {
625 self.pos += 1;
626 if matches!(self.peek(), Some(b'+' | b'-')) {
627 self.pos += 1;
756 if p < len && (src[p] == b'e' || src[p] == b'E') {
757 p += 1;
758 if p < len && (src[p] == b'+' || src[p] == b'-') {
759 p += 1;
628760 }
629 while let Some(b) = self.peek() {
630 if b.is_ascii_digit() {
631 self.pos += 1;
632 } else {
633 break;
634 }
761 while p < len && src[p].is_ascii_digit() {
762 p += 1;
635763 }
636764 }
637 let s = std::str::from_utf8(&self.src[start..self.pos])
765 self.pos = p;
766 let s = std::str::from_utf8(&src[start..p])
638767 .map_err(|_| self.err("invalid UTF-8 in number"))?;
639768 let n: f64 = s.parse().map_err(|_| self.err(format!("invalid number '{s}'")))?;
640769 Ok(LuaValue::Number(n))
641770 }
642771}
643772
773#[inline]
774fn hex_nibble(b: u8) -> Option<u8> {
775 match b {
776 b'0'..=b'9' => Some(b - b'0'),
777 b'a'..=b'f' => Some(b - b'a' + 10),
778 b'A'..=b'F' => Some(b - b'A' + 10),
779 _ => None,
780 }
781}
782
644783fn is_ident_start(b: u8) -> bool {
645784 b.is_ascii_alphabetic() || b == b'_'
646785}
......@@ -654,6 +793,9 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool {
654793 if bytes.is_empty() || !is_ident_start(bytes[0]) || !bytes[1..].iter().all(|&b| is_ident_cont(b)) {
655794 return false;
656795 }
796 if bytes.len() > 8 || bytes.len() < 2 {
797 return true;
798 }
657799 !matches!(
658800 s,
659801 "and"
......@@ -681,12 +823,39 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool {
681823 )
682824}
683825
684fn write_indent(out: &mut String, depth: usize) {
685 for _ in 0..depth {
686 out.push('\t');
826#[inline]
827pub(crate) fn write_indent(out: &mut String, mut depth: usize) {
828 const TABS: &str = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
829 while depth > 0 {
830 let chunk = depth.min(TABS.len());
831 out.push_str(&TABS[..chunk]);
832 depth -= chunk;
687833 }
688834}
689835
836#[inline]
837fn write_i64(mut v: i64, out: &mut String) {
838 if v == 0 {
839 out.push('0');
840 return;
841 }
842 let neg = v < 0;
843 let mut u = v.unsigned_abs();
844 let mut buf = [0u8; 24];
845 let mut i = buf.len();
846 while u > 0 {
847 i -= 1;
848 buf[i] = b'0' + (u % 10) as u8;
849 u /= 10;
850 }
851 if neg {
852 i -= 1;
853 buf[i] = b'-';
854 }
855 let _ = &mut v;
856 out.push_str(std::str::from_utf8(&buf[i..]).unwrap());
857}
858
690859fn write_number(n: f64, out: &mut String) {
691860 if n.is_nan() {
692861 out.push_str("nan");
......@@ -699,8 +868,7 @@ fn write_number(n: f64, out: &mut String) {
699868 } else if n == 0.0 {
700869 out.push('0');
701870 } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 {
702 use std::fmt::Write;
703 let _ = write!(out, "{}", n as i64);
871 write_i64(n as i64, out);
704872 } else {
705873 use std::fmt::Write;
706874 let _ = write!(out, "{n}");
......@@ -708,25 +876,40 @@ fn write_number(n: f64, out: &mut String) {
708876}
709877
710878fn write_string(s: &str, out: &mut String) {
711 use std::fmt::Write;
712879 out.push('"');
713 for c in s.chars() {
714 match c {
715 '\\' => out.push_str("\\\\"),
716 '"' => out.push_str("\\\""),
717 '\n' => out.push_str("\\n"),
718 '\r' => out.push_str("\\r"),
719 '\t' => out.push_str("\\t"),
720 c if (c as u32) < 0x20 || (c as u32) == 0x7F => {
721 let _ = write!(out, "\\{:03}", c as u32);
880 let bytes = s.as_bytes();
881 let mut last = 0;
882 for (i, &b) in bytes.iter().enumerate() {
883 let esc = match b {
884 b'\\' => "\\\\",
885 b'"' => "\\\"",
886 b'\n' => "\\n",
887 b'\r' => "\\r",
888 b'\t' => "\\t",
889 0x00..=0x1F | 0x7F => {
890 if i > last {
891 out.push_str(&s[last..i]);
892 }
893 let seq = [b'\\', b'0' + (b / 100), b'0' + ((b / 10) % 10), b'0' + (b % 10)];
894 out.push_str(std::str::from_utf8(&seq).unwrap());
895 last = i + 1;
896 continue;
722897 }
723 c => out.push(c),
898 _ => continue,
899 };
900 if i > last {
901 out.push_str(&s[last..i]);
724902 }
903 out.push_str(esc);
904 last = i + 1;
905 }
906 if last < bytes.len() {
907 out.push_str(&s[last..]);
725908 }
726909 out.push('"');
727910}
728911
729fn write_value(val: &LuaValue, depth: usize, out: &mut String) {
912pub(crate) fn write_value(val: &LuaValue, depth: usize, out: &mut String) {
730913 match val {
731914 LuaValue::Nil => out.push_str("nil"),
732915 LuaValue::Bool(true) => out.push_str("true"),
......@@ -737,6 +920,13 @@ fn write_value(val: &LuaValue, depth: usize, out: &mut String) {
737920 }
738921}
739922
923#[inline]
924pub(crate) fn has_call_args(tbl: &LuaTable) -> bool {
925 tbl.entries
926 .iter()
927 .any(|(k, _)| matches!(k, LuaKey::Str(s) if s == "__arg0"))
928}
929
740930fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) {
741931 let mut call_args = Vec::new();
742932 let mut next_arg = 0usize;
......@@ -763,11 +953,17 @@ fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>)
763953 (call_args, body)
764954}
765955
766fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool {
956pub(crate) fn can_use_positional<'a>(entries: impl Iterator<Item = &'a (LuaKey, LuaValue)> + Clone) -> bool {
767957 let mut expected = 1i64;
768958 let mut index_count = 0usize;
769 for (k, _) in body {
770 match k {
959 let mut len = 0usize;
960 let mut first = None;
961 for entry in entries {
962 if len == 0 {
963 first = Some(entry);
964 }
965 len += 1;
966 match &entry.0 {
771967 LuaKey::Number(_) => return false,
772968 LuaKey::Index(i) => {
773969 if *i != expected {
......@@ -779,8 +975,8 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool {
779975 LuaKey::Str(_) => {}
780976 }
781977 }
782 if index_count == 1 && body.len() == 1 {
783 if let (LuaKey::Index(1), LuaValue::Table(sub)) = body[0] {
978 if index_count == 1 && len == 1 {
979 if let Some((LuaKey::Index(1), LuaValue::Table(sub))) = first {
784980 if sub.tag.is_none()
785981 && (sub.get("Flags").is_some() || sub.get("LH").is_some() || sub.get("RH").is_some())
786982 {
......@@ -792,24 +988,20 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool {
792988}
793989
794990fn can_inline_table(tbl: &LuaTable, max_depth: usize) -> bool {
795 if max_depth == 0 {
991 if max_depth == 0 || tbl.entries.len() > 4 || tbl.tag.as_deref() == Some("ordered") {
796992 return false;
797993 }
798 if tbl.tag.as_deref() == Some("ordered") {
994 if has_call_args(tbl) {
799995 return false;
800996 }
801 let (call_args, body) = split_call_args(tbl);
802 if !call_args.is_empty() || body.len() > 4 {
803 return false;
804 }
805 body.iter().all(|(_, v)| match v {
997 tbl.entries.iter().all(|(_, v)| match v {
806998 LuaValue::Nil | LuaValue::Bool(_) | LuaValue::Number(_) => true,
807 LuaValue::String(s) => !s.contains('\n') && !s.contains('\r') && s.len() <= 48,
999 LuaValue::String(s) => s.len() <= 48 && !s.contains('\n') && !s.contains('\r'),
8081000 LuaValue::Table(sub) => max_depth > 1 && can_inline_table(sub, max_depth - 1),
8091001 })
8101002}
8111003
812fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, out: &mut String) {
1004pub(crate) fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, out: &mut String) {
8131005 if let Some(t) = tag {
8141006 out.push_str(t);
8151007 if t == "ordered" || !call_args.is_empty() {
......@@ -826,12 +1018,13 @@ fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize,
8261018 }
8271019}
8281020
829fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool {
1021pub(crate) fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool {
8301022 match key {
8311023 LuaKey::Index(_) if positional => false,
8321024 LuaKey::Index(i) => {
833 use std::fmt::Write;
834 let _ = write!(out, "[{i}] = ");
1025 out.push('[');
1026 write_i64(*i, out);
1027 out.push_str("] = ");
8351028 true
8361029 }
8371030 LuaKey::Number(n) => {
......@@ -854,36 +1047,40 @@ fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool {
8541047 }
8551048}
8561049
857fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) {
858 let (call_args, body) = split_call_args(tbl);
859 write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out);
860
861 if body.is_empty() {
1050fn write_table_body<'a>(
1051 tbl: &LuaTable,
1052 entries: impl Iterator<Item = &'a (LuaKey, LuaValue)> + Clone,
1053 depth: usize,
1054 out: &mut String,
1055) {
1056 let mut peek = entries.clone();
1057 if peek.next().is_none() {
8621058 out.push_str("{}");
8631059 return;
8641060 }
8651061
866 let positional = can_use_positional(&body);
1062 let positional = can_use_positional(entries.clone());
8671063
8681064 if depth > 0 && can_inline_table(tbl, 2) {
869 let mut inline = String::new();
870 inline.push_str("{ ");
871 for (i, (k, v)) in body.iter().enumerate() {
1065 let saved_len = out.len();
1066 out.push_str("{ ");
1067 for (i, (k, v)) in entries.clone().enumerate() {
8721068 if i > 0 {
873 inline.push_str(", ");
1069 out.push_str(", ");
8741070 }
875 write_entry_key(k, positional, &mut inline);
876 write_value(v, depth + 1, &mut inline);
1071 write_entry_key(k, positional, out);
1072 write_value(v, depth + 1, out);
8771073 }
878 inline.push_str(" }");
879 if !inline.contains('\n') && inline.len() <= 100 {
880 out.push_str(&inline);
1074 out.push_str(" }");
1075 let written = &out[saved_len..];
1076 if written.len() <= 100 && !written.contains('\n') {
8811077 return;
8821078 }
1079 out.truncate(saved_len);
8831080 }
8841081
8851082 out.push_str("{\n");
886 for (k, v) in body {
1083 for (k, v) in entries {
8871084 write_indent(out, depth + 1);
8881085 write_entry_key(k, positional, out);
8891086 write_value(v, depth + 1, out);
......@@ -892,3 +1089,15 @@ fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) {
8921089 write_indent(out, depth);
8931090 out.push('}');
8941091}
1092
1093pub(crate) fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) {
1094 if !has_call_args(tbl) {
1095 write_table_prefix(tbl.tag.as_deref(), &[], depth, out);
1096 write_table_body(tbl, tbl.entries.iter(), depth, out);
1097 return;
1098 }
1099
1100 let (call_args, body) = split_call_args(tbl);
1101 write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out);
1102 write_table_body(tbl, body.into_iter(), depth, out);
1103}