Skip to content

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

Wave 450/509: STEP import: a solid the kernel refuses, its faces too, is refused with the reason, never a mesh (and 3 more)

jyvikobc93a653f6b6
diff --git a/apps/solidcraft-cli/tests/model_cache.rs b/apps/solidcraft-cli/tests/model_cache.rs
index c08d5948b4..c53a07e8b0 100644
--- a/apps/solidcraft-cli/tests/model_cache.rs
+++ b/apps/solidcraft-cli/tests/model_cache.rs
@@ -288,3 +288,27 @@ fn undoing_an_edit_after_opening_reuses_the_saved_results() {
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_file(format!("{}.bak", path.display()));
}
+
+/// A saved model holds the results of the body check mode it was evaluated under: opened under
+/// the same mode it is taken as it is, under another the design is evaluated again.
+#[test]
+fn a_model_saved_under_another_check_mode_is_evaluated_again() {
+ let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap();
+ let mut built = Session::default();
+ for c in (plate.script)()["commands"].as_array().unwrap() {
+ built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap();
+ }
+ let path = temp("mode");
+ built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap();
+ let same = open(&path);
+ assert_eq!(same.model.validation(), built.model.validation());
+ assert_eq!(same.model.recomputed, 0, "taken from the file");
+ let mut other = Session::default();
+ other.set_validation(solidcraft_engine::kernel::Validation::EachStep);
+ assert_ne!(other.validation(), built.model.validation());
+ other.execute("doc.open", &json!({"path": path.to_string_lossy()})).unwrap();
+ assert_eq!(other.validation(), solidcraft_engine::kernel::Validation::EachStep);
+ assert!(other.model.recomputed > 0, "evaluated again under its own mode");
+ let _ = std::fs::remove_file(&path);
+ let _ = std::fs::remove_file(format!("{}.bak", path.display()));
+}
diff --git a/assets/locales/pending/import-refuses-unbuildable-brep.json b/assets/locales/pending/import-refuses-unbuildable-brep.json
new file mode 100644
index 0000000000..46f015ab65
--- /dev/null
+++ b/assets/locales/pending/import-refuses-unbuildable-brep.json
@@ -0,0 +1,30 @@
+{
+ "en": {
+ "import_report.refused_one": "1 part couldn't be made into a solid and was not imported.",
+ "import_report.refused_other": "{count} parts couldn't be made into solids and were not imported."
+ },
+ "ar": {
+ "import_report.refused_one": "تعذّر تحويل جزء واحد إلى مجسم، فلم يُستورد.",
+ "import_report.refused_other": "تعذّر تحويل {count} أجزاء إلى مجسمات، فلم تُستورد."
+ },
+ "de": {
+ "import_report.refused_one": "1 Teil konnte nicht zu einem Volumenkörper werden und wurde nicht importiert.",
+ "import_report.refused_other": "{count} Teile konnten nicht zu Volumenkörpern werden und wurden nicht importiert."
+ },
+ "he": {
+ "import_report.refused_one": "לא ניתן היה להפוך חלק אחד לגוף מוצק והוא לא יובא.",
+ "import_report.refused_other": "לא ניתן היה להפוך {count} חלקים לגופים מוצקים והם לא יובאו."
+ },
+ "ja": {
+ "import_report.refused_one": "1 個のパーツをソリッドにできず、読み込みませんでした。",
+ "import_report.refused_other": "{count} 個のパーツをソリッドにできず、読み込みませんでした。"
+ },
+ "ko": {
+ "import_report.refused_one": "부품 1개를 솔리드로 만들지 못해 가져오지 않았습니다.",
+ "import_report.refused_other": "부품 {count}개를 솔리드로 만들지 못해 가져오지 않았습니다."
+ },
+ "zh": {
+ "import_report.refused_one": "1 个零件无法生成实体,未导入。",
+ "import_report.refused_other": "{count} 个零件无法生成实体,未导入。"
+ }
+}
diff --git a/assets/locales/pending/import-report-words.json b/assets/locales/pending/import-report-words.json
index f1267216b4..a419759471 100644
--- a/assets/locales/pending/import-report-words.json
+++ b/assets/locales/pending/import-report-words.json
@@ -6,8 +6,6 @@
"import_report.hint": "Exporting these parts again from the program that made them may fix this. Copy Warning Message has the details.",
"import_report.left_out_one": "1 face couldn't be repaired and is missing.",
"import_report.left_out_other": "{count} faces couldn't be repaired and are missing.",
- "import_report.mesh_one": "1 part couldn't be made into a solid and is shown as a mesh.",
- "import_report.mesh_other": "{count} parts couldn't be made into solids and are shown as meshes.",
"import_report.not_imported_one": "1 part couldn't be imported.",
"import_report.not_imported_other": "{count} parts couldn't be imported.",
"import_report.not_shown_one": "1 face couldn't be drawn and is hidden.",
@@ -27,8 +25,6 @@
"import_report.hint": "قد يحل ذلك تصدير هذه الأجزاء مرة أخرى من البرنامج الذي أنشأها. يحتوي «نسخ رسالة التحذير» على التفاصيل.",
"import_report.left_out_one": "تعذّر إصلاح وجه واحد وهو مفقود.",
"import_report.left_out_other": "تعذّر إصلاح {count} أوجه وهي مفقودة.",
- "import_report.mesh_one": "تعذّر تحويل جزء واحد إلى مجسم، فهو معروض كشبكة.",
- "import_report.mesh_other": "تعذّر تحويل {count} أجزاء إلى مجسمات، فهي معروضة كشبكات.",
"import_report.not_imported_one": "تعذّر استيراد جزء واحد.",
"import_report.not_imported_other": "تعذّر استيراد {count} أجزاء.",
"import_report.not_shown_one": "تعذّر رسم وجه واحد وهو مخفي.",
@@ -48,8 +44,6 @@
"import_report.hint": "Die Teile erneut aus dem Programm zu exportieren, mit dem sie erstellt wurden, kann das beheben. „Warnmeldung kopieren“ enthält die Details.",
"import_report.left_out_one": "1 Fläche konnte nicht repariert werden und fehlt.",
"import_report.left_out_other": "{count} Flächen konnten nicht repariert werden und fehlen.",
- "import_report.mesh_one": "1 Teil konnte nicht zu einem Volumenkörper werden und wird als Netz gezeigt.",
- "import_report.mesh_other": "{count} Teile konnten nicht zu Volumenkörpern werden und werden als Netze gezeigt.",
"import_report.not_imported_one": "1 Teil konnte nicht importiert werden.",
"import_report.not_imported_other": "{count} Teile konnten nicht importiert werden.",
"import_report.not_shown_one": "1 Fläche konnte nicht gezeichnet werden und ist ausgeblendet.",
@@ -69,8 +63,6 @@
"import_report.hint": "ייצוא מחדש של החלקים האלה מהתוכנה שיצרה אותם עשוי לפתור זאת. ב„העתקת הודעת האזהרה” יש את הפרטים.",
"import_report.left_out_one": "לא ניתן היה לתקן פאה אחת והיא חסרה.",
"import_report.left_out_other": "לא ניתן היה לתקן {count} פאות והן חסרות.",
- "import_report.mesh_one": "לא ניתן היה להפוך חלק אחד לגוף מוצק והוא מוצג כרשת.",
- "import_report.mesh_other": "לא ניתן היה להפוך {count} חלקים לגופים מוצקים והם מוצגים כרשתות.",
"import_report.not_imported_one": "לא ניתן היה לייבא חלק אחד.",
"import_report.not_imported_other": "לא ניתן היה לייבא {count} חלקים.",
"import_report.not_shown_one": "לא ניתן היה לצייר פאה אחת והיא מוסתרת.",
@@ -90,8 +82,6 @@
"import_report.hint": "作成元のプログラムからこれらのパーツを書き出し直すと直ることがあります。詳細は「警告メッセージをコピー」で確認できます。",
"import_report.left_out_one": "1 個の面を修復できず、欠けています。",
"import_report.left_out_other": "{count} 個の面を修復できず、欠けています。",
- "import_report.mesh_one": "1 個のパーツをソリッドにできず、メッシュで表示しています。",
- "import_report.mesh_other": "{count} 個のパーツをソリッドにできず、メッシュで表示しています。",
"import_report.not_imported_one": "1 個のパーツを読み込めませんでした。",
"import_report.not_imported_other": "{count} 個のパーツを読み込めませんでした。",
"import_report.not_shown_one": "1 個の面を描画できず、非表示です。",
@@ -111,8 +101,6 @@
"import_report.hint": "이 부품을 만든 프로그램에서 다시 내보내면 해결될 수 있습니다. 세부 정보는 경고 메시지 복사에 있습니다.",
"import_report.left_out_one": "면 1개를 복구하지 못해 빠져 있습니다.",
"import_report.left_out_other": "면 {count}개를 복구하지 못해 빠져 있습니다.",
- "import_report.mesh_one": "부품 1개를 솔리드로 만들지 못해 메시로 표시합니다.",
- "import_report.mesh_other": "부품 {count}개를 솔리드로 만들지 못해 메시로 표시합니다.",
"import_report.not_imported_one": "부품 1개를 가져오지 못했습니다.",
"import_report.not_imported_other": "부품 {count}개를 가져오지 못했습니다.",
"import_report.not_shown_one": "면 1개를 그리지 못해 숨겨져 있습니다.",
@@ -132,8 +120,6 @@
"import_report.hint": "从创建这些零件的程序重新导出可能会解决此问题。“复制警告消息”中有详细信息。",
"import_report.left_out_one": "1 个面无法修复,已缺失。",
"import_report.left_out_other": "{count} 个面无法修复,已缺失。",
- "import_report.mesh_one": "1 个零件无法生成实体,以网格显示。",
- "import_report.mesh_other": "{count} 个零件无法生成实体,以网格显示。",
"import_report.not_imported_one": "1 个零件无法导入。",
"import_report.not_imported_other": "{count} 个零件无法导入。",
"import_report.not_shown_one": "1 个面无法绘制,已隐藏。",
diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs
index 2eb2fc5676..4ee5484dce 100644
--- a/crates/doc/src/model_cache.rs
+++ b/crates/doc/src/model_cache.rs
@@ -232,9 +232,10 @@ impl Model {
}
features.push(f);
}
+ // The check mode the results were evaluated under: they are another mode's results.
let records = json!({
"features": features, "states": w.states, "model_bodies": w.model_bodies, "names": w.names, "sketches": w.sketches,
- "sheets": w.sheets,
+ "sheets": w.sheets, "validation": self.validation().id(),
});
Ok(SavedModel { records, bodies: w.bodies })
})
@@ -537,10 +538,15 @@ impl SavedModel {
};
out_features.push(f);
}
- let records = json!({
+ let mut records = json!({
"features": out_features, "states": out_states, "model_bodies": out_bodies, "names": kept_of(names.as_slice(), &names_used),
"sketches": kept_of(sketches.as_slice(), &sketches_used), "sheets": sheets,
});
+ // The check mode the results were evaluated under, as the model records it (a model
+ // that records none stays without one: adopting it is refused either way).
+ if let (Some(validation), Some(out)) = (self.records.get("validation"), records.as_object_mut()) {
+ out.insert("validation".into(), validation.clone());
+ }
let kept: Vec<usize> = (0..self.bodies.len()).filter(|i| kernel_used.get(*i) == Some(&true)).collect();
let bodies = kept.iter().filter_map(|i| self.bodies.get(*i).cloned()).collect();
Some((SavedModel { records, bodies }, kept, used))
@@ -550,8 +556,9 @@ impl SavedModel {
impl Model {
/// The model a design file kept for `doc` ([`Model::saved`]), taken as `doc`'s evaluation:
/// every feature's result as saved, nothing evaluated but the features whose state the file
- /// did not keep ([`SavedModel::thinned`]). Refused (an error) unless every feature's
- /// fingerprint is the one `doc` gives it now, and every record is well formed.
+ /// did not keep ([`SavedModel::thinned`]), under the check mode it was evaluated in
+ /// ([`Model::validation`]). Refused (an error) unless every feature's fingerprint is the one
+ /// `doc` gives it now, and every record is well formed.
pub fn adopt(doc: &Document, saved: &SavedModel) -> Result<Model> {
let mut states = saved.states()?;
let frame_bodies = Arc::new(std::sync::Mutex::new(FrameBodies::default()));
@@ -565,13 +572,16 @@ impl Model {
let text =
|v: Option<&Json>| v.and_then(Json::as_str).filter(|s| s.len() <= 1 << 16).map(str::to_owned).ok_or_else(|| bad("saved model: text"));
let features = records.get("features").and_then(Json::as_array).ok_or_else(|| bad("saved model: features"))?;
+ let validation =
+ records.get("validation").and_then(Json::as_str).and_then(kernel::Validation::parse).ok_or_else(|| bad("saved model: validation"))?;
if features.len() != doc.features.len() {
return Err(bad("saved model: features"));
}
let (vals, param_errors) = evaluation_values(doc);
let step_digests = StepDigests::of(doc, &StepDigests::default());
let marker = doc.marker.unwrap_or(usize::MAX);
- let ctx = context_digest(doc, &vals);
+ // As `evaluate` digests the context under the mode, so the next evaluation reuses these.
+ let ctx = context_digest(doc, &vals) ^ validation_digest(validation);
let mut before = Arc::new(ModelState::default());
// Whether `before` is the state before the feature: one the file left out only stands in.
let mut exact = true;
@@ -613,7 +623,7 @@ impl Model {
}
results.push(result);
}
- let mut model = Model { results, param_errors, step_digests, context: ctx, frame_bodies, ..Model::default() };
+ let mut model = Model { results, param_errors, step_digests, context: ctx, frame_bodies, validation, ..Model::default() };
let unkept = model.results.iter().filter(|r| r.unkept).count();
if unkept > 0 {
// The features whose state the file did not keep, each evaluated again from the state
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 82f5ef0b4c..fc59770469 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -617,14 +617,13 @@ impl Session {
// The session keeps what is hidden (an undo step of its own); the design file carries it.
let visibility = std::mem::take(&mut doc.visibility);
let doc = Arc::new(doc);
+ // A model saved under another check mode holds that mode's results: evaluated again.
let adopted = saved
.filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none())
- .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok());
+ .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok())
+ .filter(|model| model.validation() == validation);
let model = match adopted {
- Some(mut model) => {
- model.set_validation(validation);
- model
- }
+ Some(model) => model,
None => {
let mut model = Model::new();
model.set_validation(validation);
diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs
index e6538d1d93..a91ef4e90a 100644
--- a/crates/io/src/design.rs
+++ b/crates/io/src/design.rs
@@ -1087,7 +1087,10 @@ mod tests {
.map(|(i, ms)| json!({"id": i + 1, "fingerprint": "0000000000000000", "ms": ms, "skipped": false, "state": i}))
.collect();
solidcraft_doc::SavedModel {
- records: json!({"features": features, "states": states, "model_bodies": records, "names": [{"faces": [], "info": []}], "sketches": [], "sheets": []}),
+ records: json!({
+ "features": features, "states": states, "model_bodies": records, "names": [{"faces": [], "info": []}], "sketches": [],
+ "sheets": [], "validation": "each_feature",
+ }),
bodies,
}
}
@@ -1113,6 +1116,7 @@ mod tests {
let (states, kept, all, within) = thinned(40);
assert_eq!((states, kept.len(), within), (vec![true; 4], 40, true));
assert_eq!(all.records, model.records);
+ assert_eq!(thinned(16).2.records["validation"], "each_feature", "the check mode it was evaluated under");
// The final state and the slowest other (50 ms): the shared bodies count once, else
// these two states would need 32 bodies' room.
for bodies in [24, 31] {
diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs
index 7777a52fb2..d886263b9a 100644
--- a/crates/io/src/design/native_cache.rs
+++ b/crates/io/src/design/native_cache.rs
@@ -5,7 +5,7 @@
use super::*;
use solidcraft_doc::{ModelState, SavedModel};
-const FORMAT: &str = "solidcraft-model-cache/5";
+const FORMAT: &str = "solidcraft-model-cache/6";
const PRODUCER: &str = "solidcraft-truck-adapter/4";
const MANIFEST: &str = "cache/model.json";
const PAYLOAD: &str = "cache/bodies.bin";
diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs
index f7d06860df..d491d19eb2 100644
--- a/crates/kernel/src/native.rs
+++ b/crates/kernel/src/native.rs
@@ -156,9 +156,22 @@ pub(crate) fn smlib_record_ordered(
/// Where SMLib's faces and edges of `brep` (imported from `record`) are in the record's order:
/// `None` where SMLib's export does not number them as the record does.
+///
+/// SMLib's export is in canonical order, and `order` says where SMLib's own face and edge `i`
+/// went in it. Where the canonical record numbers them as `record` does, `order` maps SMLib's
+/// to the record's. Otherwise SMLib may still keep the record's own order (an import lists
+/// SMLib's faces and edges in the record's order, and canonical order can list them otherwise,
+/// a tube's seam edges among them): the export put back in SMLib's order then numbers them as
+/// `record` does, and SMLib's face and edge `i` are the record's `i`.
fn numbering(record: &solidcraft_geom::brep::Brep, brep: &solidcraft_smlib::Brep) -> Option<solidcraft_smlib::history::Order> {
match brep.to_native_ordered() {
- Ok((back, order)) => same_numbering(record, &back).then_some(order),
+ Ok((back, order)) => {
+ if same_numbering(record, &back) {
+ return Some(order);
+ }
+ let in_smlib_order = in_smlib_order(&back, &order)?;
+ same_numbering(record, &in_smlib_order).then(solidcraft_smlib::history::Order::default)
+ }
Err(e) => {
log::debug!(target: "smlib", "no order for an operand: {e}");
None
@@ -166,6 +179,50 @@ fn numbering(record: &solidcraft_geom::brep::Brep, brep: &solidcraft_smlib::Brep
}
}
+/// The canonical record `back` with its faces and edges in SMLib's own order (`order`: where
+/// SMLib's face and edge `i` are in `back`), each loop naming its edges by SMLib's numbers.
+/// `None` where `order` is not a renumbering of `back`'s faces and edges (an edge split into
+/// pieces where solids touch along it is more than one record edge).
+fn in_smlib_order(back: &solidcraft_geom::brep::Brep, order: &solidcraft_smlib::history::Order) -> Option<solidcraft_geom::brep::Brep> {
+ use solidcraft_geom::brep::Loop;
+ let permutation = |to: &[usize], n: usize| -> Option<Vec<usize>> {
+ if to.is_empty() {
+ return Some((0..n).collect());
+ }
+ let mut from = vec![usize::MAX; n];
+ for (i, &k) in to.iter().enumerate() {
+ let slot = from.get_mut(k)?;
+ if *slot != usize::MAX {
+ return None;
+ }
+ *slot = i;
+ }
+ (to.len() == n).then_some(from)
+ };
+ if !order.pieces.is_empty() {
+ return None;
+ }
+ // `faces_from[k]`: SMLib's number of `back`'s face k; likewise for edges.
+ let faces_from = permutation(&order.faces, back.faces.len())?;
+ let edges_from = permutation(&order.edges, back.edges.len())?;
+ let mut out = back.clone();
+ for (k, face) in back.faces.iter().enumerate() {
+ let mut face = face.clone();
+ for l in &mut face.loops {
+ if let Loop::Edges { edges } = l {
+ for e in edges.iter_mut() {
+ e.edge = u32::try_from(*edges_from.get(usize::try_from(e.edge).ok()?)?).ok()?;
+ }
+ }
+ }
+ *out.faces.get_mut(*faces_from.get(k)?)? = face;
+ }
+ for (k, edge) in back.edges.iter().enumerate() {
+ *out.edges.get_mut(*edges_from.get(k)?)? = edge.clone();
+ }
+ Some(out)
+}
+
/// Whether two records of one body number its faces, edges and vertices alike: the same loops of
/// the same edges, the same edge ends, and each vertex where the other's is.
fn same_numbering(a: &solidcraft_geom::brep::Brep, b: &solidcraft_geom::brep::Brep) -> bool {
diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs
index 8b03229edd..1a4c79961e 100644
--- a/crates/kernel/src/step_in/mod.rs
+++ b/crates/kernel/src/step_in/mod.rs
@@ -57,7 +57,7 @@ pub struct ImportedBody {
pub file_faces: usize,
/// No B-rep could be made of the whole solid, and this is why (the import's warnings say so
/// too, naming each face left out): `body` is an open surface body of the solid's exact faces
- /// but those, or a mesh body of them where no surface body could be made of them.
+ /// but those.
pub refused: Option<String>,
}
@@ -99,10 +99,11 @@ pub struct StepImport {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IssueKind {
- /// No body could be made of the part: it is not in the design.
+ /// The part could not be read from the file: it is not in the design.
NotImported,
- /// No solid could be made of the part: it is shown as a mesh of its faces.
- ShownAsMesh,
+ /// The kernel refuses the part's B-rep, its faces' too: it is not in the design, and the
+ /// warning gives the kernel's reason.
+ Refused,
/// No solid could be made of the part: it came in as surfaces of its faces.
ImportedAsSurfaces,
/// A face of the part could not be read or made, and is left out.
@@ -365,6 +366,12 @@ impl Reader {
false
}
+ /// `item`'s part is not in the design: the kernel refuses its B-rep, for `why`.
+ fn refused(&mut self, item: u64, why: &str) {
+ let label = self.label(item);
+ self.note(IssueKind::Refused, Some(item), 0, format!("{label}: not imported: {why}"));
+ }
+
/// A warning about the file as a whole.
fn warn(&mut self, msg: impl Into<String>) {
self.note(IssueKind::File, None, 0, msg);
@@ -788,8 +795,7 @@ impl Reader {
}
if let Some(again) = self.unreadable.get(&item) {
if let Some(msg) = again.clone() {
- let label = self.label(item);
- self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}"));
+ self.refused(item, &msg);
}
continue;
}
@@ -816,8 +822,7 @@ impl Reader {
None => {
if let Some(again) = self.unreadable.get(&item) {
if let Some(msg) = again.clone() {
- let label = self.label(item);
- self.warn(format!("{label}: not imported: {msg}"));
+ self.refused(item, &msg);
}
continue;
}
@@ -840,9 +845,7 @@ impl Reader {
if let Some(failed) = read {
let label = self.label(item);
if let Some(why) = &part.refused {
- let kind = if part.body.is_mesh() { IssueKind::ShownAsMesh } else { IssueKind::ImportedAsSurfaces };
- let words = if part.body.is_mesh() { "shown as a mesh" } else { "imported as surfaces" };
- self.note(kind, Some(item), 0, format!("{label}: {words}: {why}"));
+ self.note(IssueKind::ImportedAsSurfaces, Some(item), 0, format!("{label}: imported as surfaces: {why}"));
}
for f in &failed {
let (kind, faces, f) = match f {
@@ -924,8 +927,12 @@ impl Reader {
});
}
Err(parallel::Failure { read, msg }) => {
- let label = self.label(item);
- self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}"));
+ if read {
+ let label = self.label(item);
+ self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}"));
+ } else {
+ self.refused(item, &msg);
+ }
// Later instances don't read the item again.
if !self.oriented.contains_key(&item) {
self.unreadable.insert(item, (!read).then_some(msg));
diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rs
index 0761251a1b..e2b32c13db 100644
--- a/crates/kernel/src/step_in/parallel.rs
+++ b/crates/kernel/src/step_in/parallel.rs
@@ -27,8 +27,7 @@ pub(super) struct Part {
/// The file face of each kernel face.
pub face_origin: Vec<u64>,
/// No B-rep could be made of the whole solid, and this is why: the body is a surface body of
- /// the faces that read ([`surface_part`]), or, where none could be made of them, a mesh of
- /// them ([`mesh_part`]).
+ /// the faces that read ([`surface_part`]).
pub refused: Option<String>,
}
@@ -204,9 +203,9 @@ const MAX_LEFT_OUT_ROUNDS: usize = 8;
/// [`MAX_LEFT_OUT_ROUNDS`] reads). A face is only ever left out where a refusal names it.
/// 2. Where a refusal names no face of the solid: the faces that read alone, stitched by SMLib
/// into one surface body (their edges sewn at ten times their tolerance).
-/// 3. Where SMLib cannot stitch them either: a mesh of them ([`mesh_part`]).
///
-/// With no face to import, the solid stays refused.
+/// Where SMLib cannot stitch them either, or there is no face to import, the solid stays refused
+/// with the reason it was: a B-rep SMLib refuses is never kept as a mesh of its faces.
fn surface_part(ex: &Exchange, item: u64, units: Units, refused: Failure) -> std::result::Result<(Part, Vec<Note>), Failure> {
let _span = solidcraft_profile::span("import", "step.refused_surfaces");
let trims = &solidcraft_smlib::pcurves::SmlibTrims;
@@ -256,13 +255,12 @@ fn surface_part(ex: &Exchange, item: u64, units: Units, refused: Failure) -> std
Err(e) => notes.push(Note::LeftOut(format!("left out: {}", e.to_string().trim_start_matches("the operation failed: ")))),
}
}
- match stitched_part(&pieces, faces.len(), &refused.msg) {
- Ok(part) => Ok((part, notes)),
- Err(e) => {
- log::debug!(target: "step", "item #{item}: its faces not stitched ({e}); meshed instead");
- mesh_part(&pieces, faces.len(), notes, refused)
- }
- }
+ // Where SMLib cannot stitch them either, the solid is refused with the reason it was.
+ let part = stitched_part(&pieces, faces.len(), &refused.msg).map_err(|e| {
+ log::debug!(target: "step", "item #{item}: its faces not stitched ({e})");
+ refused
+ })?;
+ Ok((part, notes))
}
/// The one-face surface bodies `pieces` (each with its file face) stitched by SMLib into one
@@ -290,37 +288,6 @@ fn stitched_part(pieces: &[(u64, Body)], file_faces: usize, refused: &str) -> cr
Ok(Part { body, closed, file_faces, face_origin, refused: Some(refused.to_string()) })
}
-/// The one-face surface bodies `pieces` meshed by the planner, their triangles together a mesh
-/// body: no B-rep (modelling operations refuse it), for a solid whose faces SMLib could not
-/// stitch either. Faces that cannot be meshed are left out, each named in the notes; with no
-/// face to show, the solid stays refused.
-fn mesh_part(pieces: &[(u64, Body)], file_faces: usize, mut notes: Vec<Note>, refused: Failure) -> std::result::Result<(Part, Vec<Note>), Failure> {
- let _span = solidcraft_profile::span("import", "step.refused_mesh");
- // Every face at the display tolerance of the whole solid.
- let bounds: solidcraft_geom::Aabb3 = pieces.iter().flat_map(|(_, b)| b.record().vertices.iter().map(|v| crate::body::v3(v.point))).collect();
- let size = if bounds.is_empty() { 0.0 } else { bounds.diagonal() };
- let tol = crate::MeshTolerance::display_of(if size.is_finite() { size } else { 0.0 });
- let (mut positions, mut triangles) = (Vec::new(), Vec::new());
- for (face, b) in pieces {
- match b.mesh(&tol) {
- Ok(m) if !m.triangles.is_empty() => {
- let Ok(base) = u32::try_from(positions.len()) else { break };
- positions.extend_from_slice(&m.positions);
- triangles.extend(m.triangles.iter().map(|t| t.map(|i| i.saturating_add(base))));
- }
- Ok(_) => notes.push(Note::LeftOut(format!("left out: face #{face}: no triangles"))),
- Err(e) => notes.push(Note::LeftOut(format!("left out: face #{face}: {}", e.to_string().trim_start_matches("the operation failed: ")))),
- }
- }
- if triangles.is_empty() {
- return Err(Failure { msg: format!("{} (no face could be shown as a mesh either)", refused.msg), ..refused });
- }
- let body = crate::meshbody::mesh_body(&positions, &triangles)
- .map_err(|e| Failure { msg: format!("{} (its mesh: {e})", refused.msg), read: refused.read })?;
- let closed = body.is_closed_mesh();
- Ok((Part { body, closed, file_faces, face_origin: Vec::new(), refused: Some(refused.msg) }, notes))
-}
-
/// Prepare `jobs`, the results in the jobs' order. Solids still to read and orient (the slow
/// part) are shared out between up to `workers` threads, each taking the next job when it is
/// done with one, so one large part does not hold up the rest.
diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs
index 606f556099..99049a2c40 100644
--- a/crates/kernel/src/step_in/tests.rs
+++ b/crates/kernel/src/step_in/tests.rs
@@ -490,6 +490,17 @@ fn offset_surface_cube_import_is_closed_and_editable() {
assert!(rel(measure(&result).unwrap().volume, 1000.0 - 40.0 * std::f64::consts::PI) < 1e-3);
}
+/// A solid whose B-rep SMLib refuses, its faces too (here every SMLib call: the build has no
+/// SMLib), is refused with the kernel's reason, naming the solid. It once came in as a mesh of
+/// its faces, which the planner could still triangulate.
+#[cfg(not(feature = "smlib"))]
+#[test]
+fn a_solid_smlib_refuses_with_its_faces_is_refused_not_meshed() {
+ let text = format!("{HEAD}{}#60=SHAPE_REPRESENTATION('',(#101),$);\n{TAIL}", cube_entities());
+ let why = step_import(&text).map(|imp| imp.warnings).unwrap_err().to_string();
+ assert!(why.contains("solid 'Cube': not imported: ") && why.contains("SMLib"), "{why}");
+}
+
/// A hand-written unit cube brep (`#100`…) in a representation with the given unit and items.
fn cube_entities() -> String {
let mut s = String::new();
@@ -1748,7 +1759,9 @@ fn periodic_knot_tube(first: u64, x: f64, r: f64, h: f64) -> (String, u64) {
/// Two such tubes far apart in one body: the body's size sets a chord tolerance coarse beside
/// the tubes, and meshing a face at it divided the surface's whole parameter box, whose
/// corners lay outside the domain. The division never converged there (#1374's recursion),
-/// and the import grew by gigabytes without end.
+/// and the import grew by gigabytes without end. The sheet comes in as SMLib's B-rep of its two
+/// faces, each the file's face (SMLib lists the seam edges in another canonical order than the
+/// file, and keeps the file's own order), each a cylinder's side.
#[test]
fn periodic_knot_tube_faces_import_and_mesh() {
let t0 = std::time::Instant::now();
@@ -1760,9 +1773,16 @@ fn periodic_knot_tube_faces_import_and_mesh() {
);
let imp = step_import(&text).unwrap();
assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);
- let m = measure(&imp.bodies[0].body).unwrap();
+ let tubes = &imp.bodies[0];
+ assert!(tubes.refused.is_none() && !tubes.body.is_mesh() && tubes.body.is_surface(), "{:?} {:?}", tubes.refused, imp.warnings);
+ assert_eq!(tubes.face_origin, vec![fa, fb], "{:?}", imp.warnings);
+ // Each face is the file's quadratic circle of radius r (corner weights √2/2 to 12 digits,
+ // a radius off by under 1e-12 of r) moved straight along its axis by h: a cylinder's side,
+ // 2π r h. SMLib integrates to 1e-8.
+ let m = measure(&tubes.body).unwrap();
let area = 2.0 * std::f64::consts::TAU * r * h;
- assert!(rel(m.area, area) < 0.02, "area {} (expected {area})", m.area);
+ assert!(rel(m.area, area) < 1e-6, "area {} (expected {area})", m.area);
+ assert_eq!(tubes.body.unmeshed_faces(), 0);
assert!(t0.elapsed().as_secs_f64() < 60.0, "took {:?}", t0.elapsed());
}
diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs
index 88c957f025..6dd6bbf75a 100644
--- a/crates/ui-egui/src/timeline.rs
+++ b/crates/ui-egui/src/timeline.rs
@@ -398,7 +398,7 @@ pub(crate) fn import_summary(report: &ImportReport) -> String {
}
let sentences = [
("import_report.not_imported", parts_of(IssueKind::NotImported)),
- ("import_report.mesh", parts_of(IssueKind::ShownAsMesh)),
+ ("import_report.refused", parts_of(IssueKind::Refused)),
("import_report.surfaces", parts_of(IssueKind::ImportedAsSurfaces)),
("import_report.left_out", faces_of(IssueKind::FaceLeftOut)),
("import_report.open", parts_of(IssueKind::OpenBody)),
@@ -408,7 +408,7 @@ pub(crate) fn import_summary(report: &ImportReport) -> String {
("import_report.file", file),
];
out.extend(sentences.iter().filter(|(_, n)| *n > 0).map(|(key, n)| counted(key, *n)));
- let lost = [IssueKind::NotImported, IssueKind::ShownAsMesh, IssueKind::ImportedAsSurfaces, IssueKind::FaceLeftOut, IssueKind::OpenBody];
+ let lost = [IssueKind::NotImported, IssueKind::Refused, IssueKind::ImportedAsSurfaces, IssueKind::FaceLeftOut, IssueKind::OpenBody];
if lost.iter().any(|k| parts.contains_key(k)) {
out.push(crate::i18n::tr("import_report.hint").to_string());
}
@@ -853,10 +853,10 @@ mod tests {
solids: 40,
issues: vec![
issue(
- IssueKind::ShownAsMesh,
+ IssueKind::Refused,
Some(7),
0,
- "solid #7: shown as a mesh: pcurves failed on 1 of 122 faces; first: face #9: SMLib pcurves: an edge lies 13.73370504071075 mm off the face's surface",
+ "solid #7: not imported: pcurves failed on 1 of 122 faces; first: face #9: SMLib pcurves: an edge lies 13.73370504071075 mm off the face's surface",
),
issue(
IssueKind::FaceLeftOut,
@@ -876,7 +876,7 @@ mod tests {
let summary = super::import_summary(&report);
assert_eq!(
summary,
- "Imported 40 of 43 parts as solids. 1 part couldn't be imported. 1 part couldn't be made into a solid and is shown as a mesh. \
+ "Imported 40 of 43 parts as solids. 1 part couldn't be imported. 1 part couldn't be made into a solid and was not imported. \
1 part couldn't be made into a solid and came in as surfaces. 3 faces couldn't be repaired and are missing. \
Small flaws were repaired in 2 parts. There was 1 other problem with the file. \
Exporting these parts again from the program that made them may fix this. Copy Warning Message has the details."
diff --git a/docs/design-container.md b/docs/design-container.md
index 91ca47a03b..c3a2ff065d 100644
--- a/docs/design-container.md
+++ b/docs/design-container.md
@@ -126,7 +126,9 @@ the final state fits.
The model is the whole evaluation: every feature's result (warning, boolean
diagnostics, whether it was skipped, its fingerprint) and the state after it
(bodies, solved sketches, construction geometry, sheet metal bodies, threads and
-the blend records later features read). States share what they share: a body that
+the blend records later features read), and the body check mode it was evaluated
+under (`each_step`, `each_feature` or `off`): a design opened under another mode is
+evaluated again. States share what they share: a body that
later features pass through unchanged, its face names and a solved sketch are each
recorded once. Face names are kept as worked out (saving works out any not asked
for yet), so a body taken from the file is named exactly as when it was saved.
@@ -147,7 +149,7 @@ SHA-256 of their encoding), and a placed copy of a repeated part (an instance fr
a STEP assembly) records the part and its matrix, so it shows that part's display
again instead of being meshed on its own.
-`cache/model.json` records `solidcraft-model-cache/5`, the producer revision
+`cache/model.json` records `solidcraft-model-cache/6`, the producer revision
`solidcraft-truck-adapter/4`, the application version, the build (source commit,
CPU architecture and OS), the SHA-256 of the exact `document.json` (whose blob
references pin every STEP, mesh and image payload) and of `cache/bodies.bin`, the