Agents and scripts: the contact commands describe their exact parameters and reply (#11949) (#11950)
* claim: #11949 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Contact sets: input and output schemas for the seven contact commands (#11949) describe_command now gives the exact parameters and reply of contact.enable_sets, enable_all, disable_all, create, edit, list and check, and the warn and strict parameter checks use them. The handlers read their parameters from the raw JSON, so the contracts in schema/motion.rs read each key as its handler does, with its message: `occurrences` (OccurrenceKeys) and `set` are required in the schemas but left to the handlers' messages in the types, through a small `require` transform. The replies are built from typed values instead of json! literals, with the same JSON; the listed sets mirror the doc crate's ContactSet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
63ffadfebf
commit
4678a04827
4 files changed
+393
-29
No files matched your search
@@ -14,7 +14,10 @@ use solidcraft_kernel::Body;
|
||||
use super::CommandSpec;
|
||||
use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, place_holding, value};
|
||||
use crate::params::{bad, bool_, str_, vec3};
|
||||
use crate::schema::motion::{FindLimitsParams, FindLimitsResult};
|
||||
use crate::schema::motion::{
|
||||
ContactCheck, ContactCollision, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetChange,
|
||||
ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
@@ -39,26 +42,55 @@ macro_rules! trace_doc {
|
||||
};
|
||||
}
|
||||
|
||||
const CONTACT_ENABLE_CONTRACT: TypedContract<ContactEnableParams> = TypedContract::new();
|
||||
const CONTACT_NONE_CONTRACT: TypedContract<ContactNoParams> = TypedContract::new();
|
||||
const CONTACT_CREATE_CONTRACT: TypedContract<ContactCreateParams> = TypedContract::new();
|
||||
const CONTACT_EDIT_CONTRACT: TypedContract<ContactEditParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("contact.enable_sets", "Enable Contact Sets", enable_sets).at("SOLID", "ASSEMBLE").icon("contact_sets").params(
|
||||
"enabled?: bool (default true) — driving joints and motion studies stop where bodies in one contact set would pass through each other",
|
||||
),
|
||||
CommandSpec::new("contact.enable_all", "Enable All Contact", enable_all)
|
||||
CommandSpec::new("contact.enable_sets", "Enable Contact Sets", crate::checked!("contact.enable_sets", enable_sets))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("contact_sets")
|
||||
.contract(&CONTACT_ENABLE_CONTRACT)
|
||||
.output(output_schema_for::<ContactSwitch>)
|
||||
.params(
|
||||
"enabled?: bool (default true) — driving joints and motion studies stop where bodies in one contact set would pass through each other",
|
||||
),
|
||||
CommandSpec::new("contact.enable_all", "Enable All Contact", crate::checked!("contact.enable_all", enable_all))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("contact_all")
|
||||
.contract(&CONTACT_NONE_CONTRACT)
|
||||
.output(output_schema_for::<ContactSwitch>)
|
||||
.params("every occurrence takes part in contact (one set of all)"),
|
||||
CommandSpec::new("contact.disable_all", "Disable Contact", disable_all).at("SOLID", "ASSEMBLE").icon("contact_off").params("contact off"),
|
||||
CommandSpec::new("contact.create", "New Contact Set", new_set)
|
||||
CommandSpec::new("contact.disable_all", "Disable Contact", crate::checked!("contact.disable_all", disable_all))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("contact_off")
|
||||
.contract(&CONTACT_NONE_CONTRACT)
|
||||
.output(output_schema_for::<ContactSwitch>)
|
||||
.params("contact off"),
|
||||
CommandSpec::new("contact.create", "New Contact Set", crate::checked!("contact.create", new_set))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("contact_new")
|
||||
.contract(&CONTACT_CREATE_CONTRACT)
|
||||
.output(output_schema_for::<ContactSetCreated>)
|
||||
.params("occurrences: [ids or names] (two or more); name?"),
|
||||
CommandSpec::new("contact.edit", "Edit Contact Set", edit_set)
|
||||
CommandSpec::new("contact.edit", "Edit Contact Set", crate::checked!("contact.edit", edit_set))
|
||||
.icon("edit")
|
||||
.contract(&CONTACT_EDIT_CONTRACT)
|
||||
.output(output_schema_for::<ContactSetEdited>)
|
||||
.params("set: id|name; occurrences?; name?; suppressed?: bool; delete?: bool"),
|
||||
CommandSpec::new("contact.list", "List Contact Sets", list_sets).icon("list").noundo().doc_only().params("→ sets, enabled, all"),
|
||||
CommandSpec::new("contact.check", "Check Contact", check)
|
||||
CommandSpec::new("contact.list", "List Contact Sets", crate::checked!("contact.list", list_sets))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&CONTACT_NONE_CONTRACT)
|
||||
.output(output_schema_for::<ContactSets>)
|
||||
.params("→ sets, enabled, all"),
|
||||
CommandSpec::new("contact.check", "Check Contact", crate::checked!("contact.check", check))
|
||||
.icon("interference")
|
||||
.noundo()
|
||||
.contract(&CONTACT_NONE_CONTRACT)
|
||||
.output(output_schema_for::<ContactCheck>)
|
||||
.params("→ pairs in contact sets that pass through each other now"),
|
||||
CommandSpec::new("motion.study", "Motion Study", study).at("SOLID", "ASSEMBLE").icon("play").params(
|
||||
"name?; study? (edit an existing one); steps? (timeline length, default 100); keys: [{joint, index?, points: [[step, value], …]}] \
|
||||
@@ -525,24 +557,30 @@ pub fn drive_joint_index(s: &mut Session, id: u64, q: Vec<f64>, index: usize) ->
|
||||
Ok(drive_with_contact(s, &[(id, q)], &[(id, index)].into_iter().collect())?.0)
|
||||
}
|
||||
|
||||
/// A contact command's reply as JSON: they build their replies from the types their output
|
||||
/// schemas describe, so the two can't drift apart.
|
||||
fn contact_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn enable_sets(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = bool_(p, "enabled").unwrap_or(true);
|
||||
s.doc_mut().assembly.contact_enabled = on;
|
||||
Ok(json!({"enabled": on}))
|
||||
let enabled = bool_(p, "enabled").unwrap_or(true);
|
||||
s.doc_mut().assembly.contact_enabled = enabled;
|
||||
contact_reply("contact.enable_sets", ContactSwitch { enabled, all: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn enable_all(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let a = &mut s.doc_mut().assembly;
|
||||
a.contact_enabled = true;
|
||||
a.contact_all = true;
|
||||
Ok(json!({"enabled": true, "all": true}))
|
||||
contact_reply("contact.enable_all", ContactSwitch { enabled: true, all: Some(true), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn disable_all(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let a = &mut s.doc_mut().assembly;
|
||||
a.contact_enabled = false;
|
||||
a.contact_all = false;
|
||||
Ok(json!({"enabled": false}))
|
||||
contact_reply("contact.disable_all", ContactSwitch { enabled: false, all: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn new_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -560,7 +598,7 @@ fn new_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = &mut s.doc_mut().assembly;
|
||||
a.contact_sets.push(ContactSet { id, name: name.clone(), occurrences: occ, suppressed: false });
|
||||
a.contact_enabled = true;
|
||||
Ok(json!({"set": id, "name": name}))
|
||||
contact_reply(cmd, ContactSetCreated { set: id, name, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn set_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
@@ -582,7 +620,7 @@ fn edit_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = set_index(s, p, cmd)?;
|
||||
if bool_(p, "delete").unwrap_or(false) {
|
||||
s.doc_mut().assembly.contact_sets.remove(i);
|
||||
return Ok(json!({"deleted": true}));
|
||||
return contact_reply(cmd, ContactSetEdited { change: ContactSetChange::Deleted { deleted: true }, param_warnings: Vec::new() });
|
||||
}
|
||||
let occ = if p.get("occurrences").is_some() { Some(occurrences(s, p, cmd)?) } else { None };
|
||||
if occ.as_ref().is_some_and(|o| o.len() < 2) {
|
||||
@@ -598,17 +636,19 @@ fn edit_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(x) = bool_(p, "suppressed") {
|
||||
c.suppressed = x;
|
||||
}
|
||||
Ok(json!({"set": c.id}))
|
||||
let set = c.id;
|
||||
contact_reply(cmd, ContactSetEdited { change: ContactSetChange::Changed { set }, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn list_sets(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let a = &s.doc.assembly;
|
||||
Ok(json!({"enabled": a.contact_enabled, "all": a.contact_all, "sets": a.contact_sets}))
|
||||
let sets = a.contact_sets.iter().map(ContactSetInfo::from).collect();
|
||||
contact_reply("contact.list", ContactSets { enabled: a.contact_enabled, all: a.contact_all, sets, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let c = collisions(s);
|
||||
Ok(json!({"collisions": c.iter().map(|(a, b, d)| json!({"a": a, "b": b, "depth_mm": d})).collect::<Vec<_>>()}))
|
||||
let collisions = collisions(s).into_iter().map(|(a, b, depth_mm)| ContactCollision { a, b, depth_mm }).collect();
|
||||
contact_reply("contact.check", ContactCheck { collisions, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
// ---- Motion studies ----
|
||||
|
||||
@@ -7,6 +7,8 @@ use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::check::whole;
|
||||
|
||||
/// Find where each value of a joint can go before the parts it moves touch another body. The
|
||||
/// design is not changed.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -161,6 +163,244 @@ pub struct FindLimitsResult {
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---- Contact (#11949) ----
|
||||
//
|
||||
// The contact 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 occurrences and the set
|
||||
// exist stays the handler's to check.
|
||||
|
||||
/// The most occurrences a contact set's list may name, as `cmd/motion.rs`'s `MAX_ITEMS`.
|
||||
const MAX_OCCURRENCES: usize = 10_000;
|
||||
|
||||
/// Turn contact sets on or off: while on, driving a joint or playing a motion study stops where
|
||||
/// bodies in one contact set would pass through each other. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ContactEnableParams {
|
||||
/// Whether contact sets are on. Default: true.
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
}
|
||||
|
||||
/// No parameters: `contact.enable_all` (every occurrence takes part in contact, as one set),
|
||||
/// `contact.disable_all` (contact off), `contact.list` and `contact.check` (read only).
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ContactNoParams {}
|
||||
|
||||
/// Make a contact set: occurrences whose bodies may touch but not pass through each other while
|
||||
/// joints move. Contact sets are turned on. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = occurrences_required)]
|
||||
pub struct ContactCreateParams {
|
||||
// Optional in the type and required in the schema (`occurrences_required`): left out, the
|
||||
// handler refuses it with its own message, not the check's "is required".
|
||||
#[serde(default, deserialize_with = "some_occurrences", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "OccurrenceKeys")]
|
||||
pub occurrences: Option<OccurrenceKeys>,
|
||||
/// The set's name. Default: "Contact Set" and the first number no set's name has.
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
/// Change a contact set: its occurrences, its name, or whether it's suppressed; or delete it. One
|
||||
/// undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = set_required)]
|
||||
pub struct ContactEditParams {
|
||||
// Required in the schema (`set_required`), optional in the type, as `occurrences` above.
|
||||
#[serde(default, deserialize_with = "contact_set", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "contact_set_schema")]
|
||||
pub set: Option<Value>,
|
||||
/// The set's new occurrences, replacing them all.
|
||||
#[serde(default, deserialize_with = "some_occurrences", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "OccurrenceKeys")]
|
||||
pub occurrences: Option<OccurrenceKeys>,
|
||||
/// The set's new name; blank text keeps the name.
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
/// Suppress the set (it stops nothing) or not.
|
||||
#[serde(default)]
|
||||
pub suppressed: Option<bool>,
|
||||
/// Delete the set instead; the other keys are then not used. Default: false.
|
||||
#[serde(default)]
|
||||
pub delete: Option<bool>,
|
||||
}
|
||||
|
||||
/// A contact set's occurrences, as `cmd/motion.rs`'s `occurrences` reads them: a list of ids or
|
||||
/// names, with its messages. An occurrence named twice counts once.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OccurrenceKeys(pub Vec<Value>);
|
||||
|
||||
impl<'de> Deserialize<'de> for OccurrenceKeys {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Array(list) if list.len() > MAX_OCCURRENCES => Err(D::Error::custom(whole("too many occurrences"))),
|
||||
Value::Array(list) if list.iter().all(|v| v.is_number() || v.is_string()) => Ok(OccurrenceKeys(list)),
|
||||
Value::Array(_) => Err(D::Error::custom(whole("an occurrence must be an id or a name"))),
|
||||
_ => Err(D::Error::custom(whole("`occurrences` must list occurrences"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for OccurrenceKeys {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"OccurrenceKeys".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "Two or more occurrences, each by id (a number) or name; not the root.",
|
||||
"type": "array",
|
||||
"items": {"type": ["number", "string"]},
|
||||
"minItems": 2,
|
||||
"maxItems": MAX_OCCURRENCES
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `occurrences`: given, `null` included, it must be [`OccurrenceKeys`], as the handlers read it
|
||||
/// whenever the key is there.
|
||||
fn some_occurrences<'de, D: Deserializer<'de>>(d: D) -> Result<Option<OccurrenceKeys>, D::Error> {
|
||||
OccurrenceKeys::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// `set`: an id or a name, with the handler's message for anything else, `null` included.
|
||||
fn contact_set<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
v @ (Value::Number(_) | Value::String(_)) => Ok(Some(v)),
|
||||
_ => Err(D::Error::custom(whole("`set` must be an id or a name"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn contact_set_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "The contact set, by id (a number) or name.", "type": ["number", "string"]})
|
||||
}
|
||||
|
||||
/// Adds `key` to the schema's `required` list: for a key the type has optional so that the
|
||||
/// handler, not the check, refuses it when it's left out.
|
||||
fn require(schema: &mut Schema, key: &str) {
|
||||
match schema.get_mut("required") {
|
||||
Some(Value::Array(required)) => {
|
||||
if !required.iter().any(|k| k == key) {
|
||||
required.push(key.into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
schema.insert("required".into(), Value::Array(vec![key.into()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn occurrences_required(schema: &mut Schema) {
|
||||
require(schema, "occurrences");
|
||||
}
|
||||
|
||||
fn set_required(schema: &mut Schema) {
|
||||
require(schema, "set");
|
||||
}
|
||||
|
||||
/// What `contact.enable_sets`, `contact.enable_all` and `contact.disable_all` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ContactSwitch {
|
||||
/// Whether contact is on.
|
||||
pub enabled: bool,
|
||||
/// From `contact.enable_all`: always true, every occurrence takes part.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub all: Option<bool>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// What `contact.create` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ContactSetCreated {
|
||||
/// The new set's id.
|
||||
pub set: u64,
|
||||
pub name: String,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// What `contact.edit` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ContactSetEdited {
|
||||
#[serde(flatten)]
|
||||
pub change: ContactSetChange,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// What an edit did to the set.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum ContactSetChange {
|
||||
/// The set was deleted.
|
||||
Deleted {
|
||||
/// Always true.
|
||||
deleted: bool,
|
||||
},
|
||||
/// The set was changed.
|
||||
Changed {
|
||||
/// The set's id.
|
||||
set: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `contact.list` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ContactSets {
|
||||
/// Whether contact is on.
|
||||
pub enabled: bool,
|
||||
/// Whether every occurrence takes part, as one set, instead of `sets`.
|
||||
pub all: bool,
|
||||
pub sets: Vec<ContactSetInfo>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// A contact set, as the design saves it.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ContactSetInfo {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// Its occurrences' ids.
|
||||
pub occurrences: Vec<u64>,
|
||||
/// Present, and true, when the set is suppressed.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub suppressed: bool,
|
||||
}
|
||||
|
||||
impl From<&solidcraft_doc::motion::ContactSet> for ContactSetInfo {
|
||||
fn from(set: &solidcraft_doc::motion::ContactSet) -> Self {
|
||||
ContactSetInfo { id: set.id, name: set.name.clone(), occurrences: set.occurrences.clone(), suppressed: set.suppressed }
|
||||
}
|
||||
}
|
||||
|
||||
/// What `contact.check` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ContactCheck {
|
||||
/// The pairs of occurrences in one contact set whose bodies pass through each other now;
|
||||
/// none while contact is off.
|
||||
pub collisions: Vec<ContactCollision>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// Two occurrences whose bodies pass through each other.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ContactCollision {
|
||||
/// The occurrences' names.
|
||||
pub a: String,
|
||||
pub b: String,
|
||||
/// How deep (mm).
|
||||
pub depth_mm: f64,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "motion_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,6 +1,9 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{FindLimitsParams, FindLimitsResult};
|
||||
use super::{
|
||||
ContactCheck, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetCreated, ContactSetEdited, ContactSets,
|
||||
ContactSwitch, FindLimitsParams, FindLimitsResult,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
@@ -8,17 +11,105 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<FindLimitsParams>(), &["against", "contact_sets", "index", "joint", "occurrences", "refine", "step"]);
|
||||
assert_keys(input_schema_for::<ContactEnableParams>(), &["enabled"]);
|
||||
assert_keys(input_schema_for::<ContactNoParams>(), &[]);
|
||||
assert_keys(input_schema_for::<ContactCreateParams>(), &["name", "occurrences"]);
|
||||
assert_keys(input_schema_for::<ContactEditParams>(), &["delete", "name", "occurrences", "set", "suppressed"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let many = vec!["A"; 10_001];
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("joint.find_limits", json!({"joint": true})),
|
||||
("joint.find_limits", json!({"joint": null})),
|
||||
("joint.find_limits", json!({"joint": "Hinge"})),
|
||||
("contact.create", json!({})),
|
||||
("contact.create", json!({"occurrences": null})),
|
||||
("contact.create", json!({"occurrences": "Door"})),
|
||||
("contact.create", json!({"occurrences": many})),
|
||||
("contact.create", json!({"occurrences": [true, "Door"]})),
|
||||
("contact.create", json!({"occurrences": ["Nope", "Door"]})),
|
||||
("contact.create", json!({"occurrences": ["root", "Door"]})),
|
||||
("contact.create", json!({"occurrences": [7]})),
|
||||
("contact.edit", json!({})),
|
||||
("contact.edit", json!({"set": true})),
|
||||
("contact.edit", json!({"set": null})),
|
||||
("contact.edit", json!({"set": "Nope", "delete": true})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// The contact contracts say what their handlers need: `occurrences` and `set` are required in
|
||||
/// the schemas, though the types leave them to the handlers' messages, and a list names two or
|
||||
/// more occurrences.
|
||||
#[test]
|
||||
fn the_contact_schemas_take_what_the_handlers_read() {
|
||||
let create = input_schema_for::<ContactCreateParams>();
|
||||
let create = create.as_value();
|
||||
for (p, takes) in [
|
||||
(json!({"occurrences": ["Door", 7], "name": "Swing"}), true),
|
||||
(json!({"occurrences": ["Door"]}), false),
|
||||
(json!({"occurrences": [true, "Door"]}), false),
|
||||
(json!({"name": "Swing"}), false),
|
||||
] {
|
||||
assert_eq!(conforms(create, create, &p), takes, "{p}");
|
||||
}
|
||||
let edit = input_schema_for::<ContactEditParams>();
|
||||
let edit = edit.as_value();
|
||||
for (p, takes) in [(json!({"set": 3, "suppressed": true}), true), (json!({"set": null}), false), (json!({"delete": true}), false)] {
|
||||
assert_eq!(conforms(edit, edit, &p), takes, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #11949: every contact command replies as its output schema says, in Warn without warnings:
|
||||
/// sets made, listed, changed, suppressed and deleted, contact switched on and off, and a check
|
||||
/// that finds two parts passing through each other. A misspelt key gets `param_warnings` in Warn,
|
||||
/// since the handlers ignore unknown keys, and strict refuses it.
|
||||
#[test]
|
||||
fn contact_commands_reply_with_their_schemas() {
|
||||
let mut s = door();
|
||||
// A part through the door, so a check finds them.
|
||||
for (id, p) in [
|
||||
("component.activate", json!({"component": "root"})),
|
||||
("component.create", json!({"name": "Clash", "grounded": false})),
|
||||
("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [10, -3, 0]})),
|
||||
] {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
}
|
||||
s.param_check = ParamCheck::Warn;
|
||||
let mut run = |id: &str, p: Value, schema: schemars::Schema| {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
|
||||
assert!(r.get("param_warnings").is_none(), "{r}");
|
||||
r
|
||||
};
|
||||
run("contact.list", json!({}), output_schema_for::<ContactSets>());
|
||||
let r = run("contact.create", json!({"occurrences": ["Door", "Clash"], "name": "Swing"}), output_schema_for::<ContactSetCreated>());
|
||||
assert_eq!(r["name"], "Swing", "{r}");
|
||||
let other = run("contact.create", json!({"occurrences": ["Door", "Slide", "Door"]}), output_schema_for::<ContactSetCreated>());
|
||||
let r = run("contact.check", json!({}), output_schema_for::<ContactCheck>());
|
||||
assert!(r["collisions"].as_array().is_some_and(|c| !c.is_empty()), "{r}");
|
||||
run(
|
||||
"contact.edit",
|
||||
json!({"set": "Swing", "suppressed": true, "occurrences": ["Door", "Clash", "Block"], "name": "Swing 2"}),
|
||||
output_schema_for::<ContactSetEdited>(),
|
||||
);
|
||||
let r = run("contact.list", json!({}), output_schema_for::<ContactSets>());
|
||||
assert!(r["sets"][0]["suppressed"] == true && r["sets"][1].get("suppressed").is_none(), "{r}");
|
||||
let r = run("contact.edit", json!({"set": other["set"], "delete": true}), output_schema_for::<ContactSetEdited>());
|
||||
assert_eq!(r["deleted"], true, "{r}");
|
||||
for (id, p) in [("contact.enable_sets", json!({"enabled": false})), ("contact.enable_all", json!({})), ("contact.disable_all", json!({}))] {
|
||||
run(id, p, output_schema_for::<ContactSwitch>());
|
||||
}
|
||||
let p = json!({"enable": false});
|
||||
let r = s.execute("contact.enable_sets", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
assert!(r["param_warnings"].to_string().contains("enable"), "{r}");
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let error = s.execute("contact.enable_sets", &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("`enable`"), "{error}");
|
||||
}
|
||||
|
||||
/// A 100 × 4 × 50 door hinged about Z at the origin, a block in its way and a slider beside it.
|
||||
fn door() -> Session {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -39,13 +39,6 @@ component.replace_with_link
|
||||
component.revert_position
|
||||
component.unlock
|
||||
component.update_links
|
||||
contact.check
|
||||
contact.create
|
||||
contact.disable_all
|
||||
contact.edit
|
||||
contact.enable_all
|
||||
contact.enable_sets
|
||||
contact.list
|
||||
doc.open
|
||||
doc.recover
|
||||
doc.recovery_discard
|
||||
|
||||
Reference in new issue
Block a user