Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Bill of materials: part properties on components and assembly.bom (#1888) (#1899)

NOWN-DEV99d8d382b983
diff --git a/assets/icons/ui/design/aliases.toml b/assets/icons/ui/design/aliases.toml
index ef3fbb24a5..f3443077c4 100644
--- a/assets/icons/ui/design/aliases.toml
+++ b/assets/icons/ui/design/aliases.toml
@@ -35,3 +35,4 @@ sketch_scale = { master = "scale", accent = "sketch" }
sketch_text = { master = "text", accent = "sketch" }
surface_fair = { master = "spline_cv", accent = "surface" }
mesh_export = { master = "export", accent = "mesh" }
+bom = "list"
diff --git a/assets/locales/en.json b/assets/locales/en.json
index aff0a26e6e..0e7e3226c4 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -333,6 +333,7 @@
"cmd.appearance_assign": "Appearance",
"cmd.appearance_library": "Appearance Library",
"cmd.appearance_list": "List Appearances",
+ "cmd.assembly_bom": "Bill of Materials",
"cmd.body_rename": "Rename Body",
"cmd.browser_group": "New Group",
"cmd.browser_move": "Move Browser Items",
@@ -354,6 +355,8 @@
"cmd.component_insert_design": "Insert Design",
"cmd.component_links": "List Links",
"cmd.component_list": "List Components",
+ "cmd.component_metadata": "Part Properties",
+ "cmd.component_metadata_set": "Change Part Properties",
"cmd.component_move_bodies": "Move Bodies to Component",
"cmd.component_move_sketches": "Move Sketches to Component",
"cmd.component_paste_new": "Paste New",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 205309ba66..f1f4ac4684 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -333,6 +333,7 @@
"cmd.appearance_assign": "外観",
"cmd.appearance_library": "外観ライブラリ",
"cmd.appearance_list": "外観を一覧表示",
+ "cmd.assembly_bom": "部品表",
"cmd.body_rename": "ボディの名前を変更",
"cmd.browser_group": "新規グループ",
"cmd.browser_move": "ブラウザ項目を移動",
@@ -354,6 +355,8 @@
"cmd.component_insert_design": "デザインを挿入",
"cmd.component_links": "リンクを一覧表示",
"cmd.component_list": "コンポーネントを一覧表示",
+ "cmd.component_metadata": "部品プロパティ",
+ "cmd.component_metadata_set": "部品プロパティを変更",
"cmd.component_move_bodies": "ボディをコンポーネントに移動",
"cmd.component_move_sketches": "スケッチをコンポーネントに移動",
"cmd.component_paste_new": "新規として貼り付け",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index c5181f0eca..7298363f46 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -333,6 +333,7 @@
"cmd.appearance_assign": "外观",
"cmd.appearance_library": "外观库",
"cmd.appearance_list": "列出外观",
+ "cmd.assembly_bom": "物料清单",
"cmd.body_rename": "重命名实体",
"cmd.browser_group": "新建组",
"cmd.browser_move": "移动浏览器项目",
@@ -354,6 +355,8 @@
"cmd.component_insert_design": "插入设计",
"cmd.component_links": "列出链接",
"cmd.component_list": "列出组件",
+ "cmd.component_metadata": "零件属性",
+ "cmd.component_metadata_set": "更改零件属性",
"cmd.component_move_bodies": "将实体移至组件",
"cmd.component_move_sketches": "将草图移至组件",
"cmd.component_paste_new": "粘贴为新对象",
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 1ec44993b5..34bae024eb 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -1852,13 +1852,21 @@ pub struct SketchPoints {
/// A component: a node of the design tree that owns sketches, features and bodies. The root
/// (id 0) is the design itself and is not stored.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Component {
pub id: u64,
pub name: String,
/// Parent component (0 = the root).
#[serde(default)]
pub parent: u64,
+ /// The definition's part properties (part number, description, revision…) and other tools'
+ /// data, under the same rules as the design's own `metadata`. Every occurrence shares them;
+ /// the bill of materials reads them.
+ #[serde(default, skip_serializing_if = "crate::Metadata::is_empty")]
+ pub metadata: crate::Metadata,
+ /// Free text properties of the definition (material grade, finish, supplier…), by name.
+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
+ pub properties: std::collections::BTreeMap<String, String>,
}
/// One loft section: profiles of a sketch.
@@ -2622,6 +2630,23 @@ impl Document {
*self == normalized
}
+ /// Only components' part properties (metadata and free properties) changed: nothing to
+ /// evaluate. The same whole-Document proof as [`Document::differs_only_in_render`].
+ pub fn differs_only_in_part_properties(&self, previous: &Document) -> bool {
+ if self.components.len() != previous.components.len()
+ || self.components.iter().zip(&previous.components).any(|(a, b)| a.id != b.id)
+ || self.components == previous.components
+ {
+ return false;
+ }
+ let mut normalized = previous.clone();
+ for (n, c) in normalized.components.iter_mut().zip(&self.components) {
+ n.metadata = c.metadata.clone();
+ n.properties = c.properties.clone();
+ }
+ *self == normalized
+ }
+
/// The colour a body is shown and exported in (sRGB as 0–1 fractions): its appearance,
/// else its component's, else its material's look, else the colour it was imported with.
/// (Faces may have their own: `face_looks`.)
@@ -2720,6 +2745,23 @@ impl Document {
if body.transferred || body.source_name.is_some() { body.component } else { self.legacy_body_component(&body.name, body.feature) }
}
+ /// The components that own a body in `state` ([`Document::model_body_component`] of each),
+ /// in one pass: the timeline is looked up once, not once per body.
+ pub fn body_owners(&self, state: &crate::ModelState) -> std::collections::HashSet<u64> {
+ let features: std::collections::HashMap<u64, u64> = self.features.iter().rev().map(|f| (f.id, f.component)).collect();
+ state
+ .bodies
+ .iter()
+ .map(|b| {
+ if b.transferred || b.source_name.is_some() {
+ b.component
+ } else {
+ self.body_components.get(&b.name).copied().unwrap_or_else(|| features.get(&b.feature).copied().unwrap_or(0))
+ }
+ })
+ .collect()
+ }
+
/// Recorded transfers already converted geometry into the new local frame.
pub fn model_body_offset(&self, body: &crate::ModelBody) -> Option<&crate::Mat> {
if body.transferred { None } else { self.body_offsets.get(&body.name) }
@@ -2745,7 +2787,7 @@ impl Document {
format!("Component{k}")
}
};
- self.components.push(Component { id, name, parent });
+ self.components.push(Component { id, name, parent, ..Default::default() });
self.add_occurrence(id, parent, crate::IDENTITY)?;
Ok(id)
}
diff --git a/crates/doc/src/format/pending/component-metadata.rs b/crates/doc/src/format/pending/component-metadata.rs
new file mode 100644
index 0000000000..e8b82ecab7
--- /dev/null
+++ b/crates/doc/src/format/pending/component-metadata.rs
@@ -0,0 +1,5 @@
+//! A component can carry its own part properties: `metadata` (`part_number`, `description`,
+//! `revision`… and other tools' reverse-DNS keys, under the rules of the design's own `metadata`)
+//! and `properties` (free text, by name), which every occurrence shares and the bill of materials
+//! (`assembly.bom`) reads. Older designs need no transformation: a component without them has none.
+//! The last release asks for an update instead of dropping them on save.
diff --git a/crates/engine/src/cmd/bom.rs b/crates/engine/src/cmd/bom.rs
new file mode 100644
index 0000000000..e23f7dc436
--- /dev/null
+++ b/crates/engine/src/cmd/bom.rs
@@ -0,0 +1,423 @@
+//! Part properties and the bill of materials. `component.metadata` and
+//! `component.metadata.set` read and change a component definition's part number, description,
+//! revision and free properties (shared by every occurrence, saved with the component);
+//! `assembly.bom` counts the placed components of the design, or of one component, and lists
+//! them as rows, optionally written to a CSV or JSON file. With `group_children`, a part with a
+//! part number keeps the parts placed inside it (a bolt's washers and nut) in its own row.
+
+use std::collections::{BTreeMap, HashSet};
+
+use serde_json::{Map, Value, json};
+use solidcraft_doc::metadata::{DESCRIPTION, MAX_KEYS, MAX_TEXT_BYTES, PART_NUMBER, REVISION, WELL_KNOWN};
+
+use super::CommandSpec;
+use crate::params::{bad, str_};
+use crate::{EngineError, Result, Session};
+
+pub static COMMANDS: &[CommandSpec] = &[
+ CommandSpec::new("component.metadata", "Part Properties", read).icon("settings").noundo().doc_only().params(
+ "component: id or name (0 or \"root\": the design's own properties) → component, name, part_number, description, revision, \
+ metadata (as saved, other tools' keys too), properties: {name: text}",
+ ),
+ CommandSpec::new("component.metadata.set", "Change Part Properties", set).icon("settings").doc_only().params(
+ "component: id or name (not the root: use document.metadata.set); part_number?, description?, revision?: text (empty or null \
+ removes); values?: {key: value} (SolidCraft's keys project, part_number, revision, author, organization, description, \
+ license, or a reverse-DNS key holding an object); properties?: {name: text, …} (free properties; empty or null removes). \
+ All or nothing, one undo step → component, metadata, properties, changed: [keys]",
+ ),
+ CommandSpec::new("assembly.bom", "Bill of Materials", bom).at("SOLID", "INSPECT").icon("bom").noundo().params(
+ "component?: id or name (default the design); levels?: flat (default: every part at any depth, counted through its \
+ subassemblies) | top (the component's direct children, subassemblies as one row each); group_by?: [\"part_number\"] \
+ (default; components without a part number get a row per definition) | [\"definition\"]; group_children?: true (a component \
+ with a part number is one row, the parts placed inside it listed under it as children: [{item, part_number, description, \
+ revision, each, count, definition}], not as rows of their own); path?: write a .csv or .json file (children as items 1.1, \
+ 1.2…); format?: csv|json (default from the path) → rows: [{item, part_number, description, revision, count, definition, \
+ components, properties, children?}] sorted by part number, total_occurrences (children included)",
+ ),
+];
+
+/// Longest free property name, in bytes.
+const MAX_PROPERTY_NAME_BYTES: usize = 128;
+/// How deep, and over how many placements, the bill of materials walks.
+const MAX_DEPTH: usize = 64;
+const MAX_PLACEMENTS: usize = 100_000;
+
+fn key(v: Option<&Value>) -> Option<String> {
+ match v {
+ Some(Value::Number(n)) => Some(n.to_string()),
+ Some(Value::String(s)) => Some(s.clone()),
+ _ => None,
+ }
+}
+
+fn component_id(s: &Session, p: &Value, cmd: &str) -> Result<u64> {
+ let k = key(p.get("component")).ok_or_else(|| bad(cmd, "`component` must be a component id or name"))?;
+ s.doc.find_component(&k).ok_or_else(|| bad(cmd, format!("no component `{k}`")))
+}
+
+fn read(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "component.metadata";
+ let id = component_id(s, p, cmd)?;
+ if id == 0 {
+ let m = &s.doc.metadata;
+ return Ok(json!({"component": 0, "name": s.doc.name, "part_number": m.part_number(), "description": m.description(),
+ "revision": m.revision(), "metadata": m, "properties": {}}));
+ }
+ let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?;
+ let m = &c.metadata;
+ Ok(json!({"component": id, "name": c.name, "part_number": m.part_number(), "description": m.description(),
+ "revision": m.revision(), "metadata": m, "properties": c.properties}))
+}
+
+/// A free property as it may be saved (`None`: remove it), or why not.
+fn property(name: &str, value: &Value, cmd: &str) -> Result<Option<String>> {
+ let shown: String = name.chars().take(64).collect();
+ if name.trim().is_empty() || name.len() > MAX_PROPERTY_NAME_BYTES || name.chars().any(char::is_control) {
+ return Err(bad(cmd, format!("property name `{shown}` must be 1…{MAX_PROPERTY_NAME_BYTES} bytes of text without control characters")));
+ }
+ let text = match value {
+ Value::Null => return Ok(None),
+ Value::String(t) if t.is_empty() => return Ok(None),
+ Value::String(t) => t.clone(),
+ Value::Number(n) => n.to_string(),
+ Value::Bool(b) => b.to_string(),
+ _ => return Err(bad(cmd, format!("property `{shown}` takes text"))),
+ };
+ if text.len() > MAX_TEXT_BYTES {
+ return Err(bad(cmd, format!("property `{shown}` is longer than {MAX_TEXT_BYTES} bytes")));
+ }
+ if text.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r')) {
+ return Err(bad(cmd, format!("property `{shown}` has a control character")));
+ }
+ Ok(Some(text))
+}
+
+fn set(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "component.metadata.set";
+ let id = component_id(s, p, cmd)?;
+ if id == 0 {
+ return Err(bad(cmd, "the root is the design: its properties are document.metadata.set's"));
+ }
+ let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?;
+ let (mut metadata, mut properties) = (c.metadata.clone(), c.properties.clone());
+ let mut entries: Vec<(String, Value)> = Vec::new();
+ match p.get("values") {
+ None => {}
+ Some(Value::Object(v)) if v.len() <= MAX_KEYS => entries.extend(v.iter().map(|(k, v)| (k.clone(), v.clone()))),
+ Some(Value::Object(_)) => return Err(bad(cmd, format!("`values` can hold at most {MAX_KEYS} keys"))),
+ Some(_) => return Err(bad(cmd, "`values` must be an object: {key: value, …}")),
+ }
+ for k in [PART_NUMBER, DESCRIPTION, REVISION] {
+ if let Some(v) = p.get(k) {
+ entries.push((k.to_string(), v.clone()));
+ }
+ }
+ let props: Vec<(&String, &Value)> = match p.get("properties") {
+ None => Vec::new(),
+ Some(Value::Object(v)) if v.len() <= MAX_KEYS => v.iter().collect(),
+ Some(Value::Object(_)) => return Err(bad(cmd, format!("`properties` can hold at most {MAX_KEYS} names"))),
+ Some(_) => return Err(bad(cmd, "`properties` must be an object: {name: text, …}")),
+ };
+ if entries.is_empty() && props.is_empty() {
+ return Err(bad(cmd, format!("give part_number, description, revision, values or properties ({})", WELL_KNOWN.join(", "))));
+ }
+ let mut changed: Vec<String> = Vec::new();
+ for (k, v) in entries {
+ if metadata.set(&k, v).map_err(|e| bad(cmd, e.to_string()))? && !changed.contains(&k) {
+ changed.push(k);
+ }
+ }
+ for (name, value) in props {
+ let was = properties.get(name).cloned();
+ match property(name, value, cmd)? {
+ Some(text) => {
+ properties.insert(name.clone(), text);
+ }
+ None => {
+ properties.remove(name);
+ }
+ }
+ if properties.get(name) != was.as_ref() {
+ changed.push(format!("properties.{name}"));
+ }
+ }
+ if properties.len() > MAX_KEYS {
+ return Err(bad(cmd, format!("a component holds at most {MAX_KEYS} properties")));
+ }
+ // Only a real change touches the design (an undo step, unsaved changes).
+ if !changed.is_empty()
+ && let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == id)
+ {
+ c.metadata = metadata;
+ c.properties = properties;
+ }
+ let c = s.doc.components.iter().find(|c| c.id == id);
+ Ok(json!({"component": id, "metadata": c.map(|c| &c.metadata), "properties": c.map(|c| &c.properties), "changed": changed}))
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum Levels {
+ Flat,
+ Top,
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum Group {
+ PartNumber,
+ Definition,
+}
+
+/// One row being gathered.
+struct Row {
+ part_number: String,
+ description: String,
+ revision: String,
+ count: u64,
+ components: Vec<u64>,
+ names: Vec<String>,
+ properties: BTreeMap<String, String>,
+ /// With `group_children`: what is placed inside one of this row's parts, and how often.
+ kit: BTreeMap<u64, u64>,
+}
+
+/// What the bill of materials lists and how.
+#[derive(Clone, Copy)]
+struct Options {
+ levels: Levels,
+ group: Group,
+ /// A part with a part number keeps its sub-parts in its row.
+ fold: bool,
+}
+
+fn options(p: &Value, cmd: &str) -> Result<Options> {
+ let levels = match p.get("levels") {
+ None | Some(Value::Null) => Levels::Flat,
+ Some(Value::String(l)) if l == "flat" => Levels::Flat,
+ Some(Value::String(l)) if l == "top" => Levels::Top,
+ Some(_) => return Err(bad(cmd, "`levels` is flat or top")),
+ };
+ let group = match p.get("group_by") {
+ None | Some(Value::Null) => Group::PartNumber,
+ Some(Value::String(g)) => group_key(g, cmd)?,
+ Some(Value::Array(a)) => match a.as_slice() {
+ [Value::String(g)] => group_key(g, cmd)?,
+ _ => return Err(bad(cmd, "`group_by` is [\"part_number\"] or [\"definition\"]")),
+ },
+ Some(_) => return Err(bad(cmd, "`group_by` is [\"part_number\"] or [\"definition\"]")),
+ };
+ let fold = match p.get("group_children") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(b)) => *b,
+ Some(_) => return Err(bad(cmd, "`group_children` is true or false")),
+ };
+ Ok(Options { levels, group, fold })
+}
+
+/// The design's structure, looked up once per bill of materials.
+struct Index {
+ /// What each component places (by its id; 0 is the root).
+ children: BTreeMap<u64, Vec<u64>>,
+ /// Components with bodies of their own.
+ owners: HashSet<u64>,
+ /// Components with a part number: with `group_children`, one row however much is inside.
+ numbered: HashSet<u64>,
+}
+
+impl Index {
+ fn new(s: &Session) -> Index {
+ let mut children: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
+ for o in &s.doc.occurrences {
+ children.entry(o.parent).or_default().push(o.component);
+ }
+ let numbered = s.doc.components.iter().filter(|c| c.metadata.part_number().is_some_and(|n| !n.is_empty())).map(|c| c.id).collect();
+ Index { children, owners: s.doc.body_owners(&s.model.state()), numbered }
+ }
+}
+
+fn group_key(g: &str, cmd: &str) -> Result<Group> {
+ match g {
+ "part_number" => Ok(Group::PartNumber),
+ "definition" => Ok(Group::Definition),
+ o => Err(bad(cmd, format!("can't group by `{o}` (part_number or definition)"))),
+ }
+}
+
+/// How many times each component is placed below `root`: in `Top`, its direct children; in
+/// `Flat`, every placement at any depth (a part in a subassembly placed twice counts twice),
+/// not below a numbered part when `fold`.
+fn counts(ix: &Index, root: u64, levels: Levels, fold: bool, cmd: &str) -> Result<BTreeMap<u64, u64>> {
+ let mut out: BTreeMap<u64, u64> = BTreeMap::new();
+ let mut placed = 0usize;
+ let mut stack: Vec<(u64, usize)> = vec![(root, 0)];
+ while let Some((comp, depth)) = stack.pop() {
+ for child in ix.children.get(&comp).into_iter().flatten() {
+ placed += 1;
+ if depth >= MAX_DEPTH || placed > MAX_PLACEMENTS {
+ return Err(bad(cmd, format!("the assembly is deeper than {MAX_DEPTH} levels or has more than {MAX_PLACEMENTS} placements")));
+ }
+ *out.entry(*child).or_default() += 1;
+ if levels == Levels::Flat && !(fold && ix.numbered.contains(child)) {
+ stack.push((*child, depth + 1));
+ }
+ }
+ }
+ if levels == Levels::Flat {
+ // Parts only: a subassembly is listed through its parts, unless it has bodies of its own
+ // (or, folding, a part number).
+ out.retain(|c, _| !ix.children.contains_key(c) || (fold && ix.numbered.contains(c)) || ix.owners.contains(c));
+ }
+ Ok(out)
+}
+
+/// How a kit reads when rows are compared: its parts by part number (else definition) and count.
+fn kit_key(s: &Session, kit: &BTreeMap<u64, u64>) -> String {
+ let mut parts: Vec<String> = kit
+ .iter()
+ .map(|(id, n)| {
+ let pn = s.doc.components.iter().find(|c| c.id == *id).and_then(|c| c.metadata.part_number()).unwrap_or_default();
+ if pn.is_empty() { format!("#{id}×{n}") } else { format!("{pn}×{n}") }
+ })
+ .collect();
+ parts.sort();
+ parts.join("\n")
+}
+
+fn rows(s: &Session, counts: &BTreeMap<u64, u64>, group: Group, kits: &BTreeMap<u64, BTreeMap<u64, u64>>) -> Vec<Row> {
+ let mut grouped: BTreeMap<(String, String, u64), Row> = BTreeMap::new();
+ for (id, n) in counts {
+ let Some(c) = s.doc.components.iter().find(|c| c.id == *id) else { continue };
+ let m = &c.metadata;
+ let part_number = m.part_number().unwrap_or_default().to_string();
+ let kit = kits.get(id).cloned().unwrap_or_default();
+ // Without a part number a definition is its own row; parts with different contents
+ // (a bolt with or without its nut) are different rows.
+ let k = match group {
+ Group::PartNumber if !part_number.is_empty() => (part_number.clone(), kit_key(s, &kit), 0),
+ _ => (String::new(), String::new(), *id),
+ };
+ let row = grouped.entry(k).or_insert_with(|| Row {
+ part_number: part_number.clone(),
+ description: String::new(),
+ revision: String::new(),
+ count: 0,
+ components: Vec::new(),
+ names: Vec::new(),
+ properties: BTreeMap::new(),
+ kit,
+ });
+ row.count += n;
+ row.components.push(*id);
+ if !row.names.contains(&c.name) {
+ row.names.push(c.name.clone());
+ }
+ if row.description.is_empty() {
+ row.description = m.description().unwrap_or_default().to_string();
+ }
+ if row.revision.is_empty() {
+ row.revision = m.revision().unwrap_or_default().to_string();
+ }
+ for (k, v) in &c.properties {
+ row.properties.entry(k.clone()).or_insert_with(|| v.clone());
+ }
+ }
+ let mut out: Vec<Row> = grouped.into_values().collect();
+ // By part number; rows without one after them, by name.
+ out.sort_by(|a, b| {
+ (a.part_number.is_empty(), &a.part_number, &a.names, &a.components).cmp(&(b.part_number.is_empty(), &b.part_number, &b.names, &b.components))
+ });
+ out
+}
+
+/// A CSV field, always quoted.
+fn quote(s: &str) -> String {
+ format!("\"{}\"", s.replace('"', "\"\""))
+}
+
+/// The bill of materials as CSV: fixed columns, every field quoted.
+fn csv(rows: &[Value]) -> String {
+ let mut out = ["item", "part_number", "description", "revision", "count", "definition"].map(quote).join(",");
+ out.push('\n');
+ let lines = rows.iter().flat_map(|r| std::iter::once(r).chain(r["children"].as_array().into_iter().flatten()));
+ for r in lines {
+ let text = |k: &str| match &r[k] {
+ Value::String(t) => t.clone(),
+ Value::Null => String::new(),
+ v => v.to_string(),
+ };
+ let fields = ["item", "part_number", "description", "revision", "count", "definition"].map(|k| quote(&text(k)));
+ out.push_str(&fields.join(","));
+ out.push('\n');
+ }
+ out
+}
+
+fn bom(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "assembly.bom";
+ let root = if p.get("component").is_some_and(|v| !v.is_null()) { component_id(s, p, cmd)? } else { 0 };
+ let o = options(p, cmd)?;
+ let ix = Index::new(s);
+ let counts = counts(&ix, root, o.levels, o.fold, cmd)?;
+ // Folding: what one of each numbered part holds, as parts at any depth.
+ let mut kits: BTreeMap<u64, BTreeMap<u64, u64>> = BTreeMap::new();
+ if o.fold {
+ for id in counts.keys().filter(|id| ix.numbered.contains(id)) {
+ let kit = self::counts(&ix, *id, Levels::Flat, false, cmd)?;
+ if !kit.is_empty() {
+ kits.insert(*id, kit);
+ }
+ }
+ }
+ let mut total: u64 = 0;
+ let rows: Vec<Value> = rows(s, &counts, o.group, &kits)
+ .into_iter()
+ .enumerate()
+ .map(|(i, r)| {
+ total += r.count;
+ let mut v = json!({"item": i + 1, "part_number": r.part_number, "description": r.description, "revision": r.revision,
+ "count": r.count, "definition": r.names.join("; "), "components": r.components, "properties": r.properties});
+ if !r.kit.is_empty() {
+ let children: Vec<Value> = self::rows(s, &r.kit, Group::PartNumber, &BTreeMap::new())
+ .into_iter()
+ .enumerate()
+ .map(|(j, c)| {
+ let count = c.count.saturating_mul(r.count);
+ total += count;
+ json!({"item": format!("{}.{}", i + 1, j + 1), "part_number": c.part_number, "description": c.description,
+ "revision": c.revision, "each": c.count, "count": count, "definition": c.names.join("; ")})
+ })
+ .collect();
+ v["children"] = Value::Array(children);
+ }
+ v
+ })
+ .collect();
+ let mut out = Map::new();
+ out.insert("component".into(), json!(root));
+ out.insert("levels".into(), json!(if o.levels == Levels::Top { "top" } else { "flat" }));
+ out.insert("group_by".into(), json!([if o.group == Group::Definition { "definition" } else { "part_number" }]));
+ out.insert("group_children".into(), json!(o.fold));
+ if let Some(path) = str_(p, "path") {
+ let format = match str_(p, "format").map(str::to_ascii_lowercase) {
+ Some(f) => f,
+ None if path.to_ascii_lowercase().ends_with(".json") => "json".into(),
+ None if path.to_ascii_lowercase().ends_with(".csv") => "csv".into(),
+ None => return Err(bad(cmd, "`path` must end in .csv or .json, or give `format`")),
+ };
+ let text = match format.as_str() {
+ "csv" => csv(&rows),
+ "json" => serde_json::to_string_pretty(&json!({"rows": rows, "total_occurrences": total})).map_err(|e| bad(cmd, e.to_string()))?,
+ other => return Err(bad(cmd, format!("unknown format `{other}` (csv or json)"))),
+ };
+ solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ out.insert("path".into(), json!(path));
+ out.insert("format".into(), json!(format));
+ }
+ out.insert("rows".into(), Value::Array(rows));
+ out.insert("total_occurrences".into(), json!(total));
+ Ok(Value::Object(out))
+}
+
+#[cfg(test)]
+#[path = "bom_tests.rs"]
+#[allow(clippy::unwrap_used, clippy::expect_used)]
+mod tests;
diff --git a/crates/engine/src/cmd/bom_tests.rs b/crates/engine/src/cmd/bom_tests.rs
new file mode 100644
index 0000000000..5faa6ca6f6
--- /dev/null
+++ b/crates/engine/src/cmd/bom_tests.rs
@@ -0,0 +1,277 @@
+use serde_json::{Value, json};
+
+use crate::Session;
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ match s.execute(id, &p) {
+ Ok(v) => v,
+ Err(e) => panic!("{id} {p}: {e}"),
+ }
+}
+
+/// A folder of its own for one test's files.
+fn scratch(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("solidcraft-bom-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+/// A plate placed three times, and a hinge subassembly (no bodies of its own) placed twice
+/// that holds one pin: the plate has 3 occurrences, the pin 2 (one in each hinge).
+fn assembly() -> Session {
+ let mut s = Session::default();
+ run(&mut s, "component.create", json!({"name": "Plate"}));
+ run(&mut s, "solid.box", json!({"length": 40, "width": 20, "height": 3}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ run(&mut s, "component.create", json!({"name": "Hinge", "activate": false}));
+ run(&mut s, "component.create", json!({"name": "Pin", "parent": "Hinge"}));
+ run(&mut s, "solid.cylinder", json!({"diameter": 4, "height": 30}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ for x in [50, 100] {
+ run(&mut s, "occurrence.copy", json!({"component": "Plate", "translate": [x, 0, 0]}));
+ }
+ run(&mut s, "occurrence.copy", json!({"component": "Hinge", "translate": [0, 50, 0]}));
+ run(&mut s, "component.metadata.set", json!({"component": "Plate", "part_number": "PL-100", "description": "Plate, 3 mm", "revision": "B"}));
+ run(
+ &mut s,
+ "component.metadata.set",
+ json!({"component": "Pin", "part_number": "PN-040", "description": "Pin 4 x 30", "properties": {"finish": "zinc"}}),
+ );
+ s
+}
+
+fn summary(r: &Value) -> Vec<(String, String, u64)> {
+ r["rows"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|r| (r["part_number"].as_str().unwrap().to_string(), r["definition"].as_str().unwrap().to_string(), r["count"].as_u64().unwrap()))
+ .collect()
+}
+
+#[test]
+fn flat_counts_parts_through_subassemblies_and_top_counts_children() {
+ let mut s = assembly();
+ let undo = s.undo.len();
+ let flat = run(&mut s, "assembly.bom", json!({}));
+ assert_eq!(summary(&flat), [("PL-100".into(), "Plate".into(), 3), ("PN-040".into(), "Pin".into(), 2)], "{flat}");
+ assert_eq!(flat["total_occurrences"], 5);
+ assert_eq!(flat["rows"][0]["item"], 1);
+ assert_eq!(flat["rows"][0]["description"], "Plate, 3 mm");
+ assert_eq!(flat["rows"][0]["revision"], "B");
+ assert_eq!(flat["rows"][1]["properties"], json!({"finish": "zinc"}));
+
+ let top = run(&mut s, "assembly.bom", json!({"levels": "top"}));
+ assert_eq!(summary(&top), [("PL-100".into(), "Plate".into(), 3), (String::new(), "Hinge".into(), 2)], "{top}");
+ assert_eq!(top["total_occurrences"], 5);
+
+ // One subassembly's own bill of materials.
+ let hinge = run(&mut s, "assembly.bom", json!({"component": "Hinge"}));
+ assert_eq!(summary(&hinge), [("PN-040".into(), "Pin".into(), 1)]);
+ assert_eq!(s.undo.len(), undo, "the bill of materials only reads");
+}
+
+#[test]
+fn equal_part_numbers_share_a_row_unless_grouped_by_definition() {
+ let mut s = assembly();
+ // An independent copy keeps the part properties, so it is the same part.
+ run(&mut s, "component.paste_new", json!({"component": "Plate", "translate": [0, -60, 0]}));
+ let r = run(&mut s, "assembly.bom", json!({}));
+ let plate = &r["rows"][0];
+ assert_eq!((plate["part_number"].as_str(), plate["count"].as_u64()), (Some("PL-100"), Some(4)), "{r}");
+ assert_eq!(plate["components"].as_array().map(Vec::len), Some(2));
+ let by_def = run(&mut s, "assembly.bom", json!({"group_by": ["definition"]}));
+ let counts: Vec<u64> =
+ by_def["rows"].as_array().unwrap().iter().filter(|r| r["part_number"] == "PL-100").map(|r| r["count"].as_u64().unwrap()).collect();
+ assert_eq!(counts, [3, 1], "{by_def}");
+ // Without a part number every definition is its own row, after the numbered ones.
+ run(&mut s, "component.create", json!({"name": "Spacer"}));
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ let r = run(&mut s, "assembly.bom", json!({}));
+ let last = r["rows"].as_array().unwrap().last().cloned().unwrap();
+ assert_eq!((last["part_number"].as_str(), last["definition"].as_str()), (Some(""), Some("Spacer")));
+}
+
+#[test]
+fn part_properties_survive_save_and_open_and_undo_in_one_step() {
+ let dir = scratch("roundtrip");
+ let mut s = assembly();
+ let undo = s.undo.len();
+ let r = run(&mut s, "component.metadata.set", json!({"component": "Pin", "revision": "C", "properties": {"finish": null, "material": "1.4301"}}));
+ assert_eq!(r["changed"], json!(["revision", "properties.finish", "properties.material"]));
+ assert_eq!(s.undo.len(), undo + 1, "one undo step");
+ // Setting the same values again changes nothing.
+ let r = run(&mut s, "component.metadata.set", json!({"component": "Pin", "revision": "C"}));
+ assert_eq!(r["changed"], json!([]));
+ assert_eq!(s.undo.len(), undo + 1);
+ for (file, format) in [("bom.json", "json"), ("bom.solidcraft", "container")] {
+ let path = dir.join(file);
+ run(&mut s, "file.save_as", json!({"path": path, "format": format}));
+ let mut back = Session::default();
+ run(&mut back, "doc.open", json!({"path": path}));
+ let pin = run(&mut back, "component.metadata", json!({"component": "Pin"}));
+ assert_eq!((pin["part_number"].as_str(), pin["revision"].as_str()), (Some("PN-040"), Some("C")), "{format}: {pin}");
+ assert_eq!(pin["properties"], json!({"material": "1.4301"}), "{format}");
+ assert_eq!(summary(&run(&mut back, "assembly.bom", json!({}))), summary(&run(&mut s, "assembly.bom", json!({}))), "{format}");
+ }
+ run(&mut s, "edit.undo", json!({}));
+ let pin = run(&mut s, "component.metadata", json!({"component": "Pin"}));
+ assert_eq!((pin["revision"].as_str(), &pin["properties"]), (None, &json!({"finish": "zinc"})));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn csv_quotes_every_field_and_json_writes_the_rows() {
+ let dir = scratch("export");
+ let mut s = assembly();
+ run(&mut s, "component.metadata.set", json!({"component": "Pin", "description": "Pin \"short\", 4 mm"}));
+ let csv = dir.join("bom.csv");
+ let r = run(&mut s, "assembly.bom", json!({"path": csv}));
+ assert_eq!(r["format"], "csv");
+ let text = std::fs::read_to_string(&csv).unwrap();
+ assert_eq!(
+ text,
+ "\"item\",\"part_number\",\"description\",\"revision\",\"count\",\"definition\"\n\
+ \"1\",\"PL-100\",\"Plate, 3 mm\",\"B\",\"3\",\"Plate\"\n\
+ \"2\",\"PN-040\",\"Pin \"\"short\"\", 4 mm\",\"\",\"2\",\"Pin\"\n"
+ );
+ let json_path = dir.join("bom.json");
+ run(&mut s, "assembly.bom", json!({"path": json_path, "levels": "top"}));
+ let back: Value = serde_json::from_str(&std::fs::read_to_string(&json_path).unwrap()).unwrap();
+ assert_eq!(back["total_occurrences"], 5);
+ assert_eq!(back["rows"][1]["definition"], "Hinge");
+ assert!(s.execute("assembly.bom", &json!({"path": dir.join("bom.txt")})).is_err(), "unknown extension");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn standard_parts_carry_a_part_number_that_follows_a_resize() {
+ let mut s = Session::default();
+ let a = run(&mut s, "parts.insert", json!({"family": "socket_head_cap_screw", "size": "M6", "length": 20}));
+ run(&mut s, "parts.insert", json!({"family": "socket_head_cap_screw", "size": "M6", "length": 20, "point": [30, 0, 0]}));
+ run(&mut s, "parts.insert", json!({"family": "bearing", "size": "608", "point": [60, 0, 0]}));
+ let r = run(&mut s, "assembly.bom", json!({}));
+ let rows: Vec<(String, String, u64)> = r["rows"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|r| (r["part_number"].as_str().unwrap().into(), r["description"].as_str().unwrap().into(), r["count"].as_u64().unwrap()))
+ .collect();
+ assert_eq!(
+ rows,
+ [("608".into(), "Deep groove ball bearing (envelope) 608".into(), 1), ("ISO 4762 M6x20".into(), "Socket head cap screw M6x20".into(), 2)]
+ );
+ let screws = r["rows"].as_array().unwrap().iter().find(|r| r["count"] == 2).cloned().unwrap();
+ assert_eq!(screws["definition"], "SHCS M6x20", "equal names are named once");
+ assert_eq!(screws["components"].as_array().map(Vec::len), Some(2));
+ // A resize renumbers the part; a description someone wrote stays theirs.
+ let comp = a["component"].as_u64().unwrap();
+ run(&mut s, "component.metadata.set", json!({"component": comp, "description": "Cap screw, A2"}));
+ run(&mut s, "parts.resize", json!({"component": comp, "size": "M8", "length": 25}));
+ let m = run(&mut s, "component.metadata", json!({"component": comp}));
+ assert_eq!((m["part_number"].as_str(), m["description"].as_str()), (Some("ISO 4762 M8x25"), Some("Cap screw, A2")));
+}
+
+#[test]
+fn hostile_part_properties_are_refused_without_a_change() {
+ let mut s = assembly();
+ let undo = s.undo.len();
+ for p in [
+ json!({"component": "Pin"}),
+ json!({"component": 0, "part_number": "X"}),
+ json!({"component": "Nope", "part_number": "X"}),
+ json!({"component": "Pin", "part_number": 7}),
+ json!({"component": "Pin", "part_number": "ok", "description": "bell\u{7}"}),
+ json!({"component": "Pin", "properties": {"": "x"}}),
+ json!({"component": "Pin", "properties": {"finish": ["x"]}}),
+ json!({"component": "Pin", "properties": {"finish": "x".repeat(5000)}}),
+ json!({"component": "Pin", "values": {"bogus": "x"}}),
+ json!({"component": "Pin", "values": "x"}),
+ ] {
+ assert!(s.execute("component.metadata.set", &p).is_err(), "{p}");
+ }
+ assert_eq!(s.undo.len(), undo);
+ let pin = run(&mut s, "component.metadata", json!({"component": "Pin"}));
+ assert_eq!(pin["part_number"], "PN-040", "all or nothing");
+ for p in [json!({"levels": "deep"}), json!({"group_by": ["colour"]}), json!({"group_by": 3}), json!({"component": "Nope"})] {
+ assert!(s.execute("assembly.bom", &p).is_err(), "{p}");
+ }
+ // The root reads as the design's own properties.
+ run(&mut s, "document.metadata.set", json!({"key": "part_number", "value": "ASM-1"}));
+ assert_eq!(run(&mut s, "component.metadata", json!({"component": 0}))["part_number"], "ASM-1");
+}
+
+/// Two hex bolts, each with a washer and a nut placed inside it, and a third bolt alone.
+fn bolts() -> Session {
+ let mut s = Session::default();
+ for x in [0, 30] {
+ let bolt = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M6", "length": 30, "point": [x, 0, 0], "direction": [0, 0, 1]}));
+ run(&mut s, "component.activate", json!({"component": bolt["component"]}));
+ run(&mut s, "parts.insert", json!({"family": "washer", "size": "M6", "point": [x, 0, -2], "direction": [0, 0, -1]}));
+ run(&mut s, "parts.insert", json!({"family": "hex_nut", "size": "M6", "point": [x, 0, -4], "direction": [0, 0, -1]}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ }
+ run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M6", "length": 30, "point": [60, 0, 0], "direction": [0, 0, 1]}));
+ s
+}
+
+#[test]
+fn group_children_keeps_a_bolts_washer_and_nut_in_its_row() {
+ let mut s = bolts();
+ let plain = run(&mut s, "assembly.bom", json!({}));
+ let numbers: Vec<(String, u64)> = summary(&plain).into_iter().map(|(pn, _, n)| (pn, n)).collect();
+ assert_eq!(numbers, [("ISO 4017 M6x30".into(), 3), ("ISO 4032 M6".into(), 2), ("ISO 7089 M6".into(), 2)], "{plain}");
+
+ let r = run(&mut s, "assembly.bom", json!({"group_children": true}));
+ let rows = r["rows"].as_array().unwrap();
+ assert_eq!(rows.len(), 2, "the bolts with a nut and the bolt alone: {r}");
+ let kit = &rows[0];
+ assert_eq!((kit["part_number"].as_str(), kit["count"].as_u64()), (Some("ISO 4017 M6x30"), Some(2)), "{r}");
+ let children: Vec<(&str, &str, u64, u64)> = kit["children"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| (c["item"].as_str().unwrap(), c["part_number"].as_str().unwrap(), c["each"].as_u64().unwrap(), c["count"].as_u64().unwrap()))
+ .collect();
+ assert_eq!(children, [("1.1", "ISO 4032 M6", 1, 2), ("1.2", "ISO 7089 M6", 1, 2)]);
+ assert_eq!((rows[1]["count"].as_u64(), rows[1].get("children")), (Some(1), None));
+ assert_eq!(r["total_occurrences"], plain["total_occurrences"], "the same parts, folded");
+
+ let dir = scratch("kit");
+ let path = dir.join("bom.csv");
+ run(&mut s, "assembly.bom", json!({"group_children": true, "path": path.to_str().unwrap()}));
+ let text = std::fs::read_to_string(&path).unwrap();
+ let items: Vec<&str> = text.lines().skip(1).map(|l| l.split(',').next().unwrap()).collect();
+ assert_eq!(items, ["\"1\"", "\"1.1\"", "\"1.2\"", "\"2\""], "{text}");
+ assert!(s.execute("assembly.bom", &json!({"group_children": "yes"})).is_err());
+}
+
+#[test]
+fn changing_part_properties_does_not_evaluate_the_model_again() {
+ let mut s = bolts();
+ s.evaluations = 0;
+ run(&mut s, "component.metadata.set", json!({"component": 1, "description": "Bolt", "properties": {"finish": "zinc"}}));
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "edit.redo", json!({}));
+ assert_eq!(s.evaluations, 0, "part properties change no geometry");
+ assert_eq!(run(&mut s, "component.metadata", json!({"component": 1}))["description"], "Bolt");
+ // A geometric edit after it finds every other feature's earlier result.
+ let first = run(&mut s, "assembly.bom", json!({}))["rows"][1]["components"][0].clone();
+ run(&mut s, "parts.resize", json!({"component": first, "size": "M8"}));
+ run(&mut s, "parts.resize", json!({"component": first, "size": "M6"}));
+ // Anything else still evaluates.
+ run(&mut s, "occurrence.copy", json!({"component": 1, "translate": [0, 40, 0]}));
+ assert!(s.evaluations > 0);
+}
+
+#[test]
+fn body_owners_match_each_bodys_component() {
+ for s in [assembly(), bolts()] {
+ let st = s.model.state();
+ let each: std::collections::HashSet<u64> = st.bodies.iter().map(|b| s.doc.model_body_component(b)).collect();
+ assert_eq!(s.doc.body_owners(&st), each);
+ assert!(each.len() > 1);
+ }
+}
diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs
index 368d324db4..2dcf3da9ad 100644
--- a/crates/engine/src/cmd/component_clone.rs
+++ b/crates/engine/src/cmd/component_clone.rs
@@ -253,6 +253,11 @@ pub(super) fn paste(
};
let name = unique(&c.name, &mut used);
let new = scratch.doc_mut().add_component(Some(&name), mapped_parent)?;
+ // A copy keeps the definition's part properties.
+ if let Some(added) = scratch.doc_mut().components.iter_mut().find(|x| x.id == new) {
+ added.metadata = c.metadata.clone();
+ added.properties = c.properties.clone();
+ }
components.insert(*old, new);
if *old != component {
scratch.doc_mut().occurrences.retain(|o| o.component != new);
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index d02c971485..c5a1dc0d5f 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -20,6 +20,7 @@ macro_rules! planned {
};
}
+mod bom;
mod browser;
mod clearance;
mod clipboard;
@@ -260,6 +261,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
v.extend(motion::COMMANDS.iter());
v.extend(config::COMMANDS.iter());
v.extend(parts::COMMANDS.iter());
+ v.extend(bom::COMMANDS.iter());
v.extend(browser::COMMANDS.iter());
v.extend(delete::COMMANDS.iter());
v.extend(edit::COMMANDS.iter());
diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs
index ffdb3e0936..36ffcd4fcd 100644
--- a/crates/engine/src/cmd/parts.rs
+++ b/crates/engine/src/cmd/parts.rs
@@ -316,6 +316,45 @@ fn part_name(family: &str, size: &str, sh: &Shape) -> String {
}
}
+/// A standard part's part number and description: its standard and size (`ISO 4762 M6x20`), or
+/// a bearing's designation, and the family's name with the size.
+fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) {
+ let size = match sh {
+ Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{size}x{len}"),
+ _ => size.to_string(),
+ };
+ let standard = match family {
+ "socket_head_cap_screw" => "ISO 4762",
+ "hex_bolt" => "ISO 4017",
+ "hex_nut" => "ISO 4032",
+ "washer" => "ISO 7089",
+ "set_screw" => "ISO 4026",
+ "dowel_pin" => "ISO 8734",
+ _ => "",
+ };
+ let name = FAMILIES.iter().find(|f| f.0 == family).map_or("Part", |f| f.1);
+ let part_number = if standard.is_empty() { size.clone() } else { format!("{standard} {size}") };
+ (part_number, format!("{name} {size}"))
+}
+
+/// Give a standard part its part number and description; a field someone changed since the last
+/// size (`was`) is theirs and stays.
+fn set_identity(s: &mut Session, comp: u64, now: (String, String), was: Option<(String, String)>) {
+ use solidcraft_doc::metadata::{DESCRIPTION, PART_NUMBER};
+ let Some(c) = s.doc.components.iter().find(|c| c.id == comp) else { return };
+ let mut m = c.metadata.clone();
+ for (k, new, old) in [(PART_NUMBER, now.0, was.as_ref().map(|w| w.0.as_str())), (DESCRIPTION, now.1, was.as_ref().map(|w| w.1.as_str()))] {
+ if m.text(k).is_none_or(|cur| Some(cur) == old) {
+ let _ = m.set(k, Value::String(new));
+ }
+ }
+ if m != c.metadata
+ && let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == comp)
+ {
+ c.metadata = m;
+ }
+}
+
fn label(family: &str) -> &'static str {
match family {
"socket_head_cap_screw" => "SHCS",
@@ -356,6 +395,7 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
let (comp, occ) = (c["component"].as_u64().unwrap_or(0), c["occurrence"].as_u64().unwrap_or(0));
build(s, &sh)?;
s.doc_mut().parts.insert(comp, solidcraft_doc::StandardPart { family: family.clone(), size: size.clone(), length: shape_len(&sh) });
+ set_identity(s, comp, identity(&family, &size, &sh), None);
run(s, "component.activate", json!({"component": active}))?;
let mut out = json!({"component": comp, "occurrence": occ, "name": name});
if let (Some(a), Some(h)) = (at, host) {
@@ -435,6 +475,8 @@ fn resize(s: &mut Session, p: &Value) -> Result<Value> {
run(s, "component.activate", json!({"component": comp}))?;
build(s, &sh)?;
let name = part_name(&part.family, &size, &sh);
+ let was = shape(&part.family, &part.size, part.length).ok().map(|old| identity(&part.family, &part.size, &old));
+ set_identity(s, comp, identity(&part.family, &size, &sh), was);
s.doc_mut().parts.insert(comp, solidcraft_doc::StandardPart { family: part.family.clone(), size: size.clone(), length: shape_len(&sh) });
if let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == comp) {
c.name = name.clone();
diff --git a/crates/engine/src/cmd/sketch_3d_frame_tests.rs b/crates/engine/src/cmd/sketch_3d_frame_tests.rs
index 4acd5d7df4..6dfbe7d657 100644
--- a/crates/engine/src/cmd/sketch_3d_frame_tests.rs
+++ b/crates/engine/src/cmd/sketch_3d_frame_tests.rs
@@ -215,7 +215,7 @@ fn wire_frame_wide_owner_graph_has_bounded_indexed_traversal() {
// A legal wide assembly used to force one whole occurrence scan for each leaf.
let doc = s.doc_mut();
for i in 0..9998u64 {
- doc.components.push(solidcraft_doc::Component { id: 10_000 + i, name: format!("Sibling{i}"), parent: 0 });
+ doc.components.push(solidcraft_doc::Component { id: 10_000 + i, name: format!("Sibling{i}"), parent: 0, ..Default::default() });
doc.occurrences.push(solidcraft_doc::Occurrence {
id: 100_000 + i,
component: 10_000 + i,
diff --git a/crates/engine/src/cmd/urdf_tests.rs b/crates/engine/src/cmd/urdf_tests.rs
index 47e1981562..1c497bc060 100644
--- a/crates/engine/src/cmd/urdf_tests.rs
+++ b/crates/engine/src/cmd/urdf_tests.rs
@@ -557,7 +557,12 @@ fn urdf_warns_when_placements_are_cut_off() {
let s = Session::default();
let mut doc = (*s.doc).clone();
for k in 1..=66u64 {
- doc.components.push(solidcraft_doc::Component { id: 1000 + k, name: format!("C{k}"), parent: if k == 1 { 0 } else { 999 + k } });
+ doc.components.push(solidcraft_doc::Component {
+ id: 1000 + k,
+ name: format!("C{k}"),
+ parent: if k == 1 { 0 } else { 999 + k },
+ ..Default::default()
+ });
doc.occurrences.push(solidcraft_doc::Occurrence {
id: 2000 + k,
component: 1000 + k,
@@ -569,8 +574,8 @@ fn urdf_warns_when_placements_are_cut_off() {
}
// A component placed twice with a part nested in it, next to the deep chain: its copy is
// still there, since only the branch past the limit stops.
- doc.components.push(solidcraft_doc::Component { id: 3001, name: "Leg".into(), parent: 0 });
- doc.components.push(solidcraft_doc::Component { id: 3002, name: "Foot".into(), parent: 3001 });
+ doc.components.push(solidcraft_doc::Component { id: 3001, name: "Leg".into(), parent: 0, ..Default::default() });
+ doc.components.push(solidcraft_doc::Component { id: 3002, name: "Foot".into(), parent: 3001, ..Default::default() });
// Listed first, so the walk (a stack) goes down the chain before reaching them.
for (id, component, parent, name) in [(4003, 3002, 3001, "Foot:1"), (4002, 3001, 0, "Leg:2"), (4001, 3001, 0, "Leg:1")] {
let o = solidcraft_doc::Occurrence { id, component, parent, name: name.into(), transform: solidcraft_doc::IDENTITY, grounded: false };
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index bf2318511d..889509b884 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -589,9 +589,12 @@ impl Session {
}
}
- /// Only persistent render intent changed. Never evaluate or clear a stale model here.
+ /// Only persistent render intent, or only part properties, changed. Never evaluate or clear
+ /// a stale model here.
fn render_only_change(&self, before: &Snapshot) -> bool {
- self.active_sketch == before.active_sketch && self.pending_moves == before.pending_moves && self.doc.differs_only_in_render(&before.doc)
+ self.active_sketch == before.active_sketch
+ && self.pending_moves == before.pending_moves
+ && (self.doc.differs_only_in_render(&before.doc) || self.doc.differs_only_in_part_properties(&before.doc))
}
fn refresh_render(&mut self, previous: &Arc<Document>) {
diff --git a/crates/ui-egui/src/bom_panel.rs b/crates/ui-egui/src/bom_panel.rs
new file mode 100644
index 0000000000..5bab059de9
--- /dev/null
+++ b/crates/ui-egui/src/bom_panel.rs
@@ -0,0 +1,224 @@
+//! The Bill of Materials window: `assembly.bom`'s rows (flat or top level, grouped by part
+//! number or by definition, a part's sub-parts in its row or not), with Export CSV… and Export
+//! JSON…. Picking a row edits its part
+//! number, description and revision through one `component.metadata.set` per definition. The
+//! toolbar's Bill of Materials (`ui.start` of `assembly.bom`) opens it.
+
+use egui::RichText;
+use serde_json::{Value, json};
+
+use crate::SolveApp;
+use crate::theme::Tokens;
+
+/// The window's state; the rows come from the engine.
+#[derive(Default)]
+pub struct BomPanel {
+ /// Top level instead of flat.
+ pub top: bool,
+ /// One row per definition instead of per part number.
+ pub by_definition: bool,
+ /// A part with a part number keeps its sub-parts (a bolt's washers and nut) in its row.
+ pub group_children: bool,
+ /// The rows for (design revision, top, by_definition, group_children).
+ cache: Option<(u64, [bool; 3], Value)>,
+ /// The picked row's index, and its fields as edited.
+ pub picked: Option<usize>,
+ pub fields: [String; 3],
+ /// The last refusal.
+ pub error: Option<String>,
+}
+
+impl BomPanel {
+ fn params(&self) -> Value {
+ json!({"levels": if self.top { "top" } else { "flat" }, "group_by": [if self.by_definition { "definition" } else { "part_number" }],
+ "group_children": self.group_children})
+ }
+
+ /// The bill of materials for the design as it is now (computed again only after a change).
+ fn rows(&mut self, app: &mut SolveApp) -> Value {
+ let revision = app.session.revision;
+ let key = [self.top, self.by_definition, self.group_children];
+ if let Some((r, k, v)) = &self.cache
+ && (*r, *k) == (revision, key)
+ {
+ return v.clone();
+ }
+ let v = match app.session.execute("assembly.bom", &self.params()) {
+ Ok(v) => v,
+ Err(e) => {
+ self.error = Some(e.to_string());
+ json!({"rows": [], "total_occurrences": 0})
+ }
+ };
+ self.cache = Some((revision, key, v.clone()));
+ v
+ }
+}
+
+/// Open the window.
+pub fn open(app: &mut SolveApp) {
+ app.bom = Some(BomPanel::default());
+}
+
+fn text(row: &Value, k: &str) -> String {
+ match &row[k] {
+ Value::String(t) => t.clone(),
+ Value::Null => String::new(),
+ v => v.to_string(),
+ }
+}
+
+/// Apply the picked row's fields to each of its definitions (one undo step each).
+fn apply(app: &mut SolveApp, d: &mut BomPanel, row: &Value) {
+ let [pn, desc, rev] = d.fields.clone();
+ for c in row["components"].as_array().into_iter().flatten() {
+ let r = app.run("component.metadata.set", json!({"component": c, "part_number": pn, "description": desc, "revision": rev}));
+ if let Err(e) = r {
+ d.error = Some(e);
+ return;
+ }
+ }
+ d.error = None;
+}
+
+/// Draw the window when it is open. Called once per frame.
+pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
+ let Some(mut d) = app.bom.take() else { return };
+ let t = Tokens::get();
+ let mut open = true;
+ let bom = d.rows(app);
+ let rows: Vec<Value> = bom["rows"].as_array().cloned().unwrap_or_default();
+ let (mut export, mut apply_row) = (None, None);
+ let title = RichText::new(crate::i18n::tr_label("Bill of Materials")).strong().size(13.0);
+ crate::frame::window(ctx, title, crate::frame::Width::Wide).id(egui::Id::new("sc_bom")).open(&mut open).resizable(true).show(ctx, |ui| {
+ ui.horizontal(|ui| {
+ let was = (d.top, d.by_definition, d.group_children);
+ ui.selectable_value(&mut d.top, false, "Parts only");
+ ui.selectable_value(&mut d.top, true, "Top level");
+ ui.separator();
+ ui.selectable_value(&mut d.by_definition, false, "By part number");
+ ui.selectable_value(&mut d.by_definition, true, "By definition");
+ ui.separator();
+ ui.checkbox(&mut d.group_children, "Sub-parts in their part's row");
+ if was != (d.top, d.by_definition, d.group_children) {
+ d.picked = None;
+ }
+ });
+ ui.separator();
+ egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
+ egui::Grid::new("sc_bom_grid").num_columns(6).striped(true).spacing([14.0, 4.0]).show(ui, |ui| {
+ for h in ["Item", "Part number", "Description", "Rev", "Qty", "Definition"] {
+ ui.label(RichText::new(h).strong().color(t.text_dim));
+ }
+ ui.end_row();
+ for (i, row) in rows.iter().enumerate() {
+ let picked = d.picked == Some(i);
+ if ui.selectable_label(picked, text(row, "item")).clicked() {
+ d.picked = if picked { None } else { Some(i) };
+ d.fields = [text(row, "part_number"), text(row, "description"), text(row, "revision")];
+ }
+ ui.label(text(row, "part_number"));
+ ui.label(text(row, "description"));
+ ui.label(text(row, "revision"));
+ ui.label(text(row, "count"));
+ ui.label(RichText::new(text(row, "definition")).color(t.text_dim));
+ ui.end_row();
+ for c in row["children"].as_array().into_iter().flatten() {
+ ui.label(RichText::new(text(c, "item")).color(t.text_dim));
+ ui.label(text(c, "part_number"));
+ ui.label(text(c, "description"));
+ ui.label(text(c, "revision"));
+ ui.label(text(c, "count"));
+ ui.label(RichText::new(text(c, "definition")).color(t.text_dim));
+ ui.end_row();
+ }
+ }
+ });
+ });
+ ui.label(RichText::new(format!("{} rows, {} placed", rows.len(), text(&bom, "total_occurrences"))).small().color(t.text_dim));
+ if let Some(row) = d.picked.and_then(|i| rows.get(i)) {
+ ui.separator();
+ egui::Grid::new("sc_bom_edit").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
+ for (label, field) in ["Part number", "Description", "Revision"].into_iter().zip(d.fields.iter_mut()) {
+ ui.label(label);
+ ui.add(egui::TextEdit::singleline(field).desired_width(280.0));
+ ui.end_row();
+ }
+ });
+ if ui.button("Apply").clicked() {
+ apply_row = Some(row.clone());
+ }
+ }
+ if let Some(e) = &d.error {
+ ui.label(RichText::new(e).color(t.error));
+ }
+ ui.separator();
+ ui.horizontal(|ui| {
+ for (label, ext) in [("Export CSV…", "csv"), ("Export JSON…", "json")] {
+ if ui.button(label).clicked() {
+ export = Some(ext);
+ }
+ }
+ });
+ });
+ if let Some(row) = apply_row {
+ apply(app, &mut d, &row);
+ }
+ if let Some(ext) = export {
+ let mut params = d.params();
+ params["format"] = json!(ext);
+ app.pick_save_command(&format!("bill-of-materials.{ext}"), &[ext], "assembly.bom", params);
+ }
+ if open {
+ app.bom = Some(d);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use crate::scenario::Harness;
+
+ #[test]
+ fn the_window_lists_counts_and_edits_a_part_number() {
+ let mut h = Harness::new();
+ h.app.run("component.create", json!({"name": "Plate"})).unwrap();
+ h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 3})).unwrap();
+ h.app.run("component.activate", json!({"component": 0})).unwrap();
+ h.app.run("occurrence.copy", json!({"component": "Plate", "translate": [50, 0, 0]})).unwrap();
+ h.step(&json!({"start": "assembly.bom"})).unwrap();
+ assert!(h.app.bom.is_some(), "ui.start opens the window");
+ h.frames(2);
+ assert!(h.widget("Export CSV…").is_some());
+ assert!(h.widget("1 rows, 2 placed").is_some());
+ let undo = h.app.session.undo.len();
+ h.step(&json!({"widget": "1"})).unwrap();
+ let d = h.app.bom.as_mut().unwrap();
+ assert_eq!(d.picked, Some(0));
+ d.fields[0] = "PL-100".into();
+ h.frames(2);
+ h.step(&json!({"widget": "Apply"})).unwrap();
+ let m = h.app.session.execute("component.metadata", &json!({"component": "Plate"})).unwrap();
+ assert_eq!(m["part_number"], "PL-100");
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step");
+ h.frames(2);
+ assert!(h.widget("PL-100").is_some(), "the list follows the change");
+ }
+
+ #[test]
+ fn sub_parts_show_under_their_part() {
+ let mut h = Harness::new();
+ let bolt = h.app.run("parts.insert", json!({"family": "hex_bolt", "size": "M6", "length": 30, "point": [0, 0, 0]})).unwrap();
+ h.app.run("component.activate", json!({"component": bolt["component"]})).unwrap();
+ h.app.run("parts.insert", json!({"family": "hex_nut", "size": "M6", "point": [0, 0, -4]})).unwrap();
+ h.app.run("component.activate", json!({"component": 0})).unwrap();
+ h.step(&json!({"start": "assembly.bom"})).unwrap();
+ h.frames(2);
+ assert!(h.widget("2 rows, 2 placed").is_some());
+ h.step(&json!({"widget": "Sub-parts in their part's row"})).unwrap();
+ h.frames(2);
+ assert!(h.widget("1 rows, 2 placed").is_some());
+ assert!(h.widget("1.1").is_some(), "the nut under its bolt");
+ }
+}
diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs
index 7e7656aff1..fced2be8a0 100644
--- a/crates/ui-egui/src/documents.rs
+++ b/crates/ui-egui/src/documents.rs
@@ -96,6 +96,7 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot {
app.tool = None;
app.params = None;
app.design_properties = None;
+ app.bom = None;
app.cancel_view_animation();
app.viewport.orbit_snap = None;
app.viewport.orbit_free = None;
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index c68afd2d62..b5d2d4f005 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -11,6 +11,7 @@
pub mod access;
pub mod agent_chat;
pub mod agent_cursor;
+pub mod bom_panel;
pub mod browser;
pub mod canvas;
#[cfg(test)]
@@ -316,6 +317,8 @@ pub struct SolveApp {
pub params: Option<params_dialog::ParamsDialog>,
/// The Design Properties window, when open.
pub design_properties: Option<design_properties::DesignProperties>,
+ /// The Bill of Materials window, when open.
+ pub bom: Option<bom_panel::BomPanel>,
material_card_review: Option<material_card_review::ReviewWindow>,
pub palette: palette::Palette,
/// Context menus, rename box and Properties window.
@@ -449,6 +452,7 @@ impl SolveApp {
dialog: None,
params: None,
design_properties: None,
+ bom: None,
material_card_review: None,
palette: palette::Palette::default(),
menu: context_menu::MenuState::default(),
@@ -817,6 +821,10 @@ impl SolveApp {
design_properties::open(self);
return;
}
+ if id == "assembly.bom" {
+ bom_panel::open(self);
+ return;
+ }
if id == "sketch.finish" {
self.finish_sketch();
return;
@@ -1448,6 +1456,7 @@ impl SolveApp {
self.resolve_fit(ui.ctx());
params_dialog::show(self, ui.ctx());
design_properties::show(self, ui.ctx());
+ bom_panel::show(self, ui.ctx());
material_card_review::show(self, ui.ctx());
recovery_ui::show(self, ui.ctx());
stand_up::show(self, ui.ctx());
diff --git a/crates/ui-egui/tests/window_widths.rs b/crates/ui-egui/tests/window_widths.rs
index 25a7440974..2f704929d5 100644
--- a/crates/ui-egui/tests/window_widths.rs
+++ b/crates/ui-egui/tests/window_widths.rs
@@ -53,6 +53,7 @@ fn command_dialogs_shrink_to_their_content_within_limits() {
h.app.dialog = None;
h.app.params = None;
h.app.design_properties = None;
+ h.app.bom = None;
h.app.tool = None;
if h.app.session.active_sketch.is_some() {
h.app.finish_sketch();
diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md
index f60701c1c9..0334511233 100644
--- a/docs/book/src/guide/assemblies.md
+++ b/docs/book/src/guide/assemblies.md
@@ -279,3 +279,41 @@ measures the complete assembly. Volumes are summed, including overlapping bodies
measuring their union. The same workflow is available through `component.properties` and
`occurrence.properties`; see
[placement and measurement details](https://github.com/bherbruck/solidcraft/blob/main/docs/assembly-properties.md).
+
+## Part properties and the bill of materials
+
+A component definition carries its own **part properties**: a part number, a description and a
+revision, other tools' data under a reverse-DNS key (the same rules as the design's own
+properties), and free text properties such as a material grade or a finish. Every occurrence of
+the component shares them, Paste New copies them, and they are saved with the component.
+`component.metadata {component}` reads them and
+`component.metadata.set {component, part_number?, description?, revision?, values?, properties?}`
+changes them in one undo step (an empty value removes a field). The root component is the
+design itself: its properties are `document.metadata`'s. Standard parts (`parts.insert`) get a
+part number from their standard and size (`ISO 4762 M6x20`, or a bearing's designation) and a
+description; **Change Part Size** renumbers them, keeping a field you changed yourself.
+
+**Bill of Materials** (`assembly.bom`, on the **INSPECT** panel) counts the placed components:
+
+- `levels: "flat"` (the default) lists the parts at any depth, each counted through its
+ subassemblies: a part placed once in a subassembly that is placed twice counts 2. A
+ subassembly is listed through its parts, unless it has bodies of its own.
+- `levels: "top"` lists the direct children, a subassembly as one row.
+- `group_by: ["part_number"]` (the default) puts definitions with the same part number in one
+ row; a definition without a part number gets a row of its own. `["definition"]` gives every
+ definition its own row.
+- `group_children: true` keeps what is placed inside a part with a part number in that part's
+ row: a bolt with a washer and a nut placed inside it is one row, the washer and the nut listed
+ under it as `children` (items 1.1, 1.2…, with `each` per bolt and `count` in all) instead of
+ rows of their own. Bolts with different contents (one with a nut, one without) are different
+ rows. `total_occurrences` counts the children too, so it is the same either way.
+- `component` lists one subassembly's parts instead of the design's.
+
+Rows are sorted by part number (rows without one come last) and hold `item`, `part_number`,
+`description`, `revision`, `count`, `definition` (the component names), `components` (their ids)
+and `properties`, with `total_occurrences` beside them. `path` writes them to a `.csv` file
+(the columns item, part_number, description, revision, count and definition, every field
+quoted; children follow their row) or a `.json` file. The window lists the same rows, switches
+between the levels and groupings and shows children under their part, edits a picked row's part
+number, description and revision, and exports them. Changing part properties changes no
+geometry, so it doesn't evaluate the model or re-seat joints again.