diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index 93a7d2982..4ac55c35e 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -19,6 +19,9 @@ use crate::schema::motion::{ ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo, MotionStudyParams, MotionStudySaved, }; +use crate::schema::motion_play::{ + DriveReport, ExportParams, PartPose, PlayParams, Pose, StudyExport, StudyExported, StudyPlayed, StudySample, UnmovedJoint, +}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -50,6 +53,8 @@ const CONTACT_EDIT_CONTRACT: TypedContract = TypedContract::n const STUDY_CONTRACT: TypedContract = TypedContract::new(); const STUDY_DELETE_CONTRACT: TypedContract = TypedContract::new(); const STUDY_LIST_CONTRACT: TypedContract = TypedContract::new(); +const PLAY_CONTRACT: TypedContract = TypedContract::new(); +const EXPORT_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("contact.enable_sets", "Enable Contact Sets", crate::checked!("contact.enable_sets", enable_sets)) @@ -105,15 +110,21 @@ pub static COMMANDS: &[CommandSpec] = &[ "name?; study? (edit an existing one); steps? (timeline length, default 100); keys: [{joint, index?, points: [[step, value], …]}] \ (values: degrees for angles, mm for distances, or expressions)", ), - CommandSpec::new("motion.play", "Play Motion Study", play).icon("play").params( - "study: id|name; step (0…steps) — sets the joints to the study's values there (contact sets stop them); quiet?: bool \ + CommandSpec::new("motion.play", "Play Motion Study", crate::checked!("motion.play", play)) + .icon("play") + .contract(&PLAY_CONTRACT) + .output(output_schema_for::) + .params( + "study: id|name; step (0…steps) — sets the joints to the study's values there (contact sets stop them); quiet?: bool \ (positions of only the occurrences that moved) → values: [{joint, values: [{name, value, unit}]}], positions, moved: whether \ any occurrence moved, unmoved: [{joint, name, reason}] (keyed joints that can move nothing, such as a chain joined to \ nothing grounded)", - ), - CommandSpec::new("motion.export", "Export Motion Study", export) + ), + CommandSpec::new("motion.export", "Export Motion Study", crate::checked!("motion.export", export)) .icon("export") .noundo() + .contract(&EXPORT_CONTRACT) + .output(output_schema_for::) .params("study; samples? (default steps + 1); path? (.json or .csv) → occurrence positions per step (the design is not changed)"), CommandSpec::new("motion.export_animation", "Export Motion Animation", animation::export).icon("export").noundo().params( "study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?, or \ @@ -798,8 +809,15 @@ pub(super) fn moved<'a>(before: &'a [(String, Mat)], after: &'a [(String, Mat)]) after.iter().zip(before).filter(|((_, a), (_, b))| a.iter().flatten().zip(b.iter().flatten()).any(|(x, y)| (x - y).abs() > 1e-9)).map(|(a, _)| a) } -fn pose_json(m: &Mat) -> Value { - json!({"origin": [m[3][0], m[3][1], m[3][2]], "x": [m[0][0], m[0][1], m[0][2]], "y": [m[1][0], m[1][1], m[1][2]], "z": [m[2][0], m[2][1], m[2][2]]}) +/// Where occurrence `name` is placed by `m`: its origin and axes. +fn part_pose(name: &str, m: &Mat) -> PartPose { + let row = |i: usize| m.get(i).map_or([0.0; 3], |r| [r[0], r[1], r[2]]); + PartPose { occurrence: name.to_string(), pose: Pose { origin: row(3), x: row(0), y: row(1), z: row(2) } } +} + +/// `drive_with_contact`'s report, typed. Its other callers read it as JSON, so it stays JSON there. +fn drive_report(cmd: &str, out: Value) -> Result { + serde_json::from_value(out).map_err(|e| bad(cmd, e.to_string())) } fn play(s: &mut Session, p: &Value) -> Result { @@ -809,22 +827,23 @@ fn play(s: &mut Session, p: &Value) -> Result { let step = p.get("step").and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(cmd, "`step` must be a number"))?; let want = values_at(s, &m, step.clamp(0.0, f64::from(m.steps))); let before = positions(s); - let (mut out, sol) = drive_with_contact(s, &want, &keyed(&m))?; + let (out, sol) = drive_with_contact(s, &want, &keyed(&m))?; + let drive = drive_report(cmd, out)?; let after = positions(s); let moved: Vec<&(String, Mat)> = moved(&before, &after).collect(); - out["moved"] = json!(!moved.is_empty()); + let any_moved = !moved.is_empty(); let shown: Vec<&(String, Mat)> = if bool_(p, "quiet").unwrap_or(false) { moved } else { after.iter().collect() }; - out["positions"] = shown.iter().map(|(n, t)| json!({"occurrence": n, "pose": pose_json(t)})).collect(); + let positions = shown.iter().map(|(n, t)| part_pose(n, t)).collect(); let joints: BTreeSet = m.keys.iter().map(|k| k.joint).collect(); - out["unmoved"] = joints + let unmoved = joints .iter() .filter_map(|id| { - let (why, _) = cannot_move(s, &sol, *id)?; + let (reason, _) = cannot_move(s, &sol, *id)?; let name = s.doc.assembly.joints.iter().find(|j| j.id == *id).map(|j| j.name.clone()); - Some(json!({"joint": id, "name": name, "reason": why})) + Some(UnmovedJoint { joint: *id, name, reason }) }) .collect(); - Ok(out) + typed_reply(cmd, StudyPlayed { drive, moved: any_moved, positions, unmoved, param_warnings: Vec::new() }) } fn export(s: &mut Session, p: &Value) -> Result { @@ -842,49 +861,55 @@ fn export(s: &mut Session, p: &Value) -> Result { let step = f64::from(m.steps) * k as f64 / (samples - 1) as f64; let want = values_at(&t, &m, step); let (r, _) = drive_with_contact(&mut t, &want, &keyed(&m))?; - rows.push(json!({ - "step": step, - "stopped_by_contact": r["stopped_by_contact"], - "stopped_by_loop": r["stopped_by_loop"], - "positions": positions(&t).iter().map(|(n, x)| json!({"occurrence": n, "pose": pose_json(x)})).collect::>(), - })); + let r = drive_report(cmd, r)?; + rows.push(StudySample { + step, + stopped_by_contact: r.stopped_by_contact, + stopped_by_loop: r.stopped_by_loop, + positions: positions(&t).iter().map(|(n, x)| part_pose(n, x)).collect(), + }); } - let out = json!({"study": m.name, "steps": m.steps, "samples": rows}); if let Some(path) = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096) { + let count = rows.len(); let text = if path.to_ascii_lowercase().ends_with(".csv") { let mut c = String::from("step,occurrence,x,y,z,xx,xy,xz,yx,yy,yz,zx,zy,zz\n"); for r in &rows { - for p in r["positions"].as_array().into_iter().flatten() { - let pose = &p["pose"]; - let n = |k: &str, i: usize| pose[k][i].as_f64().unwrap_or(0.0); + for at in &r.positions { + let [o, x, y, z] = [at.pose.origin, at.pose.x, at.pose.y, at.pose.z]; + // The step as JSON writes it (`0.0`, not `0`), as the file always had it. c += &format!( "{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n", - r["step"], - p["occurrence"].as_str().unwrap_or_default().replace(',', " "), - n("origin", 0), - n("origin", 1), - n("origin", 2), - n("x", 0), - n("x", 1), - n("x", 2), - n("y", 0), - n("y", 1), - n("y", 2), - n("z", 0), - n("z", 1), - n("z", 2) + Value::from(r.step), + at.occurrence.replace(',', " "), + o[0], + o[1], + o[2], + x[0], + x[1], + x[2], + y[0], + y[1], + y[2], + z[0], + z[1], + z[2] ); } } c } else { - serde_json::to_string_pretty(&out).unwrap_or_default() + // Through a `Value`, whose keys are sorted, so the file reads as it always did. + let samples = StudyExport::Samples { study: m.name, steps: m.steps, samples: rows }; + serde_json::to_value(&samples).and_then(|v| serde_json::to_string_pretty(&v)).unwrap_or_default() }; solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?; solidcraft_io::write_atomic(std::path::Path::new(path), text.as_bytes(), false).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; - return Ok(json!({"path": path, "samples": rows.len()})); + return typed_reply( + cmd, + StudyExported { export: StudyExport::Written { path: path.to_string(), samples: count }, param_warnings: Vec::new() }, + ); } - Ok(out) + typed_reply(cmd, StudyExported { export: StudyExport::Samples { study: m.name, steps: m.steps, samples: rows }, param_warnings: Vec::new() }) } /// Most samples of a motion trace: each is a solve, and a kept trace keeps every one as a fit diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 1d5742b8c..300bcbee5 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -76,6 +76,7 @@ pub mod material_properties; pub mod materials; pub mod metadata; pub mod motion; +pub mod motion_play; pub mod panels; pub mod parameter_sweep; pub mod parameters; diff --git a/crates/engine/src/schema/motion.rs b/crates/engine/src/schema/motion.rs index 88924c15c..bb51ecda5 100644 --- a/crates/engine/src/schema/motion.rs +++ b/crates/engine/src/schema/motion.rs @@ -454,14 +454,14 @@ pub struct MotionStudyDeleteParams { } /// `study`: an id or a name, with the handler's message for anything else, `null` included. -fn some_study<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { +pub(super) fn some_study<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { match Value::deserialize(d)? { v @ (Value::Number(_) | Value::String(_)) => Ok(Some(v)), _ => Err(D::Error::custom(whole("`study` must be an id or a name"))), } } -fn study_ref_schema(_: &mut SchemaGenerator) -> Schema { +pub(super) fn study_ref_schema(_: &mut SchemaGenerator) -> Schema { json_schema!({ "description": "The motion study, by id (a number) or name. A number is looked up as an id first, text as a name first.", "type": ["number", "string"] diff --git a/crates/engine/src/schema/motion_play.rs b/crates/engine/src/schema/motion_play.rs new file mode 100644 index 000000000..029a89e02 --- /dev/null +++ b/crates/engine/src/schema/motion_play.rs @@ -0,0 +1,235 @@ +//! Contracts and reply types for Play Motion Study and Export Motion Study in `cmd/motion.rs` +//! (#12668). A motion study drives an assembly's joints along a timeline of steps +//! ([`super::motion::MotionStudyParams`]). +//! +//! The handlers read their parameters from the raw JSON, so each key here reads as its handler +//! reads it and fails with the handler's message. Whether the study exists, and whether a path +//! may be written, stay the handlers' to check. Where a handler ignores a key of the wrong type +//! (a `quiet` that isn't true or false, a `path` that isn't text), the contract refuses it. + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use super::check::whole; +use super::motion::{require, some_study, study_ref_schema}; + +/// The most samples Export Motion Study takes, as `cmd/motion.rs` reads `samples`. +const MAX_SAMPLES: f64 = 10_000.0; + +fn study_required(schema: &mut Schema) { + require(schema, "study"); +} + +fn study_and_step_required(schema: &mut Schema) { + require(schema, "study"); + require(schema, "step"); +} + +/// Play a motion study: set its joints to the study's values at one step (contact sets stop them +/// where parts would pass through each other), and report where the parts went. One undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = study_and_step_required)] +pub struct PlayParams { + // `study` and `step` are optional in the type and required in the schema: left out, the + // handler refuses the call with its own message, not the check's "is required". + #[serde(default, deserialize_with = "some_study", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "study_ref_schema")] + pub study: Option, + #[serde(default, deserialize_with = "play_step", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "play_step_schema")] + pub step: Option, + /// True: `positions` lists only the occurrences that moved. Default: false, every occurrence. + #[serde(default)] + pub quiet: Option, +} + +/// `step`: a number, with the handler's message for anything else, `null` included. +fn play_step<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + Value::deserialize(d)?.as_f64().map(Some).ok_or_else(|| D::Error::custom(whole("`step` must be a number"))) +} + +fn play_step_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The step to play to: 0 to the study's `steps` (a number outside is taken to the nearer end; a fraction falls between two steps).", + "type": "number" + }) +} + +/// Export the occurrences' positions at evenly spaced steps of a motion study, as the reply or +/// written to a file. It plays the study on a copy: the design is not changed. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = study_required)] +pub struct ExportParams { + // Required in the schema (`study_required`), optional in the type, as Play's. + #[serde(default, deserialize_with = "some_study", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "study_ref_schema")] + pub study: Option, + #[serde(default, deserialize_with = "export_samples", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "export_samples_schema")] + pub samples: Option, + /// A file to write the samples to: CSV when it ends in `.csv` (one row per occurrence per + /// sample), JSON otherwise. The reply then gives the path and the number of samples. Blank + /// text is read as no path. Default: the reply carries the samples. + #[serde(default)] + pub path: Option, +} + +/// `samples`: a number from 2 to 10 000, with the handler's message for anything else, `null` +/// included. +fn export_samples<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + Value::deserialize(d)? + .as_f64() + .filter(|n| (2.0..=MAX_SAMPLES).contains(n)) + .map(Some) + .ok_or_else(|| D::Error::custom(whole("`samples` must be 2…10000"))) +} + +fn export_samples_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "How many samples, evenly spaced from the first step to the last: 2 to 10 000 (a fraction is cut to a whole number). Default: one per step, at most 10 000.", + "type": "number", + "minimum": 2, + "maximum": MAX_SAMPLES + }) +} + +/// One value of a joint, as `joint.list` gives it. +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +pub struct NamedJointValue { + /// Which value (`angle`, `distance`, …). + pub name: String, + pub value: f64, + /// `deg` or `mm`. + pub unit: String, + /// The value's limits, [lowest, highest], or `null` when it has none. + pub limits: Option<[f64; 2]>, +} + +/// A joint's values after it was driven. +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +pub struct DrivenJoint { + /// The joint's id. + pub joint: u64, + /// Its values, or `null` when the joint is gone. + pub values: Option>, +} + +/// Where contact stopped the joints: two parts touched. +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +pub struct ContactStop { + /// The two parts, by name. + pub a: String, + pub b: String, + /// How far the joints got towards the values asked for, from 0 to 1. + pub fraction: f64, +} + +/// Where a closed loop of joints could no longer close. +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +pub struct LoopStop { + /// The joint whose loop opens first, by name. + pub joint: String, + /// How far the joints got towards the values asked for, from 0 to 1. + pub fraction: f64, +} + +/// What driving the joints did, as `cmd/motion.rs`'s `drive_with_contact` reports it. +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +pub struct DriveReport { + /// Each joint driven, with its values. + pub values: Vec, + /// Where contact stopped them, or `null`. + pub stopped_by_contact: Option, + /// Where a loop stopped them, or `null`. + pub stopped_by_loop: Option, + /// How many of the joints' conditions the solver couldn't meet. + pub conflicts: usize, +} + +/// A placement: its origin and axes, in world coordinates (mm). +#[derive(Debug, Serialize, JsonSchema)] +pub struct Pose { + pub origin: [f64; 3], + pub x: [f64; 3], + pub y: [f64; 3], + pub z: [f64; 3], +} + +/// Where an occurrence is placed. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PartPose { + /// The occurrence, by name. + pub occurrence: String, + pub pose: Pose, +} + +/// A keyed joint that can move nothing, and why. +#[derive(Debug, Serialize, JsonSchema)] +pub struct UnmovedJoint { + /// The joint's id. + pub joint: u64, + /// Its name, or `null` when the joint is gone. + pub name: Option, + pub reason: String, +} + +/// What `motion.play` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StudyPlayed { + #[serde(flatten)] + pub drive: DriveReport, + /// Whether any occurrence moved. + pub moved: bool, + /// Where the occurrences are now: every one, or with `quiet` only those that moved. + pub positions: Vec, + /// The keyed joints that can move nothing, such as a chain joined to nothing grounded. + pub unmoved: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// One sample of an exported study. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StudySample { + /// The step played to. + pub step: f64, + /// Where contact stopped the joints, or `null`. + pub stopped_by_contact: Option, + /// Where a loop stopped them, or `null`. + pub stopped_by_loop: Option, + /// Where every occurrence is at that step. + pub positions: Vec, +} + +/// The samples of an exported study, or the file they were written to. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum StudyExport { + /// Without `path`: the samples themselves. + Samples { + /// The study's name. + study: String, + /// The study's number of steps. + steps: u32, + samples: Vec, + }, + /// With `path`: the file written, and how many samples it holds. + Written { path: String, samples: usize }, +} + +/// What `motion.export` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StudyExported { + #[serde(flatten)] + pub export: StudyExport, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "motion_play_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/motion_play_tests.rs b/crates/engine/src/schema/motion_play_tests.rs new file mode 100644 index 000000000..51a251ec3 --- /dev/null +++ b/crates/engine/src/schema/motion_play_tests.rs @@ -0,0 +1,157 @@ +use serde_json::{Value, json}; + +use super::{ExportParams, PlayParams, StudyExported, StudyPlayed}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +/// A door, `Door`, on a revolute joint `Hinge` at the origin, a `Block` beside it, and a motion +/// study `Swing` that turns the hinge from 0 to 90° over 10 steps. +fn door(level: ParamCheck) -> Session { + let mut s = Session::default(); + for (name, corner, size) in [("Door", [0, 0, 0], [100, 4, 50]), ("Block", [60, 30, 0], [20, 20, 50])] { + for (id, p) in [ + ("component.activate", json!({"component": "root"})), + ("component.create", json!({"name": name, "grounded": false})), + ("solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})), + ] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + } + } + let hinge = json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}); + s.execute("joint.create", &hinge).unwrap_or_else(|e| panic!("{e}")); + let swing = json!({"name": "Swing", "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [10, 90]]}]}); + s.execute("motion.study", &swing).unwrap_or_else(|e| panic!("{e}")); + s.param_check = level; + s +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["quiet", "step", "study"]); + assert_keys(input_schema_for::(), &["path", "samples", "study"]); +} + +/// #12668: calls that fail today get the same message in strict, on the door with its study. +#[test] +fn strict_keeps_todays_errors() { + for (id, p) in [ + ("motion.play", json!({"step": 5})), + ("motion.play", json!({"study": null, "step": 5})), + ("motion.play", json!({"study": true, "step": 5})), + ("motion.play", json!({"study": "Nope", "step": 5})), + ("motion.play", json!({"study": "Swing"})), + ("motion.play", json!({"study": "Swing", "step": null})), + ("motion.play", json!({"study": "Swing", "step": "5"})), + ("motion.export", json!({})), + ("motion.export", json!({"study": [1]})), + ("motion.export", json!({"study": "Nope"})), + ("motion.export", json!({"study": "Swing", "samples": 1})), + ("motion.export", json!({"study": "Swing", "samples": 10_001})), + ("motion.export", json!({"study": "Swing", "samples": null})), + ("motion.export", json!({"study": "Swing", "samples": "10"})), + ] { + let off = door(ParamCheck::Off).execute(id, &p).err().map(|e| e.to_string()); + assert!(off.is_some(), "{id} {p} should fail today"); + assert_eq!(door(ParamCheck::Strict).execute(id, &p).err().map(|e| e.to_string()), off, "{id} {p}"); + } +} + +/// #12668: keys of the wrong type that the handlers ignore today (a `quiet` that isn't true or +/// false is read as false; a `path` that isn't text as no path) are refused by the contracts: in +/// Warn the call still works, with a warning naming the key. +#[test] +fn the_contracts_refuse_what_the_handlers_ignore() { + for (id, p, key) in [ + ("motion.play", json!({"study": "Swing", "step": 5, "quiet": "yes"}), "quiet"), + ("motion.export", json!({"study": "Swing", "samples": 2, "path": 5}), "path"), + ] { + assert!(door(ParamCheck::Off).execute(id, &p).is_ok(), "{id} {p} works today"); + let warned = door(ParamCheck::Warn).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + assert!(warned["param_warnings"].to_string().contains(key), "{warned}"); + let error = door(ParamCheck::Strict).execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains(&format!("`{key}`")), "{id} {p}: {error}"); + } +} + +/// #12668: the schemas take what the handlers take. Each call is checked against both the schema +/// and the handler, with the check off, so the two can't drift apart. +#[test] +fn the_schemas_take_what_the_handlers_take() { + let play = input_schema_for::(); + let export = input_schema_for::(); + let study_id = door(ParamCheck::Off).doc.assembly.studies.first().map(|m| m.id).unwrap_or_default(); + for (id, schema, p) in [ + ("motion.play", &play, json!({"study": "Swing", "step": 5})), + ("motion.play", &play, json!({"study": study_id, "step": 2.5, "quiet": true})), + ("motion.play", &play, json!({"study": "Swing", "step": -3})), + ("motion.play", &play, json!({"study": "Swing", "step": 1e6})), + ("motion.play", &play, json!({"study": "Swing", "step": "5"})), + ("motion.play", &play, json!({"study": "Swing"})), + ("motion.play", &play, json!({"step": 5})), + ("motion.export", &export, json!({"study": "Swing"})), + ("motion.export", &export, json!({"study": study_id, "samples": 2})), + ("motion.export", &export, json!({"study": "Swing", "samples": 3.7})), + ("motion.export", &export, json!({"study": "Swing", "samples": 1})), + ("motion.export", &export, json!({"study": "Swing", "samples": 2, "path": ""})), + ("motion.export", &export, json!({"samples": 2})), + ] { + let takes = door(ParamCheck::Off).execute(id, &p).is_ok(); + assert_eq!(conforms(schema.as_value(), schema.as_value(), &p), takes, "{id} {p}"); + } +} + +/// #12668: Play and Export reply as their output schemas say, in Warn without warnings, and the +/// replies are the JSON the handlers gave before: the hinge turned to 45° with every occurrence +/// listed, then only the one that moved; the samples; and the same samples written to a JSON +/// file and to a CSV file. A misspelt key is ignored today: Warn says so, and strict refuses it. +#[test] +fn play_and_export_reply_with_their_schemas() { + let played = output_schema_for::(); + let played = played.as_value(); + let exported = output_schema_for::(); + let exported = exported.as_value(); + let mut s = door(ParamCheck::Warn); + let mut run = |id: &str, p: Value, schema: &Value| { + let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + r + }; + let r = run("motion.play", json!({"study": "Swing", "step": 5}), played); + assert_eq!(r["moved"], true, "{r}"); + assert_eq!(r["positions"].as_array().map(Vec::len), Some(2), "every occurrence: {r}"); + let hinge = &r["values"][0]["values"][0]; + assert_eq!((hinge["unit"].as_str(), hinge["value"].as_f64().map(f64::round)), (Some("deg"), Some(45.0)), "{r}"); + assert_eq!((&r["stopped_by_contact"], &r["stopped_by_loop"], &r["unmoved"]), (&json!(null), &json!(null), &json!([])), "{r}"); + let r = run("motion.play", json!({"study": "Swing", "step": 10, "quiet": true}), played); + assert_eq!(r["positions"].as_array().map(|p| p.iter().map(|x| x["occurrence"].clone()).collect::>()), Some(vec![json!("Door:1")]), "{r}"); + let samples = run("motion.export", json!({"study": "Swing", "samples": 3}), exported); + assert_eq!((&samples["study"], &samples["steps"]), (&json!("Swing"), &json!(10)), "{samples}"); + assert_eq!( + samples["samples"].as_array().map(|x| x.iter().map(|r| r["step"].clone()).collect::>()), + Some(vec![json!(0.0), json!(5.0), json!(10.0)]) + ); + let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-motion-export-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("swing.json").to_string_lossy().into_owned(); + let r = run("motion.export", json!({"study": "Swing", "samples": 3, "path": path}), exported); + assert_eq!(r, json!({"path": path, "samples": 3})); + let file: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_default()).unwrap_or_default(); + assert_eq!(file, samples, "the file holds the samples the reply gives"); + let path = dir.join("swing.csv").to_string_lossy().into_owned(); + run("motion.export", json!({"study": "Swing", "samples": 3, "path": path}), exported); + let csv = std::fs::read_to_string(&path).unwrap_or_default(); + let lines: Vec<&str> = csv.lines().collect(); + assert_eq!(lines.first().copied(), Some("step,occurrence,x,y,z,xx,xy,xz,yx,yy,yz,zx,zy,zz")); + assert_eq!(lines.len(), 1 + 3 * 2, "a row per occurrence per sample: {csv}"); + assert!(lines.get(1).is_some_and(|l| l.starts_with("0.0,")), "the step as JSON writes it: {csv}"); + let _ = std::fs::remove_dir_all(&dir); + // A misspelt key. + let p = json!({"study": "Swing", "step": 5, "quite": true}); + let r = s.execute("motion.play", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + assert!(r["param_warnings"].to_string().contains("quite"), "{r}"); + s.param_check = ParamCheck::Strict; + let error = s.execute("motion.play", &p).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("`quite`"), "{error}"); +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index 8eea70ebc..f88ee6f1f 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -65,10 +65,8 @@ joint.sweep material.assign material.list mesh.convert -motion.export motion.export_animation motion.interference -motion.play motion.plot motion.trace motion.trace.edit