1//! Unified prompt & parameter extraction for `AutoMatte` and Fusion `MagicMask`.
2//!
3//! Handles:
4//! - Real Fusion `MagicMask` nodes (`Strokes = Input { SourceOp = "MagicMask1Strokes" }` pointing
5//! at a `BezierSpline` whose `KeyFrames` carry `Value = MagicMaskStrokes { PosStrokes, NegStrokes }`,
6//! or inline `MagicMaskStrokes` tables, plus `Invert`, `MatteBlur`, `MatteContractExpand`,
7//! `ShowMask`, `MatteOnly`, `OutputMode`, `CacheDir`, `Blend`).
8//! - Fission `AutoMatte` nodes (`Points`, `PositivePoints`, `NegativePoints`, `PosPoint1..16`,
9//! `NegPoint1..16`, `PromptMode`, `QualityTier`, `AlphaFloor`, `AlphaCeiling`, `ToeGamma`,
10//! `Decontaminate`, `MatteBlur`, `MatteContractExpand`, `Invert`, `OutputMode`, `CacheDir`,
11//! `Blend`).
12
13use model::{Comp, ExprEngine, LuaKey, LuaTable, LuaValue, Node, ParamValue};
14use std::hash::{Hash, Hasher};
15
16/// Maximum seeds packed into the GPU uniform buffer per dispatch.
17pub const MAX_GPU_SEEDS: usize = 32;
18
19/// Default Clover `polish_alpha` floor (kills faint VAE haze <= 0.045).
20pub const DEFAULT_ALPHA_FLOOR: f32 = 0.045;
21/// Default Clover `polish_alpha` ceiling (crisp solid white >= 0.985).
22pub const DEFAULT_ALPHA_CEILING: f32 = 0.985;
23/// Default Clover `polish_alpha` toe gamma below 0.15.
24pub const DEFAULT_TOE_GAMMA: f32 = 1.35;
25
26/// Normalized prompt point in Fusion Y-up `[0..1]` space.
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct PromptPoint {
29 /// Horizontal normalized coordinate in `[0..1]` (left = 0, right = 1).
30 pub x: f32,
31 /// Vertical normalized coordinate in Fusion Y-up `[0..1]` (bottom = 0, top = 1).
32 pub y: f32,
33 /// `true` = foreground / positive click or stroke; `false` = background / negative.
34 pub positive: bool,
35 /// Relative seed weight (default `1.0`).
36 pub weight: f32,
37}
38
39impl PromptPoint {
40 pub fn positive(x: f32, y: f32) -> Self {
41 Self { x, y, positive: true, weight: 1.0 }
42 }
43
44 pub fn negative(x: f32, y: f32) -> Self {
45 Self { x, y, positive: false, weight: 1.0 }
46 }
47
48 /// Converts Fusion Y-up `[0..1]` into top-down GPU texture UV `[0..1]`.
49 pub fn to_gpu_uv(self) -> [f32; 2] {
50 [self.x.clamp(0.0, 1.0), (1.0 - self.y).clamp(0.0, 1.0)]
51 }
52}
53
54/// Prompt mode for `AutoMatte`.
55#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
56#[repr(u32)]
57pub enum PromptMode {
58 /// Explicit positive/negative click points or strokes.
59 #[default]
60 ClickPoints = 0,
61 /// Automatic person / center-salient foreground heuristic.
62 AutoPerson = 1,
63 /// Automatic central object heuristic.
64 Object = 2,
65}
66
67impl PromptMode {
68 pub fn from_i32(v: i32) -> Self {
69 match v {
70 1 => Self::AutoPerson,
71 2 => Self::Object,
72 _ => Self::ClickPoints,
73 }
74 }
75}
76
77/// Neural / refinement quality tier for `AutoMatte`.
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
79#[repr(u32)]
80pub enum QualityTier {
81 /// Fast interactive single-pass refinement.
82 FastInteractive = 0,
83 /// Balanced MatAnyone 2 tier (default).
84 #[default]
85 MatAnyone2 = 1,
86 /// Hero Hair / VideoMaMa tier (extra edge-preserving bilateral pass).
87 HeroHair = 2,
88}
89
90impl QualityTier {
91 pub fn from_i32(v: i32) -> Self {
92 match v {
93 0 => Self::FastInteractive,
94 2 => Self::HeroHair,
95 _ => Self::MatAnyone2,
96 }
97 }
98}
99
100/// Final compositor output mode for `AutoMatte` & `MagicMask`.
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
102#[repr(u32)]
103pub enum OutputMode {
104 /// Premultiplied cutout `(fg_clean * alpha, alpha)`.
105 #[default]
106 PremultipliedCutout = 0,
107 /// Grayscale matte `(alpha, alpha, alpha, alpha)`.
108 MatteOnly = 1,
109 /// Ruby-magenta translucent overlay preview on top of source footage.
110 OverlayPreview = 2,
111}
112
113impl OutputMode {
114 pub fn from_i32(v: i32) -> Self {
115 match v {
116 1 => Self::MatteOnly,
117 2 => Self::OverlayPreview,
118 _ => Self::PremultipliedCutout,
119 }
120 }
121}
122
123/// Unified evaluated parameters for both `AutoMatte` and `MagicMask`.
124#[derive(Clone, Debug)]
125pub struct AutoMatteParams {
126 pub is_magic_mask: bool,
127 pub prompt_mode: PromptMode,
128 pub quality_tier: QualityTier,
129 pub points: Vec<PromptPoint>,
130 pub alpha_floor: f32,
131 pub alpha_ceiling: f32,
132 pub toe_gamma: f32,
133 pub decontaminate: f32,
134 pub matte_blur: f32,
135 pub matte_contract_expand: f32,
136 pub invert: bool,
137 pub output_mode: OutputMode,
138 pub cache_dir: Option<String>,
139 pub blend: f32,
140}
141
142impl AutoMatteParams {
143 /// Deterministic parameter hash for `Engine::NodeCache` keying.
144 pub fn hash_into(&self, hasher: &mut impl Hasher) {
145 self.is_magic_mask.hash(hasher);
146 self.prompt_mode.hash(hasher);
147 self.quality_tier.hash(hasher);
148 self.points.len().hash(hasher);
149 for pt in &self.points {
150 pt.x.to_bits().hash(hasher);
151 pt.y.to_bits().hash(hasher);
152 pt.positive.hash(hasher);
153 pt.weight.to_bits().hash(hasher);
154 }
155 self.alpha_floor.to_bits().hash(hasher);
156 self.alpha_ceiling.to_bits().hash(hasher);
157 self.toe_gamma.to_bits().hash(hasher);
158 self.decontaminate.to_bits().hash(hasher);
159 self.matte_blur.to_bits().hash(hasher);
160 self.matte_contract_expand.to_bits().hash(hasher);
161 self.invert.hash(hasher);
162 self.output_mode.hash(hasher);
163 self.cache_dir.hash(hasher);
164 self.blend.to_bits().hash(hasher);
165 }
166
167 /// Returns effective seeds for the built-in GPU fallback segmentation, synthesizing
168 /// center-salient + border background seeds when `PromptMode` is `AutoPerson` or `Object`
169 /// and no explicit points were specified.
170 pub fn effective_gpu_seeds(&self) -> Vec<PromptPoint> {
171 if !self.points.is_empty() {
172 return subsample_seeds(&self.points, MAX_GPU_SEEDS);
173 }
174 match self.prompt_mode {
175 PromptMode::ClickPoints => Vec::new(),
176 PromptMode::AutoPerson => vec![
177 PromptPoint::positive(0.50, 0.52),
178 PromptPoint::positive(0.50, 0.36),
179 PromptPoint::positive(0.50, 0.68),
180 PromptPoint::negative(0.04, 0.96),
181 PromptPoint::negative(0.96, 0.96),
182 PromptPoint::negative(0.04, 0.50),
183 PromptPoint::negative(0.96, 0.50),
184 PromptPoint::negative(0.04, 0.04),
185 PromptPoint::negative(0.96, 0.04),
186 ],
187 PromptMode::Object => vec![
188 PromptPoint::positive(0.50, 0.50),
189 PromptPoint::negative(0.04, 0.04),
190 PromptPoint::negative(0.96, 0.04),
191 PromptPoint::negative(0.04, 0.96),
192 PromptPoint::negative(0.96, 0.96),
193 ],
194 }
195 }
196}
197
198fn subsample_seeds(points: &[PromptPoint], max_total: usize) -> Vec<PromptPoint> {
199 if points.len() <= max_total {
200 return points.to_vec();
201 }
202 let pos: Vec<PromptPoint> = points.iter().copied().filter(|p| p.positive).collect();
203 let neg: Vec<PromptPoint> = points.iter().copied().filter(|p| !p.positive).collect();
204 let (pos_budget, neg_budget) = if neg.is_empty() {
205 (max_total, 0)
206 } else if pos.is_empty() {
207 (0, max_total)
208 } else {
209 let neg_share = neg.len().min(max_total / 3).max(1);
210 let pos_share = max_total.saturating_sub(neg_share).min(pos.len());
211 let rem = max_total.saturating_sub(pos_share + neg_share);
212 (pos_share, (neg_share + rem).min(neg.len()))
213 };
214 let mut out = Vec::with_capacity(max_total);
215 push_uniform_stride(&pos, pos_budget, &mut out);
216 push_uniform_stride(&neg, neg_budget, &mut out);
217 out
218}
219
220fn push_uniform_stride(src: &[PromptPoint], count: usize, dst: &mut Vec<PromptPoint>) {
221 if count == 0 || src.is_empty() {
222 return;
223 }
224 if src.len() <= count {
225 dst.extend_from_slice(src);
226 return;
227 }
228 for i in 0..count {
229 let idx = (i * (src.len() - 1)) / (count - 1).max(1);
230 dst.push(src[idx]);
231 }
232}
233
234fn eval_num_alias(
235 comp: &Comp,
236 node: &Node,
237 primary: &str,
238 fallback: &str,
239 time: f64,
240 default: f64,
241 expr: &ExprEngine,
242) -> f64 {
243 if node.inputs.contains_key(primary) {
244 comp.eval_number(node, primary, time, default, expr)
245 } else if node.inputs.contains_key(fallback) {
246 comp.eval_number(node, fallback, time, default, expr)
247 } else {
248 default
249 }
250}
251
252fn eval_output_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> OutputMode {
253 if node.inputs.contains_key("OutputMode") {
254 if let Some(s) = node.static_str("OutputMode") {
255 let lower = s.to_ascii_lowercase();
256 if lower.contains("matte") || lower.contains("alpha") {
257 return OutputMode::MatteOnly;
258 }
259 if lower.contains("overlay") || lower.contains("mask") {
260 return OutputMode::OverlayPreview;
261 }
262 if lower.contains("cutout") || lower.contains("premult") || lower.contains("final") {
263 return OutputMode::PremultipliedCutout;
264 }
265 }
266 let v = comp.eval_number(node, "OutputMode", time, 0.0, expr).round() as i32;
267 return OutputMode::from_i32(v);
268 }
269 if comp.eval_number(node, "MatteOnly", time, 0.0, expr) > 0.5 {
270 return OutputMode::MatteOnly;
271 }
272 if comp.eval_number(node, "ShowMask", time, 0.0, expr) > 0.5 {
273 return OutputMode::OverlayPreview;
274 }
275 OutputMode::PremultipliedCutout
276}
277
278fn read_cache_dir(node: &Node) -> Option<String> {
279 if let Some(dir) = node.static_str("CacheDir") {
280 let trimmed = dir.trim();
281 if !trimmed.is_empty() {
282 return Some(trimmed.to_owned());
283 }
284 }
285 if let Some(dir) = node.static_str("MatteDir") {
286 let trimmed = dir.trim();
287 if !trimmed.is_empty() {
288 return Some(trimmed.to_owned());
289 }
290 }
291 None
292}
293
294/// Extracts unified parameters for a Fission `AutoMatte` node.
295pub fn extract_auto_matte_params(
296 comp: &Comp,
297 node: &Node,
298 time: f64,
299 expr: &ExprEngine,
300) -> AutoMatteParams {
301 let prompt_mode = PromptMode::from_i32(
302 comp.eval_number(node, "PromptMode", time, 0.0, expr).round() as i32,
303 );
304 let quality_tier = QualityTier::from_i32(
305 comp.eval_number(node, "QualityTier", time, 1.0, expr).round() as i32,
306 );
307 let alpha_floor = comp
308 .eval_number(node, "AlphaFloor", time, DEFAULT_ALPHA_FLOOR as f64, expr)
309 .clamp(0.0, 0.95) as f32;
310 let alpha_ceiling = comp
311 .eval_number(node, "AlphaCeiling", time, DEFAULT_ALPHA_CEILING as f64, expr)
312 .clamp((alpha_floor + 0.01) as f64, 1.0) as f32;
313 let toe_gamma = comp
314 .eval_number(node, "ToeGamma", time, DEFAULT_TOE_GAMMA as f64, expr)
315 .clamp(0.1, 4.0) as f32;
316 let decontaminate = comp
317 .eval_number(node, "Decontaminate", time, 1.0, expr)
318 .clamp(0.0, 1.0) as f32;
319 let matte_blur = eval_num_alias(comp, node, "MatteBlur", "Blur", time, 0.0, expr).max(0.0) as f32;
320 let matte_contract_expand = eval_num_alias(
321 comp,
322 node,
323 "MatteContractExpand",
324 "ContractExpand",
325 time,
326 0.0,
327 expr,
328 ) as f32;
329 let invert = eval_num_alias(comp, node, "Invert", "InvertMatte", time, 0.0, expr) > 0.5;
330 let output_mode = eval_output_mode(comp, node, time, expr);
331 let blend = comp.eval_number(node, "Blend", time, 1.0, expr).clamp(0.0, 1.0) as f32;
332 let cache_dir = read_cache_dir(node);
333
334 let mut points = extract_auto_matte_points(comp, node, time, expr);
335 if points.is_empty() {
336 points = extract_magic_mask_strokes(comp, node, time);
337 }
338
339 AutoMatteParams {
340 is_magic_mask: false,
341 prompt_mode,
342 quality_tier,
343 points,
344 alpha_floor,
345 alpha_ceiling,
346 toe_gamma,
347 decontaminate,
348 matte_blur,
349 matte_contract_expand,
350 invert,
351 output_mode,
352 cache_dir,
353 blend,
354 }
355}
356
357/// Extracts unified parameters for a Fusion `MagicMask` node, mapping its real
358/// `MagicMaskStrokes` (`PosStrokes` / `NegStrokes`), `MatteBlur`, `MatteContractExpand`,
359/// `Invert`, `ShowMask` / `OutputMode` / `MatteOnly`, and `Blend` onto the `AutoMatte` pipeline.
360pub fn extract_magic_mask_params(
361 comp: &Comp,
362 node: &Node,
363 time: f64,
364 expr: &ExprEngine,
365) -> AutoMatteParams {
366 let points = {
367 let mut pts = extract_magic_mask_strokes(comp, node, time);
368 if pts.is_empty() {
369 pts = extract_auto_matte_points(comp, node, time, expr);
370 }
371 pts
372 };
373
374 let matte_blur = eval_num_alias(comp, node, "MatteBlur", "Blur", time, 0.0, expr).max(0.0) as f32;
375 let matte_contract_expand = eval_num_alias(
376 comp,
377 node,
378 "MatteContractExpand",
379 "ContractExpand",
380 time,
381 0.0,
382 expr,
383 ) as f32;
384 let invert = eval_num_alias(comp, node, "Invert", "InvertMatte", time, 0.0, expr) > 0.5;
385 let output_mode = eval_output_mode(comp, node, time, expr);
386 let blend = comp.eval_number(node, "Blend", time, 1.0, expr).clamp(0.0, 1.0) as f32;
387 let decontaminate = comp
388 .eval_number(node, "Decontaminate", time, 1.0, expr)
389 .clamp(0.0, 1.0) as f32;
390 let alpha_floor = comp
391 .eval_number(node, "AlphaFloor", time, DEFAULT_ALPHA_FLOOR as f64, expr)
392 .clamp(0.0, 0.95) as f32;
393 let alpha_ceiling = comp
394 .eval_number(node, "AlphaCeiling", time, DEFAULT_ALPHA_CEILING as f64, expr)
395 .clamp((alpha_floor + 0.01) as f64, 1.0) as f32;
396 let toe_gamma = comp
397 .eval_number(node, "ToeGamma", time, DEFAULT_TOE_GAMMA as f64, expr)
398 .clamp(0.1, 4.0) as f32;
399 let quality_tier = QualityTier::from_i32(
400 comp.eval_number(node, "QualityTier", time, 1.0, expr).round() as i32,
401 );
402 let cache_dir = read_cache_dir(node);
403
404 AutoMatteParams {
405 is_magic_mask: true,
406 prompt_mode: PromptMode::ClickPoints,
407 quality_tier,
408 points,
409 alpha_floor,
410 alpha_ceiling,
411 toe_gamma,
412 decontaminate,
413 matte_blur,
414 matte_contract_expand,
415 invert,
416 output_mode,
417 cache_dir,
418 blend,
419 }
420}
421
422/// Parses a Fusion `MagicMaskStrokes { PosStrokes = { ... }, NegStrokes = { ... } }` Lua table.
423///
424/// Supports both flat `{ { x, y }, ... }` point arrays (Fusion 18/19/20 `.comp` format) and
425/// nested stroke polyline arrays `{ { { x, y }, ... }, ... }`.
426pub fn parse_magic_mask_strokes_table(table: &LuaTable) -> Vec<PromptPoint> {
427 let mut out = Vec::new();
428 if let Some(pos) = table.get_table("PosStrokes") {
429 collect_point_list(pos, true, &mut out);
430 }
431 if let Some(neg) = table.get_table("NegStrokes") {
432 collect_point_list(neg, false, &mut out);
433 }
434 out
435}
436
437fn collect_point_list(table: &LuaTable, positive: bool, out: &mut Vec<PromptPoint>) {
438 // Check if `table` itself is a single `{ x, y }` pair
439 if let Some([x, y]) = read_xy_pair(table) {
440 out.push(PromptPoint { x, y, positive, weight: 1.0 });
441 return;
442 }
443 for val in table.positional_values() {
444 let Some(entry) = val.as_table() else { continue };
445 if let Some([x, y]) = read_xy_pair(entry) {
446 out.push(PromptPoint { x, y, positive, weight: 1.0 });
447 } else {
448 // Nested stroke polyline `{ { x1, y1 }, { x2, y2 }, ... }`
449 for sub in entry.positional_values() {
450 if let Some(pt_tbl) = sub.as_table() {
451 if let Some([x, y]) = read_xy_pair(pt_tbl) {
452 out.push(PromptPoint { x, y, positive, weight: 1.0 });
453 }
454 }
455 }
456 }
457 }
458}
459
460fn read_xy_pair(t: &LuaTable) -> Option<[f32; 2]> {
461 let x = t.get_index(1)?.as_f64()?;
462 let y = t.get_index(2)?.as_f64()?;
463 if x.is_finite() && y.is_finite() {
464 Some([x as f32, y as f32])
465 } else {
466 None
467 }
468}
469
470fn extract_magic_mask_strokes(comp: &Comp, node: &Node, time: f64) -> Vec<PromptPoint> {
471 // 1. Follow `Strokes = Input { SourceOp = "MagicMask1Strokes", Source = "Value" }` into
472 // `comp.raw_root.Tools[source_op].KeyFrames`
473 for stroke_input in ["Strokes", "LegacyStrokes"] {
474 if let Some(binding) = node.inputs.get(stroke_input) {
475 if let Some(src_op) = &binding.source_op {
476 if let Some(pts) = read_strokes_from_spline_tool(comp, src_op, time) {
477 if !pts.is_empty() {
478 return pts;
479 }
480 }
481 }
482 if let Some(ParamValue::Raw(LuaValue::Table(t))) = &binding.value {
483 let pts = parse_magic_mask_strokes_table(t);
484 if !pts.is_empty() {
485 return pts;
486 }
487 }
488 }
489 // Also check raw `Inputs.<stroke_input>.Value` directly
490 if let Some(val_tbl) = node
491 .raw
492 .get_table("Inputs")
493 .and_then(|i| i.get_table(stroke_input))
494 .and_then(|s| s.get_table("Value"))
495 {
496 let pts = parse_magic_mask_strokes_table(val_tbl);
497 if !pts.is_empty() {
498 return pts;
499 }
500 }
501 }
502 Vec::new()
503}
504
505fn read_strokes_from_spline_tool(comp: &Comp, spline_name: &str, time: f64) -> Option<Vec<PromptPoint>> {
506 let tools = comp.raw_root.as_ref()?.get_table("Tools")?;
507 let spline_tbl = find_tool_table_recursive(tools, spline_name)?;
508 let kfs = spline_tbl.get_table("KeyFrames")?;
509
510 let mut keyframes: Vec<(f64, &LuaTable)> = Vec::new();
511 for (k, v) in &kfs.entries {
512 let kf_time = match k {
513 LuaKey::Index(i) => *i as f64,
514 LuaKey::Number(n) => *n,
515 _ => continue,
516 };
517 if !kf_time.is_finite() {
518 continue;
519 }
520 let Some(kf_tbl) = v.as_table() else { continue };
521 let Some(val_tbl) = kf_tbl.get_table("Value") else { continue };
522 keyframes.push((kf_time, val_tbl));
523 }
524 if keyframes.is_empty() {
525 return None;
526 }
527 keyframes.sort_by(|a, b| a.0.total_cmp(&b.0));
528
529 // Pick closest keyframe <= time, or earliest keyframe if time precedes all keyframes
530 let chosen = keyframes
531 .iter()
532 .rev()
533 .find(|(t, _)| *t <= time + 1e-6)
534 .unwrap_or(&keyframes[0]);
535 Some(parse_magic_mask_strokes_table(chosen.1))
536}
537
538fn find_tool_table_recursive<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a LuaTable> {
539 if let Some(t) = tools.get_table(name) {
540 return Some(t);
541 }
542 for (_, val) in &tools.entries {
543 if let Some(t) = val.as_table() {
544 if let Some(inner) = t.get_table("Tools") {
545 if let Some(found) = find_tool_table_recursive(inner, name) {
546 return Some(found);
547 }
548 }
549 }
550 }
551 None
552}
553
554fn extract_auto_matte_points(
555 comp: &Comp,
556 node: &Node,
557 time: f64,
558 expr: &ExprEngine,
559) -> Vec<PromptPoint> {
560 let mut out = Vec::new();
561
562 // 1. `Points` input: table of `{ x, y, label }` OR string `"x,y,+;x,y,-"`
563 if let Some(binding) = node.inputs.get("Points") {
564 match &binding.value {
565 Some(ParamValue::Text(s)) | Some(ParamValue::FuId(s)) => {
566 parse_points_string(s, None, &mut out);
567 }
568 Some(ParamValue::Raw(LuaValue::Table(t))) => {
569 parse_mixed_points_table(t, &mut out);
570 }
571 Some(ParamValue::Point([x, y])) => {
572 out.push(PromptPoint::positive(*x as f32, *y as f32));
573 }
574 _ => {}
575 }
576 }
577
578 // 2. `PositivePoints` / `NegativePoints`: table of `{ {x, y}, ... }` OR string `"x,y;x,y"`
579 for (key, positive) in [("PositivePoints", true), ("NegativePoints", false)] {
580 if let Some(binding) = node.inputs.get(key) {
581 match &binding.value {
582 Some(ParamValue::Text(s)) | Some(ParamValue::FuId(s)) => {
583 parse_points_string(s, Some(positive), &mut out);
584 }
585 Some(ParamValue::Raw(LuaValue::Table(t))) => {
586 collect_point_list(t, positive, &mut out);
587 }
588 Some(ParamValue::Point([x, y])) => {
589 out.push(PromptPoint {
590 x: *x as f32,
591 y: *y as f32,
592 positive,
593 weight: 1.0,
594 });
595 }
596 _ => {}
597 }
598 }
599 }
600
601 // 3. Numbered point inputs `PosPoint1..16`, `NegPoint1..16`, `Point1..16` (animated-safe!)
602 for idx in 1..=16 {
603 let pos_name = format!("PosPoint{idx}");
604 if node.inputs.contains_key(&pos_name) {
605 let [x, y] = comp.eval_point(node, &pos_name, time, [0.5, 0.5], expr);
606 out.push(PromptPoint::positive(x as f32, y as f32));
607 }
608 let neg_name = format!("NegPoint{idx}");
609 if node.inputs.contains_key(&neg_name) {
610 let [x, y] = comp.eval_point(node, &neg_name, time, [0.5, 0.5], expr);
611 out.push(PromptPoint::negative(x as f32, y as f32));
612 }
613 let pt_name = format!("Point{idx}");
614 if node.inputs.contains_key(&pt_name) {
615 let [x, y] = comp.eval_point(node, &pt_name, time, [0.5, 0.5], expr);
616 let lbl_name = format!("Point{idx}Label");
617 let positive = comp.eval_number(node, &lbl_name, time, 1.0, expr) >= 0.5;
618 out.push(PromptPoint {
619 x: x as f32,
620 y: y as f32,
621 positive,
622 weight: 1.0,
623 });
624 }
625 }
626
627 out
628}
629
630fn parse_mixed_points_table(table: &LuaTable, out: &mut Vec<PromptPoint>) {
631 // Support `Points = { PosStrokes = ..., NegStrokes = ... }` as well
632 if table.get_table("PosStrokes").is_some() || table.get_table("NegStrokes").is_some() {
633 out.extend(parse_magic_mask_strokes_table(table));
634 return;
635 }
636 for val in table.positional_values() {
637 let Some(entry) = val.as_table() else { continue };
638 let Some([x, y]) = read_xy_pair(entry) else { continue };
639 let positive = match entry.get_index(3) {
640 Some(LuaValue::Number(n)) => *n > 0.0,
641 Some(LuaValue::Bool(b)) => *b,
642 Some(LuaValue::String(s)) => !s.starts_with('-') && !s.eq_ignore_ascii_case("neg"),
643 _ => entry.get_f64("Label").is_none_or(|n| n > 0.0),
644 };
645 out.push(PromptPoint { x, y, positive, weight: 1.0 });
646 }
647}
648
649fn parse_points_string(s: &str, forced_positive: Option<bool>, out: &mut Vec<PromptPoint>) {
650 for raw_item in s.split([';', '\n']) {
651 let item = raw_item.trim();
652 if item.is_empty() {
653 continue;
654 }
655 let parts: Vec<&str> = item
656 .split(|c: char| c == ',' || c.is_whitespace())
657 .filter(|t| !t.is_empty())
658 .collect();
659 if parts.len() < 2 {
660 continue;
661 }
662 let Ok(x) = parts[0].parse::<f32>() else { continue };
663 let Ok(y) = parts[1].parse::<f32>() else { continue };
664 if !x.is_finite() || !y.is_finite() {
665 continue;
666 }
667 let positive = if let Some(p) = forced_positive {
668 p
669 } else if let Some(tag) = parts.get(2) {
670 let t = tag.trim().to_ascii_lowercase();
671 !(t == "-" || t == "0" || t == "-1" || t == "neg" || t == "bg" || t == "false")
672 } else {
673 true
674 };
675 out.push(PromptPoint { x, y, positive, weight: 1.0 });
676 }
677}