authoravatarclover caruso<git@paperclover.net>2026-12-01 05:39:03-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 06:26:56-08:00
log8cd212451d5213a9a3f96ccdfb9756f9ab15d994
tree9f55d542dd9dd027049d30864244a45bb167cfbf
parentf2a1716264a84ca38dc64149525f356134a5ff47
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Review pass 4: inspector, flow, expr/save, media and web fixes

- inspector: no panic on empty color edits, scrub coalesces on the control's primary channel, typed numbers commit to the node they were typed into (also on deselect), pages rebuild on structural change only, one catalog thread, expression badge on Point/Text rows - flow: rewire detaches after a 4px drag, keeps the wire's source output, pointer cancel and sanitize close open history groups, handle reach from rendered ports, SwitchElse/DeltaKeyer/ CheckerPieceGenerator port tables - model: expr depth/token caps, NaN comparisons, %.14g formatting, integer //,% by zero, trailing ';'; Loader timing saves into the first real clip - engine/web: EXR decode from virtual bytes, unique-basename virtual matching with 512 MiB cap, web_time Instant on wasm, surface reconfigure/retry, alpha mode, size clamp, GPU error surfacing Assisted-by: claude-sonnet-5.5

13 files changed, 842 insertions(+), 150 deletions(-)

crates/app/src/inspector/controls.rs+25-26
...@@ -14,32 +14,31 @@ const BOX_H: f32 = 20.0;...@@ -14,32 +14,31 @@ const BOX_H: f32 = 20.0;
1414
15pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {15pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
16 let channels = def.channels.as_slice();16 let channels = def.channels.as_slice();
17 let animatable = match def.kind {17 let keys = match def.kind {
18 Kind::Slider | Kind::Screw | Kind::Range | Kind::Color | Kind::Checkbox | Kind::Toggles => true,18 Kind::Slider | Kind::Screw | Kind::Range | Kind::Color | Kind::Checkbox | Kind::Toggles => true,
19 Kind::Segmented | Kind::Combo => !def.fuid,19 Kind::Segmented | Kind::Combo => !def.fuid,
20 Kind::Point | Kind::Text => false,20 Kind::Point | Kind::Text => false,
21 };21 };
22 let marks = if animatable { channels } else { &[] };
23 match def.kind {22 match def.kind {
24 Kind::Slider => {23 Kind::Slider => {
25 let ch = &channels[0];24 let ch = &channels[0];
26 let sub = sub_labels(&ch.id);25 let sub = sub_labels(&ch.id);
27 let height = px(if sub.is_some() { ROW_H + 14.0 } else { ROW_H });26 let height = px(if sub.is_some() { ROW_H + 14.0 } else { ROW_H });
28 row(ui, cx, &def.label, &ch.id, marks, height, |ui, cx| {27 row(ui, cx, &def.label, &ch.id, channels, keys, height, |ui, cx| {
29 let value = cx.number(ch);28 let value = cx.number(ch);
30 let mut spec = ui::Slider::new(value as f32, ch.scale[0] as f32, ch.scale[1] as f32, cx.default_of(ch) as f32);29 let mut spec = ui::Slider::new(value as f32, ch.scale[0] as f32, ch.scale[1] as f32, cx.default_of(ch) as f32);
31 spec.step = ch.integer.then_some(1.0);30 spec.step = ch.integer.then_some(1.0);
32 spec.sub_labels = sub;31 spec.sub_labels = sub;
33 spec.label = &def.label;32 spec.label = &def.label;
34 if let Some(next) = ui::slider(ui, ("sld", cx.node.0, ch.id.as_str()), spec) {33 if let Some(next) = ui::slider(ui, ("sld", cx.node.0, ch.id.as_str()), spec) {
35 cx.write_numbers(&def.label, &[(ch, f64::from(next))], true);34 cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id));
36 }35 }
37 number_box(ui, cx, ch, None, value, px(52.0));36 number_box(ui, cx, ch, None, value, px(52.0));
38 });37 });
39 }38 }
40 Kind::Screw => {39 Kind::Screw => {
41 let ch = &channels[0];40 let ch = &channels[0];
42 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| {41 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| {
43 let value = cx.number(ch);42 let value = cx.number(ch);
44 let mut spec = ui::ScrewControl::new(value as f32, cx.default_of(ch) as f32);43 let mut spec = ui::ScrewControl::new(value as f32, cx.default_of(ch) as f32);
45 spec.sensitivity = ((ch.scale[1] - ch.scale[0]) / 360.0).max(0.001) as f32;44 spec.sensitivity = ((ch.scale[1] - ch.scale[0]) / 360.0).max(0.001) as f32;
...@@ -47,14 +46,14 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {...@@ -47,14 +46,14 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
47 spec.width = fill();46 spec.width = fill();
48 spec.label = &def.label;47 spec.label = &def.label;
49 if let Some(next) = ui::screw_control(ui, ("scw", cx.node.0, ch.id.as_str()), spec) {48 if let Some(next) = ui::screw_control(ui, ("scw", cx.node.0, ch.id.as_str()), spec) {
50 cx.write_numbers(&def.label, &[(ch, f64::from(next))], true);49 cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id));
51 }50 }
52 number_box(ui, cx, ch, None, value, px(52.0));51 number_box(ui, cx, ch, None, value, px(52.0));
53 });52 });
54 }53 }
55 Kind::Range => {54 Kind::Range => {
56 let [start, end] = [&channels[0], &channels[1]];55 let [start, end] = [&channels[0], &channels[1]];
57 row(ui, cx, &def.label, &start.id, marks, px(ROW_H), |ui, cx| {56 row(ui, cx, &def.label, &start.id, channels, keys, px(ROW_H), |ui, cx| {
58 let [s, e] = [cx.number(start), cx.number(end)];57 let [s, e] = [cx.number(start), cx.number(end)];
59 let mut spec = ui::RangeSlider::new(58 let mut spec = ui::RangeSlider::new(
60 s as f32,59 s as f32,
...@@ -72,7 +71,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {...@@ -72,7 +71,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
72 .filter(|&(_, old, new)| moved(old, new))71 .filter(|&(_, old, new)| moved(old, new))
73 .map(|(ch, _, new)| (ch, f64::from(new)))72 .map(|(ch, _, new)| (ch, f64::from(new)))
74 .collect();73 .collect();
75 cx.write_numbers(&def.label, &edits, true);74 cx.write_numbers(&def.label, &edits, Some(&start.id));
76 }75 }
77 number_box(ui, cx, start, None, s, px(44.0));76 number_box(ui, cx, start, None, s, px(44.0));
78 number_box(ui, cx, end, None, e, px(44.0));77 number_box(ui, cx, end, None, e, px(44.0));
...@@ -81,26 +80,26 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {...@@ -81,26 +80,26 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
81 Kind::Color => color(ui, cx, def),80 Kind::Color => color(ui, cx, def),
82 Kind::Checkbox => {81 Kind::Checkbox => {
83 let ch = &channels[0];82 let ch = &channels[0];
84 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| {83 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| {
85 let on = cx.number(ch) >= 0.5;84 let on = cx.number(ch) >= 0.5;
86 if checkbox(ui, ("chk", cx.node.0, ch.id.as_str()), on, &def.label) {85 if checkbox(ui, ("chk", cx.node.0, ch.id.as_str()), on, &def.label) {
87 cx.write_numbers(&def.label, &[(ch, f64::from(u8::from(!on)))], false);86 cx.write_numbers(&def.label, &[(ch, f64::from(u8::from(!on)))], None);
88 }87 }
89 spacer(ui);88 spacer(ui);
90 });89 });
91 }90 }
92 Kind::Toggles => row(ui, cx, &def.label, &channels[0].id, marks, px(ROW_H), |ui, cx| {91 Kind::Toggles => row(ui, cx, &def.label, &channels[0].id, channels, keys, px(ROW_H), |ui, cx| {
93 for (ch, name) in channels.iter().zip(&def.entries) {92 for (ch, name) in channels.iter().zip(&def.entries) {
94 let on = cx.number(ch) >= 0.5;93 let on = cx.number(ch) >= 0.5;
95 if toggle_button(ui, cx, ("tgl", cx.node.0, ch.id.as_str()), name, on) {94 if toggle_button(ui, cx, ("tgl", cx.node.0, ch.id.as_str()), name, on) {
96 cx.write_numbers(name, &[(ch, f64::from(u8::from(!on)))], false);95 cx.write_numbers(name, &[(ch, f64::from(u8::from(!on)))], None);
97 }96 }
98 }97 }
99 spacer(ui);98 spacer(ui);
100 }),99 }),
101 Kind::Segmented => {100 Kind::Segmented => {
102 let ch = &channels[0];101 let ch = &channels[0];
103 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 2.0), |ui, cx| {102 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H + 2.0), |ui, cx| {
104 let segments: Vec<_> = def.entries.iter().map(|e| ui::MultiSegment::text(e)).collect();103 let segments: Vec<_> = def.entries.iter().map(|e| ui::MultiSegment::text(e)).collect();
105 let mut spec = ui::SegmentedControl::new(&segments, choice_index(cx, def));104 let mut spec = ui::SegmentedControl::new(&segments, choice_index(cx, def));
106 spec.width = fill();105 spec.width = fill();
...@@ -112,7 +111,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {...@@ -112,7 +111,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
112 }111 }
113 Kind::Combo => {112 Kind::Combo => {
114 let ch = &channels[0];113 let ch = &channels[0];
115 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 6.0), |ui, cx| {114 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H + 6.0), |ui, cx| {
116 let current = choice_index(cx, def);115 let current = choice_index(cx, def);
117 let items: Vec<_> = def116 let items: Vec<_> = def
118 .entries117 .entries
...@@ -129,7 +128,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {...@@ -129,7 +128,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
129 }128 }
130 Kind::Point => {129 Kind::Point => {
131 let ch = &channels[0];130 let ch = &channels[0];
132 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| {131 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| {
133 let point = cx.point(ch);132 let point = cx.point(ch);
134 for (axis, name) in ["X", "Y"].into_iter().enumerate() {133 for (axis, name) in ["X", "Y"].into_iter().enumerate() {
135 ui.leaf(name, Spec { size: [px(10.0), fill()], text: Some(name), font_size: Some(10.0), color: Some(cx.p.text_dim), center: true, ..Spec::default() });134 ui.leaf(name, Spec { size: [px(10.0), fill()], text: Some(name), font_size: Some(10.0), color: Some(cx.p.text_dim), center: true, ..Spec::default() });
...@@ -151,8 +150,8 @@ fn spacer(ui: &mut Ui) {...@@ -151,8 +150,8 @@ fn spacer(ui: &mut Ui) {
151 ui.leaf("pad", Spec { size: [px(0.0), fill()], ..Spec::default() });150 ui.leaf("pad", Spec { size: [px(0.0), fill()], ..Spec::default() });
152}151}
153152
154/// Label column, `body`, then the expression badge and keyframe diamond of `marks`.153/// Label column, `body`, then the expression badge of `marks` and, when `keys`, their keyframe diamond.
155fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks: &[Channel], height: ui::Extent, body: impl FnOnce(&mut Ui, &mut Cx)) {154fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks: &[Channel], keys: bool, height: ui::Extent, body: impl FnOnce(&mut Ui, &mut Cx)) {
156 ui.open(155 ui.open(
157 ("row", cx.node.0, key),156 ("row", cx.node.0, key),
158 Spec { size: [fill(), height], axis: ui::Axis::X, gap: 6.0, pad: [4.0, 1.0], ..Spec::default() },157 Spec { size: [fill(), height], axis: ui::Axis::X, gap: 6.0, pad: [4.0, 1.0], ..Spec::default() },
...@@ -169,7 +168,7 @@ fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks:...@@ -169,7 +168,7 @@ fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks:
169 if cx.has_expression(marks) {168 if cx.has_expression(marks) {
170 expression_badge(ui);169 expression_badge(ui);
171 }170 }
172 if marks.is_empty() {171 if !keys {
173 ui.leaf("mark-gap", Spec { size: [px(MARK_W), fill()], ..Spec::default() });172 ui.leaf("mark-gap", Spec { size: [px(MARK_W), fill()], ..Spec::default() });
174 } else {173 } else {
175 let state = cx.key_state(marks);174 let state = cx.key_state(marks);
...@@ -185,7 +184,7 @@ fn number_box(ui: &mut Ui, cx: &mut Cx, ch: &Channel, axis: Option<usize>, value...@@ -185,7 +184,7 @@ fn number_box(ui: &mut Ui, cx: &mut Cx, ch: &Channel, axis: Option<usize>, value
185 let id = ui.id(("num", cx.node.0, ch.id.as_str(), axis));184 let id = ui.id(("num", cx.node.0, ch.id.as_str(), axis));
186 let focused = ui.focused() == Some(id);185 let focused = ui.focused() == Some(id);
187 if focused && cx.edit.number.as_ref().is_none_or(|e| e.id != id) {186 if focused && cx.edit.number.as_ref().is_none_or(|e| e.id != id) {
188 cx.edit.number = Some(NumberEdit { id, buf: format_value(ch, value), channel: ch.clone(), axis });187 cx.edit.number = Some(NumberEdit { id, node: cx.node, buf: format_value(ch, value), channel: ch.clone(), axis });
189 ui.focus_all(id);188 ui.focus_all(id);
190 }189 }
191 let mut shown;190 let mut shown;
...@@ -289,7 +288,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) {...@@ -289,7 +288,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) {
289 if def.fuid {288 if def.fuid {
290 cx.write_value(&def.label, &ch.id, ParamValue::FuId(def.entries[index].clone()));289 cx.write_value(&def.label, &ch.id, ParamValue::FuId(def.entries[index].clone()));
291 } else {290 } else {
292 cx.write_numbers(&def.label, &[(ch, index as f64)], false);291 cx.write_numbers(&def.label, &[(ch, index as f64)], None);
293 }292 }
294}293}
295294
...@@ -297,7 +296,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) {...@@ -297,7 +296,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) {
297fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {296fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
298 let channels = def.channels.as_slice();297 let channels = def.channels.as_slice();
299 let current: Vec<f64> = channels.iter().map(|ch| cx.number(ch)).collect();298 let current: Vec<f64> = channels.iter().map(|ch| cx.number(ch)).collect();
300 row(ui, cx, &def.label, ("group", &channels[0].id), channels, ui::children(), |ui, cx| {299 row(ui, cx, &def.label, ("group", &channels[0].id), channels, true, ui::children(), |ui, cx| {
301 let rgba = [0, 1, 2, 3].map(|i| current.get(i).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32));300 let rgba = [0, 1, 2, 3].map(|i| current.get(i).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32));
302 let mut spec = ui::ColorPicker::new(rgba);301 let mut spec = ui::ColorPicker::new(rgba);
303 spec.width = fill();302 spec.width = fill();
...@@ -308,19 +307,19 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {...@@ -308,19 +307,19 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
308 .iter()307 .iter()
309 .zip(next)308 .zip(next)
310 .zip(rgba)309 .zip(rgba)
311 .filter(|((_, new), old)| (new - old).abs() > 1e-6)310 .filter(|((_, new), old)| (new - old).abs() > 1e-4)
312 .map(|((ch, new), _)| (ch, f64::from(new)))311 .map(|((ch, new), _)| (ch, f64::from(new)))
313 .collect();312 .collect();
314 cx.write_numbers(&def.label, &edits, true);313 cx.write_numbers(&def.label, &edits, Some(&channels[0].id));
315 }314 }
316 });315 });
317 for (ch, name) in channels.iter().zip(["Red", "Green", "Blue", "Alpha"]) {316 for (ch, name) in channels.iter().zip(["Red", "Green", "Blue", "Alpha"]) {
318 row(ui, cx, name, &ch.id, &[], px(ROW_H), |ui, cx| {317 row(ui, cx, name, &ch.id, &[], false, px(ROW_H), |ui, cx| {
319 let value = cx.number(ch);318 let value = cx.number(ch);
320 let mut spec = ui::Slider::new(value as f32, 0.0, 1.0, cx.default_of(ch) as f32);319 let mut spec = ui::Slider::new(value as f32, 0.0, 1.0, cx.default_of(ch) as f32);
321 spec.label = name;320 spec.label = name;
322 if let Some(next) = ui::slider(ui, ("clr-sld", cx.node.0, ch.id.as_str()), spec) {321 if let Some(next) = ui::slider(ui, ("clr-sld", cx.node.0, ch.id.as_str()), spec) {
323 cx.write_numbers(&def.label, &[(ch, f64::from(next))], true);322 cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id));
324 }323 }
325 number_box(ui, cx, ch, None, value, px(52.0));324 number_box(ui, cx, ch, None, value, px(52.0));
326 });325 });
...@@ -330,7 +329,7 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {...@@ -330,7 +329,7 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
330/// A text well; edits apply live and fold into one undo step until it loses the keys.329/// A text well; edits apply live and fold into one undo step until it loses the keys.
331fn text(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {330fn text(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
332 let ch = &def.channels[0];331 let ch = &def.channels[0];
333 row(ui, cx, &def.label, &ch.id, &[], px(ROW_H), |ui, cx| {332 row(ui, cx, &def.label, &ch.id, &def.channels, false, px(ROW_H), |ui, cx| {
334 let id = ui.id(("txt", cx.node.0, ch.id.as_str()));333 let id = ui.id(("txt", cx.node.0, ch.id.as_str()));
335 let focused = ui.focused() == Some(id);334 let focused = ui.focused() == Some(id);
336 let model = cx.comp.node(cx.node).static_str(&ch.id).unwrap_or(&def.default_text).to_owned();335 let model = cx.comp.node(cx.node).static_str(&ch.id).unwrap_or(&def.default_text).to_owned();
crates/app/src/inspector/edit.rs+15-8
...@@ -13,6 +13,8 @@ pub(super) const SCRUB_GRACE: Duration = Duration::from_millis(350);...@@ -13,6 +13,8 @@ pub(super) const SCRUB_GRACE: Duration = Duration::from_millis(350);
13/// A numeric box being typed into; it commits when it loses the keys.13/// A numeric box being typed into; it commits when it loses the keys.
14pub(super) struct NumberEdit {14pub(super) struct NumberEdit {
15 pub id: ui::Id,15 pub id: ui::Id,
16 /// The node the box was focused on; selection may move on before the commit.
17 pub node: NodeId,
16 pub buf: String,18 pub buf: String,
17 pub channel: Channel,19 pub channel: Channel,
18 /// `Some(0|1)` edits one axis of a Point input.20 /// `Some(0|1)` edits one axis of a Point input.
...@@ -76,11 +78,14 @@ impl Cx<'_> {...@@ -76,11 +78,14 @@ impl Cx<'_> {
76 }78 }
77 }79 }
7880
79 /// Writes numbers, as a keyframe where the input is animated. A `drag` folds into one undo81 /// Writes numbers, as a keyframe where the input is animated. A drag, named by its control's
80 /// step per input until it rests; anything else is its own step.82 /// primary channel, folds into one undo step until it rests; anything else is its own step.
81 pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: bool) {83 pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: Option<&str>) {
82 if drag {84 if edits.is_empty() {
83 let key = format!("scrub:{}:{}", self.node.0, edits[0].0.id);85 return;
86 }
87 if let Some(primary) = drag {
88 let key = format!("scrub:{}:{primary}", self.node.0);
84 self.history.push_coalesced(self.comp, format!("Adjust {label}"), key);89 self.history.push_coalesced(self.comp, format!("Adjust {label}"), key);
85 self.edit.last_scrub = Some(self.now);90 self.edit.last_scrub = Some(self.now);
86 } else {91 } else {
...@@ -105,12 +110,13 @@ impl Cx<'_> {...@@ -105,12 +110,13 @@ impl Cx<'_> {
105 self.actions.push(InspectorAction::ParamEdited(self.node));110 self.actions.push(InspectorAction::ParamEdited(self.node));
106 }111 }
107112
108 /// Commits a numeric box once it has lost the keys.113 /// Commits a numeric box once it has lost the keys, onto the node it was typed into.
109 pub fn commit_number(&mut self, edit: NumberEdit) {114 pub fn commit_number(&mut self, edit: NumberEdit) {
110 let Ok(value) = edit.buf.trim().parse::<f64>() else { return };115 let Ok(value) = edit.buf.trim().parse::<f64>() else { return };
111 if !value.is_finite() {116 if !value.is_finite() || edit.node.0 >= self.comp.nodes.len() {
112 return;117 return;
113 }118 }
119 let selected = std::mem::replace(&mut self.node, edit.node);
114 let ch = &edit.channel;120 let ch = &edit.channel;
115 match edit.axis {121 match edit.axis {
116 Some(axis) => {122 Some(axis) => {
...@@ -118,8 +124,9 @@ impl Cx<'_> {...@@ -118,8 +124,9 @@ impl Cx<'_> {
118 point[axis] = value;124 point[axis] = value;
119 self.write_value(&ch.id, &ch.id, ParamValue::Point(point));125 self.write_value(&ch.id, &ch.id, ParamValue::Point(point));
120 }126 }
121 None => self.write_numbers(&ch.id, &[(ch, value)], false),127 None => self.write_numbers(&ch.id, &[(ch, value)], None),
122 }128 }
129 self.node = selected;
123 }130 }
124131
125 /// Keys every channel at the current frame, or removes those keys when all already have one.132 /// Keys every channel at the current frame, or removes those keys when all already have one.
crates/app/src/inspector/mod.rs+57-8
...@@ -65,11 +65,11 @@ impl InspectorPalette {...@@ -65,11 +65,11 @@ impl InspectorPalette {
65 }65 }
66}66}
6767
68/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the comp68/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the node's
69/// revision moves.69/// shape (see [`pages_key`]) changes rather than on every value edit.
70struct NodePages {70struct NodePages {
71 node: NodeId,71 node: NodeId,
72 revision: u64,72 key: u64,
73 pages: Vec<Page>,73 pages: Vec<Page>,
74}74}
7575
...@@ -90,9 +90,11 @@ pub struct InspectorState {...@@ -90,9 +90,11 @@ pub struct InspectorState {
90impl InspectorState {90impl InspectorState {
91 pub fn new(theme: &ui::Theme) -> Self {91 pub fn new(theme: &ui::Theme) -> Self {
92 // Parse the catalog off the UI thread; frames wait on it with a placeholder.92 // Parse the catalog off the UI thread; frames wait on it with a placeholder.
93 std::thread::spawn(|| {93 if catalog::ready().is_none() {
94 catalog::catalog();94 std::thread::spawn(|| {
95 });95 catalog::catalog();
96 });
97 }
96 Self {98 Self {
97 palette: InspectorPalette::from_theme(theme),99 palette: InspectorPalette::from_theme(theme),
98 expr: ExprEngine::new(),100 expr: ExprEngine::new(),
...@@ -133,6 +135,7 @@ impl InspectorState {...@@ -133,6 +135,7 @@ impl InspectorState {
133 ui::Spec { size: [ui::fill(), ui::fill()], axis: ui::Axis::Y, fill: Some(p.bg), ..ui::Spec::default() },135 ui::Spec { size: [ui::fill(), ui::fill()], axis: ui::Axis::Y, fill: Some(p.bg), ..ui::Spec::default() },
134 );136 );
135 let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else {137 let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else {
138 self.commit_orphans(comp, history, &mut actions);
136 chrome::empty_state(ui, p);139 chrome::empty_state(ui, p);
137 chrome::footer(ui, p, stats);140 chrome::footer(ui, p, stats);
138 ui.close();141 ui.close();
...@@ -152,8 +155,9 @@ impl InspectorState {...@@ -152,8 +155,9 @@ impl InspectorState {
152 .or_insert_with(|| dynamic::curated_layout(&kind).unwrap_or_default()),155 .or_insert_with(|| dynamic::curated_layout(&kind).unwrap_or_default()),
153 };156 };
154157
155 if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.revision != comp.revision) {158 let key = pages_key(comp, node_id);
156 self.node_pages = Some(NodePages { node: node_id, revision: comp.revision, pages: node_pages(comp, node_id, layout) });159 if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.key != key) {
160 self.node_pages = Some(NodePages { node: node_id, key, pages: node_pages(comp, node_id, layout) });
157 }161 }
158 let dynamic_pages = self.node_pages.as_ref().map_or(&[][..], |n| n.pages.as_slice());162 let dynamic_pages = self.node_pages.as_ref().map_or(&[][..], |n| n.pages.as_slice());
159163
...@@ -215,6 +219,24 @@ impl InspectorState {...@@ -215,6 +219,24 @@ impl InspectorState {
215 actions219 actions
216 }220 }
217221
222 /// With nothing selected no box can keep the keys, so a typed value lands where it was typed.
223 fn commit_orphans(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<InspectorAction>) {
224 self.edit.text = None;
225 let Some(number) = self.edit.number.take() else { return };
226 let mut cx = edit::Cx {
227 comp,
228 history,
229 actions,
230 node: number.node,
231 frame: 0.0,
232 now: std::time::Instant::now(),
233 p: self.palette,
234 expr: &self.expr,
235 edit: &mut self.edit,
236 };
237 cx.commit_number(number);
238 }
239
218 fn loading(&self, ui: &mut ui::Ui, p: InspectorPalette, stats: &EvalStats, actions: Vec<InspectorAction>) -> Vec<InspectorAction> {240 fn loading(&self, ui: &mut ui::Ui, p: InspectorPalette, stats: &EvalStats, actions: Vec<InspectorAction>) -> Vec<InspectorAction> {
219 ui.leaf(241 ui.leaf(
220 "insp-loading",242 "insp-loading",
...@@ -244,6 +266,33 @@ fn settle_edits(ui: &mut ui::Ui, cx: &mut edit::Cx) {...@@ -244,6 +266,33 @@ fn settle_edits(ui: &mut ui::Ui, cx: &mut edit::Cx) {
244 }266 }
245}267}
246268
269/// What `node_pages` reads, minus values: kind, `UserControls` ids, and each input's name,
270/// value type and whether it is driven or wired. Order-independent over the input map.
271fn pages_key(comp: &Comp, node: NodeId) -> u64 {
272 use std::hash::{Hash, Hasher};
273 let hash = |item: &dyn Fn(&mut std::hash::DefaultHasher)| {
274 let mut h = std::hash::DefaultHasher::new();
275 item(&mut h);
276 h.finish()
277 };
278 let n = comp.node(node);
279 let controls = n.raw.get_table("UserControls").map_or(0, |t| {
280 t.entries.iter().fold(t.entries.len() as u64, |acc, (key, _)| match key {
281 model::LuaKey::Str(id) => acc.wrapping_add(hash(&|h| id.hash(h))),
282 _ => acc,
283 })
284 });
285 let inputs = n.inputs.iter().fold(0u64, |acc, (key, b)| {
286 let wired = b.source_op.as_deref().is_some_and(|op| comp.node_by_name.contains_key(op));
287 acc.wrapping_add(hash(&|h| {
288 key.hash(h);
289 b.value.as_ref().map(std::mem::discriminant).hash(h);
290 (b.expression.is_some(), b.source_op.is_some(), wired).hash(h);
291 }))
292 });
293 hash(&|h| (&n.kind, controls, inputs).hash(h))
294}
295
247/// The node's `UserControls` (one page per `ICS_ControlPage`) and inputs no catalog row covers.296/// The node's `UserControls` (one page per `ICS_ControlPage`) and inputs no catalog row covers.
248fn node_pages(comp: &Comp, node: NodeId, layout: &ToolLayout) -> Vec<Page> {297fn node_pages(comp: &Comp, node: NodeId, layout: &ToolLayout) -> Vec<Page> {
249 let mut by_page: Vec<(String, Vec<catalog::InputDef>)> = Vec::new();298 let mut by_page: Vec<(String, Vec<catalog::InputDef>)> = Vec::new();
crates/app/src/inspector/tests.rs+80
...@@ -441,4 +441,84 @@ mod catalog_layout {...@@ -441,4 +441,84 @@ mod catalog_layout {
441 assert!(h.history.undo(&mut h.comp));441 assert!(h.history.undo(&mut h.comp));
442 assert_eq!(h.number("Blend"), Some(0.2));442 assert_eq!(h.number("Blend"), Some(0.2));
443 }443 }
444
445 fn type_into(h: &mut Harness, well: [f32; 4], text: &str) {
446 h.click(center(well));
447 for ch in text.chars() {
448 let key = winit::keyboard::Key::Character(ch.to_string().into());
449 h.ui.event(ui::Event::Key { key, text: Some(ch.to_string()), modifiers: Default::default() });
450 h.frame(16);
451 }
452 }
453
454 /// A color drag that moves no RGB channel (alpha on an RGB-only group, hue on gray) reaches
455 /// `write_numbers` with nothing to write.
456 #[test]
457 fn empty_edits_write_nothing_and_never_panic() {
458 let mut h = Harness::new("Background", 0);
459 let (node, mut actions) = (h.node, Vec::new());
460 let channel = &find("Background", "TopLeftRed").channels[0];
461 let mut edit = super::super::edit::EditState::default();
462 let mut cx = super::super::edit::Cx {
463 comp: &mut h.comp,
464 history: &mut h.history,
465 actions: &mut actions,
466 node,
467 frame: 0.0,
468 now: h.at,
469 p: h.state.palette,
470 expr: &h.state.expr,
471 edit: &mut edit,
472 };
473 cx.write_numbers("Color", &[], Some(&channel.id));
474 cx.write_numbers("Color", &[], None);
475 assert!(actions.is_empty() && edit.last_scrub.is_none());
476 assert!(!h.history.undo(&mut h.comp));
477 }
478
479 #[test]
480 fn typed_value_commits_to_the_node_it_was_typed_into() {
481 let mut h = Harness::new("Blur", 0);
482 h.comp = Comp::from_fusion_str("Composition { Tools = ordered() { Blur1 = Blur {}, Merge1 = Merge {}, }, }").expect("comp");
483 h.node = h.comp.find_node("Blur1").expect("blur");
484 h.frame(0);
485 let well = h.rect(0, "XBlurSize", ("num", h.node.0, "XBlurSize", None::<usize>));
486 type_into(&mut h, well, "7");
487 let blur = h.node;
488
489 h.node = h.comp.find_node("Merge1").expect("merge");
490 h.frame(16);
491 h.frame(16);
492 assert_eq!(h.comp.node(blur).static_number("XBlurSize"), Some(7.0));
493 assert!(h.comp.node(h.node).inputs.values().all(|b| b.value.is_none()), "Merge1 was touched");
494 }
495
496 #[test]
497 fn typed_value_commits_to_its_node_on_deselect() {
498 let mut h = Harness::new("Blur", 0);
499 let well = h.rect(0, "XBlurSize", ("num", h.node.0, "XBlurSize", None::<usize>));
500 type_into(&mut h, well, "9");
501 h.at += std::time::Duration::from_millis(16);
502 h.ui.begin([360.0, 900.0], 1.0, h.at);
503 let pane = ui::Id::ROOT.child(PANE);
504 h.state.build_ui(&mut h.ui, pane, &mut h.comp, &mut h.history, None, 0.0, &engine::EvalStats::default());
505 h.ui.end();
506 assert_eq!(h.number("XBlurSize"), Some(9.0));
507 assert!(h.state.edit.number.is_none());
508 }
509
510 #[test]
511 fn pages_are_not_rebuilt_by_value_edits() {
512 let mut h = Harness::new("Merge", 2);
513 let key = |h: &Harness| h.state.node_pages.as_ref().map(|n| n.key);
514 h.comp.set_input_value(h.node, "Blend", model::ParamValue::Number(0.2));
515 h.frame(16);
516 let before = key(&h);
517 h.comp.set_input_value(h.node, "Blend", model::ParamValue::Number(0.7));
518 h.frame(16);
519 assert_eq!(key(&h), before);
520 h.comp.set_input_value(h.node, "Stray", model::ParamValue::Number(1.0));
521 h.frame(16);
522 assert_ne!(key(&h), before);
523 }
444}524}
crates/engine/src/media.rs+91-24
...@@ -58,29 +58,60 @@ struct VirtualFile {...@@ -58,29 +58,60 @@ struct VirtualFile {
58/// In-memory files that shadow the filesystem for still and sequence loading, since `wasm32` has no `std::fs`.58/// In-memory files that shadow the filesystem for still and sequence loading, since `wasm32` has no `std::fs`.
59static VIRTUAL_FILES: RwLock<Vec<VirtualFile>> = RwLock::new(Vec::new());59static VIRTUAL_FILES: RwLock<Vec<VirtualFile>> = RwLock::new(Vec::new());
6060
61/// Total bytes registered virtual files may hold, so dropping a huge folder cannot exhaust the tab.
62const MAX_VIRTUAL_BYTES: usize = 512 * 1024 * 1024;
63
64/// `path`'s components with `.`, empty and resolved `..` segments removed.
61fn path_parts(path: &Path) -> Vec<String> {65fn path_parts(path: &Path) -> Vec<String> {
62 path.to_string_lossy()66 let mut parts: Vec<String> = Vec::new();
63 .split(['/', '\\'])67 for part in path.to_string_lossy().split(['/', '\\']) {
64 .filter(|p| !p.is_empty() && *p != ".")68 match part {
65 .map(str::to_owned)69 "" | "." => {}
66 .collect()70 ".." => {
71 parts.pop();
72 }
73 _ => parts.push(part.to_owned()),
74 }
75 }
76 parts
77}
78
79/// The registered file whose path shares the most trailing components with `want`, so a comp's
80/// absolute `Loader` path still finds a file dropped under a relative one. Exact case wins over
81/// case-insensitive; a tie (`/A/bg.png` vs `/B/bg.png` for `bg.png`) matches nothing.
82fn find_virtual<'a>(files: &'a [VirtualFile], want: &[String]) -> Option<&'a VirtualFile> {
83 let exact = |a: &String, b: &String| a == b;
84 let folded = |a: &String, b: &String| a.to_lowercase() == b.to_lowercase();
85 [&exact as &dyn Fn(&String, &String) -> bool, &folded].into_iter().find_map(|same| {
86 let shared = |f: &VirtualFile| f.parts.iter().rev().zip(want.iter().rev()).take_while(|(a, b)| same(a, b)).count();
87 let best = files.iter().map(shared).max().filter(|&n| n > 0)?;
88 let mut tied = files.iter().filter(|f| shared(f) == best);
89 match (tied.next(), tied.next()) {
90 (Some(file), None) => Some(Some(file)),
91 _ => Some(None),
92 }
93 })?
67}94}
6895
69/// Bytes of the virtual file sharing the longest run of trailing path components with `path`, so a
70/// comp's absolute `Loader` path still finds a file registered under a dropped folder's relative path.
71fn virtual_bytes(path: &Path) -> Option<Arc<[u8]>> {96fn virtual_bytes(path: &Path) -> Option<Arc<[u8]>> {
72 let files = VIRTUAL_FILES.read().ok()?;97 let files = VIRTUAL_FILES.read().ok()?;
73 if files.is_empty() {98 if files.is_empty() {
74 return None;99 return None;
75 }100 }
76 let want = path_parts(path);101 find_virtual(&files, &path_parts(path)).map(|f| Arc::clone(&f.bytes))
77 let shared = |f: &VirtualFile| f.parts.iter().rev().zip(want.iter().rev()).take_while(|(a, b)| a == b).count();102}
78 files103
79 .iter()104/// Adds or replaces `parts`, refusing when `files` would then hold more than `cap` bytes.
80 .map(|f| (shared(f), f))105fn insert_capped(files: &mut Vec<VirtualFile>, cap: usize, parts: Vec<String>, bytes: Arc<[u8]>) -> bool {
81 .filter(|(n, _)| *n > 0)106 let held: usize = files.iter().filter(|f| f.parts != parts).map(|f| f.bytes.len()).sum();
82 .max_by_key(|(n, _)| *n)107 if held.saturating_add(bytes.len()) > cap {
83 .map(|(_, f)| Arc::clone(&f.bytes))108 return false;
109 }
110 match files.iter_mut().find(|f| f.parts == parts) {
111 Some(existing) => existing.bytes = bytes,
112 None => files.push(VirtualFile { parts, bytes }),
113 }
114 true
84}115}
85116
86fn path_exists(path: &Path) -> bool {117fn path_exists(path: &Path) -> bool {
...@@ -128,15 +159,11 @@ impl MediaCache {...@@ -128,15 +159,11 @@ impl MediaCache {
128 }159 }
129 }160 }
130161
131 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process.162 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false`
132 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) {163 /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged.
133 let parts = path_parts(path.as_ref());164 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) -> bool {
134 let bytes = bytes.into();165 let Ok(mut files) = VIRTUAL_FILES.write() else { return false };
135 let Ok(mut files) = VIRTUAL_FILES.write() else { return };166 insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into())
136 match files.iter_mut().find(|f| f.parts == parts) {
137 Some(existing) => existing.bytes = bytes,
138 None => files.push(VirtualFile { parts, bytes }),
139 }
140 }167 }
141168
142 pub fn clear_virtual_bytes() {169 pub fn clear_virtual_bytes() {
...@@ -955,4 +982,44 @@ mod tests {...@@ -955,4 +982,44 @@ mod tests {
955 assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png")));982 assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png")));
956 assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png")));983 assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png")));
957 }984 }
985
986 fn file(path: &str, len: usize) -> VirtualFile {
987 VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() }
988 }
989
990 fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> {
991 find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice())
992 }
993
994 #[test]
995 fn virtual_paths_normalize_dots_and_separators() {
996 assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]);
997 assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]);
998 }
999
1000 #[test]
1001 fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() {
1002 let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)];
1003 assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..]));
1004 assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2));
1005 assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename");
1006 assert_eq!(found(&files, "bg.png"), None);
1007 assert!(found(&files, "/deep/elsewhere/only.png").is_some());
1008 assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback");
1009 assert_eq!(found(&files, "/a/missing.png"), None);
1010 }
1011
1012 #[test]
1013 fn virtual_files_stop_at_the_memory_cap() {
1014 let mut files = Vec::new();
1015 let put = |files: &mut Vec<VirtualFile>, name: &str, len: usize| {
1016 insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into())
1017 };
1018 assert!(put(&mut files, "a", 6));
1019 assert!(!put(&mut files, "b", 5));
1020 assert!(put(&mut files, "b", 4));
1021 assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes");
1022 assert!(!put(&mut files, "a", 7));
1023 assert_eq!(files.iter().map(|f| f.bytes.len()).sum::<usize>(), 10);
1024 }
958}1025}
crates/engine/src/media/exr.rs+31-2
...@@ -150,13 +150,24 @@ pub(super) fn decode_exr_rgba(...@@ -150,13 +150,24 @@ pub(super) fn decode_exr_rgba(
150 blue_name: Option<&str>,150 blue_name: Option<&str>,
151 alpha_name: Option<&str>,151 alpha_name: Option<&str>,
152 post_multiply: bool,152 post_multiply: bool,
153) -> Option<DecodedImage> {
154 let names = [red_name, green_name, blue_name, alpha_name];
155 match super::virtual_bytes(path) {
156 Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply),
157 None => decode_exr_from(std::io::BufReader::new(std::fs::File::open(path).ok()?), names, post_multiply),
158 }
159}
160
161fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
162 reader: R,
163 [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4],
164 post_multiply: bool,
153) -> Option<DecodedImage> {165) -> Option<DecodedImage> {
154 use ::exr::block::reader::ChunksReader;166 use ::exr::block::reader::ChunksReader;
155 use ::exr::meta::attribute::SampleType;167 use ::exr::meta::attribute::SampleType;
156 use ::exr::prelude::*;168 use ::exr::prelude::*;
157169
158 let file = std::fs::File::open(path).ok()?;170 let chunks_reader = ::exr::block::read(reader, false).ok()?;
159 let chunks_reader = ::exr::block::read(std::io::BufReader::new(file), false).ok()?;
160 let first_header = chunks_reader.headers().first()?;171 let first_header = chunks_reader.headers().first()?;
161 let w = first_header.layer_size.width();172 let w = first_header.layer_size.width();
162 let h = first_header.layer_size.height();173 let h = first_header.layer_size.height();
...@@ -278,3 +289,21 @@ pub(super) fn decode_exr_rgba(...@@ -278,3 +289,21 @@ pub(super) fn decode_exr_rgba(
278 rgba_f32: Some(Arc::new(raw_f32)),289 rgba_f32: Some(Arc::new(raw_f32)),
279 })290 })
280}291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296 use crate::media::MediaCache;
297
298 #[test]
299 fn dropped_exr_bytes_decode_without_a_file_on_disk() {
300 let pixels = image::Rgba32FImage::from_pixel(2, 1, image::Rgba([2.5, 0.5, 0.0, 1.0]));
301 let mut out = std::io::Cursor::new(Vec::new());
302 image::DynamicImage::ImageRgba32F(pixels).write_to(&mut out, image::ImageFormat::OpenExr).unwrap();
303 assert!(MediaCache::insert_virtual_bytes("vexr_drop/frame.exr", out.into_inner()));
304
305 let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false).unwrap();
306 assert_eq!(decoded.size, [2, 1]);
307 assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]);
308 }
309}
crates/engine/src/profile.rs+3
...@@ -3,7 +3,10 @@...@@ -3,7 +3,10 @@
3use model::{Comp, NodeId};3use model::{Comp, NodeId};
4use std::collections::HashMap;4use std::collections::HashMap;
5use std::fmt::Write as _;5use std::fmt::Write as _;
6#[cfg(not(target_arch = "wasm32"))]
6use std::time::Instant;7use std::time::Instant;
8#[cfg(target_arch = "wasm32")]
9use web_time::Instant;
710
8/// Profiling telemetry for a single node lookup or evaluation within a frame.11/// Profiling telemetry for a single node lookup or evaluation within a frame.
9#[derive(Clone, Debug, PartialEq)]12#[derive(Clone, Debug, PartialEq)]
crates/flow/src/lib.rs+197-12
...@@ -77,10 +77,36 @@ struct ModalTransform {...@@ -77,10 +77,36 @@ struct ModalTransform {
77#[derive(Clone, Debug)]77#[derive(Clone, Debug)]
78struct WireDrag {78struct WireDrag {
79 src: NodeId,79 src: NodeId,
80 /// The output the wire leaves: the detached binding's own, else the source tool's default.
81 src_output: String,
80 cursor_local: [f32; 2],82 cursor_local: [f32; 2],
81 target: Option<DropTarget>,83 target: Option<DropTarget>,
82 /// Set when dragging an existing connected input off to disconnect/rewire.84 /// Set when dragging an existing connected input off to disconnect/rewire.
83 detached_from: Option<(NodeId, String)>,85 detached_from: Option<(NodeId, String)>,
86 /// Press point of a rewire drag that has not yet moved [`DETACH_DRAG`]; the wire stays
87 /// connected until it does, so a plain click changes nothing.
88 pending: Option<[f32; 2]>,
89}
90
91impl WireDrag {
92 /// Whether this drag has detached its wire inside an open history group.
93 fn owns_group(&self) -> bool {
94 self.detached_from.is_some() && self.pending.is_none()
95 }
96}
97
98/// Screen pixels a pressed input triangle must travel before its wire detaches.
99const DETACH_DRAG: f32 = 4.0;
100
101/// Output a wire from a `kind` tool leaves by: masks and materials have their own.
102fn default_output(kind: &str) -> &'static str {
103 if kind.ends_with("Mask") {
104 "Mask"
105 } else if kind.starts_with("Mtl") {
106 "MaterialOutput"
107 } else {
108 "Output"
109 }
84}110}
85111
86#[derive(Clone, Debug)]112#[derive(Clone, Debug)]
...@@ -182,6 +208,8 @@ pub struct FlowView {...@@ -182,6 +208,8 @@ pub struct FlowView {
182 hovered_wire: Option<WireRef>,208 hovered_wire: Option<WireRef>,
183 modal: Option<ModalTransform>,209 modal: Option<ModalTransform>,
184 wire_drag: Option<WireDrag>,210 wire_drag: Option<WireDrag>,
211 /// A gesture that owned a history group was dropped without its history; the next input closes it.
212 orphaned_group: bool,
185 box_select: Option<BoxSelect>,213 box_select: Option<BoxSelect>,
186 panning: Option<([f32; 2], [f32; 2])>,214 panning: Option<([f32; 2], [f32; 2])>,
187 lmb_drag_node: Option<(NodeId, [f32; 2], bool)>,215 lmb_drag_node: Option<(NodeId, [f32; 2], bool)>,
...@@ -208,6 +236,7 @@ impl FlowView {...@@ -208,6 +236,7 @@ impl FlowView {
208 hovered_wire: None,236 hovered_wire: None,
209 modal: None,237 modal: None,
210 wire_drag: None,238 wire_drag: None,
239 orphaned_group: false,
211 box_select: None,240 box_select: None,
212 panning: None,241 panning: None,
213 lmb_drag_node: None,242 lmb_drag_node: None,
...@@ -282,8 +311,7 @@ impl FlowView {...@@ -282,8 +311,7 @@ impl FlowView {
282 self.hovered_node = None;311 self.hovered_node = None;
283 self.hovered_handle = None;312 self.hovered_handle = None;
284 self.hovered_wire = None;313 self.hovered_wire = None;
285 self.modal = None;314 self.abandon_gestures();
286 self.wire_drag = None;
287 self.box_select = None;315 self.box_select = None;
288 self.lmb_drag_node = None;316 self.lmb_drag_node = None;
289 self.last_click = None;317 self.last_click = None;
...@@ -310,12 +338,17 @@ impl FlowView {...@@ -310,12 +338,17 @@ impl FlowView {
310 }338 }
311 self.hovered_handle = None;339 self.hovered_handle = None;
312 self.hovered_wire = None;340 self.hovered_wire = None;
313 self.modal = None;341 self.abandon_gestures();
314 self.wire_drag = None;
315 self.lmb_drag_node = None;342 self.lmb_drag_node = None;
316 self.last_click = None;343 self.last_click = None;
317 }344 }
318345
346 /// Drops in-flight gestures that have no history to cancel through.
347 fn abandon_gestures(&mut self) {
348 let wire = self.wire_drag.take().is_some_and(|wd| wd.owns_group());
349 self.orphaned_group |= self.modal.take().is_some() || wire;
350 }
351
319 /// Computes a clean world-space spawn position for a newly added node.352 /// Computes a clean world-space spawn position for a newly added node.
320 pub fn spawn_position(&self, comp: &Comp, is_generator: bool) -> [f32; 2] {353 pub fn spawn_position(&self, comp: &Comp, is_generator: bool) -> [f32; 2] {
321 if let Some(sel_id) = self.primary.filter(|id| id.0 < comp.nodes.len()) {354 if let Some(sel_id) = self.primary.filter(|id| id.0 < comp.nodes.len()) {
...@@ -499,11 +532,20 @@ impl FlowView {...@@ -499,11 +532,20 @@ impl FlowView {
499532
500 /// Drops an in-flight wire drag; a detached input is wired back.533 /// Drops an in-flight wire drag; a detached input is wired back.
501 fn cancel_wire_drag(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {534 fn cancel_wire_drag(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
502 if self.wire_drag.take().is_some_and(|wd| wd.detached_from.is_some()) && history.cancel_group(comp) {535 if self.wire_drag.take().is_some_and(|wd| wd.owns_group()) && history.cancel_group(comp) {
503 actions.push(FlowAction::GraphMutated(None));536 actions.push(FlowAction::GraphMutated(None));
504 }537 }
505 }538 }
506539
540 /// Ends every held gesture, as the window losing focus must.
541 fn cancel_gestures(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
542 self.cancel_modal(comp, history);
543 self.cancel_wire_drag(comp, history, actions);
544 self.panning = None;
545 self.box_select = None;
546 self.lmb_drag_node = None;
547 }
548
507 fn handle_key(549 fn handle_key(
508 &mut self,550 &mut self,
509 comp: &mut Comp,551 comp: &mut Comp,
...@@ -699,8 +741,12 @@ impl FlowView {...@@ -699,8 +741,12 @@ impl FlowView {
699 ) -> Vec<FlowAction> {741 ) -> Vec<FlowAction> {
700 let mut actions = Vec::new();742 let mut actions = Vec::new();
701 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];743 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
744 if std::mem::take(&mut self.orphaned_group) {
745 history.commit_group(comp);
746 }
702747
703 match event {748 match event {
749 ui::Event::PointerCancelled => self.cancel_gestures(comp, history, &mut actions),
704 ui::Event::PointerMoved(p) => {750 ui::Event::PointerMoved(p) => {
705 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];751 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
706 if let Some((start_p, start_pan)) = self.panning {752 if let Some((start_p, start_pan)) = self.panning {
...@@ -711,6 +757,17 @@ impl FlowView {...@@ -711,6 +757,17 @@ impl FlowView {
711 } else if self.modal.is_some() {757 } else if self.modal.is_some() {
712 self.apply_modal(comp, modifiers.shift_key());758 self.apply_modal(comp, modifiers.shift_key());
713 } else if self.wire_drag.is_some() {759 } else if self.wire_drag.is_some() {
760 if let Some(wd) = &mut self.wire_drag {
761 if let Some((press, (dst, port))) = wd.pending.zip(wd.detached_from.as_ref()) {
762 if (press[0] - self.pointer_local[0]).hypot(press[1] - self.pointer_local[1]) <= DETACH_DRAG {
763 return actions;
764 }
765 history.begin_group(comp, "Rewire");
766 comp.disconnect(*dst, port);
767 actions.push(FlowAction::GraphMutated(Some(*dst)));
768 wd.pending = None;
769 }
770 }
714 let hit = self.hit_drop_target(comp, self.pointer_local);771 let hit = self.hit_drop_target(comp, self.pointer_local);
715 if let Some(wd) = &mut self.wire_drag {772 if let Some(wd) = &mut self.wire_drag {
716 wd.cursor_local = self.pointer_local;773 wd.cursor_local = self.pointer_local;
...@@ -788,25 +845,27 @@ impl FlowView {...@@ -788,25 +845,27 @@ impl FlowView {
788 } else if let Some((src, None)) = handle {845 } else if let Some((src, None)) = handle {
789 self.wire_drag = Some(WireDrag {846 self.wire_drag = Some(WireDrag {
790 src,847 src,
848 src_output: default_output(&comp.node(src).kind).to_owned(),
791 cursor_local: self.pointer_local,849 cursor_local: self.pointer_local,
792 target: None,850 target: None,
793 detached_from: None,851 detached_from: None,
852 pending: None,
794 });853 });
795 } else if let Some((dst, Some(port), src)) = handle.and_then(|(dst, port)| {854 } else if let Some((dst, port, src)) = handle.and_then(|(dst, port)| {
796 let port = port?;855 let port = port?;
797 let src = self.upstream_of(comp, comp.node(dst), port)?;856 let src = self.upstream_of(comp, comp.node(dst), port)?;
798 Some((dst, Some(port.to_owned()), src))857 Some((dst, port.to_owned(), src))
799 }) {858 }) {
800 // Dragging a connected triangle detaches it: drop on another triangle to move859 // Dragging a connected triangle detaches it: drop on another triangle to move
801 // the wire, or on empty canvas to disconnect.860 // the wire, or on empty canvas to disconnect.
802 history.begin_group(comp, "Rewire");861 let src_output = comp.node(dst).inputs[&port].source_output.clone();
803 comp.disconnect(dst, &port);
804 actions.push(FlowAction::GraphMutated(Some(dst)));
805 self.wire_drag = Some(WireDrag {862 self.wire_drag = Some(WireDrag {
806 src,863 src,
864 src_output: src_output.unwrap_or_else(|| default_output(&comp.node(src).kind).to_owned()),
807 cursor_local: self.pointer_local,865 cursor_local: self.pointer_local,
808 target: None,866 target: None,
809 detached_from: Some((dst, port)),867 detached_from: Some((dst, port)),
868 pending: Some(self.pointer_local),
810 });869 });
811 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {870 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {
812 let double = self.last_click.is_some_and(|(t, prev)| prev == nid && at.duration_since(t) <= DOUBLE_CLICK);871 let double = self.last_click.is_some_and(|(t, prev)| prev == nid && at.duration_since(t) <= DOUBLE_CLICK);
...@@ -851,7 +910,7 @@ impl FlowView {...@@ -851,7 +910,7 @@ impl FlowView {
851 self.confirm_modal(comp, history, &mut actions);910 self.confirm_modal(comp, history, &mut actions);
852 }911 }
853 }912 }
854 if let Some(wd) = self.wire_drag.take() {913 if let Some(wd) = self.wire_drag.take().filter(|wd| wd.pending.is_none()) {
855 let detached = wd.detached_from.is_some();914 let detached = wd.detached_from.is_some();
856 let target = self.hit_drop_target(comp, self.pointer_local).map(|(node, port)| (node, port.to_owned()));915 let target = self.hit_drop_target(comp, self.pointer_local).map(|(node, port)| (node, port.to_owned()));
857 if let Some((dst, port)) = target {916 if let Some((dst, port)) = target {
...@@ -864,7 +923,7 @@ impl FlowView {...@@ -864,7 +923,7 @@ impl FlowView {
864 if !detached {923 if !detached {
865 history.begin_group(comp, "Connect");924 history.begin_group(comp, "Connect");
866 }925 }
867 match comp.connect_output(wd.src, "Output", dst, &port) {926 match comp.connect_output(wd.src, &wd.src_output, dst, &port) {
868 Ok(()) => {927 Ok(()) => {
869 history.commit_group(comp);928 history.commit_group(comp);
870 actions.push(FlowAction::GraphMutated(Some(dst)));929 actions.push(FlowAction::GraphMutated(Some(dst)));
...@@ -1286,7 +1345,10 @@ mod tests {...@@ -1286,7 +1345,10 @@ mod tests {
1286 ModifiersState::empty(),1345 ModifiersState::empty(),
1287 );1346 );
1288 assert!(flow.wire_drag.is_some());1347 assert!(flow.wire_drag.is_some());
1348 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"), "a bare press detaches nothing");
1349 flow.input(&mut comp, &mut history, ui::Event::PointerMoved([port[0] + 30.0, port[1] + 30.0]), rect, [port[0] + 30.0, port[1] + 30.0], ModifiersState::empty());
1289 assert!(comp.node(merge).inputs["Background"].source_op.is_none());1350 assert!(comp.node(merge).inputs["Background"].source_op.is_none());
1351 assert!(history.in_group());
12901352
1291 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());1353 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());
1292 assert!(flow.wire_drag.is_none());1354 assert!(flow.wire_drag.is_none());
...@@ -1460,4 +1522,127 @@ mod tests {...@@ -1460,4 +1522,127 @@ mod tests {
1460 assert!(flow.modal.is_some());1522 assert!(flow.modal.is_some());
1461 assert!(history.in_group());1523 assert!(history.in_group());
1462 }1524 }
1525
1526 fn button(pressed: bool) -> ui::Event {
1527 ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() }
1528 }
1529
1530 #[test]
1531 fn clicking_a_connected_triangle_without_dragging_changes_nothing() {
1532 let (mut comp, mut flow, mut history) = wire_flow();
1533 let merge = id(&comp, "Merge1");
1534 let tri = input_center(&flow, &comp, merge, "Background");
1535 let revision = comp.revision;
1536 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(tri), tri);
1537 send(&mut flow, &mut comp, &mut history, button(true), tri);
1538 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([tri[0] + 2.0, tri[1]]), tri);
1539 assert!(!history.in_group());
1540 send(&mut flow, &mut comp, &mut history, button(false), [tri[0] + 2.0, tri[1]]);
1541 assert!(flow.wire_drag.is_none());
1542 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1543 assert_eq!(comp.revision, revision);
1544 assert!(!history.can_undo() && !history.in_group());
1545 }
1546
1547 #[test]
1548 fn rewiring_keeps_the_wires_own_output() {
1549 let mut comp = Comp::from_fusion_str(
1550 r#"Composition {
1551 Tools = ordered() {
1552 Ellipse1 = EllipseMask { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, },
1553 Checker = Fuse.CheckerPieceGenerator { ViewInfo = OperatorInfo { Pos = { 0, 80 } }, },
1554 Mtl1 = MtlBlinn { ViewInfo = OperatorInfo { Pos = { 0, 160 } }, },
1555 Merge1 = Merge {
1556 Inputs = {
1557 Foreground = Input { SourceOp = "Checker", Source = "ExtraScale" },
1558 EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask" },
1559 },
1560 ViewInfo = OperatorInfo { Pos = { 160, 0 } },
1561 },
1562 Blur1 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 120 } }, },
1563 Blur2 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 240 } }, },
1564 },
1565 }"#,
1566 )
1567 .expect("parse comp");
1568 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1569 (flow.size, flow.pan, flow.zoom) = ([800.0, 600.0], [80.0, 60.0], 1.0);
1570 let mut history = CompHistory::new();
1571 let (merge, blur, blur2) = (id(&comp, "Merge1"), id(&comp, "Blur1"), id(&comp, "Blur2"));
1572 let output = |comp: &Comp, node: NodeId, port: &str| comp.node(node).inputs[port].source_output.clone();
1573
1574 let body = flow.world_to_local(comp.node(blur).pos);
1575 let from = input_center(&flow, &comp, merge, "Foreground");
1576 drag(&mut flow, &mut comp, &mut history, from, body);
1577 assert_eq!(output(&comp, blur, "Input").as_deref(), Some("ExtraScale"));
1578
1579 let from = input_center(&flow, &comp, merge, "EffectMask");
1580 let to = input_center(&flow, &comp, blur, "EffectMask");
1581 drag(&mut flow, &mut comp, &mut history, from, to);
1582 assert_eq!(output(&comp, blur, "EffectMask").as_deref(), Some("Mask"));
1583
1584 // A fresh wire picks the output its source tool has.
1585 let body = flow.world_to_local(comp.node(blur2).pos);
1586 for (name, expected) in [("Ellipse1", "Mask"), ("Mtl1", "MaterialOutput"), ("Checker", "Output")] {
1587 let from = output_center(&flow, &comp, id(&comp, name));
1588 drag(&mut flow, &mut comp, &mut history, from, body);
1589 assert_eq!(output(&comp, blur2, "Input").as_deref(), Some(expected), "{name}");
1590 }
1591 }
1592
1593 #[test]
1594 fn losing_pointer_focus_cancels_an_open_rewire_or_modal() {
1595 let (mut comp, mut flow, mut history) = wire_flow();
1596 let merge = id(&comp, "Merge1");
1597 let tri = input_center(&flow, &comp, merge, "Background");
1598 let far = [tri[0] + 40.0, tri[1] + 40.0];
1599 send(&mut flow, &mut comp, &mut history, button(true), tri);
1600 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(far), far);
1601 assert!(history.in_group() && source(&comp, merge, "Background").is_none());
1602
1603 send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far);
1604 assert!(flow.wire_drag.is_none() && !history.in_group() && !history.can_undo());
1605 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1606
1607 flow.selected.insert(merge);
1608 flow.primary = Some(merge);
1609 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1610 assert!(flow.modal.is_some() && history.in_group());
1611 send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far);
1612 assert!(flow.modal.is_none() && !history.in_group());
1613 }
1614
1615 #[test]
1616 fn sanitizing_mid_gesture_does_not_leave_the_history_group_open() {
1617 let (mut comp, mut flow, mut history) = wire_flow();
1618 let merge = id(&comp, "Merge1");
1619 flow.selected.insert(merge);
1620 flow.primary = Some(merge);
1621 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1622 assert!(history.in_group());
1623 flow.sanitize_ids(&comp);
1624 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([5.0, 5.0]), [5.0, 5.0]);
1625 assert!(!history.in_group());
1626 }
1627
1628 #[test]
1629 fn port_tables_follow_fusion() {
1630 let comp = Comp::from_fusion_str(
1631 "Composition { Tools = ordered() { Else = Fuse.SwitchElse {}, Key = DeltaKeyer {}, Checker = Fuse.CheckerPieceGenerator {}, }, }",
1632 )
1633 .expect("parse comp");
1634 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1635 flow.zoom = 1.0;
1636 let ports = |name: &str| {
1637 let mut found = Vec::new();
1638 flow.for_each_input(&comp, comp.node(id(&comp, name)), |s| found.push((s.port, s.color)));
1639 found
1640 };
1641 let names = |name: &str| ports(name).into_iter().map(|(p, _)| p).collect::<Vec<_>>();
1642 assert_eq!(names("Else"), ["Input1", "Input2", "EffectMask"]);
1643 assert_eq!(names("Key"), ["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]);
1644 assert_eq!(names("Checker"), ["EffectMask"]);
1645 assert!(ports("Key").iter().filter(|(p, _)| p.ends_with(".Matte")).all(|(_, c)| *c == ports::GRAY));
1646 }
1647
1463}1648}
crates/flow/src/ports.rs+12-7
...@@ -17,7 +17,7 @@ const STUB: f32 = 6.0;...@@ -17,7 +17,7 @@ const STUB: f32 = 6.0;
17const YELLOW: [f32; 4] = [0.91, 0.77, 0.23, 1.0];17const YELLOW: [f32; 4] = [0.91, 0.77, 0.23, 1.0];
18const GREEN: [f32; 4] = [0.42, 0.75, 0.23, 1.0];18const GREEN: [f32; 4] = [0.42, 0.75, 0.23, 1.0];
19const BLUE: [f32; 4] = [0.23, 0.63, 0.91, 1.0];19const BLUE: [f32; 4] = [0.23, 0.63, 0.91, 1.0];
20const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0];20pub(crate) const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0];
21const PURPLE: [f32; 4] = [0.72, 0.50, 0.92, 1.0];21const PURPLE: [f32; 4] = [0.72, 0.50, 0.92, 1.0];
2222
23static SCENE_INPUTS: [&str; 32] = [23static SCENE_INPUTS: [&str; 32] = [
...@@ -116,9 +116,10 @@ fn table(n: &Node) -> (Table, Class) {...@@ -116,9 +116,10 @@ fn table(n: &Node) -> (Table, Class) {
116 match n.kind.as_str() {116 match n.kind.as_str() {
117 "Merge" | "Dissolve" | "ChannelBoolean" => (Table::Fixed(&["Background", "Foreground", "EffectMask"]), TwoInput),117 "Merge" | "Dissolve" | "ChannelBoolean" => (Table::Fixed(&["Background", "Foreground", "EffectMask"]), TwoInput),
118 "Displace" => (Table::Fixed(&["Input", "Foreground", "EffectMask"]), TwoInput),118 "Displace" => (Table::Fixed(&["Input", "Foreground", "EffectMask"]), TwoInput),
119 "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask" => {119 "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask"
120 (Table::Fixed(&["EffectMask"]), Generator)120 | "Fuse.CheckerPieceGenerator" => (Table::Fixed(&["EffectMask"]), Generator),
121 }121 "Fuse.SwitchElse" => (Table::Fixed(&["Input1", "Input2", "EffectMask"]), Single),
122 "DeltaKeyer" => (Table::Fixed(&["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]), Single),
122 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => {123 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => {
123 (Table::Fixed(&["SceneInput"]), Single)124 (Table::Fixed(&["SceneInput"]), Single)
124 }125 }
...@@ -187,7 +188,7 @@ fn port_color(n: &Node, port: &str) -> [f32; 4] {...@@ -187,7 +188,7 @@ fn port_color(n: &Node, port: &str) -> [f32; 4] {
187 "Input1" if n.kind == "Switch" && zero_indexed(n) => GREEN,188 "Input1" if n.kind == "Switch" && zero_indexed(n) => GREEN,
188 "Input1" => YELLOW,189 "Input1" => YELLOW,
189 "Input2" | "SceneInput2" => GREEN,190 "Input2" | "SceneInput2" => GREEN,
190 "GarbageMatte" | "SolidMatte" => GRAY,191 "GarbageMatte" | "SolidMatte" | "Garbage.Matte" | "Solid.Matte" => GRAY,
191 _ => match PortRole::from_input_name(port) {192 _ => match PortRole::from_input_name(port) {
192 PortRole::Background => YELLOW,193 PortRole::Background => YELLOW,
193 PortRole::Foreground => GREEN,194 PortRole::Foreground => GREEN,
...@@ -362,8 +363,12 @@ impl FlowView {...@@ -362,8 +363,12 @@ impl FlowView {
362 /// Extra pixels around a node's rect that its handles can reach.363 /// Extra pixels around a node's rect that its handles can reach.
363 fn handle_reach(&self, n: &Node) -> f32 {364 fn handle_reach(&self, n: &Node) -> f32 {
364 let m = Metrics::at(self.zoom);365 let m = Metrics::at(self.zoom);
365 let grow = if matches!(table(n).0, Table::Grow(_)) { n.inputs.len() as f32 * 4.5 } else { 0.0 };366 let r = self.node_rect_local(n.pos);
366 HIT_IN + m.tri_len + 4.0 + grow367 let mut ports = 0_usize;
368 each_port(n, table(n).0, |_| ports += 1);
369 // One edge carrying every port spreads them past the node's shorter side.
370 let spread = (ports.saturating_sub(1) as f32 * (2.0 * m.tri_half + 1.0) - (r[2] - r[0]).min(r[3] - r[1])) * 0.5;
371 HIT_IN + m.tri_len + 4.0 + spread.max(0.0)
367 }372 }
368373
369 /// Output square (`None` port) or input triangle under `local`. A node body always wins.374 /// Output square (`None` port) or input triangle under `local`. A node body always wins.
crates/model/src/comp/save.rs+37-3
...@@ -214,9 +214,10 @@ impl Comp {...@@ -214,9 +214,10 @@ impl Comp {
214 ("Loop", edited("Loop").map(|v| LuaValue::Number(if v > 0.5 { 0.0 } else { 1.0 }))),214 ("Loop", edited("Loop").map(|v| LuaValue::Number(if v > 0.5 { 0.0 } else { 1.0 }))),
215 ("Reverse", edited("Reverse").map(|v| LuaValue::Bool(v > 0.5))),215 ("Reverse", edited("Reverse").map(|v| LuaValue::Bool(v > 0.5))),
216 ];216 ];
217 let clip = tool_tbl217 // The first clip proper, as `node.clips.first()` (what the engine plays) is.
218 .get_table_mut("Clips")218 let clip = tool_tbl.get_table_mut("Clips").and_then(|c| {
219 .and_then(|c| c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut()));219 c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut().filter(|t| t.get_str("Filename").is_some()))
220 });
220 if let Some(clip) = clip {221 if let Some(clip) = clip {
221 for (key, value) in updates {222 for (key, value) in updates {
222 if let Some(value) = value {223 if let Some(value) = value {
...@@ -779,6 +780,39 @@ mod tests {...@@ -779,6 +780,39 @@ mod tests {
779 assert_eq!(clip.global_end, 25);780 assert_eq!(clip.global_end, 25);
780 }781 }
781782
783 #[test]
784 fn loader_timing_edits_land_in_the_first_clip_of_a_multi_clip_loader() {
785 let src = r#"Composition {
786 Tools = ordered() {
787 L = Loader {
788 Clips = {
789 Note = { Comment = "not a clip", },
790 Clip {
791 Filename = "a.0000.exr",
792 GlobalStart = 0,
793 GlobalEnd = 10,
794 },
795 Clip {
796 Filename = "b.0000.exr",
797 GlobalStart = 11,
798 GlobalEnd = 30,
799 },
800 },
801 },
802 },
803 }"#;
804 let mut comp = Comp::from_fusion_str(src).unwrap();
805 let l = comp.find_node("L").unwrap();
806 comp.set_input_value(l, "GlobalOut", ParamValue::Number(25.0));
807 comp.set_input_value(l, "Reverse", ParamValue::Number(1.0));
808 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
809 let clips = &saved.node(saved.find_node("L").unwrap()).clips;
810 assert_eq!(clips.len(), 2);
811 assert_eq!((clips[0].global_end, clips[0].reverse), (25, true));
812 assert_eq!((clips[1].global_start, clips[1].global_end, clips[1].reverse), (11, 30, false));
813 assert!(comp.to_fusion_string().contains("Comment = \"not a clip\""));
814 }
815
782 #[test]816 #[test]
783 fn cleared_cross_macro_wire_keeps_its_source_op_on_save() {817 fn cleared_cross_macro_wire_keeps_its_source_op_on_save() {
784 let src = r#"Composition {818 let src = r#"Composition {
crates/model/src/expr.rs+202-17
...@@ -11,6 +11,32 @@ pub enum ExprValue {...@@ -11,6 +11,32 @@ pub enum ExprValue {
11 Text(String),11 Text(String),
12}12}
1313
14/// Lua's `tostring` for a float: C `%.14g`, so `0.1 + 0.2` reads `0.3` and `3.0` reads `3`.
15fn format_number(n: f64) -> String {
16 if !n.is_finite() {
17 return if n.is_nan() { "nan" } else if n > 0.0 { "inf" } else { "-inf" }.to_owned();
18 }
19 let sci = format!("{:.13e}", n.abs());
20 let (mantissa, exp) = sci.split_once('e').expect("`{:e}` always has an exponent");
21 let exp: i32 = exp.parse().expect("exponent is an integer");
22 let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
23 let digits = digits.trim_end_matches('0');
24 let digits = if digits.is_empty() { "0" } else { digits };
25 let sign = if n.is_sign_negative() { "-" } else { "" };
26 let (head, tail) = digits.split_at(1);
27 if !(-4..14).contains(&exp) {
28 let point = if tail.is_empty() { "" } else { "." };
29 return format!("{sign}{head}{point}{tail}e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs());
30 }
31 if exp < 0 {
32 return format!("{sign}0.{}{digits}", "0".repeat(exp.unsigned_abs() as usize - 1));
33 }
34 let int_len = exp as usize + 1;
35 let padded = format!("{digits:0<int_len$}");
36 let (int, frac) = padded.split_at(int_len);
37 format!("{sign}{int}{}{frac}", if frac.is_empty() { "" } else { "." })
38}
39
14#[cfg(not(target_arch = "wasm32"))]40#[cfg(not(target_arch = "wasm32"))]
15mod lua {41mod lua {
16 use super::ExprValue;42 use super::ExprValue;
...@@ -73,6 +99,8 @@ mod lua {...@@ -73,6 +99,8 @@ mod lua {
73 tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end99 tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end
74 iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end100 iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end
75 Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end101 Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end
102 local lua_tostring = tostring
103 tostring = function(v) if type(v) == "number" then return string.format("%.14g", v) end return lua_tostring(v) end
76 Text = function(s) return tostring(s or "") end104 Text = function(s) return tostring(s or "") end
77 clamp = function(x, lo, hi) if x < lo then return lo elseif x > hi then return hi else return x end end105 clamp = function(x, lo, hi) if x < lo then return lo elseif x > hi then return hi else return x end end
78 mix = function(a, b, t) return a + (b - a) * t end106 mix = function(a, b, t) return a + (b - a) * t end
...@@ -197,7 +225,7 @@ mod lua {...@@ -197,7 +225,7 @@ mod lua {
197 let val = self.run(expr, time, self_params, self_points, env_nodes)?;225 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
198 match val {226 match val {
199 Value::String(s) => Some(s.to_str().ok()?.to_owned()),227 Value::String(s) => Some(s.to_str().ok()?.to_owned()),
200 Value::Number(n) => Some(format!("{n}")),228 Value::Number(n) => Some(super::format_number(n)),
201 Value::Integer(i) => Some(format!("{i}")),229 Value::Integer(i) => Some(format!("{i}")),
202 Value::Table(t) => t.get::<String>("Value").ok(),230 Value::Table(t) => t.get::<String>("Value").ok(),
203 _ => None,231 _ => None,
...@@ -354,6 +382,7 @@ mod pure {...@@ -354,6 +382,7 @@ mod pure {
354 use std::collections::HashMap;382 use std::collections::HashMap;
355383
356 const MAX_DEPTH: usize = 64;384 const MAX_DEPTH: usize = 64;
385 const MAX_TOKENS: usize = 2048;
357 const MATH_FNS: &[&str] = &[386 const MATH_FNS: &[&str] = &[
358 "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "floor", "fmod", "log", "max", "min", "rad",387 "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "floor", "fmod", "log", "max", "min", "rad",
359 "sin", "sqrt", "tan",388 "sin", "sqrt", "tan",
...@@ -365,7 +394,8 @@ mod pure {...@@ -365,7 +394,8 @@ mod pure {
365394
366 #[derive(Clone, Debug, PartialEq)]395 #[derive(Clone, Debug, PartialEq)]
367 enum Tok {396 enum Tok {
368 Num(f64),397 /// `true` for a Lua integer literal, which divides by zero as an error rather than `inf`.
398 Num(f64, bool),
369 Str(String),399 Str(String),
370 Name(String),400 Name(String),
371 Op(&'static str),401 Op(&'static str),
...@@ -390,19 +420,22 @@ mod pure {...@@ -390,19 +420,22 @@ mod pure {
390 i += 1;420 i += 1;
391 }421 }
392 let digits: String = chars[start + 2..i].iter().collect();422 let digits: String = chars[start + 2..i].iter().collect();
393 toks.push(Tok::Num(u64::from_str_radix(&digits, 16).ok()? as f64));423 toks.push(Tok::Num(u64::from_str_radix(&digits, 16).ok()? as f64, true));
394 continue;424 continue;
395 }425 }
396 while chars.get(i).is_some_and(char::is_ascii_digit) {426 while chars.get(i).is_some_and(char::is_ascii_digit) {
397 i += 1;427 i += 1;
398 }428 }
429 let mut integer = true;
399 if chars.get(i) == Some(&'.') && chars.get(i + 1) != Some(&'.') {430 if chars.get(i) == Some(&'.') && chars.get(i + 1) != Some(&'.') {
431 integer = false;
400 i += 1;432 i += 1;
401 while chars.get(i).is_some_and(char::is_ascii_digit) {433 while chars.get(i).is_some_and(char::is_ascii_digit) {
402 i += 1;434 i += 1;
403 }435 }
404 }436 }
405 if matches!(chars.get(i), Some('e' | 'E')) {437 if matches!(chars.get(i), Some('e' | 'E')) {
438 integer = false;
406 i += 1;439 i += 1;
407 if matches!(chars.get(i), Some('+' | '-')) {440 if matches!(chars.get(i), Some('+' | '-')) {
408 i += 1;441 i += 1;
...@@ -411,7 +444,8 @@ mod pure {...@@ -411,7 +444,8 @@ mod pure {
411 i += 1;444 i += 1;
412 }445 }
413 }446 }
414 toks.push(Tok::Num(chars[start..i].iter().collect::<String>().parse().ok()?));447 let value: f64 = chars[start..i].iter().collect::<String>().parse().ok()?;
448 toks.push(Tok::Num(value, integer && value < 2f64.powi(63)));
415 } else if c.is_alphabetic() || c == '_' {449 } else if c.is_alphabetic() || c == '_' {
416 let start = i;450 let start = i;
417 while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_') {451 while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_') {
...@@ -453,6 +487,8 @@ mod pure {...@@ -453,6 +487,8 @@ mod pure {
453 Nil,487 Nil,
454 Bool(bool),488 Bool(bool),
455 Num(f64),489 Num(f64),
490 /// An integer literal.
491 Int(f64),
456 Str(String),492 Str(String),
457 Name(String),493 Name(String),
458 Index(Box<Ast>, Box<Ast>),494 Index(Box<Ast>, Box<Ast>),
...@@ -500,23 +536,34 @@ mod pure {...@@ -500,23 +536,34 @@ mod pure {
500 Some((op, left, right))536 Some((op, left, right))
501 }537 }
502538
503 fn expr(&mut self, min_bp: u8) -> Option<Ast> {539 /// One more level of tree height, which nesting and every left-associative link add alike,
540 /// so recursive eval and drop stay bounded.
541 fn descend(&mut self) -> Option<()> {
504 self.depth += 1;542 self.depth += 1;
505 let ast = if self.depth > MAX_DEPTH { None } else { self.binary(min_bp) };543 (self.depth <= MAX_DEPTH).then_some(())
506 self.depth -= 1;544 }
507 ast545
546 fn expr(&mut self, min_bp: u8) -> Option<Ast> {
547 let outer = self.depth;
548 self.descend()?;
549 let ast = self.binary(min_bp)?;
550 self.depth = outer;
551 Some(ast)
508 }552 }
509553
510 fn binary(&mut self, min_bp: u8) -> Option<Ast> {554 fn binary(&mut self, min_bp: u8) -> Option<Ast> {
555 let outer = self.depth;
511 let mut lhs = self.unary()?;556 let mut lhs = self.unary()?;
512 while let Some((op, left, right)) = self.binary_op() {557 while let Some((op, left, right)) = self.binary_op() {
513 if left < min_bp {558 if left < min_bp {
514 break;559 break;
515 }560 }
516 self.pos += 1;561 self.pos += 1;
562 self.descend()?;
517 let rhs = self.expr(right)?;563 let rhs = self.expr(right)?;
518 lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs));564 lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs));
519 }565 }
566 self.depth = outer;
520 Some(lhs)567 Some(lhs)
521 }568 }
522569
...@@ -533,7 +580,8 @@ mod pure {...@@ -533,7 +580,8 @@ mod pure {
533580
534 fn postfix(&mut self) -> Option<Ast> {581 fn postfix(&mut self) -> Option<Ast> {
535 let mut node = match self.toks.get(self.pos)?.clone() {582 let mut node = match self.toks.get(self.pos)?.clone() {
536 Tok::Num(n) => Ast::Num(n),583 Tok::Num(n, true) => Ast::Int(n),
584 Tok::Num(n, false) => Ast::Num(n),
537 Tok::Str(s) => Ast::Str(s),585 Tok::Str(s) => Ast::Str(s),
538 Tok::Name(n) => match n.as_str() {586 Tok::Name(n) => match n.as_str() {
539 "nil" => Ast::Nil,587 "nil" => Ast::Nil,
...@@ -553,18 +601,22 @@ mod pure {...@@ -553,18 +601,22 @@ mod pure {
553 Tok::Op(_) => return None,601 Tok::Op(_) => return None,
554 };602 };
555 self.pos += 1;603 self.pos += 1;
604 let outer = self.depth;
556 loop {605 loop {
557 if self.eat_op(".") {606 if self.eat_op(".") {
607 self.descend()?;
558 let Some(Tok::Name(key)) = self.peek().cloned() else { return None };608 let Some(Tok::Name(key)) = self.peek().cloned() else { return None };
559 self.pos += 1;609 self.pos += 1;
560 node = Ast::Index(Box::new(node), Box::new(Ast::Str(key)));610 node = Ast::Index(Box::new(node), Box::new(Ast::Str(key)));
561 } else if self.eat_op("[") {611 } else if self.eat_op("[") {
612 self.descend()?;
562 let key = self.expr(0)?;613 let key = self.expr(0)?;
563 if !self.eat_op("]") {614 if !self.eat_op("]") {
564 return None;615 return None;
565 }616 }
566 node = Ast::Index(Box::new(node), Box::new(key));617 node = Ast::Index(Box::new(node), Box::new(key));
567 } else if self.eat_op("(") {618 } else if self.eat_op("(") {
619 self.descend()?;
568 let mut args = Vec::new();620 let mut args = Vec::new();
569 if !self.eat_op(")") {621 if !self.eat_op(")") {
570 loop {622 loop {
...@@ -579,6 +631,7 @@ mod pure {...@@ -579,6 +631,7 @@ mod pure {
579 }631 }
580 node = Ast::Call(Box::new(node), args);632 node = Ast::Call(Box::new(node), args);
581 } else {633 } else {
634 self.depth = outer;
582 return Some(node);635 return Some(node);
583 }636 }
584 }637 }
...@@ -613,13 +666,23 @@ mod pure {...@@ -613,13 +666,23 @@ mod pure {
613 }666 }
614 }667 }
615668
669 /// What `..` accepts: numbers and strings.
616 fn text(&self) -> Option<String> {670 fn text(&self) -> Option<String> {
617 match self {671 match self {
618 Val::Num(n) => Some(format!("{n}")),672 Val::Num(n) => Some(super::format_number(*n)),
619 Val::Str(s) | Val::Text(s) => Some(s.clone()),673 Val::Str(s) | Val::Text(s) => Some(s.clone()),
620 _ => None,674 _ => None,
621 }675 }
622 }676 }
677
678 /// Lua's `tostring`, which also names `nil` and booleans.
679 fn tostring(&self) -> Option<String> {
680 match self {
681 Val::Nil => Some("nil".to_owned()),
682 Val::Bool(b) => Some(b.to_string()),
683 other => other.text(),
684 }
685 }
623 }686 }
624687
625 struct Scope<'a> {688 struct Scope<'a> {
...@@ -655,7 +718,7 @@ mod pure {...@@ -655,7 +718,7 @@ mod pure {
655 Some(match ast {718 Some(match ast {
656 Ast::Nil => Val::Nil,719 Ast::Nil => Val::Nil,
657 Ast::Bool(b) => Val::Bool(*b),720 Ast::Bool(b) => Val::Bool(*b),
658 Ast::Num(n) => Val::Num(*n),721 Ast::Num(n) | Ast::Int(n) => Val::Num(*n),
659 Ast::Str(s) => Val::Str(s.clone()),722 Ast::Str(s) => Val::Str(s.clone()),
660 Ast::Name(n) => self.name(n),723 Ast::Name(n) => self.name(n),
661 Ast::Neg(a) => Val::Num(-self.eval(a)?.num()?),724 Ast::Neg(a) => Val::Num(-self.eval(a)?.num()?),
...@@ -674,11 +737,28 @@ mod pure {...@@ -674,11 +737,28 @@ mod pure {
674 let a = self.eval(a)?;737 let a = self.eval(a)?;
675 if a.truthy() { a } else { self.eval(b)? }738 if a.truthy() { a } else { self.eval(b)? }
676 }739 }
677 Ast::Bin(op, a, b) => binary(op, self.eval(a)?, self.eval(b)?)?,740 Ast::Bin(op, a, b) => {
741 let (a_val, b_val) = (self.eval(a)?, self.eval(b)?);
742 // Lua 5.4 errors on integer `//` and `%` by zero; floats give `inf`/`nan`.
743 if matches!(*op, "//" | "%") && b_val.num() == Some(0.0) && is_integer(a) && is_integer(b) {
744 return None;
745 }
746 binary(op, a_val, b_val)?
747 }
678 })748 })
679 }749 }
680 }750 }
681751
752 /// Whether Lua 5.4 types `ast` as an integer: integer literals and `+ - * // %` of them.
753 fn is_integer(ast: &Ast) -> bool {
754 match ast {
755 Ast::Int(_) => true,
756 Ast::Neg(a) => is_integer(a),
757 Ast::Bin("+" | "-" | "*" | "//" | "%", a, b) => is_integer(a) && is_integer(b),
758 _ => false,
759 }
760 }
761
682 fn index<'a>(base: Val<'a>, key: Val<'a>) -> Option<Val<'a>> {762 fn index<'a>(base: Val<'a>, key: Val<'a>) -> Option<Val<'a>> {
683 Some(match (base, key) {763 Some(match (base, key) {
684 (Val::Node(fields), key) => match key {764 (Val::Node(fields), key) => match key {
...@@ -708,7 +788,7 @@ mod pure {...@@ -708,7 +788,7 @@ mod pure {
708 fn binary<'a>(op: &str, a: Val<'a>, b: Val<'a>) -> Option<Val<'a>> {788 fn binary<'a>(op: &str, a: Val<'a>, b: Val<'a>) -> Option<Val<'a>> {
709 use std::cmp::Ordering;789 use std::cmp::Ordering;
710 let ordering = |a: &Val, b: &Val| match (a, b) {790 let ordering = |a: &Val, b: &Val| match (a, b) {
711 (Val::Num(a), Val::Num(b)) => a.partial_cmp(b).map(Some),791 (Val::Num(a), Val::Num(b)) => Some(a.partial_cmp(b)),
712 (Val::Str(a), Val::Str(b)) => Some(Some(a.cmp(b))),792 (Val::Str(a), Val::Str(b)) => Some(Some(a.cmp(b))),
713 _ => None,793 _ => None,
714 };794 };
...@@ -790,7 +870,8 @@ mod pure {...@@ -790,7 +870,8 @@ mod pure {
790 }870 }
791 "mix" => Val::Num(arg(0)? + (arg(1)? - arg(0)?) * arg(2)?),871 "mix" => Val::Num(arg(0)? + (arg(1)? - arg(0)?) * arg(2)?),
792 "Point" => Val::Point([arg(0).unwrap_or(0.0), arg(1).unwrap_or(0.0)]),872 "Point" => Val::Point([arg(0).unwrap_or(0.0), arg(1).unwrap_or(0.0)]),
793 "Text" | "tostring" => Val::Str(args.first().map_or(Some(String::new()), Val::text)?),873 "tostring" => Val::Str(args.first()?.tostring()?),
874 "Text" => Val::Str(args.first().filter(|a| a.truthy()).map_or(Some(String::new()), Val::tostring)?),
794 "tonumber" => args.first()?.num().map_or(Val::Nil, Val::Num),875 "tonumber" => args.first()?.num().map_or(Val::Nil, Val::Num),
795 _ => return None,876 _ => return None,
796 })877 })
...@@ -814,10 +895,15 @@ mod pure {...@@ -814,10 +895,15 @@ mod pure {
814 read: impl FnOnce(Val) -> Option<R>,895 read: impl FnOnce(Val) -> Option<R>,
815 ) -> Option<R> {896 ) -> Option<R> {
816 let body = match expr.trim_start().strip_prefix(':') {897 let body = match expr.trim_start().strip_prefix(':') {
817 Some(stmt) => stmt.trim_start().strip_prefix("return ")?,898 Some(stmt) => {
899 let value = stmt.trim_start().strip_prefix("return ")?.trim_end();
900 value.strip_suffix(';').unwrap_or(value)
901 }
818 None => expr,902 None => expr,
819 };903 };
820 let mut parser = Parser { toks: lex(body)?, pos: 0, depth: 0 };904 // Every AST node consumes a token, so this also caps the tree's size.
905 let toks = lex(body).filter(|t| t.len() <= MAX_TOKENS)?;
906 let mut parser = Parser { toks, pos: 0, depth: 0 };
821 let ast = parser.expr(0)?;907 let ast = parser.expr(0)?;
822 if parser.pos != parser.toks.len() {908 if parser.pos != parser.toks.len() {
823 return None;909 return None;
...@@ -943,8 +1029,86 @@ mod pure {...@@ -943,8 +1029,86 @@ mod pure {
943 assert_eq!(num(src, 0.0), None, "{src:?}");1029 assert_eq!(num(src, 0.0), None, "{src:?}");
944 }1030 }
945 assert_eq!(num(":return time * 2", 2.0), Some(4.0));1031 assert_eq!(num(":return time * 2", 2.0), Some(4.0));
1032 assert_eq!(num(":return time * 2;", 2.0), Some(4.0));
946 assert_eq!(num(&"(".repeat(200), 0.0), None);1033 assert_eq!(num(&"(".repeat(200), 0.0), None);
947 }1034 }
1035
1036 #[test]
1037 fn long_chains_are_bounded_instead_of_overflowing_the_stack() {
1038 let sum = |terms: usize| vec!["1"; terms].join("+");
1039 assert_eq!(num(&sum(40), 0.0), Some(40.0));
1040 for terms in [100, 10_000, 200_000] {
1041 assert_eq!(num(&sum(terms), 0.0), None, "{terms} terms");
1042 }
1043 let path = |links: usize| format!("Ctl{}", ".Size".repeat(links));
1044 assert_eq!(num(&path(1), 0.0), Some(0.25));
1045 assert_eq!(num(&path(100), 0.0), None);
1046 assert_eq!(num(&format!("max({})", vec!["1"; 5000].join(",")), 0.0), None);
1047 assert_eq!(num(&format!("{}1{}", "-".repeat(500), ""), 0.0), None);
1048 }
1049
1050 #[test]
1051 fn nan_compares_false_instead_of_failing() {
1052 for (src, want) in [("0/0 < 1", 0.0), ("0/0 >= 1", 0.0), ("0/0 <= 0/0", 0.0), ("0/0 == 0/0", 0.0), ("0/0 ~= 0/0", 1.0)] {
1053 assert_eq!(num(src, 0.0), Some(want), "{src}");
1054 }
1055 }
1056
1057 #[test]
1058 fn integer_division_by_zero_errors_but_float_gives_inf() {
1059 assert_eq!(num("1 // 0", 0.0), None);
1060 assert_eq!(num("1 % 0", 0.0), None);
1061 assert_eq!(num("(2 + 3) % (1 - 1)", 0.0), None);
1062 assert_eq!(num("1.0 // 0", 0.0), Some(f64::INFINITY));
1063 assert_eq!(num("1 // 0.0", 0.0), Some(f64::INFINITY));
1064 assert_eq!(num("time // 0", 2.0), Some(f64::INFINITY));
1065 assert!(num("time % 0", 2.0).is_some_and(f64::is_nan));
1066 }
1067
1068 #[test]
1069 fn tostring_names_nil_and_booleans() {
1070 let e = ExprEngine::new();
1071 let (p, q, n) = (HashMap::new(), HashMap::new(), nodes());
1072 let s = |src: &str| e.eval_string(src, 0.0, &p, &q, &n);
1073 assert_eq!(s("tostring(true)").as_deref(), Some("true"));
1074 assert_eq!(s("tostring(false)").as_deref(), Some("false"));
1075 assert_eq!(s("tostring(nil)").as_deref(), Some("nil"));
1076 assert_eq!(s("Text(nil)").as_deref(), Some(""));
1077 assert_eq!(s("Text(false)").as_deref(), Some(""));
1078 assert_eq!(s("'a' .. nil"), None);
1079 assert_eq!(s("0.1 + 0.2").as_deref(), Some("0.3"));
1080 }
1081 }
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086 use super::format_number;
1087
1088 #[test]
1089 fn numbers_format_like_c_percent_14g() {
1090 for (n, want) in [
1091 (3.0, "3"),
1092 (-0.0, "-0"),
1093 (0.0, "0"),
1094 (0.1 + 0.2, "0.3"),
1095 (1.0 / 3.0, "0.33333333333333"),
1096 (2.5, "2.5"),
1097 (100.0, "100"),
1098 (123456789012345.0, "1.2345678901234e+14"),
1099 (99999999999999.0, "99999999999999"),
1100 (1e15, "1e+15"),
1101 (2f64.powi(53), "9.007199254741e+15"),
1102 (1e100, "1e+100"),
1103 (0.0001, "0.0001"),
1104 (0.00001, "1e-05"),
1105 (-1234.5, "-1234.5"),
1106 (f64::INFINITY, "inf"),
1107 (f64::NEG_INFINITY, "-inf"),
1108 (f64::NAN, "nan"),
1109 ] {
1110 assert_eq!(format_number(n), want, "{n:e}");
1111 }
948 }1112 }
949}1113}
9501114
...@@ -980,6 +1144,13 @@ mod parity {...@@ -980,6 +1144,13 @@ mod parity {
980 "max(1, time, 3) + min(time, 9) + abs(-time) + ceil(time) + sqrt(time)",1144 "max(1, time, 3) + min(time, 9) + abs(-time) + ceil(time) + sqrt(time)",
981 "cosh(time) + sinh(time) + tanh(time) + deg(1) + rad(90)",1145 "cosh(time) + sinh(time) + tanh(time) + deg(1) + rad(90)",
982 "time ~= 2.5",1146 "time ~= 2.5",
1147 "0/0 < 1",
1148 "0/0 >= 1",
1149 "1 // 0",
1150 "1 % 0",
1151 "time // 0",
1152 "1.0 % 0 < 1",
1153 ":return time * 2;",
983 "'10' + 1",1154 "'10' + 1",
984 "Nope.Size",1155 "Nope.Size",
985 "1 +",1156 "1 +",
...@@ -988,10 +1159,24 @@ mod parity {...@@ -988,10 +1159,24 @@ mod parity {
988 let l = lua.eval_number(args.0, args.1, args.2, args.3, args.4);1159 let l = lua.eval_number(args.0, args.1, args.2, args.3, args.4);
989 let p = pure.eval_number(args.0, args.1, args.2, args.3, args.4);1160 let p = pure.eval_number(args.0, args.1, args.2, args.3, args.4);
990 match (l, p) {1161 match (l, p) {
991 (Some(l), Some(p)) => assert!((l - p).abs() < 1e-9 || (l.is_nan() && p.is_nan()), "{src} @ {time}: {l} vs {p}"),1162 (Some(l), Some(p)) => assert!(l == p || (l - p).abs() < 1e-9 || (l.is_nan() && p.is_nan()), "{src} @ {time}: {l} vs {p}"),
992 _ => assert_eq!(l, p, "{src} @ {time}"),1163 _ => assert_eq!(l, p, "{src} @ {time}"),
993 }1164 }
994 }1165 }
995 }1166 }
996 }1167 }
1168
1169 #[test]
1170 fn pure_formats_numbers_like_lua() {
1171 let nodes = HashMap::new();
1172 let (lua, pure) = (ExprEngine::new(), pure::ExprEngine::new());
1173 for src in [
1174 "0.1 + 0.2", "3.0", "time", "1e15", "2^53", "1e100", "0.00001", "1/3", "-0.0", "7 // 2", "100 * 1.0",
1175 "tostring(true)", "tostring(nil)", "Text(nil)", "Text(time)", "123456789.123456789",
1176 ] {
1177 let l = lua.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes);
1178 let p = pure.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes);
1179 assert_eq!(l, p, "{src}");
1180 }
1181 }
997}1182}
crates/web/index.html+16-7
...@@ -189,18 +189,25 @@ function tick(now) {...@@ -189,18 +189,25 @@ function tick(now) {
189 $('scrub').value = frame;189 $('scrub').value = frame;
190 }190 }
191 if (dirty || frame !== lastDrawn) {191 if (dirty || frame !== lastDrawn) {
192 let ms;
192 try {193 try {
193 evalMs = app.render(frame);194 ms = app.render(frame);
194 } catch (e) {195 } catch (e) {
195 broken = true;196 broken = true;
196 fail(`Render failed: ${e.message ?? e}. Reload the page; details are in the console.`);197 fail(`Render failed: ${e.message ?? e}. Reload the page; details are in the console.`);
197 return;198 return;
198 }199 }
199 if (lastTick) fps += ((1000 / (now - lastTick)) - fps) * 0.15;200 const gpuError = app.gpu_error();
200 lastTick = now;201 if (gpuError) fail(`GPU error: ${gpuError}`);
201 lastDrawn = frame; dirty = false;202 // `undefined`: the surface was not ready; stay dirty and try again next frame.
202 const bad = app.unsupported();203 if (ms !== undefined) {
203 $('notes').dataset.unsupported = bad.join(', ');204 evalMs = ms;
205 if (lastTick) fps += ((1000 / (now - lastTick)) - fps) * 0.15;
206 lastTick = now;
207 lastDrawn = frame; dirty = false;
208 const bad = app.unsupported();
209 $('notes').dataset.unsupported = bad.join(', ');
210 }
204 } else if (!playing) {211 } else if (!playing) {
205 lastTick = 0;212 lastTick = 0;
206 }213 }
...@@ -265,9 +272,10 @@ async function ingest(files) {...@@ -265,9 +272,10 @@ async function ingest(files) {
265 if (!app) return;272 if (!app) return;
266 const comps = files.filter(({ path }) => /\.comp$/i.test(path));273 const comps = files.filter(({ path }) => /\.comp$/i.test(path));
267 if (comps.length) { app.clear_files(); sources.clear(); }274 if (comps.length) { app.clear_files(); sources.clear(); }
275 let dropped = 0;
268 for (const { path, file } of files) {276 for (const { path, file } of files) {
269 if (!MEDIA_EXT.test(path) || file.size > MAX_FILE_BYTES) continue;277 if (!MEDIA_EXT.test(path) || file.size > MAX_FILE_BYTES) continue;
270 app.add_file(path, new Uint8Array(await file.arrayBuffer()));278 if (!app.add_file(path, new Uint8Array(await file.arrayBuffer()))) dropped++;
271 }279 }
272 if (comps.length) {280 if (comps.length) {
273 comps.sort((a, b) => a.path.localeCompare(b.path));281 comps.sort((a, b) => a.path.localeCompare(b.path));
...@@ -280,6 +288,7 @@ async function ingest(files) {...@@ -280,6 +288,7 @@ async function ingest(files) {
280 refreshGraph();288 refreshGraph();
281 dirty = true;289 dirty = true;
282 }290 }
291 if (dropped) fail(`${dropped} file(s) skipped: dropped media is past the 512 MB memory limit.`);
283}292}
284293
285boot();294boot();
crates/web/src/lib.rs+76-36
...@@ -7,6 +7,7 @@ use engine::{DisplaySettings, Engine};...@@ -7,6 +7,7 @@ use engine::{DisplaySettings, Engine};
7use model::{Comp, NodeId};7use model::{Comp, NodeId};
8use serde_json::json;8use serde_json::json;
9use std::collections::HashSet;9use std::collections::HashSet;
10use std::sync::{Arc, Mutex};
10use wasm_bindgen::prelude::*;11use wasm_bindgen::prelude::*;
1112
12const DEMO_COMP: &str = include_str!("../demo.comp");13const DEMO_COMP: &str = include_str!("../demo.comp");
...@@ -20,7 +21,9 @@ struct Viewer {...@@ -20,7 +21,9 @@ struct Viewer {
20pub struct Fission {21pub struct Fission {
21 engine: Engine,22 engine: Engine,
22 surface: wgpu::Surface<'static>,23 surface: wgpu::Surface<'static>,
23 surface_format: wgpu::TextureFormat,24 config: wgpu::SurfaceConfiguration,
25 /// The latest GPU error the device raised outside any error scope, until [`Self::gpu_error`] reads it.
26 gpu_error: Arc<Mutex<Option<String>>>,
24 present: wgpu::RenderPipeline,27 present: wgpu::RenderPipeline,
25 sampler: wgpu::Sampler,28 sampler: wgpu::Sampler,
26 viewer: Option<Viewer>,29 viewer: Option<Viewer>,
...@@ -60,12 +63,31 @@ impl Fission {...@@ -60,12 +63,31 @@ impl Fission {
60 .await63 .await
61 .map_err(js_err)?;64 .map_err(js_err)?;
6265
63 let surface_format = surface66 let gpu_error = Arc::new(Mutex::new(None));
64 .get_capabilities(&adapter)67 let slot = Arc::clone(&gpu_error);
65 .formats68 device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| {
66 .into_iter()69 console_error(&format!("GPU error: {e}"));
67 .find(|f| !f.is_srgb())70 *slot.lock().unwrap() = Some(e.to_string());
68 .unwrap_or(wgpu::TextureFormat::Bgra8Unorm);71 }));
72 let slot = Arc::clone(&gpu_error);
73 device.set_device_lost_callback(move |reason, message| {
74 console_error(&format!("GPU device lost ({reason:?}): {message}"));
75 *slot.lock().unwrap() = Some(format!("The GPU device was lost ({reason:?}): {message}"));
76 });
77
78 let caps = surface.get_capabilities(&adapter);
79 let surface_format = caps.formats.iter().copied().find(|f| !f.is_srgb()).unwrap_or(wgpu::TextureFormat::Bgra8Unorm);
80 let config = wgpu::SurfaceConfiguration {
81 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
82 format: surface_format,
83 color_space: wgpu::SurfaceColorSpace::Auto,
84 width: 1,
85 height: 1,
86 present_mode: wgpu::PresentMode::AutoVsync,
87 desired_maximum_frame_latency: 2,
88 alpha_mode: caps.alpha_modes.first().copied().unwrap_or(wgpu::CompositeAlphaMode::Auto),
89 view_formats: vec![],
90 };
69 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {91 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
70 label: Some("present"),92 label: Some("present"),
71 source: wgpu::ShaderSource::Wgsl(include_str!("present.wgsl").into()),93 source: wgpu::ShaderSource::Wgsl(include_str!("present.wgsl").into()),
...@@ -83,7 +105,7 @@ impl Fission {...@@ -83,7 +105,7 @@ impl Fission {
83 module: &shader,105 module: &shader,
84 entry_point: Some("fragment"),106 entry_point: Some("fragment"),
85 compilation_options: Default::default(),107 compilation_options: Default::default(),
86 targets: &[Some(surface_format.into())],108 targets: &[Some(config.format.into())],
87 }),109 }),
88 primitive: Default::default(),110 primitive: Default::default(),
89 depth_stencil: None,111 depth_stencil: None,
...@@ -100,7 +122,8 @@ impl Fission {...@@ -100,7 +122,8 @@ impl Fission {
100 Ok(Fission {122 Ok(Fission {
101 engine: Engine::new(device, queue),123 engine: Engine::new(device, queue),
102 surface,124 surface,
103 surface_format,125 config,
126 gpu_error,
104 present,127 present,
105 sampler,128 sampler,
106 viewer: None,129 viewer: None,
...@@ -115,9 +138,11 @@ impl Fission {...@@ -115,9 +138,11 @@ impl Fission {
115 }138 }
116139
117 /// Registers a project file (a dropped folder's relative path) that `Loader` clips resolve against.140 /// Registers a project file (a dropped folder's relative path) that `Loader` clips resolve against.
118 pub fn add_file(&mut self, path: &str, bytes: &[u8]) {141 /// `false` when the files held would pass the memory cap.
119 MediaCache::insert_virtual_bytes(path, bytes);142 pub fn add_file(&mut self, path: &str, bytes: &[u8]) -> bool {
143 let added = MediaCache::insert_virtual_bytes(path, bytes);
120 self.engine.bust_all_caches();144 self.engine.bust_all_caches();
145 added
121 }146 }
122147
123 pub fn clear_files(&mut self) {148 pub fn clear_files(&mut self) {
...@@ -174,21 +199,32 @@ impl Fission {...@@ -174,21 +199,32 @@ impl Fission {
174 Ok(())199 Ok(())
175 }200 }
176201
177 /// Evaluates the selected node at `frame` into the canvas and returns the CPU-side milliseconds.202 /// Evaluates the selected node at `frame` into the canvas and returns the CPU-side milliseconds,
178 pub fn render(&mut self, frame: f64) -> Result<f64, JsError> {203 /// or `undefined` when the surface could not take the frame and the caller should retry.
204 pub fn render(&mut self, frame: f64) -> Result<Option<f64>, JsError> {
179 let (comp, target) = self.comp.as_ref().zip(self.target).ok_or_else(|| JsError::new("no comp loaded"))?;205 let (comp, target) = self.comp.as_ref().zip(self.target).ok_or_else(|| JsError::new("no comp loaded"))?;
180 // Cached by the engine, so `render_into_viewer` below reuses it; the size can change with media or time.206 // Cached by the engine, so `render_into_viewer` below reuses it; the size can change with media or time.
181 let (tex, _) = self.engine.evaluate(comp, target, frame);207 let (tex, _) = self.engine.evaluate(comp, target, frame);
182 if self.viewer.as_ref().is_none_or(|v| [v.texture.width(), v.texture.height()] != tex.canvas_size) {208 let size = fit_texture(tex.canvas_size, self.engine.device().limits().max_texture_dimension_2d);
183 self.viewer = Some(make_viewer(self.engine.device(), &self.surface, self.surface_format, &self.present, &self.sampler, tex.canvas_size));209 if self.viewer.as_ref().is_none_or(|v| [v.texture.width(), v.texture.height()] != size) {
210 [self.config.width, self.config.height] = size;
211 self.surface.configure(self.engine.device(), &self.config);
212 self.viewer = Some(make_viewer(self.engine.device(), &self.present, &self.sampler, size));
184 }213 }
185 let viewer = self.viewer.as_ref().expect("viewer sized above");214 let viewer = self.viewer.as_ref().expect("viewer sized above");
186 let stats = self.engine.render_into_viewer(comp, target, frame, &viewer.texture, DisplaySettings::default());215 let stats = self.engine.render_into_viewer(comp, target, frame, &viewer.texture, DisplaySettings::default());
187 self.unsupported = stats.unsupported_nodes;216 self.unsupported = stats.unsupported_nodes;
188217
189 let frame_tex = match self.surface.get_current_texture() {218 let (frame_tex, suboptimal) = match self.surface.get_current_texture() {
190 wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,219 wgpu::CurrentSurfaceTexture::Success(t) => (t, false),
191 _ => return Ok(stats.eval_ms),220 wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true),
221 wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
222 self.surface.configure(self.engine.device(), &self.config);
223 return Ok(None);
224 }
225 wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Validation => {
226 return Ok(None);
227 }
192 };228 };
193 let device = self.engine.device();229 let device = self.engine.device();
194 let mut encoder = device.create_command_encoder(&Default::default());230 let mut encoder = device.create_command_encoder(&Default::default());
...@@ -209,7 +245,15 @@ impl Fission {...@@ -209,7 +245,15 @@ impl Fission {
209 }245 }
210 self.engine.queue().submit(Some(encoder.finish()));246 self.engine.queue().submit(Some(encoder.finish()));
211 self.engine.queue().present(frame_tex);247 self.engine.queue().present(frame_tex);
212 Ok(stats.eval_ms)248 if suboptimal {
249 self.surface.configure(self.engine.device(), &self.config);
250 }
251 Ok(Some(stats.eval_ms))
252 }
253
254 /// Takes the latest GPU error or device loss, which would otherwise only show as a black canvas.
255 pub fn gpu_error(&self) -> Option<String> {
256 self.gpu_error.lock().unwrap().take()
213 }257 }
214258
215 /// Kinds the last rendered frame could not evaluate.259 /// Kinds the last rendered frame could not evaluate.
...@@ -218,29 +262,25 @@ impl Fission {...@@ -218,29 +262,25 @@ impl Fission {
218 }262 }
219}263}
220264
221/// Sizes the canvas and the intermediate viewer texture to the node's logical output.265#[wasm_bindgen]
266extern "C" {
267 #[wasm_bindgen(js_namespace = console, js_name = error)]
268 fn console_error(message: &str);
269}
270
271/// `size` shrunk, keeping its aspect, until both sides fit `max`; never below one pixel.
272fn fit_texture([width, height]: [u32; 2], max: u32) -> [u32; 2] {
273 let scale = (f64::from(max) / f64::from(width.max(height).max(1))).min(1.0);
274 [width, height].map(|side| ((f64::from(side) * scale).round() as u32).clamp(1, max.max(1)))
275}
276
277/// The intermediate viewer texture, sized to the (already fitted) output.
222fn make_viewer(278fn make_viewer(
223 device: &wgpu::Device,279 device: &wgpu::Device,
224 surface: &wgpu::Surface<'static>,
225 format: wgpu::TextureFormat,
226 present: &wgpu::RenderPipeline,280 present: &wgpu::RenderPipeline,
227 sampler: &wgpu::Sampler,281 sampler: &wgpu::Sampler,
228 [width, height]: [u32; 2],282 [width, height]: [u32; 2],
229) -> Viewer {283) -> Viewer {
230 surface.configure(
231 device,
232 &wgpu::SurfaceConfiguration {
233 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
234 format,
235 color_space: wgpu::SurfaceColorSpace::Auto,
236 width,
237 height,
238 present_mode: wgpu::PresentMode::AutoVsync,
239 desired_maximum_frame_latency: 2,
240 alpha_mode: wgpu::CompositeAlphaMode::Opaque,
241 view_formats: vec![],
242 },
243 );
244 let texture = device.create_texture(&wgpu::TextureDescriptor {284 let texture = device.create_texture(&wgpu::TextureDescriptor {
245 label: Some("viewer"),285 label: Some("viewer"),
246 size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },286 size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },