| author | |
| committer | |
| log | 58f0a438503070b75389125a5d64ee6e27cf4cd9 |
| tree | d69a7313ebf35fdbcd73098873fe4a5e75cbc39e |
| parent | ad4bb44659c9b2a8780f96640438f8cfcb0464e4 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
3 files changed, 1915 insertions(+), 452 deletions(-)
crates/model/src/comp/load.rs+274-133| ... | @@ -22,10 +22,13 @@ impl Comp { | ... | @@ -22,10 +22,13 @@ impl Comp { |
| 22 | } | 22 | } |
| 23 | 23 | ||
| 24 | pub fn from_fusion_str(text: &str) -> Result<Self, ParseError> { | 24 | pub fn from_fusion_str(text: &str) -> Result<Self, ParseError> { |
| 25 | let root_val = parse_lua(text)?; | 25 | let LuaValue::Table(root) = parse_lua(text)? else { |
| 26 | let root = root_val | 26 | return Err(ParseError { |
| 27 | .as_table() | 27 | offset: 0, |
| 28 | .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?; | 28 | line: 1, |
| 29 | message: "comp root is not a table".into(), | ||
| 30 | }); | ||
| 31 | }; | ||
| 29 | 32 | ||
| 30 | let current_time = root.get_f64("CurrentTime").unwrap_or(0.0); | 33 | let current_time = root.get_f64("CurrentTime").unwrap_or(0.0); |
| 31 | let global_range = root | 34 | let global_range = root |
| ... | @@ -70,9 +73,11 @@ impl Comp { | ... | @@ -70,9 +73,11 @@ impl Comp { |
| 70 | } | 73 | } |
| 71 | } | 74 | } |
| 72 | 75 | ||
| 73 | let mut nodes = Vec::new(); | 76 | let tools_len = root.get_table("Tools").map_or(0, |t| t.entries.len()); |
| 74 | let mut node_by_name = HashMap::new(); | 77 | let approx_nodes = tools_len / 2; |
| 75 | let mut splines = HashMap::new(); | 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); | ||
| 76 | let mut poly_paths = HashMap::new(); | 81 | let mut poly_paths = HashMap::new(); |
| 77 | let mut gradient_modifiers = HashMap::new(); | 82 | let mut gradient_modifiers = HashMap::new(); |
| 78 | let mut text_modifiers = HashMap::new(); | 83 | let mut text_modifiers = HashMap::new(); |
| ... | @@ -117,35 +122,45 @@ impl Comp { | ... | @@ -117,35 +122,45 @@ impl Comp { |
| 117 | 122 | ||
| 118 | // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets | 123 | // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets |
| 119 | // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`. | 124 | // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`. |
| 120 | let node_inputs_snapshot: Vec<(String, HashMap<String, InputBinding>)> = nodes | 125 | if nodes.iter().any(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) { |
| 121 | .iter() | 126 | let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(nodes.len()); |
| 122 | .map(|n| (n.name.clone(), n.inputs.clone())) | 127 | for (idx, n) in nodes.iter().enumerate() { |
| 123 | .collect(); | 128 | name_to_idx.insert(n.name.as_str(), idx); |
| 124 | let snap_map: HashMap<String, HashMap<String, InputBinding>> = node_inputs_snapshot.into_iter().collect(); | 129 | } |
| 125 | for n in &mut nodes { | 130 | let mut group_wires: Vec<(usize, Vec<(String, InputBinding)>)> = Vec::new(); |
| 126 | if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { | 131 | for (idx, n) in nodes.iter().enumerate() { |
| 127 | let mut flow_wires = HashMap::new(); | 132 | if !matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { |
| 133 | continue; | ||
| 134 | } | ||
| 135 | let mut flow_wires = Vec::new(); | ||
| 128 | for (in_name, b) in &n.inputs { | 136 | for (in_name, b) in &n.inputs { |
| 129 | if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) { | 137 | 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)) { | 138 | if let Some(&inner_idx) = name_to_idx.get(inner_op.as_str()) { |
| 131 | if let Some(ext_src) = &inner_in.source_op { | 139 | if let Some(inner_in) = nodes[inner_idx].inputs.get(inner_port) { |
| 132 | // Only connect if ext_src is a visible (non-internal) flow node | 140 | if let Some(ext_src) = &inner_in.source_op { |
| 133 | if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) { | 141 | // Only connect if ext_src is a visible (non-internal) flow node |
| 134 | flow_wires.insert( | 142 | if node_by_name.get(ext_src).is_some_and(|&id| id != n.id) { |
| 135 | in_name.clone(), | 143 | flow_wires.push(( |
| 136 | InputBinding { | 144 | in_name.clone(), |
| 137 | value: None, | 145 | InputBinding { |
| 138 | source_op: Some(ext_src.clone()), | 146 | value: None, |
| 139 | source_output: inner_in.source_output.clone(), | 147 | source_op: Some(ext_src.clone()), |
| 140 | expression: None, | 148 | source_output: inner_in.source_output.clone(), |
| 141 | }, | 149 | expression: None, |
| 142 | ); | 150 | }, |
| 151 | )); | ||
| 152 | } | ||
| 143 | } | 153 | } |
| 144 | } | 154 | } |
| 145 | } | 155 | } |
| 146 | } | 156 | } |
| 147 | } | 157 | } |
| 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); | ||
| 149 | } | 164 | } |
| 150 | } | 165 | } |
| 151 | 166 | ||
| ... | @@ -163,13 +178,20 @@ impl Comp { | ... | @@ -163,13 +178,20 @@ impl Comp { |
| 163 | .map(|mid| (*nid, mid)) | 178 | .map(|mid| (*nid, mid)) |
| 164 | }) | 179 | }) |
| 165 | .collect(); | 180 | .collect(); |
| 166 | let orig_inputs: Vec<HashMap<String, InputBinding>> = | 181 | let mut orig_inputs: HashMap<NodeId, HashMap<String, InputBinding>> = |
| 167 | nodes.iter().map(|n| n.inputs.clone()).collect(); | 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 | } | ||
| 168 | 188 | ||
| 189 | let mut visited = HashSet::new(); | ||
| 190 | let mut blocked: HashSet<String> = HashSet::new(); | ||
| 169 | for &(nid, _) in &instanced_from { | 191 | for &(nid, _) in &instanced_from { |
| 170 | let mut visited = HashSet::new(); | 192 | visited.clear(); |
| 171 | visited.insert(nid); | 193 | visited.insert(nid); |
| 172 | let mut blocked: HashSet<String> = HashSet::new(); | 194 | blocked.clear(); |
| 173 | let mut cur = nid; | 195 | let mut cur = nid; |
| 174 | for _depth in 0..8 { | 196 | for _depth in 0..8 { |
| 175 | let Some(&pid) = parent_of.get(&cur) else { | 197 | let Some(&pid) = parent_of.get(&cur) else { |
| ... | @@ -179,25 +201,26 @@ impl Comp { | ... | @@ -179,25 +201,26 @@ impl Comp { |
| 179 | break; | 201 | break; |
| 180 | } | 202 | } |
| 181 | let inst_inputs = &mut nodes[nid.0].inputs; | 203 | let inst_inputs = &mut nodes[nid.0].inputs; |
| 182 | for (inp_name, parent_binding) in &orig_inputs[pid.0] { | 204 | if let Some(parent_map) = orig_inputs.get(&pid) { |
| 183 | if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) | 205 | for (inp_name, parent_binding) in parent_map { |
| 184 | { | 206 | if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) { |
| 185 | continue; | 207 | continue; |
| 186 | } | 208 | } |
| 187 | if blocked.contains(inp_name) { | 209 | if blocked.contains(inp_name) { |
| 188 | continue; | 210 | continue; |
| 189 | } | 211 | } |
| 190 | if parent_binding.value.is_none() | 212 | if parent_binding.value.is_none() |
| 191 | && parent_binding.source_op.is_none() | 213 | && parent_binding.source_op.is_none() |
| 192 | && parent_binding.expression.is_none() | 214 | && parent_binding.expression.is_none() |
| 193 | { | 215 | { |
| 194 | // An empty `Param = Input {}` on an ancestor marks a de-instanced | 216 | // An empty `Param = Input {}` on an ancestor marks a de-instanced |
| 195 | // override to default and stops further inheritance up the chain. | 217 | // override to default and stops further inheritance up the chain. |
| 196 | blocked.insert(inp_name.clone()); | 218 | blocked.insert(inp_name.clone()); |
| 197 | continue; | 219 | continue; |
| 198 | } | 220 | } |
| 199 | if !inst_inputs.contains_key(inp_name) { | 221 | if !inst_inputs.contains_key(inp_name) { |
| 200 | inst_inputs.insert(inp_name.clone(), parent_binding.clone()); | 222 | inst_inputs.insert(inp_name.clone(), parent_binding.clone()); |
| 223 | } | ||
| 201 | } | 224 | } |
| 202 | } | 225 | } |
| 203 | cur = pid; | 226 | cur = pid; |
| ... | @@ -217,19 +240,21 @@ impl Comp { | ... | @@ -217,19 +240,21 @@ impl Comp { |
| 217 | "GreenSuppress", | 240 | "GreenSuppress", |
| 218 | "BlueSuppress", | 241 | "BlueSuppress", |
| 219 | ]; | 242 | ]; |
| 220 | let mut hue_spline_names: HashSet<String> = HashSet::new(); | 243 | if !splines.is_empty() && nodes.iter().any(|n| n.kind == "HueCurves") { |
| 221 | for n in &nodes { | 244 | let mut hue_spline_names: HashSet<String> = HashSet::new(); |
| 222 | if n.kind == "HueCurves" { | 245 | for n in &nodes { |
| 223 | for &port in HUE_CURVE_PORTS { | 246 | if n.kind == "HueCurves" { |
| 224 | if let Some(sp_name) = n.connected_node(port) { | 247 | for &port in HUE_CURVE_PORTS { |
| 225 | hue_spline_names.insert(sp_name.to_owned()); | 248 | if let Some(sp_name) = n.connected_node(port) { |
| 249 | hue_spline_names.insert(sp_name.to_owned()); | ||
| 250 | } | ||
| 226 | } | 251 | } |
| 227 | } | 252 | } |
| 228 | } | 253 | } |
| 229 | } | 254 | for sp_name in hue_spline_names { |
| 230 | for sp_name in hue_spline_names { | 255 | if let Some(sp) = splines.get_mut(&sp_name) { |
| 231 | if let Some(sp) = splines.get_mut(&sp_name) { | 256 | sp.apply_hue_curves_cyclic_ends(); |
| 232 | sp.apply_hue_curves_cyclic_ends(); | 257 | } |
| 233 | } | 258 | } |
| 234 | } | 259 | } |
| 235 | 260 | ||
| ... | @@ -272,7 +297,7 @@ impl Comp { | ... | @@ -272,7 +297,7 @@ impl Comp { |
| 272 | shakes, | 297 | shakes, |
| 273 | expression_modifiers, | 298 | expression_modifiers, |
| 274 | cross_macro_wires, | 299 | cross_macro_wires, |
| 275 | raw_root: Some(root.clone()), | 300 | raw_root: Some(root), |
| 276 | revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed), | 301 | revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed), |
| 277 | }) | 302 | }) |
| 278 | } | 303 | } |
| ... | @@ -284,9 +309,25 @@ impl Comp { | ... | @@ -284,9 +309,25 @@ impl Comp { |
| 284 | /// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was | 309 | /// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was |
| 285 | /// cleared here so saving keeps the original text. | 310 | /// cleared here so saving keeps the original text. |
| 286 | fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap<NodeId, NodeId>) -> HashSet<(String, String)> { | 311 | fn 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()); | ||
| 288 | for n in nodes.iter() { | 320 | 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 | } | ||
| 290 | } | 331 | } |
| 291 | let encloses = |outer: NodeId, mut inner: NodeId| { | 332 | let encloses = |outer: NodeId, mut inner: NodeId| { |
| 292 | loop { | 333 | loop { |
| ... | @@ -314,7 +355,11 @@ fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap<NodeId, NodeId>) | ... | @@ -314,7 +355,11 @@ fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap<NodeId, NodeId>) |
| 314 | let Some(candidates) = b.source_op.as_deref().and_then(|s| by_name.get(s)) else { | 355 | let Some(candidates) = b.source_op.as_deref().and_then(|s| by_name.get(s)) else { |
| 315 | continue; | 356 | continue; |
| 316 | }; | 357 | }; |
| 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 { | ||
| 318 | cleared.push((n.id, port.clone())); | 363 | cleared.push((n.id, port.clone())); |
| 319 | } | 364 | } |
| 320 | } | 365 | } |
| ... | @@ -368,11 +413,34 @@ fn is_non_inheritable_instance_port( | ... | @@ -368,11 +413,34 @@ fn is_non_inheritable_instance_port( |
| 368 | } | 413 | } |
| 369 | 414 | ||
| 370 | pub(super) fn parse_input_binding(t: &LuaTable) -> InputBinding { | 415 | pub(super) fn parse_input_binding(t: &LuaTable) -> InputBinding { |
| 371 | let source_op = t.get_str("SourceOp").map(str::to_owned); | 416 | let mut source_op = None; |
| 372 | let source_output = t.get_str("Source").map(str::to_owned); | 417 | let mut source_output = None; |
| 373 | let expression = t.get_str("Expression").map(str::to_owned); | 418 | let mut expression = None; |
| 374 | 419 | let mut value = None; | |
| 375 | let value = t.get("Value").map(parse_param_value); | 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 | } | ||
| 376 | InputBinding { | 444 | InputBinding { |
| 377 | value, | 445 | value, |
| 378 | source_op, | 446 | source_op, |
| ... | @@ -407,9 +475,8 @@ pub(super) fn parse_param_value(v: &LuaValue) -> ParamValue { | ... | @@ -407,9 +475,8 @@ pub(super) fn parse_param_value(v: &LuaValue) -> ParamValue { |
| 407 | } | 475 | } |
| 408 | } | 476 | } |
| 409 | 477 | ||
| 410 | fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)>> { | 478 | fn try_parse_gradient_keyframes(kfs: &LuaTable) -> Option<Vec<(f64, Gradient)>> { |
| 411 | let kfs = table.get_table("KeyFrames")?; | 479 | let mut grads = Vec::with_capacity(kfs.entries.len()); |
| 412 | let mut grads = Vec::new(); | ||
| 413 | for (k, v) in &kfs.entries { | 480 | for (k, v) in &kfs.entries { |
| 414 | let time = match k { | 481 | let time = match k { |
| 415 | LuaKey::Index(i) => *i as f64, | 482 | LuaKey::Index(i) => *i as f64, |
| ... | @@ -433,9 +500,8 @@ fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)> | ... | @@ -433,9 +500,8 @@ fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)> |
| 433 | Some(grads) | 500 | Some(grads) |
| 434 | } | 501 | } |
| 435 | 502 | ||
| 436 | fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> { | 503 | fn try_parse_text_keyframes(kfs: &LuaTable) -> Option<Vec<(f64, String)>> { |
| 437 | let kfs = table.get_table("KeyFrames")?; | 504 | let mut texts = Vec::with_capacity(kfs.entries.len()); |
| 438 | let mut texts = Vec::new(); | ||
| 439 | for (k, v) in &kfs.entries { | 505 | for (k, v) in &kfs.entries { |
| 440 | let time = match k { | 506 | let time = match k { |
| 441 | LuaKey::Index(i) => *i as f64, | 507 | LuaKey::Index(i) => *i as f64, |
| ... | @@ -458,9 +524,8 @@ fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> { | ... | @@ -458,9 +524,8 @@ fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> { |
| 458 | Some(texts) | 524 | Some(texts) |
| 459 | } | 525 | } |
| 460 | 526 | ||
| 461 | fn try_parse_polyline_keyframes(table: &LuaTable) -> Option<Vec<(f64, Vec<crate::spline::PolyPoint>)>> { | 527 | fn try_parse_polyline_keyframes(kfs: &LuaTable) -> Option<Vec<(f64, Vec<crate::spline::PolyPoint>)>> { |
| 462 | let kfs = table.get_table("KeyFrames")?; | 528 | let mut shapes = Vec::with_capacity(kfs.entries.len()); |
| 463 | let mut shapes = Vec::new(); | ||
| 464 | for (k, v) in &kfs.entries { | 529 | for (k, v) in &kfs.entries { |
| 465 | let time = match k { | 530 | let time = match k { |
| 466 | LuaKey::Index(i) => *i as f64, | 531 | LuaKey::Index(i) => *i as f64, |
| ... | @@ -505,25 +570,43 @@ fn parse_tools_table( | ... | @@ -505,25 +570,43 @@ fn parse_tools_table( |
| 505 | for (key, val) in &tools.entries { | 570 | for (key, val) in &tools.entries { |
| 506 | let LuaKey::Str(name) = key else { continue }; | 571 | let LuaKey::Str(name) = key else { continue }; |
| 507 | let Some(tbl) = val.as_table() else { continue }; | 572 | let Some(tbl) = val.as_table() else { continue }; |
| 508 | let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned()); | 573 | let kind_ref = tbl.tag.as_deref().unwrap_or("Unknown"); |
| 509 | 574 | ||
| 510 | if kind == "BezierSpline" || kind == "LUTBezier" { | 575 | if kind_ref == "BezierSpline" || kind_ref == "LUTBezier" { |
| 511 | if let Some(grads) = try_parse_gradient_keyframes(tbl) { | 576 | if let Some(kfs) = tbl.get_table("KeyFrames") { |
| 512 | gradient_modifiers.insert(name.clone(), grads); | 577 | let first_val_tag = kfs.entries.iter().find_map(|(k, v)| { |
| 513 | } else if let Some(txts) = try_parse_text_keyframes(tbl) { | 578 | if !matches!(k, LuaKey::Index(_) | LuaKey::Number(_)) { |
| 514 | text_splines.insert(name.clone(), txts); | 579 | return None; |
| 515 | } else if let Some(polys) = try_parse_polyline_keyframes(tbl) { | 580 | } |
| 516 | polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys)); | 581 | let kt = v.as_table()?; |
| 517 | } else { | 582 | kt.get_table("Value") |
| 518 | splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); | 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 | } | ||
| 519 | } | 601 | } |
| 602 | splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); | ||
| 520 | continue; | 603 | continue; |
| 521 | } | 604 | } |
| 522 | if kind == "PolyPath" || kind == "Path" { | 605 | if kind_ref == "PolyPath" || kind_ref == "Path" { |
| 523 | poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl)); | 606 | poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl)); |
| 524 | continue; | 607 | continue; |
| 525 | } | 608 | } |
| 526 | if kind == "TrackerModifier" { | 609 | if kind_ref == "TrackerModifier" { |
| 527 | if let Some(in_tbl) = tbl.get_table("Inputs") { | 610 | if let Some(in_tbl) = tbl.get_table("Inputs") { |
| 528 | if let Some(src_op) = in_tbl | 611 | if let Some(src_op) = in_tbl |
| 529 | .get_table("TrackedCenter0") | 612 | .get_table("TrackedCenter0") |
| ... | @@ -557,7 +640,7 @@ fn parse_tools_table( | ... | @@ -557,7 +640,7 @@ fn parse_tools_table( |
| 557 | } | 640 | } |
| 558 | continue; | 641 | continue; |
| 559 | } | 642 | } |
| 560 | if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" { | 643 | if kind_ref == "StyledTextCLS" || kind_ref == "CharacterLevelStyling" { |
| 561 | if let Some(in_tbl) = tbl.get_table("Inputs") { | 644 | if let Some(in_tbl) = tbl.get_table("Inputs") { |
| 562 | if let Some(txt_in) = in_tbl.get_table("Text").or_else(|| in_tbl.get_table("StyledText")) { | 645 | if let Some(txt_in) = in_tbl.get_table("Text").or_else(|| in_tbl.get_table("StyledText")) { |
| 563 | if let Some(txt) = txt_in | 646 | if let Some(txt) = txt_in |
| ... | @@ -607,9 +690,10 @@ fn parse_tools_table( | ... | @@ -607,9 +690,10 @@ fn parse_tools_table( |
| 607 | } | 690 | } |
| 608 | continue; | 691 | continue; |
| 609 | } | 692 | } |
| 610 | if kind == "Shake" { | 693 | if kind_ref == "Shake" { |
| 611 | let mut inputs = HashMap::new(); | 694 | let mut inputs = HashMap::new(); |
| 612 | if let Some(in_tbl) = tbl.get_table("Inputs") { | 695 | if let Some(in_tbl) = tbl.get_table("Inputs") { |
| 696 | inputs.reserve(in_tbl.entries.len()); | ||
| 613 | for (ik, iv) in &in_tbl.entries { | 697 | for (ik, iv) in &in_tbl.entries { |
| 614 | let LuaKey::Str(in_name) = ik else { continue }; | 698 | let LuaKey::Str(in_name) = ik else { continue }; |
| 615 | let Some(it) = iv.as_table() else { continue }; | 699 | let Some(it) = iv.as_table() else { continue }; |
| ... | @@ -619,9 +703,10 @@ fn parse_tools_table( | ... | @@ -619,9 +703,10 @@ fn parse_tools_table( |
| 619 | shakes.insert(name.clone(), ShakeModifier { inputs }); | 703 | shakes.insert(name.clone(), ShakeModifier { inputs }); |
| 620 | continue; | 704 | continue; |
| 621 | } | 705 | } |
| 622 | if kind == "Expression" { | 706 | if kind_ref == "Expression" { |
| 623 | let mut inputs = HashMap::new(); | 707 | let mut inputs = HashMap::new(); |
| 624 | if let Some(in_tbl) = tbl.get_table("Inputs") { | 708 | if let Some(in_tbl) = tbl.get_table("Inputs") { |
| 709 | inputs.reserve(in_tbl.entries.len()); | ||
| 625 | for (ik, iv) in &in_tbl.entries { | 710 | for (ik, iv) in &in_tbl.entries { |
| 626 | let LuaKey::Str(in_name) = ik else { continue }; | 711 | let LuaKey::Str(in_name) = ik else { continue }; |
| 627 | let Some(it) = iv.as_table() else { continue }; | 712 | let Some(it) = iv.as_table() else { continue }; |
| ... | @@ -653,23 +738,45 @@ fn parse_tools_table( | ... | @@ -653,23 +738,45 @@ fn parse_tools_table( |
| 653 | expression_modifiers.insert(name.clone(), ExpressionModifier { inputs }); | 738 | expression_modifiers.insert(name.clone(), ExpressionModifier { inputs }); |
| 654 | continue; | 739 | continue; |
| 655 | } | 740 | } |
| 656 | if is_modifier_type(&kind) { | 741 | if is_modifier_type(kind_ref) { |
| 657 | if tbl.get_table("KeyFrames").is_some() { | 742 | if tbl.get_table("KeyFrames").is_some() { |
| 658 | splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); | 743 | splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); |
| 659 | } | 744 | } |
| 660 | continue; | 745 | continue; |
| 661 | } | 746 | } |
| 662 | 747 | ||
| 663 | let pos = tbl | 748 | let mut view_info_tbl: Option<&LuaTable> = None; |
| 664 | .get_table("ViewInfo") | 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 | ||
| 665 | .and_then(|vi| vi.get_table("Pos")) | 772 | .and_then(|vi| vi.get_table("Pos")) |
| 666 | .and_then(read_vec2) | 773 | .and_then(read_vec2) |
| 667 | .map(|[x, y]| [x as f32, y as f32]) | 774 | .map(|[x, y]| [x as f32, y as f32]) |
| 668 | .unwrap_or([0.0, 0.0]); | 775 | .unwrap_or([0.0, 0.0]); |
| 669 | let bypassed = tbl.get_bool("PassThrough").unwrap_or(false); | ||
| 670 | 776 | ||
| 671 | let mut inputs = HashMap::new(); | 777 | 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()); | ||
| 673 | for (ik, iv) in &in_tbl.entries { | 780 | for (ik, iv) in &in_tbl.entries { |
| 674 | let LuaKey::Str(in_name) = ik else { continue }; | 781 | let LuaKey::Str(in_name) = ik else { continue }; |
| 675 | let Some(it) = iv.as_table() else { continue }; | 782 | let Some(it) = iv.as_table() else { continue }; |
| ... | @@ -679,7 +786,7 @@ fn parse_tools_table( | ... | @@ -679,7 +786,7 @@ fn parse_tools_table( |
| 679 | } | 786 | } |
| 680 | 787 | ||
| 681 | // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.) | 788 | // 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 { |
| 683 | for (uk, uv) in &uc.entries { | 790 | for (uk, uv) in &uc.entries { |
| 684 | let LuaKey::Str(uname) = uk else { continue }; | 791 | let LuaKey::Str(uname) = uk else { continue }; |
| 685 | let Some(ut) = uv.as_table() else { continue }; | 792 | let Some(ut) = uv.as_table() else { continue }; |
| ... | @@ -712,34 +819,18 @@ fn parse_tools_table( | ... | @@ -712,34 +819,18 @@ fn parse_tools_table( |
| 712 | } | 819 | } |
| 713 | 820 | ||
| 714 | let mut clips = Vec::new(); | 821 | let mut clips = Vec::new(); |
| 715 | if let Some(clips_tbl) = tbl.get_table("Clips") { | 822 | if let Some(clips_tbl) = clips_tbl { |
| 716 | for (_, cv) in &clips_tbl.entries { | 823 | for (_, cv) in &clips_tbl.entries { |
| 717 | if let Some(ct) = cv.as_table() { | 824 | if let Some(ct) = cv.as_table() { |
| 718 | if let Some(filename) = ct.get_str("Filename") { | 825 | if let Some(clip) = parse_clip_spec(ct) { |
| 719 | clips.push(ClipSpec { | 826 | clips.push(clip); |
| 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 | }); | ||
| 735 | } | 827 | } |
| 736 | } | 828 | } |
| 737 | } | 829 | } |
| 738 | } | 830 | } |
| 739 | 831 | ||
| 740 | if kind == "Saver" && clips.is_empty() { | 832 | if kind_ref == "Saver" && clips.is_empty() { |
| 741 | if let Some(c) = tbl | 833 | if let Some(c) = inputs_tbl |
| 742 | .get_table("Inputs") | ||
| 743 | .and_then(|i| i.get_table("Clip")) | 834 | .and_then(|i| i.get_table("Clip")) |
| 744 | .and_then(|c| c.get_table("Value")) | 835 | .and_then(|c| c.get_table("Value")) |
| 745 | { | 836 | { |
| ... | @@ -763,8 +854,8 @@ fn parse_tools_table( | ... | @@ -763,8 +854,8 @@ fn parse_tools_table( |
| 763 | } | 854 | } |
| 764 | 855 | ||
| 765 | // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table! | 856 | // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table! |
| 766 | if kind == "ColorCurves" || kind == "HueCurves" { | 857 | if kind_ref == "ColorCurves" || kind_ref == "HueCurves" { |
| 767 | if let Some(inner_tools) = tbl.get_table("Tools") { | 858 | if let Some(inner_tools) = inner_tools_tbl { |
| 768 | parse_tools_table( | 859 | parse_tools_table( |
| 769 | inner_tools, | 860 | inner_tools, |
| 770 | true, | 861 | true, |
| ... | @@ -788,13 +879,13 @@ fn parse_tools_table( | ... | @@ -788,13 +879,13 @@ fn parse_tools_table( |
| 788 | 879 | ||
| 789 | let mut macro_output = None; | 880 | let mut macro_output = None; |
| 790 | let mut macro_inner_start = None; | 881 | let mut macro_inner_start = None; |
| 791 | if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { | 882 | if matches!(kind_ref, "MacroOperator" | "GroupOperator") { |
| 792 | let mut out_name: Option<String> = None; | 883 | let mut out_name: Option<&str> = None; |
| 793 | if let Some(outs) = tbl.get_table("Outputs") { | 884 | if let Some(outs) = outputs_tbl { |
| 794 | for (_, ov) in &outs.entries { | 885 | for (_, ov) in &outs.entries { |
| 795 | if let Some(ot) = ov.as_table() { | 886 | if let Some(ot) = ov.as_table() { |
| 796 | if let Some(src_op) = ot.get_str("SourceOp") { | 887 | if let Some(src_op) = ot.get_str("SourceOp") { |
| 797 | out_name = Some(src_op.to_owned()); | 888 | out_name = Some(src_op); |
| 798 | break; | 889 | break; |
| 799 | } | 890 | } |
| 800 | } | 891 | } |
| ... | @@ -802,7 +893,7 @@ fn parse_tools_table( | ... | @@ -802,7 +893,7 @@ fn parse_tools_table( |
| 802 | } | 893 | } |
| 803 | let inner_start = nodes.len(); | 894 | let inner_start = nodes.len(); |
| 804 | macro_inner_start = Some(inner_start); | 895 | 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 { |
| 806 | parse_tools_table( | 897 | parse_tools_table( |
| 807 | inner_tools, | 898 | inner_tools, |
| 808 | true, | 899 | true, |
| ... | @@ -827,7 +918,7 @@ fn parse_tools_table( | ... | @@ -827,7 +918,7 @@ fn parse_tools_table( |
| 827 | .iter() | 918 | .iter() |
| 828 | .find(|n| n.name == oname) | 919 | .find(|n| n.name == oname) |
| 829 | .map(|n| n.id) | 920 | .map(|n| n.id) |
| 830 | .or_else(|| node_by_name.get(&oname).copied()); | 921 | .or_else(|| node_by_name.get(oname).copied()); |
| 831 | } | 922 | } |
| 832 | } | 923 | } |
| 833 | 924 | ||
| ... | @@ -841,13 +932,13 @@ fn parse_tools_table( | ... | @@ -841,13 +932,13 @@ fn parse_tools_table( |
| 841 | if !is_internal || !node_by_name.contains_key(name) { | 932 | if !is_internal || !node_by_name.contains_key(name) { |
| 842 | node_by_name.insert(name.clone(), id); | 933 | node_by_name.insert(name.clone(), id); |
| 843 | } | 934 | } |
| 844 | if let Some(master) = tbl.get_str("SourceOp") { | 935 | if let Some(master) = source_op_str { |
| 845 | instanced_from.push((id, master.to_owned())); | 936 | instanced_from.push((id, master.to_owned())); |
| 846 | } | 937 | } |
| 847 | nodes.push(Node { | 938 | nodes.push(Node { |
| 848 | id, | 939 | id, |
| 849 | name: name.clone(), | 940 | name: name.clone(), |
| 850 | kind, | 941 | kind: kind_ref.to_owned(), |
| 851 | pos, | 942 | pos, |
| 852 | bypassed, | 943 | bypassed, |
| 853 | internal: is_internal, | 944 | internal: is_internal, |
| ... | @@ -859,6 +950,56 @@ fn parse_tools_table( | ... | @@ -859,6 +950,56 @@ fn parse_tools_table( |
| 859 | } | 950 | } |
| 860 | } | 951 | } |
| 861 | 952 | ||
| 953 | fn 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 | |||
| 862 | #[cfg(test)] | 1003 | #[cfg(test)] |
| 863 | mod tests { | 1004 | mod tests { |
| 864 | use super::*; | 1005 | use super::*; |
crates/model/src/comp/save.rs+1168-55| ... | @@ -1,13 +1,61 @@ | ... | @@ -1,13 +1,61 @@ |
| 1 | use super::load::{parse_input_binding, parse_param_value}; | 1 | use super::load::{parse_input_binding, parse_param_value}; |
| 2 | use super::math::find_raw_tool_mut; | 2 | use super::math::find_raw_tool_mut; |
| 3 | use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type}; | 3 | use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type}; |
| 4 | use crate::lua_value::{LuaKey, LuaTable, LuaValue}; | 4 | use crate::lua_value::{ |
| 5 | use crate::spline::{BezierSpline, read_vec2}; | 5 | LuaKey, LuaTable, LuaValue, can_use_positional, has_call_args, write_entry_key, write_indent, |
| 6 | use std::collections::{HashMap, HashSet, VecDeque}; | 6 | write_table, write_table_prefix, write_value, |
| 7 | }; | ||
| 8 | use crate::spline::{BezierSpline, Gradient, HandleMode, KeyFlags, read_vec2}; | ||
| 9 | use std::collections::{HashMap, HashSet}; | ||
| 7 | use std::io::Write; | 10 | use std::io::Write; |
| 8 | use std::path::{Path, PathBuf}; | 11 | use std::path::{Path, PathBuf}; |
| 9 | use std::sync::atomic::{AtomicU64, Ordering}; | 12 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 10 | 13 | ||
| 14 | enum NodePool<'a> { | ||
| 15 | One(&'a Node), | ||
| 16 | Many(Vec<&'a Node>, usize), | ||
| 17 | } | ||
| 18 | |||
| 19 | impl<'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 | |||
| 44 | fn 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 | |||
| 11 | impl Comp { | 59 | impl Comp { |
| 12 | /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits, | 60 | /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits, |
| 13 | /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST, | 61 | /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST, |
| ... | @@ -87,10 +135,17 @@ impl Comp { | ... | @@ -87,10 +135,17 @@ impl Comp { |
| 87 | tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl)); | 135 | tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl)); |
| 88 | } | 136 | } |
| 89 | 137 | ||
| 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(); | ||
| 91 | let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new(); | 140 | let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new(); |
| 92 | for node in &self.nodes { | 141 | 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 | } | ||
| 94 | if !is_group_kind(&node.kind) { | 149 | if !is_group_kind(&node.kind) { |
| 95 | continue; | 150 | continue; |
| 96 | } | 151 | } |
| ... | @@ -100,30 +155,33 @@ impl Comp { | ... | @@ -100,30 +155,33 @@ impl Comp { |
| 100 | } | 155 | } |
| 101 | } | 156 | } |
| 102 | } | 157 | } |
| 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); |
| 104 | 159 | ||
| 105 | // Sync BezierSpline edits (only touch splines that actually differ from the raw AST) | 160 | // Sync BezierSpline edits (walk `Tools` once in top-level-then-nested order -> O(T), not O(S * T)) |
| 106 | let mut spline_names: Vec<&String> = self.splines.keys().collect(); | 161 | if !self.splines.is_empty() { |
| 107 | spline_names.sort(); | 162 | let mut remaining: HashMap<&str, &BezierSpline> = |
| 108 | for spline_name in spline_names { | 163 | self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect(); |
| 109 | let spline = &self.splines[spline_name]; | 164 | sync_existing_splines_in_tools(tools, &mut remaining); |
| 110 | if let Some(tbl) = find_raw_tool_mut(tools, spline_name) { | 165 | if !remaining.is_empty() { |
| 111 | sync_spline_table(spline_name, spline, tbl); | 166 | let mut new_names: Vec<&str> = remaining.keys().copied().collect(); |
| 112 | continue; | 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 | } | ||
| 113 | } | 184 | } |
| 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)); | ||
| 127 | } | 185 | } |
| 128 | 186 | ||
| 129 | root | 187 | root |
| ... | @@ -135,27 +193,35 @@ impl Comp { | ... | @@ -135,27 +193,35 @@ impl Comp { |
| 135 | &'a self, | 193 | &'a self, |
| 136 | tools: &mut LuaTable, | 194 | tools: &mut LuaTable, |
| 137 | internal: bool, | 195 | 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>>, | ||
| 139 | instance_defaults: &HashMap<(&str, &str), ParamValue>, | 198 | instance_defaults: &HashMap<(&str, &str), ParamValue>, |
| 140 | ) { | 199 | ) { |
| 141 | tools.entries.retain(|(k, v)| { | 200 | { |
| 142 | let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true }; | 201 | let pool = if internal { &*inner_pool } else { &*top_pool }; |
| 143 | is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) | 202 | tools.entries.retain(|(k, v)| { |
| 144 | || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty()) | 203 | let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true }; |
| 145 | }); | 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 | } | ||
| 146 | 208 | ||
| 147 | for (k, v) in &mut tools.entries { | 209 | for (k, v) in &mut tools.entries { |
| 148 | let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue }; | 210 | let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue }; |
| 149 | if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) { | 211 | if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) { |
| 150 | continue; | 212 | continue; |
| 151 | } | 213 | } |
| 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 { | ||
| 153 | continue; | 219 | continue; |
| 154 | }; | 220 | }; |
| 155 | self.sync_node_tool(node, tool_tbl, instance_defaults); | 221 | self.sync_node_tool(node, tool_tbl, instance_defaults); |
| 156 | if is_group_kind(&node.kind) { | 222 | if is_group_kind(&node.kind) { |
| 157 | if let Some(inner) = tool_tbl.get_table_mut("Tools") { | 223 | 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); |
| 159 | } | 225 | } |
| 160 | sync_group_wiring(node, tool_tbl); | 226 | sync_group_wiring(node, tool_tbl); |
| 161 | } | 227 | } |
| ... | @@ -205,8 +271,12 @@ impl Comp { | ... | @@ -205,8 +271,12 @@ impl Comp { |
| 205 | if node.kind == "Loader" { | 271 | if node.kind == "Loader" { |
| 206 | let edited = |port: &str| { | 272 | let edited = |port: &str| { |
| 207 | let now = node.static_number(port)?; | 273 | 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); | 274 | let before = tool_tbl |
| 209 | (before.and_then(|b| b.value?.as_f64()) != Some(now)).then_some(now) | 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) | ||
| 210 | }; | 280 | }; |
| 211 | let updates = [ | 281 | let updates = [ |
| 212 | ("GlobalStart", edited("GlobalIn").map(LuaValue::Number)), | 282 | ("GlobalStart", edited("GlobalIn").map(LuaValue::Number)), |
| ... | @@ -240,6 +310,9 @@ impl Comp { | ... | @@ -240,6 +310,9 @@ impl Comp { |
| 240 | 310 | ||
| 241 | /// Serializes this composition back to a Blackmagic Fusion `.comp` string. | 311 | /// Serializes this composition back to a Blackmagic Fusion `.comp` string. |
| 242 | pub fn to_fusion_string(&self) -> String { | 312 | pub fn to_fusion_string(&self) -> String { |
| 313 | if let Some(s) = self.try_to_fusion_string_streaming() { | ||
| 314 | return s; | ||
| 315 | } | ||
| 243 | let mut s = self.sync_to_raw_ast().to_fusion_string(); | 316 | let mut s = self.sync_to_raw_ast().to_fusion_string(); |
| 244 | if !s.ends_with('\n') { | 317 | if !s.ends_with('\n') { |
| 245 | s.push('\n'); | 318 | s.push('\n'); |
| ... | @@ -247,6 +320,631 @@ impl Comp { | ... | @@ -247,6 +320,631 @@ impl Comp { |
| 247 | s | 320 | s |
| 248 | } | 321 | } |
| 249 | 322 | ||
| 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 | } | ||
| 250 | /// Atomically saves this composition to `path`. | 948 | /// Atomically saves this composition to `path`. |
| 251 | /// If `path` already exists, backs up the original bytes to | 949 | /// If `path` already exists, backs up the original bytes to |
| 252 | /// `<temp_dir>/fission-backups/<stem>_<unix_millis>_<pid>_<seq>.comp.bak` and returns `Ok(Some(backup_path))`. | 950 | /// `<temp_dir>/fission-backups/<stem>_<unix_millis>_<pid>_<seq>.comp.bak` and returns `Ok(Some(backup_path))`. |
| ... | @@ -325,6 +1023,239 @@ impl Comp { | ... | @@ -325,6 +1023,239 @@ impl Comp { |
| 325 | } | 1023 | } |
| 326 | } | 1024 | } |
| 327 | 1025 | ||
| 1026 | fn 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 | |||
| 1034 | fn 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 | |||
| 1060 | fn 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 | |||
| 1086 | fn 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 | |||
| 1105 | fn 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 | |||
| 1135 | fn 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 | |||
| 1151 | fn 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 | |||
| 1192 | fn 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 | |||
| 328 | pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue { | 1259 | pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue { |
| 329 | LuaValue::Table(LuaTable { | 1260 | LuaValue::Table(LuaTable { |
| 330 | tag: None, | 1261 | tag: None, |
| ... | @@ -467,6 +1398,88 @@ fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) { | ... | @@ -467,6 +1398,88 @@ fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) { |
| 467 | } | 1398 | } |
| 468 | } | 1399 | } |
| 469 | 1400 | ||
| 1401 | fn 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 | |||
| 1410 | fn 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 | |||
| 1438 | fn 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 | |||
| 470 | fn sync_node_inputs( | 1483 | fn sync_node_inputs( |
| 471 | node: &Node, | 1484 | node: &Node, |
| 472 | master_inputs: Option<&HashMap<String, InputBinding>>, | 1485 | master_inputs: Option<&HashMap<String, InputBinding>>, |
| ... | @@ -487,37 +1500,38 @@ fn sync_node_inputs( | ... | @@ -487,37 +1500,38 @@ fn sync_node_inputs( |
| 487 | 1500 | ||
| 488 | // Collect sorted port names for deterministic output when appending new inputs. | 1501 | // Collect sorted port names for deterministic output when appending new inputs. |
| 489 | let mut ports: Vec<&String> = node.inputs.keys().collect(); | 1502 | let mut ports: Vec<&String> = node.inputs.keys().collect(); |
| 490 | ports.sort(); | 1503 | if ports.len() > 1 { |
| 1504 | ports.sort(); | ||
| 1505 | } | ||
| 491 | 1506 | ||
| 492 | for port in ports { | 1507 | for port in ports { |
| 493 | let binding = &node.inputs[port]; | 1508 | let binding = &node.inputs[port]; |
| 494 | // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default. | 1509 | // 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() | ||
| 496 | && binding.expression.is_none() | 1512 | && binding.expression.is_none() |
| 497 | && binding.value.is_some() | 1513 | && binding.value.is_some() |
| 498 | && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str())) | 1514 | && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str())) |
| 499 | && tool_tbl | 1515 | && tool_tbl |
| 500 | .get_table("Inputs") | 1516 | .get_table("Inputs") |
| 501 | .and_then(|i| i.get_table(port)) | 1517 | .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()) |
| 503 | { | 1519 | { |
| 504 | continue; | 1520 | continue; |
| 505 | } | 1521 | } |
| 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 | }); | ||
| 516 | 1522 | ||
| 517 | if let Some(orig) = existing_binding { | 1523 | let existing_tbl = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port)); |
| 518 | if orig == *binding { | 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) { | ||
| 519 | continue; | 1529 | continue; |
| 520 | } | 1530 | } |
| 1531 | let mut orig = parse_input_binding(it); | ||
| 1532 | if clear_src { | ||
| 1533 | orig.source_op = None; | ||
| 1534 | } | ||
| 521 | // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools. | 1535 | // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools. |
| 522 | if orig.value.is_none() | 1536 | if orig.value.is_none() |
| 523 | && orig.source_op.is_none() | 1537 | && orig.source_op.is_none() |
| ... | @@ -591,7 +1605,7 @@ fn sync_node_inputs( | ... | @@ -591,7 +1605,7 @@ fn sync_node_inputs( |
| 591 | 1605 | ||
| 592 | let mut it = LuaTable { | 1606 | let mut it = LuaTable { |
| 593 | tag: Some("Input".to_owned()), | 1607 | tag: Some("Input".to_owned()), |
| 594 | entries: Vec::new(), | 1608 | entries: Vec::with_capacity(4), |
| 595 | }; | 1609 | }; |
| 596 | if let Some(op) = &binding.source_op { | 1610 | if let Some(op) = &binding.source_op { |
| 597 | it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())); | 1611 | it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())); |
| ... | @@ -670,11 +1684,110 @@ fn build_keyframes_table(spline: &BezierSpline) -> LuaTable { | ... | @@ -670,11 +1684,110 @@ fn build_keyframes_table(spline: &BezierSpline) -> LuaTable { |
| 670 | tbl | 1684 | tbl |
| 671 | } | 1685 | } |
| 672 | 1686 | ||
| 1687 | /// Walks `tools` in top-level-before-nested order to sync all existing splines in one O(T) pass. | ||
| 1688 | fn 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 | |||
| 1711 | fn 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 | |||
| 1724 | fn 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 | |||
| 673 | fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) { | 1783 | fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) { |
| 674 | let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); | 1784 | if spline_color_from_lua(tbl) != spline.color { |
| 675 | if existing.color != spline.color { | ||
| 676 | tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color)); | 1785 | tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color)); |
| 677 | } | 1786 | } |
| 1787 | if keyframes_match_lua(spline, tbl) { | ||
| 1788 | return; | ||
| 1789 | } | ||
| 1790 | let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); | ||
| 678 | let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && { | 1791 | let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && { |
| 679 | let mut normalized = existing.clone(); | 1792 | let mut normalized = existing.clone(); |
| 680 | normalized.apply_hue_curves_cyclic_ends(); | 1793 | normalized.apply_hue_curves_cyclic_ends(); |
crates/model/src/lua_value.rs+473-264| ... | @@ -97,7 +97,10 @@ impl LuaTable { | ... | @@ -97,7 +97,10 @@ impl LuaTable { |
| 97 | 97 | ||
| 98 | /// Serializes this table using Blackmagic Fusion `.comp` Lua table syntax. | 98 | /// Serializes this table using Blackmagic Fusion `.comp` Lua table syntax. |
| 99 | pub fn to_fusion_string(&self) -> String { | 99 | 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); | ||
| 101 | write_table(self, 0, &mut out); | 104 | write_table(self, 0, &mut out); |
| 102 | out | 105 | out |
| 103 | } | 106 | } |
| ... | @@ -221,32 +224,53 @@ impl<'a> Parser<'a> { | ... | @@ -221,32 +224,53 @@ impl<'a> Parser<'a> { |
| 221 | Some(b) | 224 | Some(b) |
| 222 | } | 225 | } |
| 223 | 226 | ||
| 227 | #[inline(always)] | ||
| 224 | fn skip_ws_and_comments(&mut self) -> Result<(), ParseError> { | 228 | 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; | ||
| 225 | loop { | 248 | loop { |
| 226 | while let Some(b) = self.peek() { | 249 | while p < len && matches!(src[p], b' ' | b'\t' | b'\r' | b'\n') { |
| 227 | if matches!(b, b' ' | b'\t' | b'\r' | b'\n') { | 250 | p += 1; |
| 228 | self.pos += 1; | ||
| 229 | } else { | ||
| 230 | break; | ||
| 231 | } | ||
| 232 | } | 251 | } |
| 233 | if self.peek() == Some(b'-') && self.peek_at(1) == Some(b'-') { | 252 | if p + 1 < len && src[p] == b'-' && src[p + 1] == b'-' { |
| 234 | self.pos += 2; | 253 | p += 2; |
| 235 | if self.peek() == Some(b'[') { | 254 | if p < len && src[p] == b'[' { |
| 255 | self.pos = p; | ||
| 236 | if let Some(level) = self.try_open_long_bracket() { | 256 | if let Some(level) = self.try_open_long_bracket() { |
| 237 | self.skip_long_bracket(level)?; | 257 | self.skip_long_bracket(level)?; |
| 258 | p = self.pos; | ||
| 238 | continue; | 259 | continue; |
| 239 | } | 260 | } |
| 261 | p = self.pos; | ||
| 240 | } | 262 | } |
| 241 | while let Some(b) = self.bump() { | 263 | while p < len && src[p] != b'\n' { |
| 242 | if b == b'\n' { | 264 | p += 1; |
| 243 | break; | 265 | } |
| 244 | } | 266 | if p < len { |
| 267 | p += 1; | ||
| 245 | } | 268 | } |
| 246 | continue; | 269 | continue; |
| 247 | } | 270 | } |
| 248 | break; | 271 | break; |
| 249 | } | 272 | } |
| 273 | self.pos = p; | ||
| 250 | Ok(()) | 274 | Ok(()) |
| 251 | } | 275 | } |
| 252 | 276 | ||
| ... | @@ -269,22 +293,29 @@ impl<'a> Parser<'a> { | ... | @@ -269,22 +293,29 @@ impl<'a> Parser<'a> { |
| 269 | 293 | ||
| 270 | fn skip_long_bracket(&mut self, level: usize) -> Result<String, ParseError> { | 294 | fn skip_long_bracket(&mut self, level: usize) -> Result<String, ParseError> { |
| 271 | let start = self.pos; | 295 | let start = self.pos; |
| 272 | while self.pos < self.src.len() { | 296 | let src = self.src; |
| 273 | if self.src[self.pos] == b']' { | 297 | let len = src.len(); |
| 274 | let mut i = self.pos + 1; | 298 | let mut p = start; |
| 275 | let mut eq = 0; | 299 | while let Some(rel) = src[p..].iter().position(|&b| b == b']') { |
| 276 | while i < self.src.len() && self.src[i] == b'=' && eq < level { | 300 | let close_start = p + rel; |
| 277 | i += 1; | 301 | let mut i = close_start + 1; |
| 278 | eq += 1; | 302 | let mut eq = 0; |
| 279 | } | 303 | while i < len && src[i] == b'=' && eq < level { |
| 280 | if eq == level && i < self.src.len() && self.src[i] == b']' { | 304 | i += 1; |
| 281 | let s = String::from_utf8_lossy(&self.src[start..self.pos]).into_owned(); | 305 | eq += 1; |
| 282 | self.pos = i + 1; | ||
| 283 | return Ok(s); | ||
| 284 | } | ||
| 285 | } | 306 | } |
| 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; | ||
| 287 | } | 317 | } |
| 318 | self.pos = len; | ||
| 288 | Err(self.err("unterminated long bracket string/comment")) | 319 | Err(self.err("unterminated long bracket string/comment")) |
| 289 | } | 320 | } |
| 290 | 321 | ||
| ... | @@ -318,26 +349,31 @@ impl<'a> Parser<'a> { | ... | @@ -318,26 +349,31 @@ impl<'a> Parser<'a> { |
| 318 | 349 | ||
| 319 | fn parse_ident_or_constructor(&mut self) -> Result<LuaValue, ParseError> { | 350 | fn parse_ident_or_constructor(&mut self) -> Result<LuaValue, ParseError> { |
| 320 | let start = self.pos; | 351 | let start = self.pos; |
| 321 | while let Some(b) = self.peek() { | 352 | let src = self.src; |
| 322 | if is_ident_cont(b) || b == b'.' { | 353 | let len = src.len(); |
| 323 | self.pos += 1; | 354 | let mut p = start; |
| 324 | } else { | 355 | while p < len && (is_ident_cont(src[p]) || src[p] == b'.') { |
| 325 | break; | 356 | p += 1; |
| 326 | } | ||
| 327 | } | 357 | } |
| 328 | let ident = std::str::from_utf8(&self.src[start..self.pos]) | 358 | self.pos = p; |
| 329 | .map_err(|_| self.err("invalid UTF-8 identifier"))? | 359 | self.finish_ident_or_constructor(start, p) |
| 330 | .to_owned(); | 360 | } |
| 331 | 361 | ||
| 332 | match ident.as_str() { | 362 | fn finish_ident_or_constructor(&mut self, start: usize, end: usize) -> Result<LuaValue, ParseError> { |
| 333 | "true" => return Ok(LuaValue::Bool(true)), | 363 | let ident_bytes = &self.src[start..end]; |
| 334 | "false" => return Ok(LuaValue::Bool(false)), | 364 | match ident_bytes { |
| 335 | "nil" => return Ok(LuaValue::Nil), | 365 | b"true" => return Ok(LuaValue::Bool(true)), |
| 336 | "inf" | "INF" => return Ok(LuaValue::Number(f64::INFINITY)), | 366 | b"false" => return Ok(LuaValue::Bool(false)), |
| 337 | "nan" | "NaN" | "NAN" => return Ok(LuaValue::Number(f64::NAN)), | 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)), | ||
| 338 | _ => {} | 370 | _ => {} |
| 339 | } | 371 | } |
| 340 | 372 | ||
| 373 | let ident = std::str::from_utf8(ident_bytes) | ||
| 374 | .map_err(|_| self.err("invalid UTF-8 identifier"))? | ||
| 375 | .to_owned(); | ||
| 376 | |||
| 341 | self.skip_ws_and_comments()?; | 377 | self.skip_ws_and_comments()?; |
| 342 | 378 | ||
| 343 | // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)` | 379 | // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)` |
| ... | @@ -369,7 +405,7 @@ impl<'a> Parser<'a> { | ... | @@ -369,7 +405,7 @@ impl<'a> Parser<'a> { |
| 369 | return Ok(LuaValue::Table(table)); | 405 | return Ok(LuaValue::Table(table)); |
| 370 | } | 406 | } |
| 371 | // Standalone call like `Point(0.5, 0.5)` or `FuID("Foo")` | 407 | // 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()) }; |
| 373 | for (i, arg) in args.into_iter().enumerate() { | 409 | for (i, arg) in args.into_iter().enumerate() { |
| 374 | table.entries.push((LuaKey::Index((i + 1) as i64), arg)); | 410 | table.entries.push((LuaKey::Index((i + 1) as i64), arg)); |
| 375 | } | 411 | } |
| ... | @@ -397,61 +433,38 @@ impl<'a> Parser<'a> { | ... | @@ -397,61 +433,38 @@ impl<'a> Parser<'a> { |
| 397 | if self.bump() != Some(b'{') { | 433 | if self.bump() != Some(b'{') { |
| 398 | return Err(self.err("expected '{'")); | 434 | return Err(self.err("expected '{'")); |
| 399 | } | 435 | } |
| 400 | let mut entries = Vec::new(); | 436 | let mut first_entry: Option<(LuaKey, LuaValue)> = None; |
| 437 | let mut entries: Option<Vec<(LuaKey, LuaValue)>> = None; | ||
| 401 | let mut next_index: i64 = 1; | 438 | let mut next_index: i64 = 1; |
| 402 | 439 | ||
| 403 | loop { | 440 | loop { |
| 404 | self.skip_ws_and_comments()?; | 441 | self.skip_ws_and_comments()?; |
| 405 | match self.peek() { | 442 | let Some(b) = self.peek() else { |
| 406 | None => { | 443 | // Gracefully close open tables on truncated/export-clipped `.comp` files. |
| 407 | // Gracefully close open tables on truncated/export-clipped `.comp` files. | 444 | break; |
| 408 | break; | 445 | }; |
| 409 | } | 446 | match b { |
| 410 | Some(b'}') => { | 447 | b'}' => { |
| 411 | self.pos += 1; | 448 | self.pos += 1; |
| 412 | break; | 449 | break; |
| 413 | } | 450 | } |
| 414 | Some(b',') | Some(b';') => { | 451 | b',' | b';' => { |
| 415 | self.pos += 1; | 452 | self.pos += 1; |
| 416 | continue; | 453 | continue; |
| 417 | } | 454 | } |
| 418 | _ => {} | 455 | _ => {} |
| 419 | } | 456 | } |
| 420 | 457 | ||
| 421 | // Decide between `[expr] = val`, `ident = val`, or positional `val` | 458 | let entry = self.parse_table_entry(b, &mut next_index)?; |
| 422 | if self.peek() == Some(b'[') && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') { | 459 | if let Some(ref mut vec) = entries { |
| 423 | self.pos += 1; // consume '[' | 460 | vec.push(entry); |
| 424 | self.skip_ws_and_comments()?; | 461 | } else if let Some(prev) = first_entry.take() { |
| 425 | let key_val = self.parse_value()?; | 462 | let mut vec = Vec::with_capacity(4); |
| 426 | self.skip_ws_and_comments()?; | 463 | vec.push(prev); |
| 427 | if self.bump() != Some(b']') { | 464 | vec.push(entry); |
| 428 | return Err(self.err("expected ']' after table key")); | 465 | entries = Some(vec); |
| 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)); | ||
| 451 | } else { | 466 | } else { |
| 452 | let val = self.parse_value()?; | 467 | first_entry = Some(entry); |
| 453 | entries.push((LuaKey::Index(next_index), val)); | ||
| 454 | next_index += 1; | ||
| 455 | } | 468 | } |
| 456 | 469 | ||
| 457 | self.skip_ws_and_comments()?; | 470 | self.skip_ws_and_comments()?; |
| ... | @@ -460,187 +473,313 @@ impl<'a> Parser<'a> { | ... | @@ -460,187 +473,313 @@ impl<'a> Parser<'a> { |
| 460 | } | 473 | } |
| 461 | } | 474 | } |
| 462 | 475 | ||
| 476 | let entries = match (entries, first_entry) { | ||
| 477 | (Some(vec), _) => vec, | ||
| 478 | (None, Some(e)) => vec![e], | ||
| 479 | (None, None) => Vec::new(), | ||
| 480 | }; | ||
| 463 | Ok(LuaTable { tag, entries }) | 481 | Ok(LuaTable { tag, entries }) |
| 464 | } | 482 | } |
| 465 | 483 | ||
| 466 | fn try_ident_equals(&mut self) -> Option<(String, usize)> { | 484 | #[inline(always)] |
| 467 | let saved = self.pos; | 485 | fn parse_table_entry(&mut self, b: u8, next_index: &mut i64) -> Result<(LuaKey, LuaValue), ParseError> { |
| 468 | let b = self.peek()?; | 486 | if b == b'[' && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') { |
| 469 | if !is_ident_start(b) { | 487 | self.pos += 1; // consume '[' |
| 470 | return None; | 488 | self.skip_ws_and_comments()?; |
| 471 | } | 489 | let key_val = self.parse_value()?; |
| 472 | let start = self.pos; | 490 | self.skip_ws_and_comments()?; |
| 473 | while let Some(c) = self.peek() { | 491 | if self.bump() != Some(b']') { |
| 474 | if is_ident_cont(c) { | 492 | return Err(self.err("expected ']' after table key")); |
| 475 | self.pos += 1; | 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)) | ||
| 476 | } else { | 530 | } 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 | } | ||
| 478 | } | 546 | } |
| 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)) | ||
| 486 | } else { | 547 | } else { |
| 487 | self.pos = saved; | 548 | let val = self.parse_value()?; |
| 488 | None | 549 | let idx = *next_index; |
| 550 | *next_index += 1; | ||
| 551 | Ok((LuaKey::Index(idx), val)) | ||
| 489 | } | 552 | } |
| 490 | } | 553 | } |
| 491 | 554 | ||
| 492 | fn parse_quoted_string(&mut self) -> Result<String, ParseError> { | 555 | fn parse_quoted_string(&mut self) -> Result<String, ParseError> { |
| 493 | let quote = self.bump().ok_or_else(|| self.err("expected quote"))?; | 556 | let quote = self.bump().ok_or_else(|| self.err("expected quote"))?; |
| 494 | let mut out = Vec::new(); | 557 | let src = self.src; |
| 495 | while let Some(b) = self.bump() { | 558 | let len = src.len(); |
| 559 | let start = self.pos; | ||
| 560 | let mut p = start; | ||
| 561 | while p < len { | ||
| 562 | let b = src[p]; | ||
| 496 | if b == quote { | 563 | 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 | }); | ||
| 498 | } | 570 | } |
| 499 | if b == b'\\' { | 571 | if b == b'\\' { |
| 500 | let Some(esc) = self.bump() else { | 572 | break; |
| 501 | return Err(self.err("unterminated escape sequence")); | 573 | } |
| 502 | }; | 574 | p += 1; |
| 503 | match esc { | 575 | } |
| 504 | b'n' => out.push(b'\n'), | 576 | if p >= len { |
| 505 | b'r' => out.push(b'\r'), | 577 | self.pos = len; |
| 506 | b't' => out.push(b'\t'), | 578 | return Err(self.err("unterminated string literal")); |
| 507 | b'\\' => out.push(b'\\'), | 579 | } |
| 508 | b'"' => out.push(b'"'), | 580 | |
| 509 | b'\'' => out.push(b'\''), | 581 | let mut out = Vec::with_capacity((p - start).saturating_add(16)); |
| 510 | b'a' => out.push(0x07), | 582 | if p > start { |
| 511 | b'b' => out.push(0x08), | 583 | out.extend_from_slice(&src[start..p]); |
| 512 | b'f' => out.push(0x0C), | 584 | } |
| 513 | b'v' => out.push(0x0B), | 585 | self.pos = p; |
| 514 | b'\n' => out.push(b'\n'), | 586 | |
| 515 | b'\r' => { | 587 | while self.pos < len { |
| 516 | if self.peek() == Some(b'\n') { | 588 | let chunk_start = self.pos; |
| 517 | self.pos += 1; | 589 | let mut q = chunk_start; |
| 518 | } | 590 | let mut found_quote = false; |
| 519 | out.push(b'\n'); | 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; | ||
| 520 | } | 637 | } |
| 521 | b'z' => { | 638 | out.push(b'\n'); |
| 522 | while let Some(ws) = self.peek() { | 639 | } |
| 523 | if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') { | 640 | b'z' => { |
| 524 | self.pos += 1; | 641 | while let Some(ws) = self.peek() { |
| 525 | } else { | 642 | if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') { |
| 526 | break; | 643 | self.pos += 1; |
| 527 | } | 644 | } else { |
| 645 | break; | ||
| 528 | } | 646 | } |
| 529 | } | 647 | } |
| 530 | b'x' => { | 648 | } |
| 531 | let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; | 649 | b'x' => { |
| 532 | let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; | 650 | let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; |
| 533 | let s = [h1, h2]; | 651 | let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; |
| 534 | let byte = u8::from_str_radix(std::str::from_utf8(&s).unwrap_or("00"), 16) | 652 | let n1 = hex_nibble(h1).ok_or_else(|| self.err("invalid hex escape"))?; |
| 535 | .map_err(|_| self.err("invalid hex escape"))?; | 653 | let n2 = hex_nibble(h2).ok_or_else(|| self.err("invalid hex escape"))?; |
| 536 | out.push(byte); | 654 | out.push((n1 << 4) | n2); |
| 537 | } | 655 | } |
| 538 | b'0'..=b'9' => { | 656 | b'0'..=b'9' => { |
| 539 | let mut val = (esc - b'0') as u32; | 657 | let mut val = (esc - b'0') as u32; |
| 540 | for _ in 0..2 { | 658 | for _ in 0..2 { |
| 541 | if let Some(d @ b'0'..=b'9') = self.peek() { | 659 | if let Some(d @ b'0'..=b'9') = self.peek() { |
| 542 | self.pos += 1; | 660 | self.pos += 1; |
| 543 | val = val * 10 + (d - b'0') as u32; | 661 | val = val * 10 + (d - b'0') as u32; |
| 544 | } else { | 662 | } else { |
| 545 | break; | 663 | break; |
| 546 | } | ||
| 547 | } | 664 | } |
| 548 | out.push((val & 0xFF) as u8); | ||
| 549 | } | 665 | } |
| 550 | other => out.push(other), | 666 | out.push((val & 0xFF) as u8); |
| 551 | } | 667 | } |
| 552 | } else { | 668 | other => out.push(other), |
| 553 | out.push(b); | ||
| 554 | } | 669 | } |
| 555 | } | 670 | } |
| 556 | Err(self.err("unterminated string literal")) | 671 | Err(self.err("unterminated string literal")) |
| 557 | } | 672 | } |
| 558 | 673 | ||
| 559 | fn parse_number(&mut self) -> Result<LuaValue, ParseError> { | 674 | fn parse_number(&mut self) -> Result<LuaValue, ParseError> { |
| 675 | let src = self.src; | ||
| 676 | let len = src.len(); | ||
| 560 | let start = self.pos; | 677 | let start = self.pos; |
| 561 | if matches!(self.peek(), Some(b'-' | b'+')) { | 678 | let mut p = start; |
| 562 | self.pos += 1; | 679 | let mut neg = false; |
| 563 | } | 680 | if p < len { |
| 564 | // Check for -inf / -nan / -1.#INF / -1.#IND (Windows MSVC Fusion files!) | 681 | if src[p] == b'-' { |
| 565 | if self.src[self.pos..].starts_with(b"inf") || self.src[self.pos..].starts_with(b"INF") { | 682 | neg = true; |
| 566 | self.pos += 3; | 683 | p += 1; |
| 567 | let neg = self.src[start] == b'-'; | 684 | } else if src[p] == b'+' { |
| 568 | return Ok(LuaValue::Number(if neg { f64::NEG_INFINITY } else { f64::INFINITY })); | 685 | p += 1; |
| 569 | } | 686 | } |
| 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)); | ||
| 573 | } | 687 | } |
| 574 | 688 | ||
| 575 | // Hex integer / float `0x...` | 689 | if p < len && src[p].is_ascii_digit() { |
| 576 | if self.peek() == Some(b'0') && matches!(self.peek_at(1), Some(b'x' | b'X')) { | 690 | // Hex integer `0x...` |
| 577 | self.pos += 2; | 691 | if src[p] == b'0' && p + 1 < len && (src[p + 1] == b'x' || src[p + 1] == b'X') { |
| 578 | let hex_start = self.pos; | 692 | p += 2; |
| 579 | while let Some(b) = self.peek() { | 693 | let hex_start = p; |
| 580 | if b.is_ascii_hexdigit() { | 694 | let mut val: u64 = 0; |
| 581 | self.pos += 1; | 695 | while p < len && src[p].is_ascii_hexdigit() { |
| 582 | } else { | 696 | if p - hex_start < 16 { |
| 583 | break; | 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 })); | ||
| 584 | } | 707 | } |
| 708 | let v = val as f64; | ||
| 709 | return Ok(LuaValue::Number(if neg { -v } else { v })); | ||
| 585 | } | 710 | } |
| 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 | } | ||
| 591 | 711 | ||
| 592 | while let Some(b) = self.peek() { | 712 | let int_start = p; |
| 593 | if b.is_ascii_digit() { | 713 | let mut int_val: u64 = 0; |
| 594 | self.pos += 1; | 714 | while p < len && src[p].is_ascii_digit() { |
| 595 | } else { | 715 | if p - int_start < 15 { |
| 596 | break; | 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)); | ||
| 597 | } | 735 | } |
| 598 | } | 736 | } |
| 599 | if self.peek() == Some(b'.') { | 737 | |
| 600 | self.pos += 1; | 738 | if p < len && src[p] == b'.' { |
| 739 | p += 1; | ||
| 601 | // Handle Windows MSVC `1.#INF`, `1.#IND`, `1.#QNAN` | 740 | // Handle Windows MSVC `1.#INF`, `1.#IND`, `1.#QNAN` |
| 602 | if self.peek() == Some(b'#') { | 741 | if p < len && src[p] == b'#' { |
| 603 | while let Some(b) = self.peek() { | 742 | while p < len && (src[p].is_ascii_alphanumeric() || src[p] == b'#') { |
| 604 | if b.is_ascii_alphanumeric() || b == b'#' { | 743 | p += 1; |
| 605 | self.pos += 1; | ||
| 606 | } else { | ||
| 607 | break; | ||
| 608 | } | ||
| 609 | } | 744 | } |
| 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(""); | ||
| 611 | if raw.contains("INF") { | 747 | if raw.contains("INF") { |
| 612 | return Ok(LuaValue::Number(if raw.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY })); | 748 | return Ok(LuaValue::Number(if raw.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY })); |
| 613 | } | 749 | } |
| 614 | return Ok(LuaValue::Number(f64::NAN)); | 750 | return Ok(LuaValue::Number(f64::NAN)); |
| 615 | } | 751 | } |
| 616 | while let Some(b) = self.peek() { | 752 | while p < len && src[p].is_ascii_digit() { |
| 617 | if b.is_ascii_digit() { | 753 | p += 1; |
| 618 | self.pos += 1; | ||
| 619 | } else { | ||
| 620 | break; | ||
| 621 | } | ||
| 622 | } | 754 | } |
| 623 | } | 755 | } |
| 624 | if matches!(self.peek(), Some(b'e' | b'E')) { | 756 | if p < len && (src[p] == b'e' || src[p] == b'E') { |
| 625 | self.pos += 1; | 757 | p += 1; |
| 626 | if matches!(self.peek(), Some(b'+' | b'-')) { | 758 | if p < len && (src[p] == b'+' || src[p] == b'-') { |
| 627 | self.pos += 1; | 759 | p += 1; |
| 628 | } | 760 | } |
| 629 | while let Some(b) = self.peek() { | 761 | while p < len && src[p].is_ascii_digit() { |
| 630 | if b.is_ascii_digit() { | 762 | p += 1; |
| 631 | self.pos += 1; | ||
| 632 | } else { | ||
| 633 | break; | ||
| 634 | } | ||
| 635 | } | 763 | } |
| 636 | } | 764 | } |
| 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]) | ||
| 638 | .map_err(|_| self.err("invalid UTF-8 in number"))?; | 767 | .map_err(|_| self.err("invalid UTF-8 in number"))?; |
| 639 | let n: f64 = s.parse().map_err(|_| self.err(format!("invalid number '{s}'")))?; | 768 | let n: f64 = s.parse().map_err(|_| self.err(format!("invalid number '{s}'")))?; |
| 640 | Ok(LuaValue::Number(n)) | 769 | Ok(LuaValue::Number(n)) |
| 641 | } | 770 | } |
| 642 | } | 771 | } |
| 643 | 772 | ||
| 773 | #[inline] | ||
| 774 | fn 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 | |||
| 644 | fn is_ident_start(b: u8) -> bool { | 783 | fn is_ident_start(b: u8) -> bool { |
| 645 | b.is_ascii_alphabetic() || b == b'_' | 784 | b.is_ascii_alphabetic() || b == b'_' |
| 646 | } | 785 | } |
| ... | @@ -654,6 +793,9 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool { | ... | @@ -654,6 +793,9 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool { |
| 654 | if bytes.is_empty() || !is_ident_start(bytes[0]) || !bytes[1..].iter().all(|&b| is_ident_cont(b)) { | 793 | if bytes.is_empty() || !is_ident_start(bytes[0]) || !bytes[1..].iter().all(|&b| is_ident_cont(b)) { |
| 655 | return false; | 794 | return false; |
| 656 | } | 795 | } |
| 796 | if bytes.len() > 8 || bytes.len() < 2 { | ||
| 797 | return true; | ||
| 798 | } | ||
| 657 | !matches!( | 799 | !matches!( |
| 658 | s, | 800 | s, |
| 659 | "and" | 801 | "and" |
| ... | @@ -681,12 +823,39 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool { | ... | @@ -681,12 +823,39 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool { |
| 681 | ) | 823 | ) |
| 682 | } | 824 | } |
| 683 | 825 | ||
| 684 | fn write_indent(out: &mut String, depth: usize) { | 826 | #[inline] |
| 685 | for _ in 0..depth { | 827 | pub(crate) fn write_indent(out: &mut String, mut depth: usize) { |
| 686 | out.push('\t'); | 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; | ||
| 687 | } | 833 | } |
| 688 | } | 834 | } |
| 689 | 835 | ||
| 836 | #[inline] | ||
| 837 | fn 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 | |||
| 690 | fn write_number(n: f64, out: &mut String) { | 859 | fn write_number(n: f64, out: &mut String) { |
| 691 | if n.is_nan() { | 860 | if n.is_nan() { |
| 692 | out.push_str("nan"); | 861 | out.push_str("nan"); |
| ... | @@ -699,8 +868,7 @@ fn write_number(n: f64, out: &mut String) { | ... | @@ -699,8 +868,7 @@ fn write_number(n: f64, out: &mut String) { |
| 699 | } else if n == 0.0 { | 868 | } else if n == 0.0 { |
| 700 | out.push('0'); | 869 | out.push('0'); |
| 701 | } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 { | 870 | } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 { |
| 702 | use std::fmt::Write; | 871 | write_i64(n as i64, out); |
| 703 | let _ = write!(out, "{}", n as i64); | ||
| 704 | } else { | 872 | } else { |
| 705 | use std::fmt::Write; | 873 | use std::fmt::Write; |
| 706 | let _ = write!(out, "{n}"); | 874 | let _ = write!(out, "{n}"); |
| ... | @@ -708,25 +876,40 @@ fn write_number(n: f64, out: &mut String) { | ... | @@ -708,25 +876,40 @@ fn write_number(n: f64, out: &mut String) { |
| 708 | } | 876 | } |
| 709 | 877 | ||
| 710 | fn write_string(s: &str, out: &mut String) { | 878 | fn write_string(s: &str, out: &mut String) { |
| 711 | use std::fmt::Write; | ||
| 712 | out.push('"'); | 879 | out.push('"'); |
| 713 | for c in s.chars() { | 880 | let bytes = s.as_bytes(); |
| 714 | match c { | 881 | let mut last = 0; |
| 715 | '\\' => out.push_str("\\\\"), | 882 | for (i, &b) in bytes.iter().enumerate() { |
| 716 | '"' => out.push_str("\\\""), | 883 | let esc = match b { |
| 717 | '\n' => out.push_str("\\n"), | 884 | b'\\' => "\\\\", |
| 718 | '\r' => out.push_str("\\r"), | 885 | b'"' => "\\\"", |
| 719 | '\t' => out.push_str("\\t"), | 886 | b'\n' => "\\n", |
| 720 | c if (c as u32) < 0x20 || (c as u32) == 0x7F => { | 887 | b'\r' => "\\r", |
| 721 | let _ = write!(out, "\\{:03}", c as u32); | 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; | ||
| 722 | } | 897 | } |
| 723 | c => out.push(c), | 898 | _ => continue, |
| 899 | }; | ||
| 900 | if i > last { | ||
| 901 | out.push_str(&s[last..i]); | ||
| 724 | } | 902 | } |
| 903 | out.push_str(esc); | ||
| 904 | last = i + 1; | ||
| 905 | } | ||
| 906 | if last < bytes.len() { | ||
| 907 | out.push_str(&s[last..]); | ||
| 725 | } | 908 | } |
| 726 | out.push('"'); | 909 | out.push('"'); |
| 727 | } | 910 | } |
| 728 | 911 | ||
| 729 | fn write_value(val: &LuaValue, depth: usize, out: &mut String) { | 912 | pub(crate) fn write_value(val: &LuaValue, depth: usize, out: &mut String) { |
| 730 | match val { | 913 | match val { |
| 731 | LuaValue::Nil => out.push_str("nil"), | 914 | LuaValue::Nil => out.push_str("nil"), |
| 732 | LuaValue::Bool(true) => out.push_str("true"), | 915 | LuaValue::Bool(true) => out.push_str("true"), |
| ... | @@ -737,6 +920,13 @@ fn write_value(val: &LuaValue, depth: usize, out: &mut String) { | ... | @@ -737,6 +920,13 @@ fn write_value(val: &LuaValue, depth: usize, out: &mut String) { |
| 737 | } | 920 | } |
| 738 | } | 921 | } |
| 739 | 922 | ||
| 923 | #[inline] | ||
| 924 | pub(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 | |||
| 740 | fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) { | 930 | fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) { |
| 741 | let mut call_args = Vec::new(); | 931 | let mut call_args = Vec::new(); |
| 742 | let mut next_arg = 0usize; | 932 | let mut next_arg = 0usize; |
| ... | @@ -763,11 +953,17 @@ fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) | ... | @@ -763,11 +953,17 @@ fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) |
| 763 | (call_args, body) | 953 | (call_args, body) |
| 764 | } | 954 | } |
| 765 | 955 | ||
| 766 | fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { | 956 | pub(crate) fn can_use_positional<'a>(entries: impl Iterator<Item = &'a (LuaKey, LuaValue)> + Clone) -> bool { |
| 767 | let mut expected = 1i64; | 957 | let mut expected = 1i64; |
| 768 | let mut index_count = 0usize; | 958 | let mut index_count = 0usize; |
| 769 | for (k, _) in body { | 959 | let mut len = 0usize; |
| 770 | match k { | 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 { | ||
| 771 | LuaKey::Number(_) => return false, | 967 | LuaKey::Number(_) => return false, |
| 772 | LuaKey::Index(i) => { | 968 | LuaKey::Index(i) => { |
| 773 | if *i != expected { | 969 | if *i != expected { |
| ... | @@ -779,8 +975,8 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { | ... | @@ -779,8 +975,8 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { |
| 779 | LuaKey::Str(_) => {} | 975 | LuaKey::Str(_) => {} |
| 780 | } | 976 | } |
| 781 | } | 977 | } |
| 782 | if index_count == 1 && body.len() == 1 { | 978 | if index_count == 1 && len == 1 { |
| 783 | if let (LuaKey::Index(1), LuaValue::Table(sub)) = body[0] { | 979 | if let Some((LuaKey::Index(1), LuaValue::Table(sub))) = first { |
| 784 | if sub.tag.is_none() | 980 | if sub.tag.is_none() |
| 785 | && (sub.get("Flags").is_some() || sub.get("LH").is_some() || sub.get("RH").is_some()) | 981 | && (sub.get("Flags").is_some() || sub.get("LH").is_some() || sub.get("RH").is_some()) |
| 786 | { | 982 | { |
| ... | @@ -792,24 +988,20 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { | ... | @@ -792,24 +988,20 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { |
| 792 | } | 988 | } |
| 793 | 989 | ||
| 794 | fn can_inline_table(tbl: &LuaTable, max_depth: usize) -> bool { | 990 | fn 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") { |
| 796 | return false; | 992 | return false; |
| 797 | } | 993 | } |
| 798 | if tbl.tag.as_deref() == Some("ordered") { | 994 | if has_call_args(tbl) { |
| 799 | return false; | 995 | return false; |
| 800 | } | 996 | } |
| 801 | let (call_args, body) = split_call_args(tbl); | 997 | tbl.entries.iter().all(|(_, v)| match v { |
| 802 | if !call_args.is_empty() || body.len() > 4 { | ||
| 803 | return false; | ||
| 804 | } | ||
| 805 | body.iter().all(|(_, v)| match v { | ||
| 806 | LuaValue::Nil | LuaValue::Bool(_) | LuaValue::Number(_) => true, | 998 | 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'), |
| 808 | LuaValue::Table(sub) => max_depth > 1 && can_inline_table(sub, max_depth - 1), | 1000 | LuaValue::Table(sub) => max_depth > 1 && can_inline_table(sub, max_depth - 1), |
| 809 | }) | 1001 | }) |
| 810 | } | 1002 | } |
| 811 | 1003 | ||
| 812 | fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, out: &mut String) { | 1004 | pub(crate) fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, out: &mut String) { |
| 813 | if let Some(t) = tag { | 1005 | if let Some(t) = tag { |
| 814 | out.push_str(t); | 1006 | out.push_str(t); |
| 815 | if t == "ordered" || !call_args.is_empty() { | 1007 | if t == "ordered" || !call_args.is_empty() { |
| ... | @@ -826,12 +1018,13 @@ fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, | ... | @@ -826,12 +1018,13 @@ fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, |
| 826 | } | 1018 | } |
| 827 | } | 1019 | } |
| 828 | 1020 | ||
| 829 | fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { | 1021 | pub(crate) fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { |
| 830 | match key { | 1022 | match key { |
| 831 | LuaKey::Index(_) if positional => false, | 1023 | LuaKey::Index(_) if positional => false, |
| 832 | LuaKey::Index(i) => { | 1024 | LuaKey::Index(i) => { |
| 833 | use std::fmt::Write; | 1025 | out.push('['); |
| 834 | let _ = write!(out, "[{i}] = "); | 1026 | write_i64(*i, out); |
| 1027 | out.push_str("] = "); | ||
| 835 | true | 1028 | true |
| 836 | } | 1029 | } |
| 837 | LuaKey::Number(n) => { | 1030 | LuaKey::Number(n) => { |
| ... | @@ -854,36 +1047,40 @@ fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { | ... | @@ -854,36 +1047,40 @@ fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { |
| 854 | } | 1047 | } |
| 855 | } | 1048 | } |
| 856 | 1049 | ||
| 857 | fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { | 1050 | fn write_table_body<'a>( |
| 858 | let (call_args, body) = split_call_args(tbl); | 1051 | tbl: &LuaTable, |
| 859 | write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out); | 1052 | entries: impl Iterator<Item = &'a (LuaKey, LuaValue)> + Clone, |
| 860 | 1053 | depth: usize, | |
| 861 | if body.is_empty() { | 1054 | out: &mut String, |
| 1055 | ) { | ||
| 1056 | let mut peek = entries.clone(); | ||
| 1057 | if peek.next().is_none() { | ||
| 862 | out.push_str("{}"); | 1058 | out.push_str("{}"); |
| 863 | return; | 1059 | return; |
| 864 | } | 1060 | } |
| 865 | 1061 | ||
| 866 | let positional = can_use_positional(&body); | 1062 | let positional = can_use_positional(entries.clone()); |
| 867 | 1063 | ||
| 868 | if depth > 0 && can_inline_table(tbl, 2) { | 1064 | if depth > 0 && can_inline_table(tbl, 2) { |
| 869 | let mut inline = String::new(); | 1065 | let saved_len = out.len(); |
| 870 | inline.push_str("{ "); | 1066 | out.push_str("{ "); |
| 871 | for (i, (k, v)) in body.iter().enumerate() { | 1067 | for (i, (k, v)) in entries.clone().enumerate() { |
| 872 | if i > 0 { | 1068 | if i > 0 { |
| 873 | inline.push_str(", "); | 1069 | out.push_str(", "); |
| 874 | } | 1070 | } |
| 875 | write_entry_key(k, positional, &mut inline); | 1071 | write_entry_key(k, positional, out); |
| 876 | write_value(v, depth + 1, &mut inline); | 1072 | write_value(v, depth + 1, out); |
| 877 | } | 1073 | } |
| 878 | inline.push_str(" }"); | 1074 | out.push_str(" }"); |
| 879 | if !inline.contains('\n') && inline.len() <= 100 { | 1075 | let written = &out[saved_len..]; |
| 880 | out.push_str(&inline); | 1076 | if written.len() <= 100 && !written.contains('\n') { |
| 881 | return; | 1077 | return; |
| 882 | } | 1078 | } |
| 1079 | out.truncate(saved_len); | ||
| 883 | } | 1080 | } |
| 884 | 1081 | ||
| 885 | out.push_str("{\n"); | 1082 | out.push_str("{\n"); |
| 886 | for (k, v) in body { | 1083 | for (k, v) in entries { |
| 887 | write_indent(out, depth + 1); | 1084 | write_indent(out, depth + 1); |
| 888 | write_entry_key(k, positional, out); | 1085 | write_entry_key(k, positional, out); |
| 889 | write_value(v, depth + 1, out); | 1086 | write_value(v, depth + 1, out); |
| ... | @@ -892,3 +1089,15 @@ fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { | ... | @@ -892,3 +1089,15 @@ fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { |
| 892 | write_indent(out, depth); | 1089 | write_indent(out, depth); |
| 893 | out.push('}'); | 1090 | out.push('}'); |
| 894 | } | 1091 | } |
| 1092 | |||
| 1093 | pub(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 | } |