diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 48fa4f674..7a1427012 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -69,7 +69,13 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "MODIFY") .icon("material") .params("bodies: [names]; material: name (Steel, Aluminum, ABS Plastic, …, or one made with material.create; `material.list`)"), - CommandSpec::new("appearance.assign", "Appearance", appearance).at("SOLID", "MODIFY").icon("appearance").key("A").params( + CommandSpec::new("appearance.assign", "Appearance", crate::checked!("appearance.assign", appearance)) + .at("SOLID", "MODIFY") + .icon("appearance") + .key("A") + .contract(&ASSIGN_CONTRACT) + .output(crate::schema::output_schema_for::) + .params( "bodies?: [names]; faces?: [[x,y,z] on faces] (body?: which body, default the nearest); components?: [names or ids, or occurrence names]; \ appearance?: library name or stable starter.* ID (appearance.library) | color: \"#rrggbb\" or [r, g, b] (0–255), opacity? (0–1, default 1); \ name?: inert copied look label (requires color, mutually exclusive with appearance); pbr?: {metallic:0..1, roughness:0.045..1, dielectric_ior:1..3} (requires color/appearance and opacity 1); a starter ID or registered starter name resolves its recipe before color overrides; omitted pbr retains that response and pbr: null explicitly clears it. Unavailable glass recipes refuse through either selector. Other custom labels with an explicit color retain legacy scalar behavior. Neither appearance nor color (or color: null): clear, so the face follows its body, the body its component, the component its material", @@ -86,11 +92,17 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("appearance.replace", "Replace Appearance", appearance_chain::replace).icon("appearance").params( "from: library name | saved look {name,color,opacity,pbr?} (copy appearance.list in_design); to: library name | assignment look {appearance? | color, name?, opacity?, pbr?} (appearance.assign rules; no clear). Matches the full look including name and PBR. scope?: {bodies?: [names], components?: [names or ids]} (a placed copy's name means the body or component it shows), at most 10000 targets; body scope includes face overrides, component scope selects only the component override. Omitted scope means all overrides, including hidden/suppressed ones; physical defaults are unchanged. Duplicate targets count once. Returns count of rewritten overrides; zero adds no history. One undo step, atomic; no dialogs. Designs above 100000 overrides refuse", ), - CommandSpec::new("appearance.library", "Appearance Library", appearance_library).icon("library") + CommandSpec::new("appearance.library", "Appearance Library", crate::checked!("appearance.library", appearance_library)) + .icon("library") .noundo() + .contract(&LIBRARY_CONTRACT) + .output(crate::schema::output_schema_for::) .params("→ 20 legacy scalar appearances, six opaque PBR finishes and 40 starter recipes with IDs, categories, provenance, requirements and availability; six starter glass recipes are unavailable"), - CommandSpec::new("appearance.list", "List Appearances", appearance_list).icon("list") + CommandSpec::new("appearance.list", "List Appearances", crate::checked!("appearance.list", appearance_list)) + .icon("list") .noundo() + .contract(&LIST_CONTRACT) + .output(crate::schema::output_schema_for::) .params("body?: name (or a placed copy's, `KB (K:2)`: the body it shows) → assigned appearances; with body, its resolved look and its faces' (face index, look)"), CommandSpec::new("material.list", "List Materials", material_list).icon("list") .noundo() @@ -531,7 +543,7 @@ fn physical_material(s: &mut Session, p: &Value) -> Result { } /// A colour parameter: `"#rrggbb"` or `[r, g, b]` (0–255). -pub(super) fn color_param(v: &Value) -> Option<[u8; 3]> { +pub(crate) fn color_param(v: &Value) -> Option<[u8; 3]> { if let Some(t) = v.as_str() { let h = t.trim().trim_start_matches('#'); if h.len() != 6 || !h.is_ascii() { @@ -545,6 +557,21 @@ pub(super) fn color_param(v: &Value) -> Option<[u8; 3]> { Some([c(0)?, c(1)?, c(2)?]) } +use crate::schema::appearance::{ + AppearanceAssignParams, AppearanceAssignResult, AppearanceLibraryParams, AppearanceLibraryResult, AppearanceListParams, AppearanceListResult, + BodyLooks, ComponentLookReply, FaceIndexLook, FaceLookReply, FaceSpot, LibraryAppearance, LookInDesign, LookReply, PbrReply, PlainAppearance, + StarterAppearance, +}; + +const ASSIGN_CONTRACT: TypedContract = TypedContract::new(); +const LIBRARY_CONTRACT: TypedContract = TypedContract::new(); +const LIST_CONTRACT: TypedContract = TypedContract::new(); + +/// An appearance command's reply, built from its schema's type so the two can't drift apart. +fn appearance_reply(cmd: &str, r: impl serde::Serialize) -> Result { + serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string())) +} + pub(super) fn appearance(s: &mut Session, p: &Value) -> Result { use solidcraft_doc::appearance::FaceLook; let cmd = "appearance.assign"; @@ -639,12 +666,9 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result { }) }); } - Ok(json!({ - "bodies": bodies, - "faces": faces.iter().map(|(b, p)| json!({"body": b, "point": p})).collect::>(), - "components": comps, - "appearance": look.as_ref().map(look_json), - })) + let faces = faces.iter().map(|(body, p)| FaceSpot { body: body.clone(), point: [p.x, p.y, p.z] }).collect(); + let appearance = look.as_ref().map(LookReply::from); + appearance_reply(cmd, AppearanceAssignResult { bodies, faces, components: comps, appearance, param_warnings: Vec::new() }) } /// Shared look parser for assignment and atomic replacement. @@ -766,35 +790,45 @@ pub(super) fn attach_pbr(cmd: &str, params: &Value, look: &mut solidcraft_doc::a } fn appearance_library(_s: &mut Session, _p: &Value) -> Result { - let mut list: Vec = solidcraft_doc::appearance::LIBRARY + let category = |name: &str| name.split(" - ").next().unwrap_or(name).to_string(); + let mut list: Vec = solidcraft_doc::appearance::LIBRARY .iter() .map(|(n, c, o)| { - let category = n.split(" - ").next().unwrap_or(n); - json!({"name": n, "category": category, "color": format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]), "opacity": o}) + let look = LookReply { name: n.to_string(), color: format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]), opacity: *o, pbr: None }; + LibraryAppearance::Plain(PlainAppearance { look, category: category(n) }) }) .collect(); list.extend(solidcraft_doc::appearance::OPAQUE_FINISHES.iter().filter_map(|(name, ..)| { let look = solidcraft_doc::appearance::library(name)?; - let mut value = look_json(&look); - value["category"] = json!(name.split(" - ").next().unwrap_or(name)); - Some(value) + Some(LibraryAppearance::Plain(PlainAppearance { look: LookReply::from(&look), category: category(name) })) })); for preset in solidcraft_doc::appearance_pack::STARTER_PACK { let c = preset.preview_color(); - let pbr = preset.opaque_look().ok().and_then(|look| look.pbr); - list.push(json!({"id":preset.id,"name":preset.name,"category":preset.category,"revision":preset.revision, - "color":format!("#{:02x}{:02x}{:02x}",c[0],c[1],c[2]),"opacity":1.0,"pbr":pbr, - "available":preset.is_opaque(),"requirements":preset.requirements,"provenance":preset.provenance, - "recipe":preset.recipe,"preview_note":preset.preview_note,"future_texture_recipe":preset.future_texture_recipe})); + list.push(LibraryAppearance::Starter(StarterAppearance { + id: preset.id.to_string(), + name: preset.name.to_string(), + category: json!(preset.category), + revision: preset.revision, + color: format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]), + opacity: 1.0, + pbr: preset.opaque_look().ok().and_then(|look| look.pbr).map(PbrReply::from), + available: preset.is_opaque(), + requirements: json!(preset.requirements), + provenance: json!(preset.provenance), + recipe: json!(preset.recipe), + preview_note: preset.preview_note.to_string(), + future_texture_recipe: json!(preset.future_texture_recipe), + })); } - Ok(json!({"appearances": list})) + appearance_reply("appearance.library", AppearanceLibraryResult { appearances: list, param_warnings: Vec::new() }) } fn appearance_list(s: &mut Session, p: &Value) -> Result { let a = &s.doc.appearances; // "In this design": each look used, with where. - let mut used: Vec<(solidcraft_doc::appearance::Look, Vec, Vec, Vec)> = Vec::new(); - fn slot(used: &mut Vec<(solidcraft_doc::appearance::Look, Vec, Vec, Vec)>, l: &solidcraft_doc::appearance::Look) -> usize { + type Used = Vec<(solidcraft_doc::appearance::Look, Vec, Vec, Vec)>; + let mut used: Used = Vec::new(); + fn slot(used: &mut Used, l: &solidcraft_doc::appearance::Look) -> usize { match used.iter().position(|(u, ..)| u == l) { Some(i) => i, None => { @@ -806,51 +840,49 @@ fn appearance_list(s: &mut Session, p: &Value) -> Result { for (b, l) in &a.bodies { let i = slot(&mut used, l); if let Some(u) = used.get_mut(i) { - u.1.push(json!(b)); + u.1.push(b.clone()); } } for f in &a.faces { let i = slot(&mut used, &f.look); if let Some(u) = used.get_mut(i) { - u.2.push(json!({"body": f.body, "point": f.point})); + u.2.push(FaceSpot { body: f.body.clone(), point: [f.point.x, f.point.y, f.point.z] }); } } for (c, l) in &a.components { let i = slot(&mut used, l); if let Some(u) = used.get_mut(i) { - u.3.push(json!(c)); + u.3.push(*c); } } - let in_design: Vec = used - .iter() - .map(|(l, b, f, c)| { - let mut value = look_json(l); - value["bodies"] = json!(b); - value["faces"] = json!(f); - value["components"] = json!(c); - value - }) - .collect(); - let mut out = json!({ - "in_design": in_design, - "bodies": a.bodies.iter().map(|(b, l)| (b.clone(), look_json(l))).collect::>(), - "faces": a.faces.iter().map(|f| json!({"body": f.body, "point": f.point, "appearance": look_json(&f.look)})).collect::>(), - "components": a.components.iter().map(|(c, l)| json!({"component": c, "appearance": look_json(l)})).collect::>(), - }); + let in_design = + used.into_iter().map(|(l, bodies, faces, components)| LookInDesign { look: LookReply::from(&l), bodies, faces, components }).collect(); + let mut out = AppearanceListResult { + in_design, + bodies: a.bodies.iter().map(|(b, l)| (b.clone(), LookReply::from(l))).collect(), + faces: a + .faces + .iter() + .map(|f| FaceLookReply { body: f.body.clone(), point: [f.point.x, f.point.y, f.point.z], appearance: LookReply::from(&f.look) }) + .collect(), + components: a.components.iter().map(|(c, l)| ComponentLookReply { component: *c, appearance: LookReply::from(l) }).collect(), + body: None, + param_warnings: Vec::new(), + }; if let Some(name) = str_(p, "body") { let st = s.model.state(); // A placed copy's name (`KB (K:2)`) means the body it shows, as appearance.assign takes // it (#9740): the reply names that body. let own = s.own_body_name(name); let b = own.as_deref().and_then(|n| st.body(n)).ok_or_else(|| bad("appearance.list", format!("no body `{name}`")))?; - out["body"] = json!({ - "name": b.name, - "appearance": s.doc.model_body_look(b).map(|l| look_json(&l)), - "color": s.doc.body_color(b), - "faces": s.doc.face_colors(b).iter().map(|(i, l)| json!({"face": i, "appearance": look_json(l)})).collect::>(), + out.body = Some(BodyLooks { + name: b.name.clone(), + appearance: s.doc.model_body_look(b).as_ref().map(LookReply::from), + color: s.doc.body_color(b), + faces: s.doc.face_colors(b).iter().map(|(i, l)| FaceIndexLook { face: *i, appearance: LookReply::from(l) }).collect(), }); } - Ok(out) + appearance_reply("appearance.list", out) } fn material_list(s: &mut Session, _p: &Value) -> Result { diff --git a/crates/engine/src/schema/appearance.rs b/crates/engine/src/schema/appearance.rs new file mode 100644 index 000000000..ef18ad14f --- /dev/null +++ b/crates/engine/src/schema/appearance.rs @@ -0,0 +1,384 @@ +//! Contracts and result types for the appearance commands in `cmd/inspect.rs`: +//! `appearance.assign`, `appearance.library` and `appearance.list`. + +use std::borrow::Cow; +use std::collections::BTreeMap; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Value, json}; +use solidcraft_doc::appearance::Look; +use solidcraft_doc::pbr_appearance::PbrParameters; + +use super::check::whole; +use super::types::{Point3, StringList}; +use crate::params; + +/// Give bodies, faces or components a look, or clear theirs: a library appearance or a starter +/// recipe by `appearance`, or a `color`. With neither (or `color: null`) the targets' own looks +/// are cleared, so a face follows its body, a body its component and a component its material. +/// One undo step; no dialogs. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppearanceAssignParams { + /// Bodies, by name (a placed copy's name, `KB (K:2)`, means the body it shows). + #[serde(default)] + pub bodies: Option, + /// Faces, by a point on each, at most 10000. + #[serde(default)] + pub faces: Option, + /// The body the `faces` points are on, for points that don't name one. Default: the + /// nearest body with a face there. + #[serde(default)] + pub body: Option, + /// Components, by name or id, or a placement's name (`K:2`). + #[serde(default)] + pub components: Option, + /// A library appearance's name or a starter recipe's name or stable `starter.*` id (see + /// `appearance.library`). With `color` too, that colour under this name. A recipe that + /// needs refraction (the glass ones) is refused. + #[serde(default)] + pub appearance: Option, + /// The colour, `"#rrggbb"` or `[r, g, b]` (0–255); with `appearance`, it replaces the + /// recipe's colour. `null` (without `appearance`) clears the targets' looks. + #[serde(default)] + pub color: Option, + /// 0 (clear) to 1 (opaque). Default: 1, or the appearance's own. With `color` alone it + /// must be within 0–1; with `appearance` it is clamped there. + #[serde(default)] + pub opacity: Option, + /// A label for a copied look: needs `color`, not with `appearance`. + #[serde(default)] + pub name: Option, + /// The opaque PBR response (needs `color` or `appearance`, and opacity 1). Left out, a + /// recipe keeps its own; `null` clears it. + #[serde(default)] + pub pbr: Option, +} + +/// `appearance.assign`'s `faces`: at most 10000 points, each `[x, y, z]` (or `{x, y, z}`) or +/// `{"point": [x, y, z], "body": name}`, read as the handler reads them. +#[derive(Clone, Debug, PartialEq)] +pub struct FaceSpots(pub Vec); + +impl<'de> Deserialize<'de> for FaceSpots { + fn deserialize>(d: D) -> Result { + let fail = || D::Error::custom("must list points [x, y, z]"); + let list = match Value::deserialize(d)? { + Value::Array(list) if list.len() <= 10_000 => list, + _ => return Err(fail()), + }; + let point = |v: &Value| params::vec3(v).or_else(|| v.get("point").and_then(params::vec3)); + if list.iter().all(|v| point(v).is_some()) { Ok(FaceSpots(list)) } else { Err(fail()) } + } +} + +impl JsonSchema for FaceSpots { + fn schema_name() -> Cow<'static, str> { + "FaceSpots".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + let on_body = json!({ + "type": "object", + "properties": {"point": point, "body": {"type": "string"}}, + "required": ["point"] + }); + json_schema!({ + "description": "Points in mm, one on each face: [x, y, z], or {\"point\": [x, y, z], \"body\": name} to say which body.", + "type": "array", + "items": {"anyOf": [point, on_body]}, + "maxItems": 10000 + }) + } +} + +/// A colour, `"#rrggbb"` (the `#` optional) or `[r, g, b]` of numbers 0–255, as +/// `inspect::color_param` reads it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ColorParam(pub [u8; 3]); + +impl<'de> Deserialize<'de> for ColorParam { + fn deserialize>(d: D) -> Result { + crate::cmd::inspect::color_param(&Value::deserialize(d)?) + .map(ColorParam) + .ok_or_else(|| D::Error::custom("must be \"#rrggbb\" or [r, g, b] with values 0–255")) + } +} + +impl JsonSchema for ColorParam { + fn schema_name() -> Cow<'static, str> { + "Color".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let channel = json!({"type": "number", "minimum": 0, "maximum": 255}); + json_schema!({ + "description": "A colour: \"#rrggbb\" or [r, g, b] with values 0–255.", + "anyOf": [ + {"type": "string", "pattern": "^#?[0-9A-Fa-f]{6}$"}, + {"type": "array", "items": channel, "minItems": 3, "maxItems": 3} + ] + }) + } +} + +/// A copied look's label: 1 to 128 characters, none of them a control character. +#[derive(Clone, Debug, PartialEq)] +pub struct LookLabel(pub String); + +impl<'de> Deserialize<'de> for LookLabel { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) if !s.is_empty() && s.chars().count() <= 128 && !s.chars().any(char::is_control) => Ok(LookLabel(s)), + _ => Err(D::Error::custom("must be a nonempty label of at most 128 characters without controls")), + } + } +} + +impl JsonSchema for LookLabel { + fn schema_name() -> Cow<'static, str> { + "LookLabel".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A label for a copied look, without control characters.", + "type": "string", + "minLength": 1, + "maxLength": 128 + }) + } +} + +/// An opaque PBR response, exactly `metallic`, `roughness` and `dielectric_ior`, checked as +/// the handler checks it (`attach_pbr`), with its messages. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PbrParam(pub PbrParameters); + +impl<'de> Deserialize<'de> for PbrParam { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + let object = value + .as_object() + .filter(|o| o.len() == 3 && o.keys().all(|k| matches!(k.as_str(), "metallic" | "roughness" | "dielectric_ior"))) + .ok_or_else(|| D::Error::custom(whole("`pbr` requires exactly metallic, roughness and dielectric_ior")))?; + let number = |key: &str| { + object.get(key).and_then(Value::as_f64).ok_or_else(|| D::Error::custom(whole(format!("`pbr.{key}` must be a finite number")))) + }; + PbrParameters::new(number("metallic")?, number("roughness")?, number("dielectric_ior")?).map(PbrParam).map_err(|e| D::Error::custom(whole(e))) + } +} + +impl JsonSchema for PbrParam { + fn schema_name() -> Cow<'static, str> { + "PbrParameters".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "An opaque PBR response.", + "type": "object", + "properties": { + "metallic": {"type": "number", "minimum": 0, "maximum": 1}, + "roughness": {"type": "number", "minimum": 0.045, "maximum": 1}, + "dielectric_ior": {"type": "number", "minimum": 1, "maximum": 3} + }, + "required": ["metallic", "roughness", "dielectric_ior"], + "additionalProperties": false + }) + } +} + +/// A look's PBR response, as the appearance commands report it. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +pub struct PbrReply { + pub metallic: f64, + pub roughness: f64, + pub dielectric_ior: f64, +} + +impl From for PbrReply { + fn from(p: PbrParameters) -> Self { + PbrReply { metallic: p.metallic(), roughness: p.roughness(), dielectric_ior: p.dielectric_ior() } + } +} + +/// A look, as the appearance commands report it. +#[derive(Clone, Debug, Serialize, JsonSchema)] +pub struct LookReply { + /// The library appearance's or recipe's name, or the look's label (`Custom` for a plain + /// colour). + pub name: String, + /// `"#rrggbb"`. + pub color: String, + /// 0 (clear) to 1 (opaque). + pub opacity: f64, + /// Its opaque PBR response, when it has one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pbr: Option, +} + +impl From<&Look> for LookReply { + fn from(l: &Look) -> Self { + LookReply { name: l.name.clone(), color: l.hex(), opacity: l.opacity, pbr: l.pbr.map(PbrReply::from) } + } +} + +/// A face with a look of its own: its body and the point on it the look was given at. +#[derive(Clone, Debug, Serialize, JsonSchema)] +pub struct FaceSpot { + pub body: String, + /// `[x, y, z]` in mm. + pub point: [f64; 3], +} + +/// What `appearance.assign` returns: the targets, and the look they got (`null`: cleared). +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppearanceAssignResult { + pub bodies: Vec, + pub faces: Vec, + /// The components, by id. + pub components: Vec, + pub appearance: Option, + /// 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, +} + +/// `appearance.library` takes no parameters. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppearanceLibraryParams {} + +/// What `appearance.library` returns: every appearance `appearance.assign` takes by name. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppearanceLibraryResult { + pub appearances: 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 library entry: a plain appearance or finish, or a starter recipe. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum LibraryAppearance { + Plain(PlainAppearance), + Starter(StarterAppearance), +} + +/// A legacy scalar appearance, or an opaque PBR finish (which has `pbr`). +#[derive(Debug, Serialize, JsonSchema)] +pub struct PlainAppearance { + #[serde(flatten)] + pub look: LookReply, + /// The part of the name before ` - `, such as `Aluminum`. + pub category: String, +} + +/// A starter recipe: its look, where it comes from and what showing it needs. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StarterAppearance { + /// Its stable id, `starter.*`, which `appearance.assign` takes as `appearance`. + pub id: String, + pub name: String, + /// wood, metal, plastic, glass, solar or regolith. + pub category: Value, + pub revision: u32, + /// Its preview colour, `"#rrggbb"`. + pub color: String, + pub opacity: f64, + /// Its opaque PBR response; `null` for a recipe that has none (glass). + pub pbr: Option, + /// False for a recipe this build can't show (the glass ones need refraction). + pub available: bool, + /// What showing it needs: opaque_pbr, refraction, certified_thin_or_closed. + pub requirements: Value, + /// Who made it and under which licence: {author, license, source, kind}. + pub provenance: Value, + /// Its optical recipe: {kind: opaque, color, metallic, roughness, dielectric_ior} or + /// {kind: glass, dielectric_ior, transmission_linear_rgb, reference_path_mm, boundary}. + pub recipe: Value, + pub preview_note: String, + /// The texture it is meant to get later ({id, repeat_mm, grain_axis}), or `null`. + pub future_texture_recipe: Value, +} + +/// `appearance.list` takes one parameter, `body`, optional. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppearanceListParams { + /// A body (or a placed copy's name, `KB (K:2)`, for the body it shows): the reply adds + /// `body`, its resolved look and its faces' looks. + #[serde(default)] + pub body: Option, +} + +/// What `appearance.list` returns: the looks the design assigns, by look and by target. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppearanceListResult { + /// Each look the design uses, with where it is used. + pub in_design: Vec, + /// The bodies with a look of their own, by name. + pub bodies: BTreeMap, + /// The faces with a look of their own. + pub faces: Vec, + /// The components with a look of their own. + pub components: Vec, + /// With `body`: that body's resolved look and its faces'. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option, + /// 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, +} + +/// A look the design uses, and the bodies, faces and components it is given to. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LookInDesign { + #[serde(flatten)] + pub look: LookReply, + pub bodies: Vec, + pub faces: Vec, + /// Components, by id. + pub components: Vec, +} + +/// A face's own look. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FaceLookReply { + pub body: String, + /// `[x, y, z]` in mm: the point the look was given at. + pub point: [f64; 3], + pub appearance: LookReply, +} + +/// A component's own look. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ComponentLookReply { + /// The component's id. + pub component: u64, + pub appearance: LookReply, +} + +/// A body's resolved look and its faces' looks. +#[derive(Debug, Serialize, JsonSchema)] +pub struct BodyLooks { + pub name: String, + /// The look it shows (its own, else its component's, else its material's), or `null`. + pub appearance: Option, + /// The colour it is drawn in, `[r, g, b]` from 0 to 1, or `null` for the default. + pub color: Option<[f32; 3]>, + /// Its faces with a look (their own or imported), by face index. + pub faces: Vec, +} + +/// A face's look, by the face's index in `model.faces`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FaceIndexLook { + pub face: usize, + pub appearance: LookReply, +} + +#[cfg(test)] +#[path = "appearance_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/appearance_tests.rs b/crates/engine/src/schema/appearance_tests.rs new file mode 100644 index 000000000..c25e7aa12 --- /dev/null +++ b/crates/engine/src/schema/appearance_tests.rs @@ -0,0 +1,82 @@ +use serde_json::{Value, json}; + +use super::{ + AppearanceAssignParams, AppearanceAssignResult, AppearanceLibraryParams, AppearanceLibraryResult, AppearanceListParams, AppearanceListResult, +}; +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}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys( + input_schema_for::(), + &["appearance", "bodies", "body", "color", "components", "faces", "name", "opacity", "pbr"], + ); + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &["body"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("appearance.assign", json!({"faces": [[1, 2]]})), + ("appearance.assign", json!({"faces": [{"body": "Box1"}]})), + ("appearance.assign", json!({"color": "red"})), + ("appearance.assign", json!({"color": [0, 128, 300]})), + ("appearance.assign", json!({"color": "#ff0000", "name": ""})), + ("appearance.assign", json!({"color": "#ff0000", "pbr": {"metallic": 1}})), + ("appearance.assign", json!({"color": "#ff0000", "pbr": {"metallic": "1", "roughness": 0.5, "dielectric_ior": 1.5}})), + ("appearance.assign", json!({"color": "#ff0000", "pbr": {"metallic": 2, "roughness": 0.5, "dielectric_ior": 1.5}})), + ]); +} + +/// A library look, a starter recipe, a colour with PBR on a face, a cleared body, the library +/// and the list with and without `body`, in Warn: each reply matches its output schema and +/// carries no warning; a misspelt key's warning still matches. +#[test] +fn replies_match_the_output_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: schemars::Schema, id: &str, reply: &Value| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}"); + }; + let assigned = |reply: &Value| { + assert!(reply.get("param_warnings").is_none(), "{reply}"); + matches(output_schema_for::(), "appearance.assign", reply); + }; + let made = run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 0]})); + let body = made["created_bodies"][0].as_str().unwrap_or_default().to_string(); + let library = run("appearance.library", json!({})); + assert!(library.get("param_warnings").is_none(), "{library}"); + matches(output_schema_for::(), "appearance.library", &library); + let entries = library["appearances"].as_array().cloned().unwrap_or_default(); + let named = |pick: &dyn Fn(&Value) -> bool| entries.iter().find(|e| pick(e)).and_then(|e| e["name"].as_str()).unwrap_or_default().to_string(); + let plain = named(&|e| e.get("id").is_none() && e.get("pbr").is_none()); + let finish = named(&|e| e.get("id").is_none() && e.get("pbr").is_some()); + let starter = entries.iter().find(|e| e["available"] == true).and_then(|e| e["id"].as_str()).unwrap_or_default().to_string(); + assert!(!plain.is_empty() && !finish.is_empty() && !starter.is_empty(), "{library}"); + assigned(&run("appearance.assign", json!({"bodies": [body], "appearance": plain, "opacity": 0.5}))); + assigned(&run("appearance.assign", json!({"bodies": body, "appearance": finish}))); + assigned(&run("appearance.assign", json!({"bodies": [body], "appearance": starter}))); + let face = run( + "appearance.assign", + json!({"faces": [{"point": [5, 5, 10], "body": body}], "color": [200, 40, 40], "name": "Signal red", + "pbr": {"metallic": 0, "roughness": 0.4, "dielectric_ior": 1.5}}), + ); + assert_eq!(face["faces"][0]["point"], json!([5.0, 5.0, 10.0]), "{face}"); + assigned(&face); + let all = run("appearance.list", json!({})); + assert!(all.get("param_warnings").is_none() && all.get("body").is_none(), "{all}"); + matches(output_schema_for::(), "appearance.list", &all); + let one = run("appearance.list", json!({"body": body})); + assert_eq!(one["body"]["faces"].as_array().map(Vec::len), Some(1), "{one}"); + matches(output_schema_for::(), "appearance.list", &one); + let cleared = run("appearance.assign", json!({"bodies": [body]})); + assert!(cleared["appearance"].is_null(), "{cleared}"); + assigned(&cleared); + let warned = run("appearance.list", json!({"bodyy": body})); + assert!(warned["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{warned}"); + matches(output_schema_for::(), "appearance.list", &warned); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 655e62acb..2981f17f7 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -54,6 +54,7 @@ mod coverage_tests; mod tests; // The contracts, by command file. +pub mod appearance; pub mod bom; pub mod browser; pub mod component; diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index f98799380..0d2ceb349 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -2,9 +2,6 @@ # (coverage_tests.rs). This list only shrinks: when you give a command its contract and output # type, remove its line. Never add one: a new command comes with both schemas. Sorted, one id # per line. -appearance.assign -appearance.library -appearance.list body.rename browser.collapse_all browser.expand_all