diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs index de13ec34b..90ea1580e 100644 --- a/crates/ui-egui/src/dialogs_motion.rs +++ b/crates/ui-egui/src/dialogs_motion.rs @@ -438,8 +438,6 @@ fn joints_moving(app: &SolveApp) -> Vec<(usize, String, JointKind)> { /// The dialog's rows; true when Enter was pressed in a value. pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [SelInput]) -> bool { let t = Tokens::get(); - // Physical materials for the configuration table's Library: the library's, then the design's own. - let material_names = app.session.doc.material_names(); let mut enter = false; match k { Mo::ContactSet { name, check } => { @@ -499,201 +497,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [Sel ui.end_row(); } } - Mo::MotionStudy { name, study, steps, tracks, step, playing, looping, speed, shown, saved, error, analysis } => { - // An existing study opens to edit (and to chart); New makes another from these keys. - // By id: two studies may share a name. - let studies: Vec<(String, String)> = app.session.doc.assembly.studies.iter().map(|m| (m.id.to_string(), m.name.clone())).collect(); - if !studies.is_empty() { - let labels: Vec<&str> = std::iter::once("New study").chain(studies.iter().map(|(_, n)| n.as_str())).collect(); - let was = study.as_ref().and_then(|id| studies.iter().position(|(x, _)| x == id)).map_or(0, |i| i + 1); - let mut pick = was; - row_label(ui, "Study"); - combo(ui, "ms_study", &labels, &mut pick); - ui.end_row(); - if pick != was { - match pick.checked_sub(1).and_then(|i| studies.get(i)).map(|(id, _)| study_tracks(&app.session, id, true)) { - Some(Ok((id, n, st, t))) => { - (*study, *name, *steps, *tracks, *shown, *playing) = (Some(id.to_string()), n, st, t, None, false) - } - Some(Err(e)) => app.set_status(e, true), - None => *study = None, - } - } - } - row_label(ui, "Name"); - ui.text_edit_singleline(name); - ui.end_row(); - row_label(ui, "Steps"); - enter |= field(ui, steps); - ui.end_row(); - let total = steps.trim().parse::().unwrap_or(100).clamp(1, 100_000); - let moving = joints_moving(app); - if moving.is_empty() { - row_label(ui, ""); - ui.label(RichText::new(crate::i18n::tr_label("no joint that moves yet")).color(t.text_dim)); - ui.end_row(); - return enter; - } - // Playback: to start, step back, play/stop, step on, to end; loop and speed. - row_label(ui, "Playback"); - ui.horizontal(|ui| { - let last = f64::from(total); - if transport(ui, Transport::Start, "To the start").clicked() { - *step = 0.0; - *playing = false; - } - if transport(ui, Transport::Back, "Step back").clicked() { - *step = (step.round() - 1.0).max(0.0); - *playing = false; - } - let (what, tip) = if *playing { (Transport::Stop, "Stop") } else { (Transport::Play, "Play") }; - if transport(ui, what, tip).clicked() { - // Play from the start again when at the end. - if !*playing && step.round() >= last { - *step = 0.0; - } - *playing = !*playing; - } - if transport(ui, Transport::Forward, "Step on").clicked() { - *step = (step.round() + 1.0).min(last); - *playing = false; - } - if transport(ui, Transport::End, "To the end").clicked() { - *step = last; - *playing = false; - } - ui.add_space(6.0); - ui.checkbox(looping, crate::i18n::tr_label("Loop")); - let names: Vec = SPEEDS.iter().map(|x| format!("{x}×")).collect(); - let refs: Vec<&str> = names.iter().map(String::as_str).collect(); - combo(ui, "ms_speed", &refs, speed); - }); - ui.end_row(); - row_label(ui, "Step"); - ui.horizontal(|ui| { - ui.spacing_mut().slider_width = 260.0; - if ui.add(egui::Slider::new(step, 0.0..=f64::from(total)).integer().show_value(false)).dragged() { - *playing = false; - } - ui.label(RichText::new(format!("{} / {total}", step.round() as u32)).color(t.text_dim)); - }); - ui.end_row(); - if *playing { - let dt = f64::from(ui.input(|i| i.stable_dt).min(0.1)); - let fps = STEPS_PER_S * SPEEDS.get(*speed).copied().unwrap_or(1.0); - (*step, *playing) = advance(*step, dt * fps, total, *looping); - ui.ctx().request_repaint(); - } - // The chart and the collision check, by the timeline. - let study_now = study_params(&app.session, name, study.as_deref(), steps, tracks); - plot::rows(app, ui, analysis, &study_now, step, playing, total, inputs); - // Tracks: a row per keyed joint value, its keys on a strip under the steps. - let now = step.round() as u32; - let mut remove: Option = None; - for (ti, tr) in tracks.iter_mut().enumerate() { - let labels: Vec = moving.iter().map(|(_, n, _)| n.clone()).collect(); - let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); - let mut pos = moving.iter().position(|(i, _, _)| *i == tr.joint).unwrap_or(0); - row_label(ui, &format!("Track {}", ti + 1)); - ui.horizontal(|ui| { - combo(ui, &format!("ms_joint{ti}"), &refs, &mut pos); - if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Remove the track")).clicked() { - remove = Some(ti); - } - }); - ui.end_row(); - if let Some((ji, _, kind)) = moving.get(pos) { - tr.joint = *ji; - let dofs = kind.dofs(); - if dofs.len() > 1 { - row_label(ui, " Of"); - let caps: Vec<&str> = dofs.to_vec(); - combo(ui, &format!("ms_idx{ti}"), &caps, &mut tr.index); - ui.end_row(); - } else { - tr.index = 0; - } - } - row_label(ui, " Keys"); - key_strip(ui, tr, total, now, &t); - ui.end_row(); - // The key at this step, if any: its value. - if let Some(p) = tr.points.iter_mut().find(|(s, _)| *s == now) { - // The key's value (Enter commits it; OK makes the study). - row_label(ui, "Value"); - let _ = field(ui, &mut p.1); - ui.end_row(); - } - row_label(ui, ""); - ui.horizontal(|ui| { - if ui.small_button("Key here").on_hover_text("Add a key at this step with the joint's value now").clicked() - && !tr.points.iter().any(|(s, _)| *s == now) - { - let unit = app - .session - .doc - .assembly - .joints - .get(tr.joint) - .map(|j| if j.kind.is_angle(tr.index) { "deg" } else { "mm" }) - .unwrap_or("mm"); - tr.points.push((now, format!("0 {unit}"))); - tr.points.sort_by_key(|p| p.0); - } - if ui.small_button("Delete key").clicked() { - tr.points.retain(|(s, _)| *s != now); - } - }); - ui.end_row(); - } - if let Some(i) = remove { - tracks.remove(i); - } - row_label(ui, ""); - let mut export = false; - ui.horizontal(|ui| { - if ui.button(crate::i18n::tr_label("Add Key")).on_hover_text(crate::i18n::tr_label("Key a joint's value at this step")).clicked() - && let Some((ji, _, kind)) = moving.first() - { - let unit = if kind.is_angle(0) { "deg" } else { "mm" }; - tracks.push(Track { joint: *ji, index: 0, points: vec![(now, format!("0 {unit}"))] }); - } - export = ui - .button(crate::i18n::tr_label("Export Animation…")) - .on_hover_text(crate::i18n::tr_label("Save the study as an animated GIF, seen as the viewport shows it")) - .clicked(); - }); - ui.end_row(); - // Show the pose at this step (again when the step or the keys change). - let params = study_params(&app.session, name, study.as_deref(), steps, tracks); - if export { - match ¶ms { - Ok(p) => export_animation(app, p.clone(), name), - Err(e) => *error = Some(e.clone()), - } - } - let key = { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - format!("{params:?}").hash(&mut h); - h.finish() - }; - if *shown != Some((u64::from(now), key)) { - match params.and_then(|p| study_pose(app, &p, now)) { - Ok(m) => { - display(app, saved, m); - *error = None; - } - Err(e) => *error = Some(e), - } - *shown = Some((u64::from(now), key)); - } - if let Some(e) = error { - row_label(ui, ""); - ui.label(RichText::new(e.as_str()).color(t.text_dim)); - ui.end_row(); - } - } + Mo::MotionStudy { .. } => enter = motion_study_rows(app, ui, k, inputs, t), Mo::Explode { name, scale, shown, saved, error } => { row_label(ui, "Name"); ui.text_edit_singleline(name); @@ -719,321 +523,513 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [Sel ui.end_row(); } } - Mo::Configurations { new_row, error, rule_editor } => { - let revision = app.session.revision; - let v = rule_editor.table.as_ref().filter(|(r, _)| *r == revision).map(|(_, v)| v.clone()).unwrap_or_else(|| { - let value = app.session.execute("config.table", &json!({})).unwrap_or(Value::Null); - rule_editor.table = Some((revision, value.clone())); - value - }); - let mut tb = table(&v); - // Bare numbers show with their parameter's unit ("40" is 40 mm), as Fusion shows them. - let kinds = app.session.doc.all_param_exprs(); - for (_, vals) in &mut tb.rows { - for (c, val) in tb.columns.iter().zip(vals.iter_mut()) { - let (kind, n) = column_parts(c); - if kind == "param" - && val.trim().parse::().is_ok() - && let Some(unit) = app.session.doc.param(n).map(|parameter| parameter.unit.clone()).or_else(|| { - kinds.iter().find(|x| x.0 == n).and_then(|x| { - unit_of(x.2).map(|unit| { - if x.2 == solidcraft_engine::doc::expr::Kind::Length { app.session.doc.units.clone() } else { unit.to_string() } - }) - }) - }) - { - *val = format!("{} {unit}", val.trim()); - } - } - } - let run = |app: &mut SolveApp, error: &mut Option, id: &str, p: Value| { - *error = app.run(id, p).err(); - }; - egui::ScrollArea::horizontal().id_salt("configuration_columns").auto_shrink([false, true]).show(ui, |ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); - egui::Grid::new("configuration_table").num_columns(2).min_col_width(210.0).spacing(vec2(10.0, 8.0)).show(ui, |ui| { - // Header. - ui.label(RichText::new(crate::i18n::tr_label("Configuration")).strong()); - ui.horizontal(|ui| { - for c in &tb.columns { - ui.allocate_ui_with_layout(vec2(190.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { - let (kind, n) = column_parts(c); - let label = match kind { - "material" => format!("Material: {n}"), - "appearance" => format!("Appearance: {n}"), - "suppress" => format!("Suppress: {n}"), - _ => n.to_string(), - }; - let label = v["targets"] - .as_array() - .and_then(|targets| targets.iter().find(|target| target["key"].as_str() == Some(c))) - .and_then(|target| target["label"].as_str()) - .filter(|_| matches!(kind, "component_appearance" | "face_appearance")) - .map(str::to_string) - .unwrap_or(label); - ui.add_sized(vec2(156.0, 22.0), egui::Label::new(RichText::new(label).strong()).truncate()).on_hover_text(c); - if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Remove the column")).clicked() { - let key = if kind == "suppress" { "feature" } else { kind }; - run( - app, - error, - "config.column", - json!({ key: if kind == "face_appearance" {c.as_str()} else {n}, "delete": true }), - ); - } - }); - } - }); - ui.end_row(); - for (name, vals) in &tb.rows { - let active = tb.active.as_deref() == Some(name.as_str()); - ui.horizontal(|ui| { - ui.add_sized( - vec2(100.0, 22.0), - egui::Label::new(if active { RichText::new(name).strong() } else { RichText::new(name) }).truncate(), - ) - .on_hover_text(name); - if active { - ui.label(RichText::new(crate::i18n::tr_label("Active")).color(t.accent)); - if v.get("matches").and_then(Value::as_bool) == Some(false) && ui.button("Apply").clicked() { - run(app, error, "config.activate", json!({ "row": name })); - } - } else if ui.button(crate::i18n::tr_label("Activate")).clicked() { - run(app, error, "config.activate", json!({ "row": name })); - } - }); - ui.horizontal(|ui| { - for (c, val) in tb.columns.iter().zip(vals) { - ui.allocate_ui_with_layout(vec2(190.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { - let (kind, _) = column_parts(c); - let appearance = matches!(kind, "appearance" | "component_appearance" | "face_appearance"); - let shown = if appearance { - solidcraft_engine::doc::config::appearance_cell(val) - .ok() - .flatten() - .filter(|look| solidcraft_engine::doc::appearance::library(&look.name).as_ref() == Some(look)) - .map(|look| look.name) - .unwrap_or_else(|| val.clone()) - } else { - val.clone() - }; - let style = kind == "material" || appearance; - if style { - let mut choice = None; - ui.menu_button("Library", |ui| { - if ui - .button(if kind == "appearance" { - "Follow material" - } else if appearance { - "Follow inherited appearance" - } else { - "Default material" - }) - .clicked() - { - choice = Some("Default".to_string()); - ui.close(); - } - if kind == "material" { - for name in material_names.iter().filter(|n| *n != "Default") { - if ui.button(name).clicked() { - choice = Some(name.to_string()); - ui.close(); - } - } - } else { - for (name, _, _) in solidcraft_engine::doc::appearance::LIBRARY { - if ui.button(name).clicked() { - choice = Some(name.to_string()); - ui.close(); - } - } - } - }); - if let Some(choice) = choice { - run(app, error, "config.row", json!({"name": name, "values": { c: choice }})); - } - } - let id = (name.clone(), c.clone()); - let mut text = rule_editor.drafts.get(&id).cloned().unwrap_or_else(|| shown.clone()); - let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(if style { 106.0 } else { 164.0 })); - if r.changed() { - rule_editor.drafts.insert(id.clone(), text.clone()); - } - if r.lost_focus() { - rule_editor.drafts.remove(&id); - if text != shown { - run(app, error, "config.row", json!({"name": name, "values": { c: cell_value(c, &text) }})); - } - } - }); - } - if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Delete the row")).clicked() { - run(app, error, "config.row", json!({"name": name, "delete": true})); - } - }); - ui.end_row(); - } - }); - }); - // New row (a copy of the active one) and new column. - ui.horizontal(|ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); - ui.add(egui::TextEdit::singleline(new_row).hint_text(crate::i18n::tr_label("new configuration")).desired_width(160.0)); - if ui - .button(crate::i18n::tr_label("Add Row")) - .on_hover_text(crate::i18n::tr_label("A new configuration, a copy of the active one")) - .clicked() - { - let name = if new_row.trim().is_empty() { - (tb.rows.len() + 1..).map(|k| format!("Configuration{k}")).find(|n| !tb.rows.iter().any(|r| &r.0 == n)).unwrap_or_default() - } else { - new_row.trim().to_string() - }; - let mut p = json!({ "name": name }); - if let Some(a) = &tb.active { - p["from"] = json!(a); - } - run(app, error, "config.row", p); - new_row.clear(); - } - // A column: a parameter's value or a feature's suppression. - let mut options: Vec<(String, Value)> = Vec::new(); - for p in app.session.doc.all_param_exprs() { - if !tb.columns.contains(&format!("param:{}", p.0)) { - options.push((format!("{} (parameter)", p.0), json!({ "param": p.0 }))); - } - } - for f in &app.session.doc.features { - if !tb.columns.contains(&format!("suppress:{}", f.name)) { - options.push((format!("Suppress {}", f.name), json!({ "feature": f.name }))); - } - } - for body in &app.session.model.state().bodies { - for kind in ["material", "appearance"] { - if !tb.columns.contains(&format!("{kind}:{}", body.name)) { - options.push((format!("{} ({kind})", body.name), json!({kind: body.name}))); - } - } - } - for component in &app.session.doc.components { - if component.id != 0 && !tb.columns.contains(&format!("component_appearance:{}", component.id)) { - options.push((format!("{} (component appearance)", component.name), json!({"component_appearance":component.id}))); - } - } - for selected in &app.session.selection { - if let solidcraft_engine::Sel::Face { body, point, .. } = selected { - options - .push((format!("Selected face on {body} (shared appearance)"), json!({"face_appearance":{"body":body,"point":point}}))); - } - } - let mut pick: Option = None; - ui.menu_button("Add Column", |ui| { - egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { - for (label, p) in &options { - if ui.button(label.as_str()).clicked() { - pick = Some(p.clone()); - ui.close(); - } - } - ui.menu_button("Face Appearance", |ui| { - ui.label(crate::i18n::tr_label("Semantic faces share their appearance across instances.")); - let state = app.session.model.state(); - for body in &state.bodies { - if body.body.is_mesh() { - continue; - } - ui.menu_button(format!("Faces on {}", body.name), |ui| { - if let Ok(faces) = body.body.faces((body.body.size() * 2e-3).max(1e-3)) { - let mut seen = std::collections::BTreeSet::new(); - let mesh = body.mesh(); - let mut points = std::collections::BTreeMap::new(); - for (triangle, index) in mesh.triangles.iter().zip(&mesh.tri_face) { - if let std::collections::btree_map::Entry::Vacant(entry) = points.entry(*index as usize) - && let Some([a, b, c]) = mesh.tri(triangle) - { - entry.insert((a + b + c) * (1. / 3.)); - } - } - for face in faces { - // A curved face centroid can lie on another surface. - // Pick an interior triangle point on this actual face. - let Some(point) = points.get(&face.index).copied() else { continue }; - let Ok(target) = app.session.doc.configuration_face_target(body, face.index, point) else { continue }; - let supported = if target.certificate.is_some() { - // Capture read this exact face's current source certificate. - // Enumerate its pieces once in the command, not per menu face. - app.session.doc.certify_config_face(&target).is_ok() - } else { - app.session.doc.configuration_face_indices(body, &target).is_ok() - }; - if !supported || !seen.insert(target.name.clone()) { - continue; - } - let Some((_, role)) = target.name.split_once(':') else { continue }; - if ui.button(role).clicked() { - pick = Some(json!({"face_appearance":{"target":target}})); - ui.close(); - } - } - } - }); - } - }); - }); - }); - if let Some(p) = pick { - // The first column starts the table (with a Default row of the current values). - let (id, p) = if tb.columns.is_empty() { - ( - "config.configure", - if let Some(n) = p.get("param") { - json!({ "params": [n] }) - } else if let Some(n) = p.get("feature") { - json!({ "features": [n] }) - } else if let Some(n) = p.get("material") { - json!({ "materials": [n] }) - } else if let Some(n) = p.get("component_appearance") { - json!({ "component_appearances": [n] }) - } else if let Some(n) = p.get("face_appearance") { - json!({ "face_appearances": [n] }) - } else { - json!({ "appearances": [p.get("appearance")] }) - }, - ) - } else { - ("config.column", p) - }; - run(app, error, id, p); - } - }); - ui.end_row(); - configuration_rules_ui::show(ui, app, error, rule_editor); - if let Some(styles) = v["style_status"].as_array() { - for style in styles.iter().filter(|style| style["dormant"].as_bool() == Some(true)) { - ui.add( - egui::Label::new(format!( - "{}: appearance dormant while its feature is suppressed", - style["target"].as_str().unwrap_or("Face") - )) - .wrap(), - ); - } - } - if let Some(message) = v["style_error"].as_str() { - ui.add(egui::Label::new(RichText::new(message).color(t.error)).wrap()); - } - if let Some(e) = error { - ui.label(""); - ui.label(RichText::new(e.as_str()).color(t.error)); - ui.end_row(); - } - } + Mo::Configurations { new_row, error, rule_editor } => configurations_rows(app, ui, new_row, error, rule_editor, t), } let _ = inputs; enter } +/// The Motion Study rows; true when Enter was pressed in a value. +fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [SelInput], t: Tokens) -> bool { + let Mo::MotionStudy { name, study, steps, tracks, step, playing, looping, speed, shown, saved, error, analysis } = k else { return false }; + let mut enter = false; + // An existing study opens to edit (and to chart); New makes another from these keys. + // By id: two studies may share a name. + let studies: Vec<(String, String)> = app.session.doc.assembly.studies.iter().map(|m| (m.id.to_string(), m.name.clone())).collect(); + if !studies.is_empty() { + let labels: Vec<&str> = std::iter::once("New study").chain(studies.iter().map(|(_, n)| n.as_str())).collect(); + let was = study.as_ref().and_then(|id| studies.iter().position(|(x, _)| x == id)).map_or(0, |i| i + 1); + let mut pick = was; + row_label(ui, "Study"); + combo(ui, "ms_study", &labels, &mut pick); + ui.end_row(); + if pick != was { + match pick.checked_sub(1).and_then(|i| studies.get(i)).map(|(id, _)| study_tracks(&app.session, id, true)) { + Some(Ok((id, n, st, t))) => (*study, *name, *steps, *tracks, *shown, *playing) = (Some(id.to_string()), n, st, t, None, false), + Some(Err(e)) => app.set_status(e, true), + None => *study = None, + } + } + } + row_label(ui, "Name"); + ui.text_edit_singleline(name); + ui.end_row(); + row_label(ui, "Steps"); + enter |= field(ui, steps); + ui.end_row(); + let total = steps.trim().parse::().unwrap_or(100).clamp(1, 100_000); + let moving = joints_moving(app); + if moving.is_empty() { + row_label(ui, ""); + ui.label(RichText::new(crate::i18n::tr_label("no joint that moves yet")).color(t.text_dim)); + ui.end_row(); + return enter; + } + // Playback: to start, step back, play/stop, step on, to end; loop and speed. + row_label(ui, "Playback"); + ui.horizontal(|ui| { + let last = f64::from(total); + if transport(ui, Transport::Start, "To the start").clicked() { + *step = 0.0; + *playing = false; + } + if transport(ui, Transport::Back, "Step back").clicked() { + *step = (step.round() - 1.0).max(0.0); + *playing = false; + } + let (what, tip) = if *playing { (Transport::Stop, "Stop") } else { (Transport::Play, "Play") }; + if transport(ui, what, tip).clicked() { + // Play from the start again when at the end. + if !*playing && step.round() >= last { + *step = 0.0; + } + *playing = !*playing; + } + if transport(ui, Transport::Forward, "Step on").clicked() { + *step = (step.round() + 1.0).min(last); + *playing = false; + } + if transport(ui, Transport::End, "To the end").clicked() { + *step = last; + *playing = false; + } + ui.add_space(6.0); + ui.checkbox(looping, crate::i18n::tr_label("Loop")); + let names: Vec = SPEEDS.iter().map(|x| format!("{x}×")).collect(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + combo(ui, "ms_speed", &refs, speed); + }); + ui.end_row(); + row_label(ui, "Step"); + ui.horizontal(|ui| { + ui.spacing_mut().slider_width = 260.0; + if ui.add(egui::Slider::new(step, 0.0..=f64::from(total)).integer().show_value(false)).dragged() { + *playing = false; + } + ui.label(RichText::new(format!("{} / {total}", step.round() as u32)).color(t.text_dim)); + }); + ui.end_row(); + if *playing { + let dt = f64::from(ui.input(|i| i.stable_dt).min(0.1)); + let fps = STEPS_PER_S * SPEEDS.get(*speed).copied().unwrap_or(1.0); + (*step, *playing) = advance(*step, dt * fps, total, *looping); + ui.ctx().request_repaint(); + } + // The chart and the collision check, by the timeline. + let study_now = study_params(&app.session, name, study.as_deref(), steps, tracks); + plot::rows(app, ui, analysis, &study_now, step, playing, total, inputs); + // Tracks: a row per keyed joint value, its keys on a strip under the steps. + let now = step.round() as u32; + let mut remove: Option = None; + for (ti, tr) in tracks.iter_mut().enumerate() { + let labels: Vec = moving.iter().map(|(_, n, _)| n.clone()).collect(); + let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); + let mut pos = moving.iter().position(|(i, _, _)| *i == tr.joint).unwrap_or(0); + row_label(ui, &format!("Track {}", ti + 1)); + ui.horizontal(|ui| { + combo(ui, &format!("ms_joint{ti}"), &refs, &mut pos); + if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Remove the track")).clicked() { + remove = Some(ti); + } + }); + ui.end_row(); + if let Some((ji, _, kind)) = moving.get(pos) { + tr.joint = *ji; + let dofs = kind.dofs(); + if dofs.len() > 1 { + row_label(ui, " Of"); + let caps: Vec<&str> = dofs.to_vec(); + combo(ui, &format!("ms_idx{ti}"), &caps, &mut tr.index); + ui.end_row(); + } else { + tr.index = 0; + } + } + row_label(ui, " Keys"); + key_strip(ui, tr, total, now, &t); + ui.end_row(); + // The key at this step, if any: its value. + if let Some(p) = tr.points.iter_mut().find(|(s, _)| *s == now) { + // The key's value (Enter commits it; OK makes the study). + row_label(ui, "Value"); + let _ = field(ui, &mut p.1); + ui.end_row(); + } + row_label(ui, ""); + ui.horizontal(|ui| { + if ui.small_button("Key here").on_hover_text("Add a key at this step with the joint's value now").clicked() + && !tr.points.iter().any(|(s, _)| *s == now) + { + let unit = + app.session.doc.assembly.joints.get(tr.joint).map(|j| if j.kind.is_angle(tr.index) { "deg" } else { "mm" }).unwrap_or("mm"); + tr.points.push((now, format!("0 {unit}"))); + tr.points.sort_by_key(|p| p.0); + } + if ui.small_button("Delete key").clicked() { + tr.points.retain(|(s, _)| *s != now); + } + }); + ui.end_row(); + } + if let Some(i) = remove { + tracks.remove(i); + } + row_label(ui, ""); + let mut export = false; + ui.horizontal(|ui| { + if ui.button(crate::i18n::tr_label("Add Key")).on_hover_text(crate::i18n::tr_label("Key a joint's value at this step")).clicked() + && let Some((ji, _, kind)) = moving.first() + { + let unit = if kind.is_angle(0) { "deg" } else { "mm" }; + tracks.push(Track { joint: *ji, index: 0, points: vec![(now, format!("0 {unit}"))] }); + } + export = ui + .button(crate::i18n::tr_label("Export Animation…")) + .on_hover_text(crate::i18n::tr_label("Save the study as an animated GIF, seen as the viewport shows it")) + .clicked(); + }); + ui.end_row(); + // Show the pose at this step (again when the step or the keys change). + let params = study_params(&app.session, name, study.as_deref(), steps, tracks); + if export { + match ¶ms { + Ok(p) => export_animation(app, p.clone(), name), + Err(e) => *error = Some(e.clone()), + } + } + let key = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + format!("{params:?}").hash(&mut h); + h.finish() + }; + if *shown != Some((u64::from(now), key)) { + match params.and_then(|p| study_pose(app, &p, now)) { + Ok(m) => { + display(app, saved, m); + *error = None; + } + Err(e) => *error = Some(e), + } + *shown = Some((u64::from(now), key)); + } + if let Some(e) = error { + row_label(ui, ""); + ui.label(RichText::new(e.as_str()).color(t.text_dim)); + ui.end_row(); + } + enter +} + +/// The Configurations table, its rules and errors. +fn configurations_rows( + app: &mut SolveApp, + ui: &mut egui::Ui, + new_row: &mut String, + error: &mut Option, + rule_editor: &mut configuration_rules_ui::Editor, + t: Tokens, +) { + // Physical materials for the configuration table's Library: the library's, then the design's own. + let material_names = app.session.doc.material_names(); + let revision = app.session.revision; + let v = rule_editor.table.as_ref().filter(|(r, _)| *r == revision).map(|(_, v)| v.clone()).unwrap_or_else(|| { + let value = app.session.execute("config.table", &json!({})).unwrap_or(Value::Null); + rule_editor.table = Some((revision, value.clone())); + value + }); + let mut tb = table(&v); + // Bare numbers show with their parameter's unit ("40" is 40 mm), as Fusion shows them. + let kinds = app.session.doc.all_param_exprs(); + for (_, vals) in &mut tb.rows { + for (c, val) in tb.columns.iter().zip(vals.iter_mut()) { + let (kind, n) = column_parts(c); + if kind == "param" + && val.trim().parse::().is_ok() + && let Some(unit) = app.session.doc.param(n).map(|parameter| parameter.unit.clone()).or_else(|| { + kinds.iter().find(|x| x.0 == n).and_then(|x| { + unit_of(x.2).map(|unit| { + if x.2 == solidcraft_engine::doc::expr::Kind::Length { app.session.doc.units.clone() } else { unit.to_string() } + }) + }) + }) + { + *val = format!("{} {unit}", val.trim()); + } + } + } + let run = |app: &mut SolveApp, error: &mut Option, id: &str, p: Value| { + *error = app.run(id, p).err(); + }; + egui::ScrollArea::horizontal().id_salt("configuration_columns").auto_shrink([false, true]).show(ui, |ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + egui::Grid::new("configuration_table").num_columns(2).min_col_width(210.0).spacing(vec2(10.0, 8.0)).show(ui, |ui| { + // Header. + ui.label(RichText::new(crate::i18n::tr_label("Configuration")).strong()); + ui.horizontal(|ui| { + for c in &tb.columns { + ui.allocate_ui_with_layout(vec2(190.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + let (kind, n) = column_parts(c); + let label = match kind { + "material" => format!("Material: {n}"), + "appearance" => format!("Appearance: {n}"), + "suppress" => format!("Suppress: {n}"), + _ => n.to_string(), + }; + let label = v["targets"] + .as_array() + .and_then(|targets| targets.iter().find(|target| target["key"].as_str() == Some(c))) + .and_then(|target| target["label"].as_str()) + .filter(|_| matches!(kind, "component_appearance" | "face_appearance")) + .map(str::to_string) + .unwrap_or(label); + ui.add_sized(vec2(156.0, 22.0), egui::Label::new(RichText::new(label).strong()).truncate()).on_hover_text(c); + if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Remove the column")).clicked() { + let key = if kind == "suppress" { "feature" } else { kind }; + run(app, error, "config.column", json!({ key: if kind == "face_appearance" {c.as_str()} else {n}, "delete": true })); + } + }); + } + }); + ui.end_row(); + for (name, vals) in &tb.rows { + let active = tb.active.as_deref() == Some(name.as_str()); + ui.horizontal(|ui| { + ui.add_sized( + vec2(100.0, 22.0), + egui::Label::new(if active { RichText::new(name).strong() } else { RichText::new(name) }).truncate(), + ) + .on_hover_text(name); + if active { + ui.label(RichText::new(crate::i18n::tr_label("Active")).color(t.accent)); + if v.get("matches").and_then(Value::as_bool) == Some(false) && ui.button("Apply").clicked() { + run(app, error, "config.activate", json!({ "row": name })); + } + } else if ui.button(crate::i18n::tr_label("Activate")).clicked() { + run(app, error, "config.activate", json!({ "row": name })); + } + }); + ui.horizontal(|ui| { + for (c, val) in tb.columns.iter().zip(vals) { + ui.allocate_ui_with_layout(vec2(190.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + let (kind, _) = column_parts(c); + let appearance = matches!(kind, "appearance" | "component_appearance" | "face_appearance"); + let shown = if appearance { + solidcraft_engine::doc::config::appearance_cell(val) + .ok() + .flatten() + .filter(|look| solidcraft_engine::doc::appearance::library(&look.name).as_ref() == Some(look)) + .map(|look| look.name) + .unwrap_or_else(|| val.clone()) + } else { + val.clone() + }; + let style = kind == "material" || appearance; + if style { + let mut choice = None; + ui.menu_button("Library", |ui| { + if ui + .button(if kind == "appearance" { + "Follow material" + } else if appearance { + "Follow inherited appearance" + } else { + "Default material" + }) + .clicked() + { + choice = Some("Default".to_string()); + ui.close(); + } + if kind == "material" { + for name in material_names.iter().filter(|n| *n != "Default") { + if ui.button(name).clicked() { + choice = Some(name.to_string()); + ui.close(); + } + } + } else { + for (name, _, _) in solidcraft_engine::doc::appearance::LIBRARY { + if ui.button(name).clicked() { + choice = Some(name.to_string()); + ui.close(); + } + } + } + }); + if let Some(choice) = choice { + run(app, error, "config.row", json!({"name": name, "values": { c: choice }})); + } + } + let id = (name.clone(), c.clone()); + let mut text = rule_editor.drafts.get(&id).cloned().unwrap_or_else(|| shown.clone()); + let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(if style { 106.0 } else { 164.0 })); + if r.changed() { + rule_editor.drafts.insert(id.clone(), text.clone()); + } + if r.lost_focus() { + rule_editor.drafts.remove(&id); + if text != shown { + run(app, error, "config.row", json!({"name": name, "values": { c: cell_value(c, &text) }})); + } + } + }); + } + if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Delete the row")).clicked() { + run(app, error, "config.row", json!({"name": name, "delete": true})); + } + }); + ui.end_row(); + } + }); + }); + // New row (a copy of the active one) and new column. + ui.horizontal(|ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + ui.add(egui::TextEdit::singleline(new_row).hint_text(crate::i18n::tr_label("new configuration")).desired_width(160.0)); + if ui.button(crate::i18n::tr_label("Add Row")).on_hover_text(crate::i18n::tr_label("A new configuration, a copy of the active one")).clicked() + { + let name = if new_row.trim().is_empty() { + (tb.rows.len() + 1..).map(|k| format!("Configuration{k}")).find(|n| !tb.rows.iter().any(|r| &r.0 == n)).unwrap_or_default() + } else { + new_row.trim().to_string() + }; + let mut p = json!({ "name": name }); + if let Some(a) = &tb.active { + p["from"] = json!(a); + } + run(app, error, "config.row", p); + new_row.clear(); + } + // A column: a parameter's value or a feature's suppression. + let mut options: Vec<(String, Value)> = Vec::new(); + for p in app.session.doc.all_param_exprs() { + if !tb.columns.contains(&format!("param:{}", p.0)) { + options.push((format!("{} (parameter)", p.0), json!({ "param": p.0 }))); + } + } + for f in &app.session.doc.features { + if !tb.columns.contains(&format!("suppress:{}", f.name)) { + options.push((format!("Suppress {}", f.name), json!({ "feature": f.name }))); + } + } + for body in &app.session.model.state().bodies { + for kind in ["material", "appearance"] { + if !tb.columns.contains(&format!("{kind}:{}", body.name)) { + options.push((format!("{} ({kind})", body.name), json!({kind: body.name}))); + } + } + } + for component in &app.session.doc.components { + if component.id != 0 && !tb.columns.contains(&format!("component_appearance:{}", component.id)) { + options.push((format!("{} (component appearance)", component.name), json!({"component_appearance":component.id}))); + } + } + for selected in &app.session.selection { + if let solidcraft_engine::Sel::Face { body, point, .. } = selected { + options.push((format!("Selected face on {body} (shared appearance)"), json!({"face_appearance":{"body":body,"point":point}}))); + } + } + let mut pick: Option = None; + ui.menu_button("Add Column", |ui| { + egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { + for (label, p) in &options { + if ui.button(label.as_str()).clicked() { + pick = Some(p.clone()); + ui.close(); + } + } + ui.menu_button("Face Appearance", |ui| { + ui.label(crate::i18n::tr_label("Semantic faces share their appearance across instances.")); + let state = app.session.model.state(); + for body in &state.bodies { + if body.body.is_mesh() { + continue; + } + ui.menu_button(format!("Faces on {}", body.name), |ui| { + if let Ok(faces) = body.body.faces((body.body.size() * 2e-3).max(1e-3)) { + let mut seen = std::collections::BTreeSet::new(); + let mesh = body.mesh(); + let mut points = std::collections::BTreeMap::new(); + for (triangle, index) in mesh.triangles.iter().zip(&mesh.tri_face) { + if let std::collections::btree_map::Entry::Vacant(entry) = points.entry(*index as usize) + && let Some([a, b, c]) = mesh.tri(triangle) + { + entry.insert((a + b + c) * (1. / 3.)); + } + } + for face in faces { + // A curved face centroid can lie on another surface. + // Pick an interior triangle point on this actual face. + let Some(point) = points.get(&face.index).copied() else { continue }; + let Ok(target) = app.session.doc.configuration_face_target(body, face.index, point) else { continue }; + let supported = if target.certificate.is_some() { + // Capture read this exact face's current source certificate. + // Enumerate its pieces once in the command, not per menu face. + app.session.doc.certify_config_face(&target).is_ok() + } else { + app.session.doc.configuration_face_indices(body, &target).is_ok() + }; + if !supported || !seen.insert(target.name.clone()) { + continue; + } + let Some((_, role)) = target.name.split_once(':') else { continue }; + if ui.button(role).clicked() { + pick = Some(json!({"face_appearance":{"target":target}})); + ui.close(); + } + } + } + }); + } + }); + }); + }); + if let Some(p) = pick { + // The first column starts the table (with a Default row of the current values). + let (id, p) = if tb.columns.is_empty() { + ( + "config.configure", + if let Some(n) = p.get("param") { + json!({ "params": [n] }) + } else if let Some(n) = p.get("feature") { + json!({ "features": [n] }) + } else if let Some(n) = p.get("material") { + json!({ "materials": [n] }) + } else if let Some(n) = p.get("component_appearance") { + json!({ "component_appearances": [n] }) + } else if let Some(n) = p.get("face_appearance") { + json!({ "face_appearances": [n] }) + } else { + json!({ "appearances": [p.get("appearance")] }) + }, + ) + } else { + ("config.column", p) + }; + run(app, error, id, p); + } + }); + ui.end_row(); + configuration_rules_ui::show(ui, app, error, rule_editor); + if let Some(styles) = v["style_status"].as_array() { + for style in styles.iter().filter(|style| style["dormant"].as_bool() == Some(true)) { + ui.add( + egui::Label::new(format!("{}: appearance dormant while its feature is suppressed", style["target"].as_str().unwrap_or("Face"))) + .wrap(), + ); + } + } + if let Some(message) = v["style_error"].as_str() { + ui.add(egui::Label::new(RichText::new(message).color(t.error)).wrap()); + } + if let Some(e) = error { + ui.label(""); + ui.label(RichText::new(e.as_str()).color(t.error)); + ui.end_row(); + } +} + /// A JSON name or id as text. fn name_of(v: &Value) -> String { v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())