From 53e469da48811ed53ce5bff6ec1f84c29e13c40e Mon Sep 17 00:00:00 2001 From: Karl Von Richter Date: Sat, 7 Nov 2026 19:41:11 +1000 Subject: [PATCH 1/2] Weldments: End Cap closes frame member ends with a plate (#4003) End Cap (WELDMENTS > CREATE, `frame.end_cap`) closes the open ends of frame members with plates, one body per end named after its member. - The plate covers the outside of the profile: a closed section's outer outline; an open section's outside with its rounds and chamfers, slots and the gap between flanges closed along the bounding rectangle. - Offset (off by default) sets it in from that edge, as a ratio of the thickness or a length; Corner Chamfer cuts its outside corners. - Direction: Outward on top of the end; Inward cuts the member back and sets the plate where the end was. Two new original direction icons. - Refused, leaving the document unchanged: an inset that leaves no plate, a chamfer too large for its edges, a face that is not an end of a frame member, the same end picked twice (by its exact plane, however it was picked), hostile values. - In assemblies: an inward cap cuts its member where the member is placed, even in another component or moved by a body offset; moving the member's occurrence rebuilds the cap; a cap copied without its member is reported as using what is outside the copy. - A cap made while another is suppressed never takes that one's name, and editing a cap keeps each remaining end's name with that end: a new end never takes a kept end's name, and a removed end's name is kept back. - Caps follow member edits, renames, undo and reopen, and the dialog remembers its sizes with "remember dialog values" on. Editing a cap whose end can no longer be found starts with no faces picked and names the missing end, rather than dropping it unasked. - One pending format file, input and output schemas, pending locale strings in 12 languages and attribution rows. No kernel changes. Tested in crates/engine/src/cmd/frame_tests.rs (hand-derived volumes), crates/doc/src/frame_tests.rs and crates/ui-egui/src/dialogs_frame_tests.rs; frame.end_cap has its tests/kernel-cases/EXEMPT line. Co-Authored-By: Claude Opus 5.5 --- assets/icons/ui/design/requested_icons.txt | 3 + assets/icons/ui/design/svg/model/end_cap.svg | 14 + .../ui/design/svg/model/end_cap_inward.svg | 17 + .../ui/design/svg/model/end_cap_outward.svg | 17 + assets/locales/pending/frame-end-caps.json | 206 +++++++ attribution/pending/frame-end-caps.md | 3 + crates/doc/src/clipboard.rs | 10 + crates/doc/src/document.rs | 23 + crates/doc/src/end_cap.rs | 582 ++++++++++++++++++ crates/doc/src/eval.rs | 21 +- crates/doc/src/eval_frame.rs | 65 +- crates/doc/src/feature_walk_tests/fixtures.rs | 4 + .../src/feature_walk_tests/golden_exprs.txt | 8 + .../feature_walk_tests/golden_geometry.txt | 2 + .../src/feature_walk_tests/golden_refs.txt | 2 + .../doc/src/format/pending/frame-end-caps.rs | 4 + crates/doc/src/frame.rs | 2 +- crates/doc/src/frame_tests.rs | 103 ++++ crates/doc/src/lib.rs | 1 + crates/engine/src/cmd/browser.rs | 12 +- crates/engine/src/cmd/component_clone.rs | 31 + .../engine/src/cmd/component_foreign_tests.rs | 29 + crates/engine/src/cmd/edit.rs | 32 + crates/engine/src/cmd/features.rs | 2 +- crates/engine/src/cmd/frame_end_cap.rs | 74 +++ crates/engine/src/cmd/frame_tests.rs | 296 +++++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/schema/end_cap.rs | 49 ++ crates/engine/src/schema/mod.rs | 1 + crates/ui-egui/src/command_help.rs | 1 + crates/ui-egui/src/dialogs.rs | 11 +- crates/ui-egui/src/dialogs_all_tests.rs | 31 +- crates/ui-egui/src/dialogs_dense.rs | 2 + crates/ui-egui/src/dialogs_end_cap.rs | 161 +++++ crates/ui-egui/src/dialogs_frame_tests.rs | 47 ++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/timeline.rs | 1 + crates/ui-egui/src/workspace.rs | 8 +- docs/book/src/reference/glossary.md | 13 + docs/frames.md | 41 +- tests/kernel-cases/EXEMPT | 1 + 41 files changed, 1906 insertions(+), 27 deletions(-) create mode 100644 assets/icons/ui/design/svg/model/end_cap.svg create mode 100644 assets/icons/ui/design/svg/model/end_cap_inward.svg create mode 100644 assets/icons/ui/design/svg/model/end_cap_outward.svg create mode 100644 assets/locales/pending/frame-end-caps.json create mode 100644 attribution/pending/frame-end-caps.md create mode 100644 crates/doc/src/end_cap.rs create mode 100644 crates/doc/src/format/pending/frame-end-caps.rs create mode 100644 crates/engine/src/cmd/frame_end_cap.rs create mode 100644 crates/engine/src/schema/end_cap.rs create mode 100644 crates/ui-egui/src/dialogs_end_cap.rs diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt index 3cbf6d22c95..07bc4681f40 100644 --- a/assets/icons/ui/design/requested_icons.txt +++ b/assets/icons/ui/design/requested_icons.txt @@ -103,6 +103,9 @@ dxf false edit false ellipse false emboss false +end_cap false +end_cap_inward false +end_cap_outward false environment_map false equation_curve false error false diff --git a/assets/icons/ui/design/svg/model/end_cap.svg b/assets/icons/ui/design/svg/model/end_cap.svg new file mode 100644 index 00000000000..064cafdf738 --- /dev/null +++ b/assets/icons/ui/design/svg/model/end_cap.svg @@ -0,0 +1,14 @@ + + End Cap + + + + + + + + + + + + diff --git a/assets/icons/ui/design/svg/model/end_cap_inward.svg b/assets/icons/ui/design/svg/model/end_cap_inward.svg new file mode 100644 index 00000000000..3cf5680daa7 --- /dev/null +++ b/assets/icons/ui/design/svg/model/end_cap_inward.svg @@ -0,0 +1,17 @@ + + End Cap Inward + + + + + + + + + + + + + + + diff --git a/assets/icons/ui/design/svg/model/end_cap_outward.svg b/assets/icons/ui/design/svg/model/end_cap_outward.svg new file mode 100644 index 00000000000..0585abdf2dc --- /dev/null +++ b/assets/icons/ui/design/svg/model/end_cap_outward.svg @@ -0,0 +1,17 @@ + + End Cap Outward + + + + + + + + + + + + + + + diff --git a/assets/locales/pending/frame-end-caps.json b/assets/locales/pending/frame-end-caps.json new file mode 100644 index 00000000000..ca82cd40858 --- /dev/null +++ b/assets/locales/pending/frame-end-caps.json @@ -0,0 +1,206 @@ +{ + "en": { + "cmd.frame_end_cap": "End Cap", + "error.end_cap_faces": "Pick at least one open end face of a frame member", + "error.end_cap_unresolved": "End {ends} of this cap is no longer on the model. Pick the end faces again", + "help.frame.end_cap": "Closes the open ends of frame members with plates shaped like the profile's outline. Use it to seal tubes, angles and beams, on top of the end or set into it.", + "ui.end_cap.chamfer": "Corner Chamfer", + "ui.end_cap.direction": "Direction", + "ui.end_cap.faces": "End Faces", + "ui.end_cap.inset": "Inset", + "ui.end_cap.inset_kind": "Inset By", + "ui.end_cap.inset_ratio": "Inset Ratio", + "ui.end_cap.inward": "Inward", + "ui.end_cap.length": "Length", + "ui.end_cap.outward": "Outward", + "ui.end_cap.ratio": "Ratio of thickness", + "ui.end_cap_title": "END CAP" + }, + "ar": { + "cmd.frame_end_cap": "غطاء طرفي", + "error.end_cap_faces": "اختر وجهًا طرفيًا مفتوحًا واحدًا على الأقل لعضو إطار", + "error.end_cap_unresolved": "الطرف {ends} لهذا الغطاء لم يعد موجودًا في النموذج. اختر الأوجه الطرفية مرة أخرى", + "help.frame.end_cap": "يغلق الأطراف المفتوحة لأعضاء الإطار بألواح على شكل محيط المقطع. استخدمه لسد الأنابيب والزوايا والعوارض، فوق الطرف أو مغروسًا فيه.", + "ui.end_cap.chamfer": "شطف الزوايا", + "ui.end_cap.direction": "الاتجاه", + "ui.end_cap.faces": "الوجوه الطرفية", + "ui.end_cap.inset": "الإزاحة للداخل", + "ui.end_cap.inset_kind": "الإزاحة حسب", + "ui.end_cap.inset_ratio": "نسبة الإزاحة", + "ui.end_cap.inward": "للداخل", + "ui.end_cap.length": "الطول", + "ui.end_cap.outward": "للخارج", + "ui.end_cap.ratio": "نسبة من السماكة", + "ui.end_cap_title": "غطاء طرفي" + }, + "de": { + "cmd.frame_end_cap": "Endkappe", + "error.end_cap_faces": "Mindestens eine offene Stirnfläche eines Rahmenelements auswählen", + "error.end_cap_unresolved": "Ende {ends} dieser Abdeckung ist nicht mehr im Modell. Stirnflächen erneut auswählen", + "help.frame.end_cap": "Schließt offene Enden von Rahmenelementen mit Platten in der Form des Profilumrisses. Damit verschließen Sie Rohre, Winkel und Träger, auf dem Ende oder darin eingelassen.", + "ui.end_cap.chamfer": "Eckfase", + "ui.end_cap.direction": "Richtung", + "ui.end_cap.faces": "Stirnflächen", + "ui.end_cap.inset": "Einzug", + "ui.end_cap.inset_kind": "Einzug als", + "ui.end_cap.inset_ratio": "Einzugsverhältnis", + "ui.end_cap.inward": "Nach innen", + "ui.end_cap.length": "Länge", + "ui.end_cap.outward": "Nach außen", + "ui.end_cap.ratio": "Anteil der Dicke", + "ui.end_cap_title": "ENDKAPPE" + }, + "es": { + "cmd.frame_end_cap": "Tapa de extremo", + "error.end_cap_faces": "Selecciona al menos una cara de extremo abierta de un miembro", + "error.end_cap_unresolved": "El extremo {ends} de esta tapa ya no está en el modelo. Vuelve a seleccionar las caras de extremo", + "help.frame.end_cap": "Cierra los extremos abiertos de los miembros de una estructura con placas con la forma del contorno del perfil. Úsalo para tapar tubos, angulares y vigas, sobre el extremo o embutidas en él.", + "ui.end_cap.chamfer": "Chaflán de esquina", + "ui.end_cap.direction": "Dirección", + "ui.end_cap.faces": "Caras de extremo", + "ui.end_cap.inset": "Retranqueo", + "ui.end_cap.inset_kind": "Retranqueo por", + "ui.end_cap.inset_ratio": "Proporción de retranqueo", + "ui.end_cap.inward": "Hacia dentro", + "ui.end_cap.length": "Longitud", + "ui.end_cap.outward": "Hacia fuera", + "ui.end_cap.ratio": "Proporción del espesor", + "ui.end_cap_title": "TAPA DE EXTREMO" + }, + "fr": { + "cmd.frame_end_cap": "Bouchon d'extrémité", + "error.end_cap_faces": "Sélectionnez au moins une face d'extrémité ouverte d'un élément de structure", + "error.end_cap_unresolved": "L'extrémité {ends} de ce bouchon n'est plus sur le modèle. Sélectionnez à nouveau les faces d'extrémité", + "help.frame.end_cap": "Ferme les extrémités ouvertes des éléments de structure avec des plaques à la forme du contour du profil. Utilisez-le pour boucher tubes, cornières et poutres, sur l'extrémité ou encastrées.", + "ui.end_cap.chamfer": "Chanfrein d'angle", + "ui.end_cap.direction": "Direction", + "ui.end_cap.faces": "Faces d'extrémité", + "ui.end_cap.inset": "Retrait", + "ui.end_cap.inset_kind": "Retrait en", + "ui.end_cap.inset_ratio": "Rapport de retrait", + "ui.end_cap.inward": "Vers l'intérieur", + "ui.end_cap.length": "Longueur", + "ui.end_cap.outward": "Vers l'extérieur", + "ui.end_cap.ratio": "Rapport de l'épaisseur", + "ui.end_cap_title": "BOUCHON D'EXTRÉMITÉ" + }, + "he": { + "cmd.frame_end_cap": "מכסה קצה", + "error.end_cap_faces": "בחר לפחות פאת קצה פתוחה אחת של איבר מסגרת", + "error.end_cap_unresolved": "קצה {ends} של מכסה זה כבר אינו במודל. בחר שוב את פאות הקצה", + "help.frame.end_cap": "סוגר קצוות פתוחים של איברי מסגרת בלוחות בצורת קו המתאר של הפרופיל. השתמש בו כדי לאטום צינורות, זוויתנים וקורות, מעל הקצה או שקוע בו.", + "ui.end_cap.chamfer": "שיפוע פינות", + "ui.end_cap.direction": "כיוון", + "ui.end_cap.faces": "פאות קצה", + "ui.end_cap.inset": "היסט פנימה", + "ui.end_cap.inset_kind": "היסט לפי", + "ui.end_cap.inset_ratio": "יחס היסט", + "ui.end_cap.inward": "פנימה", + "ui.end_cap.length": "אורך", + "ui.end_cap.outward": "החוצה", + "ui.end_cap.ratio": "יחס מהעובי", + "ui.end_cap_title": "מכסה קצה" + }, + "it": { + "cmd.frame_end_cap": "Tappo di estremità", + "error.end_cap_faces": "Seleziona almeno una faccia di estremità aperta di un elemento", + "error.end_cap_unresolved": "L'estremità {ends} di questa chiusura non è più nel modello. Seleziona di nuovo le facce di estremità", + "help.frame.end_cap": "Chiude le estremità aperte degli elementi con piastre sagomate sul contorno del profilo. Usalo per chiudere tubi, angolari e travi, sopra l'estremità o incassate.", + "ui.end_cap.chamfer": "Smusso degli angoli", + "ui.end_cap.direction": "Direzione", + "ui.end_cap.faces": "Facce di estremità", + "ui.end_cap.inset": "Rientro", + "ui.end_cap.inset_kind": "Rientro come", + "ui.end_cap.inset_ratio": "Rapporto di rientro", + "ui.end_cap.inward": "Verso l'interno", + "ui.end_cap.length": "Lunghezza", + "ui.end_cap.outward": "Verso l'esterno", + "ui.end_cap.ratio": "Rapporto dello spessore", + "ui.end_cap_title": "TAPPO DI ESTREMITÀ" + }, + "ja": { + "cmd.frame_end_cap": "エンドキャップ", + "error.end_cap_faces": "フレーム部材の開いた端面を1つ以上選択してください", + "error.end_cap_unresolved": "このエンドキャップの端 {ends} はモデル上にありません。端面を選択し直してください", + "help.frame.end_cap": "フレーム部材の開いた端を、プロファイルの外形に沿ったプレートで閉じます。パイプ、アングル、梁の端をふさぐときに、端の上に載せるか端に埋め込んで使います。", + "ui.end_cap.chamfer": "角の面取り", + "ui.end_cap.direction": "方向", + "ui.end_cap.faces": "端面", + "ui.end_cap.inset": "内側オフセット", + "ui.end_cap.inset_kind": "オフセットの指定", + "ui.end_cap.inset_ratio": "オフセット比", + "ui.end_cap.inward": "内向き", + "ui.end_cap.length": "長さ", + "ui.end_cap.outward": "外向き", + "ui.end_cap.ratio": "厚さに対する比", + "ui.end_cap_title": "エンドキャップ" + }, + "pt-BR": { + "cmd.frame_end_cap": "Tampa de extremidade", + "error.end_cap_faces": "Selecione pelo menos uma face de extremidade aberta de um membro", + "error.end_cap_unresolved": "A extremidade {ends} desta tampa não está mais no modelo. Selecione as faces de extremidade novamente", + "help.frame.end_cap": "Fecha as extremidades abertas dos membros com placas no formato do contorno do perfil. Use para tampar tubos, cantoneiras e vigas, sobre a extremidade ou embutidas nela.", + "ui.end_cap.chamfer": "Chanfro dos cantos", + "ui.end_cap.direction": "Direção", + "ui.end_cap.faces": "Faces de extremidade", + "ui.end_cap.inset": "Recuo", + "ui.end_cap.inset_kind": "Recuo por", + "ui.end_cap.inset_ratio": "Proporção de recuo", + "ui.end_cap.inward": "Para dentro", + "ui.end_cap.length": "Comprimento", + "ui.end_cap.outward": "Para fora", + "ui.end_cap.ratio": "Proporção da espessura", + "ui.end_cap_title": "TAMPA DE EXTREMIDADE" + }, + "vi": { + "cmd.frame_end_cap": "Nắp đầu", + "error.end_cap_faces": "Chọn ít nhất một mặt đầu hở của một thanh khung", + "error.end_cap_unresolved": "Đầu {ends} của nắp này không còn trên mô hình. Hãy chọn lại các mặt đầu", + "help.frame.end_cap": "Đóng các đầu hở của thanh khung bằng tấm có hình đường bao của tiết diện. Dùng để bịt ống, thép góc và dầm, đặt lên đầu hoặc lắp chìm vào đầu.", + "ui.end_cap.chamfer": "Vát góc", + "ui.end_cap.direction": "Hướng", + "ui.end_cap.faces": "Mặt đầu", + "ui.end_cap.inset": "Thụt vào", + "ui.end_cap.inset_kind": "Thụt vào theo", + "ui.end_cap.inset_ratio": "Tỉ lệ thụt vào", + "ui.end_cap.inward": "Vào trong", + "ui.end_cap.length": "Chiều dài", + "ui.end_cap.outward": "Ra ngoài", + "ui.end_cap.ratio": "Tỉ lệ theo độ dày", + "ui.end_cap_title": "NẮP ĐẦU" + }, + "zh": { + "cmd.frame_end_cap": "端盖", + "error.end_cap_faces": "请至少选择一个框架构件的开放端面", + "error.end_cap_unresolved": "此端盖的端 {ends} 已不在模型上。请重新选择端面", + "help.frame.end_cap": "用符合型材外形的板封闭框架构件的开放端。用于封住管材、角钢和梁的端部,可盖在端面上或嵌入端部。", + "ui.end_cap.chamfer": "角部倒角", + "ui.end_cap.direction": "方向", + "ui.end_cap.faces": "端面", + "ui.end_cap.inset": "内缩", + "ui.end_cap.inset_kind": "内缩方式", + "ui.end_cap.inset_ratio": "内缩比例", + "ui.end_cap.inward": "向内", + "ui.end_cap.length": "长度", + "ui.end_cap.outward": "向外", + "ui.end_cap.ratio": "厚度比例", + "ui.end_cap_title": "端盖" + }, + "zh-TW": { + "cmd.frame_end_cap": "端蓋", + "error.end_cap_faces": "請至少選取一個框架構件的開放端面", + "error.end_cap_unresolved": "此端蓋的端 {ends} 已不在模型上。請重新選取端面", + "help.frame.end_cap": "以符合型材外形的板封閉框架構件的開放端。用於封住管材、角鋼與樑的端部,可蓋在端面上或嵌入端部。", + "ui.end_cap.chamfer": "角落倒角", + "ui.end_cap.direction": "方向", + "ui.end_cap.faces": "端面", + "ui.end_cap.inset": "內縮", + "ui.end_cap.inset_kind": "內縮方式", + "ui.end_cap.inset_ratio": "內縮比例", + "ui.end_cap.inward": "向內", + "ui.end_cap.length": "長度", + "ui.end_cap.outward": "向外", + "ui.end_cap.ratio": "厚度比例", + "ui.end_cap_title": "端蓋" + } +} diff --git a/attribution/pending/frame-end-caps.md b/attribution/pending/frame-end-caps.md new file mode 100644 index 00000000000..c5361b2af9c --- /dev/null +++ b/attribution/pending/frame-end-caps.md @@ -0,0 +1,3 @@ +| assets/icons/ui/design/svg/model/end_cap.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/model/end_cap_inward.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/model/end_cap_outward.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index 3a8bb4a3c36..81a106ef2ca 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -213,6 +213,11 @@ impl crate::Feature { checked_link(&link.source, 0)?; } } + K::FrameEndCap { ends, .. } => { + for end in ends { + checked_plane(&end.plane, 0)?; + } + } K::ConstructionPlane { plane } | K::Split { plane, .. } | K::SplitFace { plane, .. } @@ -283,6 +288,11 @@ impl crate::Feature { } } } + K::FrameEndCap { ends, .. } => { + for end in ends { + remap_plane(&mut end.plane, ids, bodies, 0)?; + } + } K::ConstructionPlane { plane } | K::Split { plane, .. } | K::SplitFace { plane, .. } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 996e63caccf..0dcff2a7299 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1156,6 +1156,25 @@ pub enum FeatureKind { #[serde(default, skip_serializing_if = "Vec::is_empty")] targets: Vec, }, + /// Plates closing open ends of frame members (#4003), one body per end, each the outside of + /// the member's profile, optionally set in from its edge. + FrameEndCap { + ends: Vec, + #[walk(length = "Thickness")] + thickness: Expr, + /// The inset from the outline's edge as a length, or `ratio` of the thickness; neither: + /// flush with the outside of the profile. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(length = "Inset")] + offset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(unitless = "Inset Ratio")] + ratio: Option, + #[walk(length = "Corner Chamfer")] + chamfer: Expr, + #[serde(default)] + direction: crate::end_cap::Direction, + }, /// Structural members (#4003): one body per straight line of a frame sketch (2D sketch lines /// and 3D sketch lines), its cross-section the profile, square to the line from end to end. FrameMember { @@ -2699,6 +2718,7 @@ impl FeatureKind { FeatureKind::SurfaceOffset { .. } => "OffsetSurfaceFeature", FeatureKind::BoundingSolid { .. } => "BoundingSolidFeature", FeatureKind::Pipe { .. } => "PipeFeature", + FeatureKind::FrameEndCap { .. } => "EndCapFeature", FeatureKind::FrameMember { .. } => "FrameMemberFeature", FeatureKind::Emboss { .. } => "EmbossFeature", FeatureKind::Boss { .. } => "BossFeature", @@ -2781,6 +2801,7 @@ impl FeatureKind { FeatureKind::DeleteFace { .. } => "delete_face", FeatureKind::BoundingSolid { .. } => "bounding_solid", FeatureKind::Pipe { .. } => "pipe", + FeatureKind::FrameEndCap { .. } => "frame_end_cap", FeatureKind::FrameMember { .. } => "frame_member", FeatureKind::Emboss { .. } => "emboss", FeatureKind::Rib { .. } => "rib", @@ -2865,6 +2886,7 @@ impl FeatureKind { "OffsetSurfaceFeature" => "surface_offset", "BoundingSolidFeature" => "bounding_solid", "PipeFeature" => "pipe", + "EndCapFeature" => "frame_end_cap", "FrameMemberFeature" => "frame_member", "EmbossFeature" => "emboss", "BossFeature" => "boss", @@ -2948,6 +2970,7 @@ impl FeatureKind { FeatureKind::SurfaceOffset { .. } => "OffsetSurface", FeatureKind::BoundingSolid { .. } => "BoundingSolid", FeatureKind::Pipe { .. } => "Pipe", + FeatureKind::FrameEndCap { .. } => "EndCap", FeatureKind::FrameMember { .. } => "Member", FeatureKind::Emboss { .. } => "Emboss", FeatureKind::Boss { .. } => "Boss", diff --git a/crates/doc/src/end_cap.rs b/crates/doc/src/end_cap.rs new file mode 100644 index 00000000000..28df53fe21d --- /dev/null +++ b/crates/doc/src/end_cap.rs @@ -0,0 +1,582 @@ +//! End caps (#4003): a plate closing the open end of a frame member, its outline the member +//! profile's outer outline set in from the edge, built from existing extrude and boolean +//! operations. +use std::collections::BTreeMap; + +use crate::expr::{Kind, Value}; +use crate::{DocError, Document, Feature, FeatureKind, ModelBody, ModelState, PlaneRef, Result}; +use serde::{Deserialize, Serialize}; +use solidcore_record::{Loop2, Plane, Region2, Seg2, Vec2}; +use solidcraft_geom::prelude::*; +use solidcraft_kernel::{self as kernel, BoolOp}; + +/// Most end faces one end cap feature closes. +pub const MAX_FACES: usize = 256; + +/// The member a capped face belongs to: its feature and line, which outlive body renames. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +#[serde(deny_unknown_fields)] +pub struct Member { + pub feature: crate::FeatureId, + pub line: String, +} + +/// One capped end: the member's planar end face and the member it belongs to. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +#[serde(deny_unknown_fields)] +pub struct End { + pub plane: PlaneRef, + pub member: Member, +} + +/// Which way the cap goes from the end face. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, solidcraft_derive::Walk)] +#[serde(rename_all = "snake_case")] +pub enum Direction { + /// Past the end: the frame gets longer by the thickness. + #[default] + Outward, + /// Into the member, which is cut back by the thickness: the frame keeps its length. + Inward, +} + +fn invalid(s: impl Into) -> DocError { + DocError::Invalid(s.into()) +} + +/// The member that `plane`'s face belongs to; an error when it is no frame member's face. +pub fn member(doc: &Document, st: &ModelState, plane: &PlaneRef) -> Result { + let PlaneRef::Face { anchor: Some(anchor), .. } = plane else { return Err(invalid("an end cap needs a planar face picked on a frame member")) }; + let source = doc.feature(anchor.target.origin_feature).ok_or_else(|| invalid("the capped member's feature no longer exists"))?; + let FeatureKind::FrameMember { names, .. } = &source.kind else { return Err(invalid("the face is not on a frame member")) }; + let ids = crate::frame::member_line_ids(st, &source.kind)?; + let line = if source.body_names.is_empty() { + ids.iter().find(|line| names.get(*line).is_some_and(|name| *name == anchor.target.body)) + } else { + source.body_names.iter().position(|name| *name == anchor.target.body).and_then(|i| ids.get(i)) + } + .ok_or_else(|| invalid("the face is no longer on the member it was picked on"))?; + Ok(Member { feature: source.id.into(), line: line.clone() }) +} + +fn length(v: f64, what: &str, min: f64) -> Result { + if !v.is_finite() || v > 1e6 || v < min { + return Err(invalid(format!("the end cap's {what} must be a length from {min} to 1e6 mm"))); + } + Ok(v) +} + +/// Most edges in an outline an end cap follows. +const MAX_EDGES: usize = 4096; + +/// Where a segment of the outline goes when it moves in: a line through a point along a unit +/// direction, or a circle. +#[derive(Clone, Copy)] +enum Carrier { + Line(Vec2, Vec2), + Circle(Vec2, f64), +} + +/// The points where two carriers cross. +fn crossings(c1: Carrier, c2: Carrier) -> Vec { + match (c1, c2) { + (Carrier::Line(p1, t1), Carrier::Line(p2, t2)) => { + let den = t1.cross(t2); + if den.abs() < 1e-9 { Vec::new() } else { vec![p1 + t1 * ((p2 - p1).cross(t2) / den)] } + } + (Carrier::Line(p, t), Carrier::Circle(c, r)) | (Carrier::Circle(c, r), Carrier::Line(p, t)) => { + let foot = p + t * (c - p).dot(t); + let h2 = r * r - (c - foot).dot(c - foot); + if h2 < -1e-9 * r.max(1.0) { + return Vec::new(); + } + let h = h2.max(0.0).sqrt(); + vec![foot - t * h, foot + t * h] + } + (Carrier::Circle(c1, r1), Carrier::Circle(c2, r2)) => { + let dd = c1.dist(c2); + if dd < 1e-12 { + return Vec::new(); + } + let u = (c2 - c1) / dd; + let along = (r1 * r1 - r2 * r2 + dd * dd) / (2.0 * dd); + let h2 = r1 * r1 - along * along; + if h2 < -1e-9 * r1.max(1.0) { + return Vec::new(); + } + let h = h2.max(0.0).sqrt(); + let foot = c1 + u * along; + vec![foot - u.perp() * h, foot + u.perp() * h] + } + } +} + +/// How far `p` is from segment `s` (a line or an arc). +fn distance(s: &Seg2, p: Vec2) -> f64 { + match *s { + Seg2::Line { a, b } => { + let ab = b - a; + let l2 = ab.dot(ab); + let u = if l2 > 0.0 { ((p - a).dot(ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; + p.dist(a + ab * u) + } + Seg2::Arc { center, radius, start, sweep } => { + let tau = std::f64::consts::TAU; + let rel = (p - center).angle() - start; + let u = if sweep >= 0.0 { rel.rem_euclid(tau) } else { (-rel).rem_euclid(tau) }; + if u <= sweep.abs() { (p.dist(center) - radius).abs() } else { p.dist(s.start()).min(p.dist(s.end())) } + } + _ => p.dist(s.start()).min(p.dist(s.end())), + } +} + +/// Points along `s`: a few on a line, more on an arc. +fn samples(s: &Seg2) -> Vec { + let k = match *s { + Seg2::Arc { sweep, .. } => ((sweep.abs() / (std::f64::consts::PI / 32.0)).ceil() as usize).clamp(2, 128), + _ => 8, + }; + (0..=k).map(|i| s.point_at(i as f64 / k as f64)).collect() +} + +/// Whether two straight pieces cross (touching at their ends does not count). +fn pieces_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool { + let (o1, o2) = ((b - a).cross(c - a), (b - a).cross(d - a)); + let (o3, o4) = ((d - c).cross(a - c), (d - c).cross(b - c)); + let eps = 1e-12 * (1.0 + a.dist(b) + c.dist(d)).powi(2); + o1 * o2 < -eps && o3 * o4 < -eps +} + +/// Whether `lp`'s edges cross one another. +fn crosses_itself(lp: &Loop2) -> bool { + let pts: Vec = lp + .segs + .iter() + .flat_map(|s| { + let mut v = samples(s); + v.pop(); + v + }) + .collect(); + let n = pts.len(); + for i in 0..n { + for j in i + 2..n { + if i == 0 && j + 1 == n { + continue; + } + let (Some(&a), Some(&b), Some(&c), Some(&d)) = (pts.get(i), pts.get((i + 1) % n), pts.get(j), pts.get((j + 1) % n)) else { + continue; + }; + if pieces_cross(a, b, c, d) { + return true; + } + } + } + false +} + +/// `outline`, a counter-clockwise loop of lines and arcs, moved in by `d` all round: lines move +/// along their inward normal, arcs that bulge out lose `d` of radius and arcs that curve in (the +/// root of an angle or a beam) gain it. An arc that shrinks away leaves its neighbours meeting +/// at a corner. Any shape works: round and rectangular tubes as well as angles, channels and +/// beams. An inset more than half a wall somewhere (an angle's leg, a beam's web) is refused. +pub(crate) fn inset(outline: &Loop2, d: f64) -> Result { + let no_plate = || { + invalid(format!( + "an inset of {} mm leaves no plate inside the profile's outline (it is more than half a wall somewhere)", + crate::frame::short(d) + )) + }; + if !d.is_finite() || d < 0.0 { + return Err(invalid("the end cap's inset must be a length of 0 or more")); + } + let segs = &outline.segs; + let n = segs.len(); + if n == 0 || outline.signed_area() <= 0.0 { + return Err(invalid("the profile's outline has no area")); + } + if n > MAX_EDGES { + return Err(invalid(format!("end caps follow outlines of at most {MAX_EDGES} edges"))); + } + // A full circle (arcs on one circle): its radius shrinks. + if let Some(Seg2::Arc { center, radius, .. }) = segs.first().copied() + && segs + .iter() + .all(|s| matches!(*s, Seg2::Arc { center: c, radius: r, sweep, .. } if c.dist(center) < 1e-9 && (r - radius).abs() < 1e-9 && sweep > 0.0)) + { + return if radius - d > 1e-6 { Ok(Loop2::circle(center, radius - d)) } else { Err(no_plate()) }; + } + let mut carriers = Vec::with_capacity(n); + for s in segs { + carriers.push(match *s { + Seg2::Line { a, b } => { + let t = (b - a).normalized().ok_or_else(|| invalid("the profile's outline has an edge of no length"))?; + Some(Carrier::Line(a + t.perp() * d, t)) + } + // Counter-clockwise arcs bulge out and shrink; clockwise ones curve in and grow. + Seg2::Arc { center, radius, sweep, .. } if sweep.abs() > 1e-12 && radius > 0.0 => { + let r = radius - d * sweep.signum(); + (r > 1e-6).then_some(Carrier::Circle(center, r)) + } + Seg2::Arc { .. } => return Err(invalid("the profile's outline has an arc of no length")), + _ => return Err(invalid("end caps follow outlines of lines and arcs (a spline or conic outline is not supported)")), + }); + } + let kept: Vec = (0..n).filter(|i| carriers.get(*i).is_some_and(Option::is_some)).collect(); + let m = kept.len(); + if m < 2 { + return Err(no_plate()); + } + // Where kept segment `k` starts: after a smooth join, the old point moved in; otherwise (a + // corner, or arcs shrunk away between) where it meets the previous kept segment, nearest the + // corner it replaces. + let mut starts = Vec::with_capacity(m); + for (j, &k) in kept.iter().enumerate() { + let p = kept.get((j + m - 1) % m).copied().ok_or_else(no_plate)?; + let (Some(prev), Some(this)) = (segs.get(p), segs.get(k)) else { return Err(no_plate()) }; + let (tin, tout) = (prev.end_tangent(), this.start_tangent()); + if (p + 1) % n == k && tin.cross(tout).abs() < 1e-7 && tin.dot(tout) > 0.0 { + starts.push(this.start() + tout.perp() * d); + continue; + } + let (Some(Some(c1)), Some(Some(c2))) = (carriers.get(p).copied(), carriers.get(k).copied()) else { return Err(no_plate()) }; + let near = prev.end().lerp(this.start(), 0.5); + let best = crossings(c1, c2).into_iter().min_by(|a, b| a.dist(near).total_cmp(&b.dist(near))).ok_or_else(no_plate)?; + starts.push(best); + } + let mut out = Vec::with_capacity(m); + for (j, &k) in kept.iter().enumerate() { + let (Some(&a), Some(&b)) = (starts.get(j), starts.get((j + 1) % m)) else { return Err(no_plate()) }; + match (segs.get(k).copied(), carriers.get(k).copied()) { + (Some(Seg2::Line { a: oa, b: ob }), _) => { + if (b - a).dot(ob - oa) <= 1e-6 * oa.dist(ob) || a.dist(b) < 1e-6 { + return Err(no_plate()); + } + out.push(Seg2::Line { a, b }); + } + (Some(Seg2::Arc { sweep, .. }), Some(Some(Carrier::Circle(center, r)))) => { + let tau = std::f64::consts::TAU; + let (s, e) = ((a - center).angle(), (b - center).angle()); + let sw = if sweep > 0.0 { (e - s).rem_euclid(tau) } else { -(s - e).rem_euclid(tau) }; + // An arc turned inside out shows as one sweeping most of the way round. + if sw.abs() < 1e-9 || sw.abs() > sweep.abs() + std::f64::consts::FRAC_PI_2 { + return Err(no_plate()); + } + out.push(Seg2::Arc { center, radius: r, start: s, sweep: sw }); + } + _ => return Err(no_plate()), + } + } + let lp = Loop2 { segs: out }; + // Every point of the plate's edge is at least `d` from the profile's: closer means the inset + // reached across a wall thinner than twice the inset. + let tol = 1e-6 * (1.0 + d); + let far_enough = lp.segs.iter().flat_map(samples).all(|q| segs.iter().map(|s| distance(s, q)).fold(f64::INFINITY, f64::min) >= d - tol); + if !(lp.signed_area() > 1e-6) || !far_enough || crosses_itself(&lp) { + return Err(no_plate()); + } + Ok(lp) +} + +/// `outline` (as [`inset`] makes it) with every outside corner cut by a chamfer `c` long along +/// each edge, measured from where the edges meet. A rounded corner is cut away whole, so `c` +/// must be at least as long as its rounding. Inside corners (the root of an angle or a beam) +/// stay as they are. +pub(crate) fn chamfered(outline: &Loop2, c: f64) -> Result { + if !c.is_finite() || c < 0.0 { + return Err(invalid("the end cap's chamfer must be a length of 0 or more")); + } + if c == 0.0 { + return Ok(outline.clone()); + } + let segs = &outline.segs; + let n = segs.len(); + let round = || invalid("a round end cap has no corners to chamfer (set the chamfer to 0)"); + // The lines in order from the first; an outline with none is round. + let first = segs.iter().position(|s| matches!(s, Seg2::Line { .. })).ok_or_else(round)?; + let lines: Vec = (0..n).map(|i| (first + i) % n).filter(|i| matches!(segs.get(*i), Some(Seg2::Line { .. }))).collect(); + let k = lines.len(); + if k < 2 { + return Err(round()); + } + let line = |i: usize| -> Result<(Vec2, Vec2, Vec2)> { + match lines.get(i % k).and_then(|j| segs.get(*j)).copied() { + Some(Seg2::Line { a, b }) => Ok((a, b, (b - a).normalized().ok_or_else(|| invalid("the end cap's outline has an edge of no length"))?)), + _ => Err(invalid("the end cap's outline lost an edge")), + } + }; + // The segments between line `i` and the next line. + let between = |i: usize| -> Vec { + let (Some(&a), Some(&b)) = (lines.get(i % k), lines.get((i + 1) % k)) else { return Vec::new() }; + let count = (b + n - a - 1) % n; + (1..=count).filter_map(|o| segs.get((a + o) % n).copied()).collect() + }; + // Each line's corner at its end, where chamfered: an outside corner, sharp or rounded by arcs + // that bulge out. + let mut corners = Vec::with_capacity(k); + for i in 0..k { + let (a1, b1, t1) = line(i)?; + let (a2, _, t2) = line(i + 1)?; + let den = t1.cross(t2); + let outside = den > 1e-9 && between(i).iter().all(|s| matches!(*s, Seg2::Arc { sweep, .. } if sweep > 0.0)); + if !outside { + corners.push(None); + continue; + } + let v = a1 + t1 * ((a2 - a1).cross(t2) / den); + let setback = v.dist(b1).max(v.dist(a2)); + if c + 1e-9 < setback { + return Err(invalid(format!( + "the chamfer must be at least the corner rounding it cuts away ({} mm), or 0", + crate::frame::short(setback) + ))); + } + corners.push(Some((v - t1 * c, v + t2 * c))); + } + if corners.iter().all(Option::is_none) { + return Err(invalid("the end cap has no outside corners to chamfer (set the chamfer to 0)")); + } + let too_large = || invalid("the chamfer is too large for the end cap's edges"); + let mut out = Vec::with_capacity(2 * n); + for i in 0..k { + let (a, b, t) = line(i)?; + let start = match corners.get((i + k - 1) % k) { + Some(Some((_, s))) => *s, + _ => a, + }; + let end = match corners.get(i) { + Some(Some((e, _))) => *e, + _ => b, + }; + if (end - start).dot(t) <= 1e-6 { + return Err(too_large()); + } + out.push(Seg2::Line { a: start, b: end }); + match corners.get(i) { + Some(Some((e, s))) => out.push(Seg2::Line { a: *e, b: *s }), + _ => out.extend(between(i)), + } + } + let lp = Loop2 { segs: out }; + if !(lp.signed_area() > 1e-6) || crosses_itself(&lp) { + return Err(too_large()); + } + Ok(lp) +} + +/// A free body name for the cap on `member`: ` End Cap`, then `… (2)`, `… (3)`… +fn cap_name(st: &mut ModelState, f: &Feature, k: usize, member: &str) -> String { + if f.body_names.get(k).is_some_and(|n| !n.is_empty()) { + return crate::eval::new_name(st, f, k); + } + let base = format!("{member} End Cap"); + // Not a name the design keeps for a suppressed feature or a rename (#4302, #4957): a cap + // made while another is suppressed must not take that one's name. Nor one another end of + // this cap has stored, which is built after this one when an end is added before it. + let tries = st.bodies.len() + st.reserved_body_names.len() + f.body_names.len() + 2; + (1..=tries) + .map(|i| if i == 1 { base.clone() } else { format!("{base} ({i})") }) + .find(|n| st.body(n).is_none() && !st.reserved_body_names.contains(n) && !f.body_names.contains(n)) + .unwrap_or(base) +} + +/// A capped end, worked out before any body changes. +struct Planned { + body: String, + plane: Plane, + region: Region2, + /// The cap's extent along the plane's normal, and the slab cut from an inward cap's member. + cap: (f64, f64), + cut: Option<(Region2, f64, f64)>, + /// The cap's frame to the member body's own: the cap is authored in this feature's frame, the + /// member is stored in its component's (moved by its body offset), and the cut is made there. + to_member: crate::Mat, +} + +pub(crate) fn evaluate(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { + let FeatureKind::FrameEndCap { ends, thickness, offset, ratio, chamfer, direction } = &f.kind else { + return Err(invalid("not an end cap")); + }; + if ends.is_empty() { + return Err(invalid("pick at least one open end face of a frame member")); + } + if ends.len() > MAX_FACES { + return Err(invalid(format!("at most {MAX_FACES} end faces in one end cap feature"))); + } + let t = length(crate::eval::val(vals, thickness, Kind::Length)?, "thickness", 0.01)?; + let d = match (offset, ratio) { + (Some(e), None) => length(crate::eval::val(vals, e, Kind::Length)?, "inset", 0.0)?, + (None, Some(e)) => { + let r = crate::eval::val(vals, e, Kind::Unitless)?; + if !r.is_finite() || !(0.0..=1000.0).contains(&r) { + return Err(invalid("the end cap's inset ratio must be from 0 to 1000 times the thickness")); + } + r * t + } + // Neither: flush with the outside of the profile. + (None, None) => 0.0, + _ => return Err(invalid("give the end cap's inset as either a length or a ratio of the thickness, not both")), + }; + let c = length(crate::eval::val(vals, chamfer, Kind::Length)?, "chamfer", 0.0)?; + let mut planned = Vec::with_capacity(ends.len()); + for end in ends { + let PlaneRef::Face { anchor: Some(anchor), .. } = &end.plane else { + return Err(invalid("an end cap needs a planar face picked on a frame member")); + }; + if member(doc, st, &end.plane)? != end.member { + return Err(invalid("the capped face is no longer on the member it was picked on")); + } + let face = doc.resolve_face_anchor(anchor, f.component, st).map_err(|e| invalid(format!("the capped end face: {e}")))?; + let body = st.body(&anchor.target.body).ok_or_else(|| invalid("the capped member's body no longer exists"))?; + let source = doc.feature(end.member.feature.0).ok_or_else(|| invalid("the capped member's feature no longer exists"))?; + let (section, len, region) = crate::eval::frame_member::member_section(doc, vals, source, st, &end.member.line)?; + let to_author = anchor.source_to_author(doc, f.component, body)?; + let section = Plane::new( + crate::apply_point(&to_author, section.origin), + crate::apply_vector(&to_author, section.x), + crate::apply_vector(&to_author, section.y), + ) + .ok_or_else(|| invalid("the member's placement is degenerate"))?; + let along = section.normal(); + let facing = face.normal().dot(along); + if facing.abs() < 1.0 - 1e-7 { + return Err(invalid("the picked face is not an end of the member (it is not square to the member's line)")); + } + let plane = Plane::new(section.origin + along * (face.origin - section.origin).dot(along), section.x, section.y) + .ok_or_else(|| invalid("the end face's plane is degenerate"))?; + // The same end, however it was picked (another point on its face, another anchor): the + // same body with an earlier cap on this exact end plane. + let same_end = |p: &Planned| { + p.body == anchor.target.body && p.plane.origin.dist(plane.origin) < 1e-6 && p.plane.normal().dot(plane.normal()).abs() > 1.0 - 1e-9 + }; + if planned.iter().any(same_end) { + return Err(invalid("an end face is picked twice")); + } + let outline = chamfered(&inset(&cap_outline(®ion.outer), d)?, c)?; + let cap_region = Region2 { outer: outline, holes: Vec::new() }; + // Along the plane's normal: the member lies behind an end facing that way. + let s = facing.signum(); + let (cap, cut) = match direction { + Direction::Outward => (if s > 0.0 { (0.0, t) } else { (-t, 0.0) }, None), + Direction::Inward => { + if t >= len - 1e-3 { + return Err(invalid(format!("an inward end cap {} mm thick needs a longer member", crate::frame::short(t)))); + } + // A slab wider than the profile and past the end, so no face of it lies on the + // member's. + let bb = region.outer.polyline(1e-3).bounds(); + let m = 1.0 + 0.01 * (bb.max - bb.min).len(); + let (lo, hi) = (bb.min - Vec2::new(m, m), bb.max + Vec2::new(m, m)); + let slab = Region2 { outer: Loop2::polygon(&[lo, Vec2::new(hi.x, lo.y), hi, Vec2::new(lo.x, hi.y)]), holes: Vec::new() }; + let (a, b) = if s > 0.0 { (-t, m) } else { (-m, t) }; + (if s > 0.0 { (-t, 0.0) } else { (0.0, t) }, Some((slab, a, b))) + } + }; + let to_member = crate::mat_inverse(&to_author).ok_or_else(|| invalid("the member's placement is degenerate"))?; + planned.push(Planned { body: anchor.target.body.clone(), plane, region: cap_region, cap, cut, to_member }); + } + for (k, p) in planned.into_iter().enumerate() { + if let Some((slab, a, b)) = &p.cut { + let i = st.bodies.iter().position(|b| b.name == p.body).ok_or_else(|| invalid("the capped member's body no longer exists"))?; + let mb = st.bodies.get(i).cloned().ok_or_else(|| invalid("the capped member's body no longer exists"))?; + let at = Plane::new( + crate::apply_point(&p.to_member, p.plane.origin), + crate::apply_vector(&p.to_member, p.plane.x), + crate::apply_vector(&p.to_member, p.plane.y), + ) + .ok_or_else(|| invalid("the member's placement is degenerate"))?; + let tool = one(kernel::extrude(&at, std::slice::from_ref(slab), *a, *b)?)?; + let tool = crate::lineage::numbered_tool(tool); + let cut = kernel::boolean(&mb.body, &tool.body, BoolOp::Cut)? + .ok_or_else(|| invalid("cutting the member back for an inward end cap left nothing"))?; + let cut = crate::lineage::Traced::step(cut, &[&mb.traced(), &tool]); + if let Some(slot) = st.bodies.get_mut(i) { + *slot = ModelBody::traced_new(mb.name, cut, mb.feature); + } + } + let body = one(kernel::extrude(&p.plane, std::slice::from_ref(&p.region), p.cap.0, p.cap.1)?)?; + let name = cap_name(st, f, k, &p.body); + st.bodies.push(ModelBody::traced_new(name, crate::lineage::numbered_tool(body), f.id)); + } + Ok(()) +} + +/// The outline an end cap is cut from: the outside of the profile. A closed section (a tube, a +/// pipe, a bar) keeps its own outline. An open section that turns inward somewhere (an angle, a +/// channel, a beam, an extrusion with slots) keeps the edges on its bounding rectangle and the +/// rounds and chamfers turning between them, and bridges each inward stretch along the +/// rectangle, so the plate closes the whole end with the profile's own outside corners. +pub(crate) fn cap_outline(outer: &Loop2) -> Loop2 { + let ring = outer.polyline(1e-3); + let convex = ring.corners().all(|(p, c, n)| (*c - *p).cross(*n - *c) >= -1e-9); + if convex { + return outer.clone(); + } + let bb = ring.bounds(); + let rect = Loop2::polygon(&[bb.min, Vec2::new(bb.max.x, bb.min.y), bb.max, Vec2::new(bb.min.x, bb.max.y)]); + let tol = 1e-6 * (1.0 + bb.max.dist(bb.min)); + // How far a point is off each side of the rectangle (0 bottom, 1 right, 2 top, 3 left, + // counter-clockwise); a line lies on a side when both its ends do. + let off = |q: Vec2| [(q.y - bb.min.y).abs(), (q.x - bb.max.x).abs(), (q.y - bb.max.y).abs(), (q.x - bb.min.x).abs()]; + let on_side = |s: &Seg2| match *s { + Seg2::Line { a, b } => (0..4).find(|i| off(a).get(*i).is_some_and(|e| *e < tol) && off(b).get(*i).is_some_and(|e| *e < tol)), + _ => None, + }; + let segs = &outer.segs; + let n = segs.len(); + let sides: Vec> = segs.iter().map(on_side).collect(); + let Some(first) = sides.iter().position(Option::is_some) else { return rect }; + let corner = |i: usize| [Vec2::new(bb.max.x, bb.min.y), bb.max, Vec2::new(bb.min.x, bb.max.y), bb.min].get(i % 4).copied(); + let mut out: Vec = Vec::with_capacity(n + 4); + let mut i = first; + for _ in 0..n { + let (Some(&seg), Some(&Some(si))) = (segs.get(i), sides.get(i)) else { return rect }; + out.push(seg); + // The stretch up to the next edge on the rectangle. + let mut j = (i + 1) % n; + let mut run = Vec::new(); + while sides.get(j).is_some_and(Option::is_none) { + run.push(j); + j = (j + 1) % n; + } + let (Some(&next), Some(&Some(sj))) = (segs.get(j), sides.get(j)) else { return rect }; + // Kept when it only turns outward from one side to the next: a round or a chamfer. + let mut chain = vec![seg]; + chain.extend(run.iter().filter_map(|k| segs.get(*k).copied())); + chain.push(next); + let turns_out = chain.windows(2).all(|w| matches!(w, [a, b] if a.end_tangent().cross(b.start_tangent()) >= -1e-9)) + && chain.iter().all(|s| !matches!(*s, Seg2::Arc { sweep, .. } if sweep < 0.0)); + if !run.is_empty() && turns_out && sj == (si + 1) % 4 { + out.extend(run.iter().filter_map(|k| segs.get(*k).copied())); + } else if !run.is_empty() || seg.end().dist(next.start()) > tol { + // Along the rectangle from this side round to the next one's. + let mut p = seg.end(); + let steps = (sj + 4 - si) % 4; + let steps = if steps == 0 && (next.start() - p).dot(corner(si).unwrap_or(p) - p) < 0.0 { 4 } else { steps }; + for k in 0..steps { + let Some(c) = corner(si + k) else { return rect }; + if p.dist(c) > tol { + out.push(Seg2::Line { a: p, b: c }); + } + p = c; + } + if p.dist(next.start()) > tol { + out.push(Seg2::Line { a: p, b: next.start() }); + } + } + if j == first { + break; + } + i = j; + } + let lp = Loop2 { segs: out }; + if lp.signed_area() > 0.0 && lp.is_closed(tol) && !crosses_itself(&lp) { lp } else { rect } +} + +fn one(mut bodies: Vec) -> Result { + let body = bodies.pop().ok_or_else(|| invalid("the end cap is not one solid"))?; + if !bodies.is_empty() { + return Err(invalid("the end cap is not one solid")); + } + Ok(body) +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index d6bc9273702..542e8592da8 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2015,6 +2015,24 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64 reads.link(doc, st, &link.source); } } + // Each end is read as a sketch on a face is: in the frame it was capped in, its member + // through the placement it was picked at, so moving that occurrence rebuilds the cap. + FeatureKind::FrameEndCap { ends, .. } => { + for anchor in ends.iter().filter_map(|end| crate::face_anchor::plane_face_anchor(&end.plane)) { + match anchor.author_frame(doc, f.component) { + Ok(m) => { + hash_placement(&m, &mut h); + frame.get_or_insert(m); + } + Err(e) => e.to_string().hash(&mut h), + } + if anchor.path.is_empty() { + reads.components.insert(anchor.component); + } else { + reads.paths.push(anchor.path.clone()); + } + } + } _ => {} } if reads.is_empty() { @@ -3060,7 +3078,7 @@ pub fn curve_pick_error(e: solidcraft_sketch::CurvePick, ids: &[String], sketch: } } -fn new_name(state: &mut ModelState, f: &Feature, k: usize) -> String { +pub(crate) fn new_name(state: &mut ModelState, f: &Feature, k: usize) -> String { if let Some(n) = f.body_names.get(k) && !n.is_empty() && state.body(n).is_none() @@ -8522,6 +8540,7 @@ fn eval_feature( } Ok(()) } + FeatureKind::FrameEndCap { .. } => crate::end_cap::evaluate(doc, vals, f, st), FeatureKind::FrameMember { .. } => frame_member::evaluate(doc, vals, f, st), FeatureKind::BoundingSolid { bodies, margin } => { let m = val(vals, margin, Kind::Length)?; diff --git a/crates/doc/src/eval_frame.rs b/crates/doc/src/eval_frame.rs index 7abd78ec794..289e1fd6ecc 100644 --- a/crates/doc/src/eval_frame.rs +++ b/crates/doc/src/eval_frame.rs @@ -25,23 +25,10 @@ const STRAIGHT_TOL: f64 = 1e-3; /// Evaluate a `FrameMember` feature: one new body per line, each named /// ([`member_names`], or by position for a copy whose `body_names` were set). pub(super) fn evaluate(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { - let FeatureKind::FrameMember { path_sketch, lines, profile, anchor, angle, mirror, body_name, names } = &f.kind else { + let FeatureKind::FrameMember { body_name, names, .. } = &f.kind else { return Err(DocError::Invalid("not a frame member feature".into())); }; - let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; - // The frame sketch in this feature's component frame: its plane, and its 3D lines. - let mapped = - if ps.sketch.wires.is_empty() { Cow::Owned(sketch_in_feature_frame(doc, ps, f.component)?) } else { path_in_frame(doc, ps, f.component)? }; - let segments = member_lines(mapped.as_ref(), lines)?; - let (mut regions, description) = profile_regions(vals, st, profile)?; - if *mirror { - regions = regions.iter().map(frame::mirrored).collect(); - } - let at = frame::anchor_point(®ions, *anchor); - let turn = match angle { - Some(e) => val(vals, e, Kind::Angle)?, - None => 0.0, - }; + let Layout { segments, regions, description, at, turn } = layout(doc, vals, f, st)?; let mut made = Vec::with_capacity(segments.len()); for (id, a, b) in &segments { let (x, y) = frame::member_axes(*b - *a, turn).ok_or_else(|| DocError::Invalid(format!("line `{id}` has no length")))?; @@ -70,6 +57,54 @@ pub(super) fn evaluate(doc: &Document, vals: &BTreeMap, f: &Featu Ok(()) } +/// A member feature's lines (in its component frame), profile regions, default name, the +/// profile point that sits on the lines and the profile's turn about them. +struct Layout { + segments: Vec<(String, Vec3, Vec3)>, + regions: Vec, + description: String, + at: Vec2, + turn: f64, +} + +fn layout(doc: &Document, vals: &BTreeMap, f: &Feature, st: &ModelState) -> Result { + let FeatureKind::FrameMember { path_sketch, lines, profile, anchor, angle, mirror, .. } = &f.kind else { + return Err(DocError::Invalid("not a frame member feature".into())); + }; + let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; + // The frame sketch in this feature's component frame: its plane, and its 3D lines. + let mapped = + if ps.sketch.wires.is_empty() { Cow::Owned(sketch_in_feature_frame(doc, ps, f.component)?) } else { path_in_frame(doc, ps, f.component)? }; + let segments = member_lines(mapped.as_ref(), lines)?; + let (mut regions, description) = profile_regions(vals, st, profile)?; + if *mirror { + regions = regions.iter().map(frame::mirrored).collect(); + } + let at = frame::anchor_point(®ions, *anchor); + let turn = match angle { + Some(e) => val(vals, e, Kind::Angle)?, + None => 0.0, + }; + Ok(Layout { segments, regions, description, at, turn }) +} + +/// The member of feature `f` on line `line`, as its body was made: the plane square to the line +/// at its start (x × y along the line), its length, and its profile in that plane. +pub(crate) fn member_section( + doc: &Document, + vals: &BTreeMap, + f: &Feature, + st: &ModelState, + line: &str, +) -> Result<(Plane, f64, Region2)> { + let Layout { segments, regions, at, turn, .. } = layout(doc, vals, f, st)?; + let (_, a, b) = segments.iter().find(|(id, _, _)| id == line).ok_or_else(|| DocError::Unknown(format!("line `{line}` of the member feature")))?; + let (x, y) = frame::member_axes(*b - *a, turn).ok_or_else(|| DocError::Invalid(format!("line `{line}` has no length")))?; + let plane = Plane::new(*a - x * at.x - y * at.y, x, y).ok_or_else(|| DocError::Invalid(format!("line `{line}`: no plane square to it")))?; + let region = regions.into_iter().next().ok_or_else(|| DocError::Invalid("the member profile has no area".into()))?; + Ok((plane, a.dist(*b), region)) +} + /// The body name of the member on each of `lines`: its own name from `pinned` (by line id) when no /// other body has it, else the first free one of `base`, `base (2)`, `base (3)`… that no line has /// pinned. A member therefore keeps its name when other lines are added, deleted or reordered. diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index f592fbe1d99..be9fcb1ca2b 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -30,6 +30,10 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { |h: Value| json!({"type": "hole", "position": o, "direction": [0, 0, 1], "diameter": "hole.diameter", "depth": "hole.depth", "hole": h}); vec![ ("newer_file_feature", json!({"type": "newer_file_feature", "raw": {"type": "gyroid_lattice", "cell": 2}})), + ( + "frame_end_cap", + json!({"type":"frame_end_cap","ends":[{"plane":plane("cap1"),"member":{"feature":7,"line":"l1"}}],"thickness":"cap.thickness","ratio":"cap.ratio","chamfer":"cap.chamfer","direction":"inward"}), + ), ( "body_transfer", json!({"type": "body_transfer", "bodies": ["B"], "from": 0, "to": 1, "transform": [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]}), diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index 94ef147e4bf..03c6bd0c28c 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -1,4 +1,12 @@ newer_file_feature +frame_end_cap + inputs: + Angle = cap1.angle (Angle) + Offset = cap1.offset (Length) + Thickness = cap.thickness (Length) + Inset Ratio = cap.ratio (Unitless) + Corner Chamfer = cap.chamfer (Length) + expressions: cap1.angle, cap1.offset, cap.thickness, cap.ratio, cap.chamfer body_transfer sketch inputs: diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 555ef3bcb84..52bb9cb4d8a 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -1,4 +1,6 @@ newer_file_feature +frame_end_cap + moves: ends[0].plane.axis_dir[0], ends[0].plane.axis_dir[1], ends[0].plane.axis_origin[0], ends[0].plane.axis_origin[1], ends[0].plane.axis_origin[2] body_transfer sketch moves: plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index cc7c9ba356a..a1f8e6a4d06 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -1,4 +1,6 @@ newer_file_feature +frame_end_cap + remap_refs: ends[0].member.feature, ends[0].plane.base.base.feature body_transfer remap_bodies: bodies[0] sketch diff --git a/crates/doc/src/format/pending/frame-end-caps.rs b/crates/doc/src/format/pending/frame-end-caps.rs new file mode 100644 index 00000000000..97e0ff780e2 --- /dev/null +++ b/crates/doc/src/format/pending/frame-end-caps.rs @@ -0,0 +1,4 @@ +//! Designs save frame_end_cap features: the capped end faces as persistent face anchors with +//! their members' feature and line, the thickness, the inset as a length or a ratio of the +//! thickness, the corner chamfer and the direction. Older designs have no end caps and need no +//! migration. The last release refuses this newer format rather than dropping the cap bodies. diff --git a/crates/doc/src/frame.rs b/crates/doc/src/frame.rs index 47b9b02d442..72a84730dfb 100644 --- a/crates/doc/src/frame.rs +++ b/crates/doc/src/frame.rs @@ -366,7 +366,7 @@ fn at_most(what: &str, r: f64, room: f64, why: &str) -> Result<()> { } /// A number for a name: up to four decimals, without trailing zeros. -fn short(x: f64) -> String { +pub(crate) fn short(x: f64) -> String { let t = format!("{x:.4}"); let t = if t.contains('.') { t.trim_end_matches('0').trim_end_matches('.') } else { &t }; if t == "-0" { "0".into() } else { t.to_string() } diff --git a/crates/doc/src/frame_tests.rs b/crates/doc/src/frame_tests.rs index e1a295ea96a..e2b57b9452f 100644 --- a/crates/doc/src/frame_tests.rs +++ b/crates/doc/src/frame_tests.rs @@ -411,3 +411,106 @@ fn a_line_a_hair_off_vertical_is_vertical() { let (_, y) = member_axes(Vec3::new(1e-3, 0.0, 1.0), 0.0).unwrap(); assert!(y.z > 0.0 && y.x < 0.0, "{y:?}"); } + +#[test] +fn end_cap_outlines_inset_and_chamfer_exactly() { + use crate::end_cap::{chamfered, inset}; + // A 40 square with corners of radius 6, in by 3: a 34 square with corners of radius 3. + let tube = Profile::RectTube { width: 40.0, height: 40.0, wall: 3.0, outer_radius: Some(6.0) }.region().unwrap(); + let lp = inset(&tube.outer, 3.0).unwrap(); + close(lp.signed_area(), 34.0 * 34.0 - (4.0 - std::f64::consts::PI) * 9.0, "rounded inset"); + // In by 8, past the rounding: a sharp 24 square. + close(inset(&tube.outer, 8.0).unwrap().signed_area(), 24.0 * 24.0, "sharp inset"); + // Chamfers at least the rounding cut it away; shorter ones are refused. + close(chamfered(&lp, 3.0).unwrap().signed_area(), 34.0 * 34.0 - 4.0 * 4.5, "chamfer"); + assert!(chamfered(&lp, 2.0).is_err()); + assert!(chamfered(&lp, 17.0).is_err()); + let round = Profile::RoundTube { diameter: 40.0, wall: 3.0 }.region().unwrap(); + close(inset(&round.outer, 2.0).unwrap().signed_area(), std::f64::consts::PI * 324.0, "round inset"); + assert!(inset(&round.outer, 20.0).is_err()); + assert!(chamfered(&inset(&round.outer, 2.0).unwrap(), 1.0).is_err()); + // A 40 x 40 x 4 angle in by 1: an L 38 long each way and 2 thick, 38 * 2 + 36 * 2. + let angle = Profile::Angle { width: 40.0, height: 40.0, thickness: 4.0, root_radius: Some(0.0), toe_radius: Some(0.0) }.region().unwrap(); + let l = inset(&angle.outer, 1.0).unwrap(); + close(l.signed_area(), 148.0, "angle inset"); + // Five outside corners lose 0.5 * 0.5 / 2 each; the inside corner stays. A chamfer of 1 eats + // the 2 mm toes whole. + close(chamfered(&l, 0.5).unwrap().signed_area(), 148.0 - 5.0 * 0.125, "angle chamfer"); + assert!(chamfered(&l, 1.0).is_err()); + // Half the leg thickness or more leaves no plate. + assert!(inset(&angle.outer, 2.0).is_err()); + assert!(inset(&angle.outer, 2.5).is_err()); + // A root rounding of 3 grows to 4 and keeps its fillet: 16 - 4 pi more than the sharp L. + let rooted = Profile::Angle { width: 40.0, height: 40.0, thickness: 4.0, root_radius: Some(3.0), toe_radius: Some(0.0) }.region().unwrap(); + close(inset(&rooted.outer, 1.0).unwrap().signed_area(), 148.0 + 16.0 - 4.0 * std::f64::consts::PI, "rooted angle inset"); + // A 100 x 50 I-beam (web 4.5, flanges 7) in by 1: flanges 48 x 5, a web 2.5 x 88. + let beam = Profile::IBeam { height: 100.0, width: 50.0, web: 4.5, flange: 7.0, root_radius: Some(0.0) }.region().unwrap(); + close(inset(&beam.outer, 1.0).unwrap().signed_area(), 2.0 * 48.0 * 5.0 + 2.5 * 88.0, "beam inset"); + assert!(inset(&beam.outer, 2.3).is_err()); + let channel = + Profile::Channel { height: 100.0, width: 50.0, web: 6.0, flange: 8.0, root_radius: Some(5.0), toe_radius: Some(2.0) }.region().unwrap(); + let c = inset(&channel.outer, 1.5).unwrap(); + assert!(chamfered(&c, 3.0).is_err(), "3 + 3 is more than the 5 mm flange tip"); + let cut = chamfered(&c, 2.0).unwrap(); + assert!(cut.signed_area() < c.signed_area() && cut.signed_area() > c.signed_area() - 30.0); + for d in [f64::NAN, f64::INFINITY, -1.0, 1e300] { + let _ = inset(&tube.outer, d).and_then(|l| chamfered(&l, d)); + } +} + +#[test] +fn end_caps_close_open_sections_with_the_outside_of_the_profile() { + use crate::end_cap::cap_outline; + // Closed sections keep their own outline: the rounded tube, the round tube. + let tube = Profile::RectTube { width: 40.0, height: 30.0, wall: 3.0, outer_radius: Some(6.0) }.region().unwrap(); + close(cap_outline(&tube.outer).signed_area(), tube.outer.signed_area(), "rect tube"); + let round = Profile::RoundTube { diameter: 40.0, wall: 3.0 }.region().unwrap(); + close(cap_outline(&round.outer).signed_area(), round.outer.signed_area(), "round tube"); + // Open sections (an L, a C, an I) get the rectangle round them. + let open = [ + (Profile::Angle { width: 40.0, height: 30.0, thickness: 4.0, root_radius: Some(3.0), toe_radius: Some(1.0) }, 40.0 * 30.0), + (Profile::Channel { height: 100.0, width: 50.0, web: 6.0, flange: 8.0, root_radius: Some(5.0), toe_radius: Some(2.0) }, 100.0 * 50.0), + (Profile::IBeam { height: 100.0, width: 50.0, web: 4.5, flange: 7.0, root_radius: Some(4.5) }, 100.0 * 50.0), + ]; + for (p, area) in open { + close(cap_outline(&p.region().unwrap().outer).signed_area(), area, "open section"); + } + // The outside of the profile, rounds and chamfers included: a 40 x 40 extrusion with r 3 + // corners but a 2 x 2 chamfer at the bottom left, and a 6 wide, 5 deep slot in each side, + // gets the rounded, chamfered square with the slots closed: 1600 - 3 r² (1 - π/4) - 2. + use solidcore_record::{Loop2, Seg2, Vec2}; + use std::f64::consts::{FRAC_PI_2, PI}; + let (h, r, w, dp) = (20.0, 3.0, 3.0, 5.0); + let v = Vec2::new; + let line = |a: Vec2, b: Vec2| Seg2::Line { a, b }; + let round = |center: Vec2, start: f64| Seg2::Arc { center, radius: r, start, sweep: FRAC_PI_2 }; + let segs = vec![ + line(v(-h + 2.0, -h), v(-w, -h)), + line(v(-w, -h), v(-w, -h + dp)), + line(v(-w, -h + dp), v(w, -h + dp)), + line(v(w, -h + dp), v(w, -h)), + line(v(w, -h), v(h - r, -h)), + round(v(h - r, -h + r), -FRAC_PI_2), + line(v(h, -h + r), v(h, -w)), + line(v(h, -w), v(h - dp, -w)), + line(v(h - dp, -w), v(h - dp, w)), + line(v(h - dp, w), v(h, w)), + line(v(h, w), v(h, h - r)), + round(v(h - r, h - r), 0.0), + line(v(h - r, h), v(w, h)), + line(v(w, h), v(w, h - dp)), + line(v(w, h - dp), v(-w, h - dp)), + line(v(-w, h - dp), v(-w, h)), + line(v(-w, h), v(-h + r, h)), + round(v(-h + r, h - r), FRAC_PI_2), + line(v(-h, h - r), v(-h, w)), + line(v(-h, w), v(-h + dp, w)), + line(v(-h + dp, w), v(-h + dp, -w)), + line(v(-h + dp, -w), v(-h, -w)), + line(v(-h, -w), v(-h, -h + 2.0)), + line(v(-h, -h + 2.0), v(-h + 2.0, -h)), + ]; + let cap = cap_outline(&Loop2 { segs }); + close(cap.signed_area(), 1600.0 - 3.0 * r * r * (1.0 - PI / 4.0) - 2.0, "slotted extrusion"); + assert_eq!(cap.segs.iter().filter(|s| matches!(s, Seg2::Arc { .. })).count(), 3, "its three rounds are kept"); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d4cb45c6e38..cc8f1a01fca 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -27,6 +27,7 @@ pub mod display_quality; pub mod display_units; mod document; pub mod drawing; +pub mod end_cap; mod eval; pub mod expr; pub mod face_anchor; diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 0c1739943f5..b0825302fe3 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -1233,7 +1233,7 @@ fn replace_body_name(v: &mut Value, old: &str, new: &str, names_body: bool, dept /// A frame member feature's bodies by line id, as its own result made them: what pins each /// member's name to its line. `None` for any other feature, or when they don't pair up. -fn member_pins(s: &Session, fid: u64) -> Option> { +pub(super) fn member_pins(s: &Session, fid: u64) -> Option> { let f = s.doc.feature(fid)?; let result = s.model.result(fid)?; let lines = solidcraft_doc::frame::member_line_ids(&result.state, &f.kind).ok()?; @@ -1440,6 +1440,16 @@ fn rename_body(s: &mut Session, p: &Value) -> Result { } } } + if let FeatureKind::FrameEndCap { ends, .. } = &mut f.kind { + for end in ends { + if let Some(anchor) = super::sketch::face::anchor_mut(&mut end.plane) + && anchor.target.body == old + { + let ids = std::collections::BTreeMap::from([(anchor.target.origin_feature, anchor.target.origin_feature)]); + anchor.remap_target(&ids, &std::collections::BTreeMap::from([(old.clone(), name.to_string())]))?; + } + } + } let Ok(mut v) = serde_json::to_value(&f.kind) else { continue }; if replace_body_name(&mut v, &old, name, false, 0) { match serde_json::from_value(v) { diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index 5a352dac6f2..dc0bbcd0194 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -510,6 +510,20 @@ pub(super) fn build( } anchor.author_path = cloned_path(source, &original.author_path, component, &clone_path, &occurrences)?; } + if let (FeatureKind::FrameEndCap { ends, .. }, FeatureKind::FrameEndCap { ends: originals, .. }) = (&mut f.kind, &old.kind) { + for (end, original) in ends.iter_mut().zip(originals) { + if let (Some(anchor), Some(original)) = + (super::sketch::face::anchor_mut(&mut end.plane), super::sketch::face::anchor(&original.plane)) + { + if bodies.contains_key(&original.target.body) { + anchor.component = + *components.get(&original.component).ok_or_else(|| bad(CMD, "end cap's member is outside the copied graph"))?; + anchor.path = cloned_path(source, &original.path, component, &clone_path, &occurrences)?; + } + anchor.author_path = cloned_path(source, &original.author_path, component, &clone_path, &occurrences)?; + } + } + } if let Some(slot) = scratch.doc_mut().feature_mut(f.id) { *slot = f; } @@ -651,6 +665,23 @@ pub(super) fn build( feature.name, anchor.target.body, anchor.target.origin_feature )); } + // A cap closes the end of a member it does not copy: that member, and the face it was + // picked on, stay outside. + if let FeatureKind::FrameEndCap { ends, .. } = &feature.kind { + for end in ends { + if !features.contains_key(&end.member.feature.0) { + notices.push(format!("{} retains external feature reference {}", feature.name, end.member.feature)); + } + if let Some(anchor) = super::sketch::face::anchor(&end.plane) + && !bodies.contains_key(&anchor.target.body) + { + notices.push(format!( + "{} retains external exact face attachment to {} (producer {})", + feature.name, anchor.target.body, anchor.target.origin_feature + )); + } + } + } for id in feature.kind.input_sketches() { if !features.contains_key(&id) { notices.push(format!("{} retains an external sketch reference to {id}", feature.name)); diff --git a/crates/engine/src/cmd/component_foreign_tests.rs b/crates/engine/src/cmd/component_foreign_tests.rs index 1e989339e0f..99421f8ab0c 100644 --- a/crates/engine/src/cmd/component_foreign_tests.rs +++ b/crates/engine/src/cmd/component_foreign_tests.rs @@ -113,6 +113,35 @@ fn a_component_using_what_is_outside_it_is_refused_saying_what() { assert_eq!(s.doc.to_json(), saved); } +/// An end cap in a component, closing a frame member outside it, uses that member and the face +/// it was picked on: it isn't pasted into another design, which has neither. +#[test] +fn an_end_cap_on_a_member_outside_its_component_is_refused_saying_what() { + let mut source = design("Rack"); + run(&mut source, "sketch.create", json!({"plane": "XY", "name": "Post path"})); + run(&mut source, "sketch.options", json!({"sketch_3d": true})); + run(&mut source, "sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 300]]})); + run(&mut source, "sketch.finish", json!({})); + let tube = json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3, "outer_radius": 0}); + run(&mut source, "frame.member", json!({"sketch": "Post path", "name": "Post member", "body_name": "Post", "profile": tube})); + let (_, at) = created(&mut source, "Caps"); + let index = { + let st = source.model.state(); + let b = st.body("Post").unwrap(); + (0..b.body.face_count()) + .find(|i| b.body.planar_face(*i).is_some_and(|pl| pl.normal().z > 0.999 && (pl.origin.z - 300.0).abs() < 1e-6)) + .unwrap() + }; + run(&mut source, "frame.end_cap", json!({"faces": [{"body": "Post", "index": index, "face": [18.5, 0, 300]}], "thickness": 6})); + + let mut s = design("Frame"); + s.foreign_copy = copied(&source, vec![at]); + let saved = s.doc.to_json(); + let error = s.execute("component.paste_from_design", &json!({})).unwrap_err().to_string(); + assert!(error.contains("uses feature reference") && error.contains("uses exact face attachment to Post"), "{error}"); + assert_eq!(s.doc.to_json(), saved); +} + /// A component that bodies were moved into (a body transfer, as Create Components from Bodies /// makes) pastes into another design, which has none of the components the transfer names. #[test] diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a99cb516b9d..97d92307d79 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1938,6 +1938,7 @@ fn redefine(s: &mut Session, p: &Value) -> Result { | "plastic.lip" | "plastic.snap_fit" | "plastic.rest" + | "frame.end_cap" | "frame.member" ); if !constructor { @@ -1994,6 +1995,11 @@ fn redefine(s: &mut Session, p: &Value) -> Result { let shared = kept.clone().unwrap_or_default(); trial.model.keep(Some(shared.clone())); trial.active_component = old.component; + if let FeatureKind::FrameEndCap { ends, .. } = &old.kind + && let Some(anchor) = ends.first().and_then(|e| super::sketch::face::anchor(&e.plane)) + { + trial.active_occurrence_path = (!anchor.author_path.is_empty()).then(|| anchor.author_path.clone()); + } if let FeatureKind::Emboss { face: Some(face), .. } = &old.kind { trial.active_occurrence_path = (!face.author_path.is_empty()).then(|| face.author_path.clone()); } @@ -2075,8 +2081,34 @@ fn redefine(s: &mut Session, p: &Value) -> Result { if made == s.doc.next_id && trial.doc.next_id == made.saturating_add(1) { trial.doc_mut().next_id = s.doc.next_id; } + // A cap's stored names go by end: each end kept keeps its own (the same member line and the + // same face), a new end has none yet, and a removed end's name is kept back as a renamed + // body's is (#4957), so no other cap is given it and what was set on it stays behind. + let cap_names = match (&old.kind, &new.kind) { + (FeatureKind::FrameEndCap { ends: before, .. }, FeatureKind::FrameEndCap { ends: after, .. }) => { + let key = |e: &solidcraft_doc::end_cap::End| (e.member.clone(), super::sketch::face::anchor(&e.plane).map(|a| a.target.key())); + let names = after + .iter() + .map(|e| before.iter().position(|b| key(b) == key(e)).and_then(|i| old.body_names.get(i)).cloned().unwrap_or_default()) + .collect::>(); + let removed = before + .iter() + .zip(&old.body_names) + .filter(|(b, n)| !n.is_empty() && !after.iter().any(|e| key(e) == key(b))) + .map(|(_, n)| n.clone()) + .collect::>(); + Some((names, removed)) + } + _ => None, + }; + if let Some((_, removed)) = &cap_names { + trial.doc_mut().reserved_body_names.extend(removed.iter().cloned()); + } if let Some(slot) = trial.doc_mut().feature_mut(id) { slot.suppressed = old.suppressed; + if let Some((names, _)) = cap_names { + slot.body_names = names; + } slot.kind = new.kind; slot.edge_refs = new.edge_refs; slot.edge_names = new.edge_names; diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index b474a769ea7..e825d3e7d94 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -703,7 +703,7 @@ pub(super) fn add_feature(s: &mut Session, p: &Value, kind: FeatureKind) -> Resu } /// `add_feature`; `world` is false when `kind` is already in the active component's frame. -fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> Result { +pub(super) fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> Result { let name = str_(p, "name"); // What a join makes of pieces that share no face (`Touching`): separate unless asked. let touching = match p.get("touching") { diff --git a/crates/engine/src/cmd/frame_end_cap.rs b/crates/engine/src/cmd/frame_end_cap.rs new file mode 100644 index 00000000000..6260596180e --- /dev/null +++ b/crates/engine/src/cmd/frame_end_cap.rs @@ -0,0 +1,74 @@ +//! End caps on the open ends of frame members. +use super::{CommandSpec, not_in_sketch}; +use crate::params::bad; +use crate::schema::end_cap::{Direction, EndCapParams}; +use crate::schema::features::FeatureResult; +use crate::schema::{Contract, TypedContract, output_schema_for}; +use crate::{Result, Session}; +use serde_json::{Value, json}; +use solidcraft_doc::{FeatureKind, end_cap}; + +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("frame.end_cap", "End Cap", crate::checked!("frame.end_cap", end_cap_cmd)) + .contract(&CONTRACT) + .output(output_schema_for::) + .at("WELDMENTS", "CREATE") + .icon("end_cap") + .enabled(not_in_sketch) + .params("faces: [{face:[x,y,z],body,index,path?}] planar end faces of frame members, picked in world mm (1–256); thickness: length in design units or a parameter expression; offset?: inset of the plate from the outside of the profile, a length; ratio?: the inset as a share of the thickness (give offset or ratio, not both; neither: the plate is flush with the outside of the profile); chamfer?: corner chamfer length along each edge from the corner (default 0; a rounded corner needs at least its rounding); direction?: outward|inward (default outward: past the end; inward: the member is cut back by the thickness and the cap takes its place). One separate body per face, named ` End Cap`; the plate is the profile's outer outline on a closed section (tube, pipe, bar), its outside on an open one (angle, channel, beam, slotted extrusion): the edges on the rectangle round the profile with their rounds and chamfers, inward stretches closed along the rectangle. Common name/body_names fields supported.")]; + +fn end_cap_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "frame.end_cap"; + let args: EndCapParams = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, e.to_string()))?; + let allowed = CONTRACT.allowed_keys(); + if let Some(key) = p.as_object().and_then(|object| object.keys().find(|key| !allowed.contains(key.as_str()))) { + return Err(bad(cmd, format!("unknown parameter `{key}`"))); + } + if args.faces.is_empty() || args.faces.len() > end_cap::MAX_FACES { + return Err(bad(cmd, format!("pick 1 to {} end faces", end_cap::MAX_FACES))); + } + if args.offset.is_some() && args.ratio.is_some() { + return Err(bad(cmd, "give `offset` or `ratio`, not both")); + } + let mut ends = Vec::with_capacity(args.faces.len()); + for pick in args.faces { + let mut value = json!({"face": pick.face.0, "body": pick.body, "index": pick.index}); + if let Some(path) = pick.path { + value["path"] = json!(path); + } + let plane = super::sketch::face::capture(s, &value, cmd)?; + // Pin each member's name to its line, so the cap finds its member after renames and + // when other lines come and go. + if let Some(anchor) = super::sketch::face::anchor(&plane) + && let Some(pins) = super::browser::member_pins(s, anchor.target.origin_feature) + { + let source = s.doc_mut().feature_mut(anchor.target.origin_feature).ok_or_else(|| bad(cmd, "the member's feature disappeared"))?; + if let FeatureKind::FrameMember { names, .. } = &mut source.kind { + if names.len().saturating_add(pins.keys().filter(|id| !names.contains_key(*id)).count()) > solidcraft_doc::frame::MAX_MEMBERS { + return Err(bad(cmd, "too many member names to pin")); + } + names.extend(pins); + source.body_names.clear(); + } + } + let member = end_cap::member(&s.doc, &s.model.state(), &plane).map_err(|e| bad(cmd, e.to_string()))?; + super::sketch::face::capture_positions(s, &plane)?; + ends.push(end_cap::End { plane, member }); + } + let kind = FeatureKind::FrameEndCap { + ends, + thickness: args.thickness.0, + offset: args.offset.map(|v| v.0), + ratio: args.ratio.map(|r| r.0), + chamfer: args.chamfer.map(|v| v.0).unwrap_or_else(|| "0 mm".into()), + direction: match args.direction { + Direction::Outward => end_cap::Direction::Outward, + Direction::Inward => end_cap::Direction::Inward, + }, + }; + for (label, expr, kind) in kind.inputs() { + super::features::check_expr(s, &expr, kind, cmd, label)?; + } + super::features::add_feature_in(s, p, kind, false) +} diff --git a/crates/engine/src/cmd/frame_tests.rs b/crates/engine/src/cmd/frame_tests.rs index 5559b909351..b5ef21fd94e 100644 --- a/crates/engine/src/cmd/frame_tests.rs +++ b/crates/engine/src/cmd/frame_tests.rs @@ -1,6 +1,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; +use solidcraft_geom::prelude::*; use std::f64::consts::PI; use crate::Session; @@ -638,3 +639,298 @@ fn editing_the_feature_keeps_member_names_until_it_names_them() { run(&mut s, "edit.undo", json!({})); assert_eq!(boxes(&mut s).into_keys().collect::>(), names); } + +/// A 300 mm post up Z from the origin of `profile`, its member body `Post`, made by the feature +/// `Post member` from the 3D sketch `Post path`. +fn capped_post(profile: Value) -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Post path"})); + run(&mut s, "sketch.options", json!({"sketch_3d": true})); + run(&mut s, "sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 300]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "frame.member", json!({"sketch": "Post path", "name": "Post member", "body_name": "Post", "profile": profile})); + s +} + +/// The face of `body` through `point` facing along `normal`, as the view picks it. +fn face_pick(s: &Session, body: &str, point: [f64; 3], normal: [f64; 3]) -> Value { + let st = s.model.state(); + let b = st.body(body).unwrap(); + let at = solidcore_record::Vec3::new(point[0], point[1], point[2]); + let n = solidcore_record::Vec3::new(normal[0], normal[1], normal[2]); + let i = (0..b.body.face_count()) + .find(|i| b.body.planar_face(*i).is_some_and(|pl| pl.normal().dot(n) > 0.999 && (pl.origin - at).dot(n).abs() < 1e-6)) + .unwrap(); + json!({"body": body, "index": i, "face": point}) +} + +fn square_tube() -> Value { + json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3, "outer_radius": 0}) +} + +fn measured(s: &mut Session, name: &str) -> Measured { + bodies(s).into_iter().find(|b| b.0 == name).unwrap_or_else(|| panic!("no body {name}")) +} + +#[test] +fn an_end_cap_is_flush_with_the_outside_unless_offset() { + let mut s = capped_post(square_tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let r = run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 6})); + assert_eq!(r["created_bodies"], json!(["Post End Cap"]), "{r}"); + // No offset: the plate is the profile's outside, 40 x 40, 6 thick, on top. + let cap = measured(&mut s, "Post End Cap"); + assert!(rel(cap.1, 40.0 * 40.0 * 6.0) < 1e-9, "{cap:?}"); + assert!(near3(cap.2, [-20.0, -20.0, 300.0]) && near3(cap.3, [20.0, 20.0, 306.0]), "{cap:?}"); + // The bottom end faces down: its cap hangs below the post. Offset by half its thickness of + // 4: a 36 x 36 plate. + let bottom = face_pick(&s, "Post", [18.5, 0.0, 0.0], [0.0, 0.0, -1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [bottom], "thickness": 4, "ratio": 0.5})); + let cap = measured(&mut s, "Post End Cap (2)"); + assert!(near3(cap.2, [-18.0, -18.0, -4.0]) && near3(cap.3, [18.0, 18.0, 0.0]), "{cap:?}"); +} + +/// A cap made while another is suppressed doesn't take that one's name: restored, each keeps its +/// own, so what refers to the second cap by name still finds it. +#[test] +fn an_end_cap_made_while_another_is_suppressed_keeps_a_name_of_its_own() { + let mut s = capped_post(square_tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let bottom = face_pick(&s, "Post", [18.5, 0.0, 0.0], [0.0, 0.0, -1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 6, "name": "Top cap"})); + run(&mut s, "timeline.suppress", json!({"feature": "Top cap"})); + let r = run(&mut s, "frame.end_cap", json!({"faces": [bottom], "thickness": 4, "name": "Bottom cap"})); + assert_eq!(r["created_bodies"], json!(["Post End Cap (2)"]), "{r}"); + run(&mut s, "timeline.suppress", json!({"feature": "Top cap", "suppressed": false})); + // The top cap on top, the bottom one below the post, each under the name it was made with. + assert!(measured(&mut s, "Post End Cap").2[2] > 299.0); + assert!(measured(&mut s, "Post End Cap (2)").3[2] < 1e-6); +} + +#[test] +fn end_cap_corner_chamfers_cut_each_corner() { + let mut s = capped_post(square_tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 5, "offset": 2, "chamfer": 4})); + // 36 x 36 less four 4 x 4 corner triangles. + let v = measured(&mut s, "Post End Cap").1; + assert!(rel(v, (36.0 * 36.0 - 4.0 * 8.0) * 5.0) < 1e-9, "{v}"); +} + +#[test] +fn end_cap_on_a_rounded_tube_keeps_the_rounding_less_the_inset() { + // Outer radius 6 (twice the wall): inset 3 leaves 34 x 34 with corners of radius 3. + let mut s = capped_post(tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let before = s.doc.to_json(); + let e = s.execute("frame.end_cap", &json!({"faces": [top.clone()], "thickness": 6, "ratio": 0.5, "chamfer": 2})).unwrap_err().to_string(); + assert!(e.contains("at least the corner rounding"), "{e}"); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "frame.end_cap", json!({"faces": [top.clone()], "thickness": 6, "ratio": 0.5})); + let v = measured(&mut s, "Post End Cap").1; + assert!(rel(v, (34.0 * 34.0 - (4.0 - PI) * 9.0) * 6.0) < MEASURED, "{v}"); + run(&mut s, "edit.undo", json!({})); + // A chamfer as long as the rounding cuts it away: four 3 x 3 triangles off the 34 square. + run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 6, "ratio": 0.5, "chamfer": 3})); + let v = measured(&mut s, "Post End Cap").1; + assert!(rel(v, (34.0 * 34.0 - 4.0 * 4.5) * 6.0) < 1e-9, "{v}"); +} + +#[test] +fn an_end_cap_on_an_i_beam_closes_its_whole_end_square() { + // An I-beam is open, so its cap is the 50 x 100 rectangle round it, in by 1: 48 x 98. + let mut s = capped_post(json!({"kind": "i_beam", "height": 100, "width": 50, "web": 4.5, "flange": 7})); + let post = measured(&mut s, "Post"); + let mid = [(post.2[0] + post.3[0]) / 2.0, (post.2[1] + post.3[1]) / 2.0, 300.0]; + let top = face_pick(&s, "Post", mid, [0.0, 0.0, 1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 6, "offset": 1})); + let cap = measured(&mut s, "Post End Cap"); + assert!(rel(cap.1, 48.0 * 98.0 * 6.0) < 1e-9, "{cap:?}"); + // A 2 mm chamfer cuts the rectangle's four corners. + run(&mut s, "edit.undo", json!({})); + let top = face_pick(&s, "Post", mid, [0.0, 0.0, 1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [top.clone()], "thickness": 6, "offset": 1, "chamfer": 2})); + let v = measured(&mut s, "Post End Cap").1; + assert!(rel(v, (48.0 * 98.0 - 4.0 * 2.0) * 6.0) < 1e-9, "{v}"); + // An inset of half the beam's width leaves no plate, and nothing changes. + run(&mut s, "edit.undo", json!({})); + let before = s.doc.to_json(); + let e = s.execute("frame.end_cap", &json!({"faces": [top], "thickness": 6, "offset": 25})).unwrap_err().to_string(); + assert!(e.contains("leaves no plate"), "{e}"); + assert_eq!(s.doc.to_json(), before); +} + +#[test] +fn an_inward_end_cap_cuts_the_member_back() { + let mut s = capped_post(json!({"kind": "round_tube", "diameter": 40, "wall": 3})); + let ring = PI * (400.0 - 289.0); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let r = run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 4, "ratio": 0.5, "direction": "inward"})); + assert_eq!(r["changed_bodies"], json!(["Post"]), "{r}"); + let post = measured(&mut s, "Post"); + assert!(rel(post.1, ring * 296.0) < MEASURED, "{post:?}"); + assert!((post.3[2] - 296.0).abs() < 1e-6, "{post:?}"); + // Radius 20 less an inset of 2, 4 thick, flush with the old end. + let cap = measured(&mut s, "Post End Cap"); + assert!(rel(cap.1, PI * 18.0 * 18.0 * 4.0) < MEASURED, "{cap:?}"); + assert!((cap.2[2] - 296.0).abs() < 1e-6 && (cap.3[2] - 300.0).abs() < 1e-6, "{cap:?}"); +} + +/// The post's body moved into a component placed 50 along Y, capped from the top of the design: +/// the cap is authored in the design's frame, the post is stored in its component's. The inward +/// cut is made where the post is, so it is cut back by the cap's thickness, not missed. +fn a_post_in_a_placed_component() -> Session { + let mut s = capped_post(square_tube()); + let holder = run(&mut s, "component.create", json!({"name": "Holder", "grounded": false}))["component"].as_u64().unwrap(); + run(&mut s, "occurrence.move", json!({"occurrence": "Holder:1", "translate": [0, 50, 0]})); + run(&mut s, "component.activate", json!({"component": 0})); + std::sync::Arc::make_mut(&mut s.doc).body_components.insert("Post".into(), holder); + s.refresh(); + s +} + +#[test] +fn an_inward_end_cap_cuts_a_member_in_a_placed_component_where_it_stands() { + let mut s = a_post_in_a_placed_component(); + let post = measured(&mut s, "Post"); + assert!(near3(post.2, [-20.0, 30.0, 0.0]) && near3(post.3, [20.0, 70.0, 300.0]), "{post:?}"); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let top = json!({"body": top["body"], "index": top["index"], "face": [18.5, 50.0, 300.0]}); + run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 4, "direction": "inward"})); + // 40 x 40 x 3 tube, 296 long after the cut; the cap 40 x 40 x 4 where the end was. + let post = measured(&mut s, "Post"); + assert!(near3(post.2, [-20.0, 30.0, 0.0]) && near3(post.3, [20.0, 70.0, 296.0]), "{post:?}"); + assert!(rel(post.1, (1600.0 - 34.0 * 34.0) * 296.0) < 1e-9, "{post:?}"); + let cap = measured(&mut s, "Post End Cap"); + assert!(near3(cap.2, [-20.0, 30.0, 296.0]) && near3(cap.3, [20.0, 70.0, 300.0]), "{cap:?}"); +} + +/// Moving the occurrence a capped member is placed by rebuilds the cap: the incremental model +/// gives what a model built from scratch does. +#[test] +fn moving_a_capped_members_occurrence_rebuilds_the_cap_as_from_scratch() { + let mut s = a_post_in_a_placed_component(); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let top = json!({"body": top["body"], "index": top["index"], "face": [18.5, 50.0, 300.0]}); + run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 4, "direction": "inward"})); + run(&mut s, "occurrence.move", json!({"occurrence": "Holder:1", "translate": [30, 0, 0]})); + let warm = bodies(&mut s); + let mut cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + let cold = bodies(&mut cold); + assert_eq!(warm.len(), cold.len(), "{warm:?} vs {cold:?}"); + for (w, c) in warm.iter().zip(&cold) { + assert!(w.0 == c.0 && rel(w.1, c.1) < 1e-9 && near3(w.2, c.2) && near3(w.3, c.3), "{w:?} vs {c:?}"); + } +} + +/// Editing a cap down to its second end leaves that cap its own name: the first end's name goes +/// with the end, so what was set on it (a material, a reference) doesn't move to the other cap. +#[test] +fn an_end_cap_edit_that_drops_an_end_keeps_each_remaining_cap_its_name() { + let mut s = capped_post(square_tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let bottom = face_pick(&s, "Post", [18.5, 0.0, 0.0], [0.0, 0.0, -1.0]); + let r = run(&mut s, "frame.end_cap", json!({"faces": [top, bottom.clone()], "thickness": 6, "name": "Caps"})); + assert_eq!(r["created_bodies"], json!(["Post End Cap", "Post End Cap (2)"]), "{r}"); + run(&mut s, "timeline.redefine", json!({"feature": "Caps", "command": "frame.end_cap", "params": {"faces": [bottom], "thickness": 6}})); + let st = s.model.state(); + assert!(st.body("Post End Cap").is_none(), "{:?}", st.bodies.iter().map(|b| &b.name).collect::>()); + drop(st); + assert!(measured(&mut s, "Post End Cap (2)").3[2] < 1e-6, "the bottom cap keeps its name"); +} + +/// Editing a cap from one end onto another: the new end's cap is not given the removed end's +/// name, which stays kept back as a renamed body's is. +#[test] +fn an_end_cap_edit_onto_another_end_does_not_hand_it_the_removed_ends_name() { + let mut s = capped_post(square_tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let bottom = face_pick(&s, "Post", [18.5, 0.0, 0.0], [0.0, 0.0, -1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [top], "thickness": 6, "name": "Cap"})); + run(&mut s, "timeline.redefine", json!({"feature": "Cap", "command": "frame.end_cap", "params": {"faces": [bottom], "thickness": 6}})); + assert!(s.model.state().body("Post End Cap").is_none()); + assert!(measured(&mut s, "Post End Cap (2)").3[2] < 1e-6, "the bottom end's cap has a name of its own"); +} + +/// An end added before one the cap already closes doesn't take that one's name: the kept end's +/// cap keeps it, and the new one is numbered after it. +#[test] +fn an_end_added_before_a_kept_end_leaves_that_cap_its_name() { + let mut s = capped_post(square_tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let bottom = face_pick(&s, "Post", [18.5, 0.0, 0.0], [0.0, 0.0, -1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [bottom.clone()], "thickness": 6, "name": "Cap"})); + run(&mut s, "timeline.redefine", json!({"feature": "Cap", "command": "frame.end_cap", "params": {"faces": [top, bottom], "thickness": 6}})); + assert!(measured(&mut s, "Post End Cap").3[2] < 1e-6, "the bottom cap keeps its name"); + assert!(measured(&mut s, "Post End Cap (2)").2[2] > 299.0, "the new top cap is numbered after it"); +} + +#[test] +fn end_caps_follow_member_edits_renames_undo_and_reopen() { + let mut s = capped_post(square_tube()); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let bottom = face_pick(&s, "Post", [18.5, 0.0, 0.0], [0.0, 0.0, -1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [top, bottom], "thickness": 6, "ratio": 0.5, "name": "Caps"})); + run(&mut s, "body.rename", json!({"body": "Post", "name": "Column"})); + let params = json!({"sketch": "Post path", "body_name": "Column", "profile": {"kind": "rect_tube", "width": 60, "height": 40, "wall": 3, "outer_radius": 0}}); + run(&mut s, "timeline.redefine", json!({"feature": "Post member", "command": "frame.member", "params": params})); + let cap = measured(&mut s, "Post End Cap"); + assert!(rel(cap.1, 54.0 * 34.0 * 6.0) < 1e-9, "{cap:?}"); + assert!(near3(cap.2, [-27.0, -17.0, 300.0]), "{cap:?}"); + assert!(measured(&mut s, "Post End Cap (2)").2[2] < -5.9); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(rel(reopened.model.state().body("Post End Cap").unwrap().mesh().measure().volume, 54.0 * 34.0 * 6.0) < 1e-7); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(s.model.state().body("Post End Cap").is_none()); + run(&mut s, "edit.redo", json!({})); + assert!(rel(measured(&mut s, "Post End Cap").1, 34.0 * 34.0 * 6.0) < 1e-9); +} + +#[test] +fn end_caps_refuse_bad_picks_and_values_atomically() { + let mut s = capped_post(square_tube()); + run(&mut s, "solid.box", json!({"corner": [100, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "Block"})); + let top = face_pick(&s, "Post", [18.5, 0.0, 300.0], [0.0, 0.0, 1.0]); + let side = face_pick(&s, "Post", [20.0, 0.0, 150.0], [1.0, 0.0, 0.0]); + let block = face_pick(&s, "Block", [105.0, 5.0, 10.0], [0.0, 0.0, 1.0]); + // The same end face picked at another point on it is still the same end. + let top_again = face_pick(&s, "Post", [0.0, 18.5, 300.0], [0.0, 0.0, 1.0]); + let good = json!({"faces": [top.clone()], "thickness": 6}); + let cases = [ + (json!({"faces": [side]}), "not an end"), + (json!({"faces": [block]}), "not on a frame member"), + (json!({"faces": [top.clone(), top.clone()]}), "twice"), + (json!({"faces": [top, top_again.clone()]}), "twice"), + (json!({"faces": [top_again.clone(), top_again], "direction": "inward"}), "twice"), + (json!({"faces": []}), ""), + (json!({"offset": 20}), "leaves no plate"), + (json!({"ratio": 4}), "leaves no plate"), + (json!({"offset": 1, "ratio": 0.5}), "not both"), + (json!({"chamfer": 25}), "too large"), + (json!({"thickness": -1}), "thickness"), + (json!({"thickness": "1e99 mm"}), ""), + (json!({"thickness": 0}), "thickness"), + (json!({"ratio": "-1"}), "ratio"), + (json!({"direction": "sideways"}), ""), + (json!({"direction": "inward", "thickness": 300, "offset": 0}), "longer member"), + (json!({"unsupported": true}), ""), + ]; + for (change, why) in cases { + let mut p = good.clone(); + for (k, v) in change.as_object().unwrap() { + p[k] = v.clone(); + } + let before = s.doc.to_json(); + let e = s.execute("frame.end_cap", &p).map(|_| ()).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + assert_eq!(s.doc.to_json(), before, "{p}"); + } + // An angle is open too: its cap is the 40 x 40 square round it, in by 1 (half of 2). + let mut s = capped_post(json!({"kind": "angle", "width": 40, "height": 40, "thickness": 4})); + let end = face_pick(&s, "Post", [-18.0, -19.0, 300.0], [0.0, 0.0, 1.0]); + run(&mut s, "frame.end_cap", json!({"faces": [end], "thickness": 2, "ratio": 0.5})); + let v = measured(&mut s, "Post End Cap").1; + assert!(rel(v, 38.0 * 38.0 * 2.0) < 1e-9, "{v}"); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 25fcf2c8b90..e096e2c8621 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -70,6 +70,7 @@ mod config; mod design_link; mod file; mod frame; +mod frame_end_cap; pub(crate) mod inspect; mod interference; pub(crate) mod joints; @@ -348,6 +349,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(sheet::COMMANDS.iter()); v.extend(plastic::COMMANDS.iter()); v.extend(frame::COMMANDS.iter()); + v.extend(frame_end_cap::COMMANDS.iter()); v.extend(component::COMMANDS.iter()); v.extend(component_link::COMMANDS.iter()); v.extend(joints::COMMANDS.iter()); diff --git a/crates/engine/src/schema/end_cap.rs b/crates/engine/src/schema/end_cap.rs new file mode 100644 index 00000000000..174d15b23a8 --- /dev/null +++ b/crates/engine/src/schema/end_cap.rs @@ -0,0 +1,49 @@ +//! Command contract for frame member end caps. +use super::{FeatureCommon, LengthExpr, NumberExpr, Point3, feature_common}; +use schemars::JsonSchema; +use serde::Deserialize; + +/// A face picked in the view: a world point on it, and the body and face it was picked on. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct FacePick { + pub face: Point3, + pub body: String, + pub index: usize, + #[serde(default)] + #[schemars(length(max = 64))] + pub path: Option>, +} + +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Direction { + /// Past the end: the frame gets longer by the thickness. + #[default] + Outward, + /// Into the member, which is cut back by the thickness. + Inward, +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct EndCapParams { + /// The open end faces to close, each a planar end of a frame member. + #[schemars(length(min = 1, max = 256))] + pub faces: Vec, + pub thickness: LengthExpr, + /// The inset from the profile's outer edge as a length (give this or `ratio`). + #[serde(default)] + pub offset: Option, + /// The inset as a share of the thickness (give this or `offset`; neither: flush with the + /// outside of the profile). + #[serde(default)] + pub ratio: Option, + /// The corner chamfer, along each edge from the corner (default 0: sharp corners). + #[serde(default)] + pub chamfer: Option, + #[serde(default)] + pub direction: Direction, + #[serde(flatten, deserialize_with = "feature_common")] + pub common: FeatureCommon, +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 480e7e6a678..07477152a0e 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -68,6 +68,7 @@ pub mod construct; pub mod delete; pub mod diagnostics; pub mod edit; +pub mod end_cap; pub mod features; pub mod features_more; pub mod file; diff --git a/crates/ui-egui/src/command_help.rs b/crates/ui-egui/src/command_help.rs index 5eef0583a23..0898580b2c0 100644 --- a/crates/ui-egui/src/command_help.rs +++ b/crates/ui-egui/src/command_help.rs @@ -63,6 +63,7 @@ pub const DOCUMENTED: &[&str] = &[ "file.insert_step", "file.save_mesh", "file.send_to_slicer", + "frame.end_cap", "frame.member", "inspect.accessibility", "inspect.center_of_mass", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8c7248634b7..192efda8016 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -416,6 +416,8 @@ crate::dialog_descriptor::dialog_descriptors! { Plastic(crate::dialogs_plastic::Pl), /// Frame members (`dialogs_frame`). Frame(crate::dialogs_frame::Member), + /// End caps on frame members (`dialogs_end_cap`). + EndCap(crate::dialogs_end_cap::EndCap), /// Appearance (`dialogs_appearance`). Appearance(crate::dialogs_appearance::Ap), /// Contact sets, motion studies, exploded views, configurations (`dialogs_motion`). @@ -1133,6 +1135,7 @@ impl Dialog { .or_else(|| crate::view_gizmo::start(app, id)) .or_else(|| crate::dialogs_plastic::start(app, id)) .or_else(|| crate::dialogs_frame::start(app, id)) + .or_else(|| crate::dialogs_end_cap::start(app, id)) .or_else(|| crate::dialogs_appearance::start(app, id)) .or_else(|| crate::dialogs_motion::start(app, id)) .or_else(|| crate::dialogs_parts::start(app, id)) @@ -1379,7 +1382,7 @@ impl Dialog { Kind::Surface(_) => return true, Kind::SketchModify(k) => return k.previews(), Kind::Plastic(k) => return k.previews(), - Kind::Frame(_) => return true, + Kind::Frame(_) | Kind::EndCap(_) => return true, Kind::Part(_) | Kind::PartSize(_) | Kind::InsertDrawing(_) => return true, // Web previews run synchronously; a modelled thread can take seconds. Kind::Thread { .. } => return !cfg!(target_arch = "wasm32") && self.extra.get("modeled").and_then(Value::as_bool).unwrap_or(false), @@ -2629,6 +2632,7 @@ fn title(k: &Kind) -> &'static str { Kind::InsertDrawing(p) => crate::dialogs_insert_drawing::title(p), Kind::Plastic(k) => k.title(), Kind::Frame(_) => "FRAME MEMBER", + Kind::EndCap(_) => "ui.end_cap_title", Kind::Appearance(_) => "APPEARANCE", Kind::Motion(k) => k.title(), Kind::Part(_) => "INSERT PART", @@ -4298,6 +4302,7 @@ fn rememberable(kind: &Kind) -> bool { | crate::dialogs_plastic::Pl::SnapFit { .. }, ) | Kind::Frame(_) + | Kind::EndCap(_) ) } @@ -4351,6 +4356,8 @@ fn recall(app: &SolveApp, dialog: &mut Dialog) { } (Kind::Revolve { axis, .. }, Kind::Revolve { axis: fresh, .. }) => *axis = fresh.clone(), (Kind::PathPlane { sketch, .. }, Kind::PathPlane { sketch: fresh, .. }) => *sketch = *fresh, + // The sizes come back; which ends an edit could not find belonged to that edit. + (Kind::EndCap(c), Kind::EndCap(_)) => c.unresolved.clear(), (Kind::Thread { designation, suggested, of, .. }, Kind::Thread { suggested: fresh_suggested, of: fresh_of, .. }) => { // A remembered auto-suggestion belonged to the old face: the new face gets its own. // An authored designation stays. @@ -6045,6 +6052,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Kind::InsertDrawing(p) => return crate::dialogs_insert_drawing::commands(p), Kind::Plastic(k) => return crate::dialogs_plastic::commands(app, k, &d.inputs, &d.extra), Kind::Frame(k) => return crate::dialogs_frame::commands(app, k, &d.inputs, &d.extra), + Kind::EndCap(k) => return crate::dialogs_end_cap::commands(app, k, &d.inputs, &d.extra), Kind::Appearance(k) => return Ok(crate::dialogs_appearance::commands(k, &d.inputs)), Kind::Motion(k) => return crate::dialogs_motion::commands(app, k, &d.inputs), Kind::Part(k) => return crate::dialogs_parts::commands(app, k, &d.inputs), @@ -7715,6 +7723,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option Option { "Operation" | "Type" | "Orientation" | "Move Type" | "Object Type" | "Rule" | "Rim Edge" | "Catch Direction" | "Shape" | "Holes" | "Size" | "Bend Line Position" | "From Snap" | "To Snap" | "Joint" | "Joint 1" | "Joint 2" | "Gear 1" | "Gear 2" | "Pinion" | "Rack" | "Screw" | "Nut" | "Cam" | "Follower" | "Anchor" => Role::ComboBox, + "Inset By" => Role::ComboBox, "Radius" if command == "joint.rack_pinion" => Role::Label, "Pitch" | "Form" | "Hand" | "Starts" | "Extent" | "Start" | "End" if command == "solid.thread" => Role::ComboBox, "Automatic size" | "Reverse" | "Other side" | "All Lines" | "Mirror" => Role::CheckBox, + "Offset" if command == "frame.end_cap" => Role::CheckBox, "Animate" => Role::Button, "Ratio" if command.starts_with("joint.") && command != "joint.motion_link" => return None, _ => Role::TextInput, @@ -439,6 +467,7 @@ form_case!(revolve, "solid.revolve", ["Angle", "Direction", "Type"]); form_case!(shell, "solid.shell", ["Thickness", "Direction"]); form_case!(draft, "solid.draft", ["Angle"]); form_case!(mirror, "solid.mirror", ["Operation"]); +form_case!(end_cap, "frame.end_cap", ["Thickness", "Direction", "Offset", "Corner Chamfer"]); /// The Motion Study's and Motion Trace's hints read in the user's language: the dialogs drew them /// as they got them, in English. diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index fc232677f7c..46fe1a19ff1 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -82,6 +82,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> { _ => k.simple_metadata().map(|(command, _)| command), }, Kind::Frame(_) => Some("frame.member"), + Kind::EndCap(_) => Some("frame.end_cap"), Kind::Plastic(k) => match k { crate::dialogs_plastic::Pl::SnapFit { .. } => Some("plastic.snap_fit"), crate::dialogs_plastic::Pl::Assign { .. } => Some("plastic.assign_rule"), @@ -1168,6 +1169,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo Kind::Sheet(k) => enter |= crate::dialogs_sheet::rows(app, ui, k, &mut d.inputs), Kind::Plastic(k) => enter |= crate::dialogs_plastic::rows(app, ui, k, &d.inputs), Kind::Frame(k) => enter |= crate::dialogs_frame::rows(app, ui, k, &d.inputs), + Kind::EndCap(k) => enter |= crate::dialogs_end_cap::rows(app, ui, k, &d.inputs), Kind::Assembly(k) => enter |= crate::dialogs_assembly::rows(app, ui, k, &mut d.inputs, &mut d.active), Kind::Measure { result, show, .. } => measure_rows(app, ui, result.as_ref(), show), Kind::Section { offset, flip, hatch } => { diff --git a/crates/ui-egui/src/dialogs_end_cap.rs b/crates/ui-egui/src/dialogs_end_cap.rs new file mode 100644 index 00000000000..4d331f418c8 --- /dev/null +++ b/crates/ui-egui/src/dialogs_end_cap.rs @@ -0,0 +1,161 @@ +//! End caps on frame members: the faces to close and the plate's sizes. The command checks the +//! faces and the plate. +use crate::{ + SolveApp, + dialogs::{Kind, check, shown_expr}, + selection::{PLANAR_FACES, SelInput}, + ui_kit::{IconSegment, choice_row, expr_row, row, segmented_icons}, +}; +use serde_json::{Map, Value, json}; +use solidcraft_engine::{ + Sel, + doc::{FeatureKind, end_cap::Direction, expr::Kind as ValueKind}, +}; + +#[derive(Clone, Debug)] +pub struct EndCap { + pub thickness: String, + /// 0: outward, 1: inward. + pub direction: usize, + /// The plate set in from the profile's outside; off: flush with it. + pub use_offset: bool, + /// 0: the inset as a ratio of the thickness, 1: as a length. + pub inset_kind: usize, + pub ratio: String, + pub offset: String, + pub chamfer: String, + /// Editing: the saved ends (1-based) no face could be found for. The faces start empty then, + /// so OK never drops those ends unasked: what the user picks again is the new set of ends. + pub unresolved: Vec, +} + +impl Default for EndCap { + fn default() -> Self { + Self { + thickness: "6 mm".into(), + direction: 0, + use_offset: false, + inset_kind: 0, + ratio: "0.5".into(), + offset: "3 mm".into(), + chamfer: "0 mm".into(), + unresolved: Vec::new(), + } + } +} + +pub fn start(_: &SolveApp, id: &str) -> Option<(Kind, Vec)> { + (id == "frame.end_cap").then(|| (Kind::EndCap(EndCap::default()), vec![SelInput::new("ui.end_cap.faces", PLANAR_FACES, true)])) +} + +pub fn rows(app: &SolveApp, ui: &mut egui::Ui, c: &mut EndCap, inputs: &[SelInput]) -> bool { + if !c.unresolved.is_empty() && crate::selection::items(inputs, 0).is_empty() { + crate::ui_kit::text(ui, &unresolved(app, c), crate::ui_kit::Text::Hint("end_cap_unresolved")); + } + let mut enter = expr_row(ui, app.tr("ui.thickness"), &mut c.thickness); + // On top of the end, or set into it with the member cut back: the icons show which. + row(ui, app.tr("ui.end_cap.direction"), |ui| { + let options = [ + IconSegment { key: "outward", icon: "end_cap_outward", tip: app.tr("ui.end_cap.outward").to_string() }, + IconSegment { key: "inward", icon: "end_cap_inward", tip: app.tr("ui.end_cap.inward").to_string() }, + ]; + segmented_icons(ui, &mut c.direction, &options, &[]); + }); + // Off: the plate is flush with the outside of the profile. + row(ui, app.tr("ui.offset"), |ui| check(ui, &mut c.use_offset)); + if c.use_offset { + choice_row( + ui, + app.tr("ui.end_cap.inset_kind"), + "end_cap_inset_kind", + &mut c.inset_kind, + &[app.tr("ui.end_cap.ratio"), app.tr("ui.end_cap.length")], + ); + if c.inset_kind == 0 { + enter |= expr_row(ui, app.tr("ui.end_cap.inset_ratio"), &mut c.ratio); + } else { + enter |= expr_row(ui, app.tr("ui.end_cap.inset"), &mut c.offset); + } + } + enter |= expr_row(ui, app.tr("ui.end_cap.chamfer"), &mut c.chamfer); + enter +} + +pub fn commands(app: &SolveApp, c: &EndCap, inputs: &[SelInput], extra: &Map) -> Result, String> { + let faces: Vec = crate::selection::items(inputs, 0) + .iter() + .filter_map(|s| match s { + Sel::Face { body, index, point } => Some(json!({"face": point, "body": body, "index": index})), + _ => None, + }) + .collect(); + if faces.is_empty() { + return Err(if c.unresolved.is_empty() { app.tr("error.end_cap_faces").into() } else { unresolved(app, c) }); + } + let direction = if c.direction == 1 { "inward" } else { "outward" }; + let mut args = json!({"faces": faces, "thickness": c.thickness, "direction": direction, "chamfer": c.chamfer}); + if let Value::Object(args) = &mut args { + // Neither: the plate is flush with the outside of the profile. + if c.use_offset { + let (key, value) = if c.inset_kind == 0 { ("ratio", &c.ratio) } else { ("offset", &c.offset) }; + args.insert(key.into(), json!(value)); + } + for (k, v) in extra { + args.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + Ok(vec![("frame.end_cap".into(), args)]) +} + +pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec, Map)> { + let FeatureKind::FrameEndCap { ends, thickness, offset, ratio, chamfer, direction } = kind else { return None }; + let (_, mut inputs) = start(app, "frame.end_cap")?; + let length = |e: &solidcraft_engine::doc::Expr| shown_expr(e, ValueKind::Length); + let mut c = EndCap { + thickness: length(thickness), + direction: usize::from(*direction == Direction::Inward), + use_offset: offset.is_some() || ratio.is_some(), + inset_kind: usize::from(offset.is_some()), + ratio: ratio.as_ref().map_or_else(|| "0.5".into(), |e| shown_expr(e, ValueKind::Unitless)), + offset: offset.as_ref().map_or_else(|| "3 mm".into(), length), + chamfer: length(chamfer), + ..EndCap::default() + }; + let state = app.session.model.state(); + let world = app.session.world_state().ok(); + let mut items = Vec::new(); + for (k, end) in ends.iter().enumerate() { + let found = items.len(); + if let Some(anchor) = solidcraft_engine::doc::face_anchor::plane_face_anchor(&end.plane) + && let Some(body) = state.body(&anchor.target.body) + { + let name = app.session.doc.world_body_name(&state, &body.name, anchor.component, &anchor.path); + let indices = app.session.doc.configuration_face_indices(body, &anchor.target).ok(); + if let Some(body) = world.as_ref().and_then(|w| w.body(&name)) { + let mesh = body.mesh(); + if let Some((tri, index)) = + mesh.triangles.iter().zip(&mesh.tri_face).find(|(_, i)| indices.as_ref().is_some_and(|is| is.contains(&(**i as usize)))) + && let Some([a, b, c]) = mesh.tri(tri) + { + items.push(Sel::Face { body: name, index: *index as usize, point: (a + b + c) / 3. }); + } + } + } + if items.len() == found { + c.unresolved.push(k + 1); + } + } + // An end not found: the user picks the ends again rather than confirming a shorter list. + if c.unresolved.is_empty() + && let Some(input) = inputs.first_mut() + { + input.items = items; + } + Some((Kind::EndCap(c), inputs, Map::new())) +} + +/// Which saved ends could not be found, and what to do about it. +fn unresolved(app: &SolveApp, c: &EndCap) -> String { + let ends = c.unresolved.iter().map(ToString::to_string).collect::>().join(", "); + app.tr("error.end_cap_unresolved").replace("{ends}", &ends) +} diff --git a/crates/ui-egui/src/dialogs_frame_tests.rs b/crates/ui-egui/src/dialogs_frame_tests.rs index b231ffd55ad..c603cdc932b 100644 --- a/crates/ui-egui/src/dialogs_frame_tests.rs +++ b/crates/ui-egui/src/dialogs_frame_tests.rs @@ -200,3 +200,50 @@ fn picked_lines_stay_in_the_sketch_they_were_picked_in() { d.inputs[0].items.push(Sel::ExternalSketchCurve { sketch: rails, id: ids[0].clone() }); assert!(apply_commands(&app, &d).unwrap_err().contains("one sketch")); } + +/// Editing an end cap shows a face for each saved end. When one cannot be found, the faces start +/// empty and OK names the missing end instead of dropping it unasked; what is picked again is taken, +/// even fewer ends. +#[test] +fn an_end_cap_edit_refuses_to_drop_an_end_it_cannot_find() { + let tube = json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3, "outer_radius": 0}); + let mut app = app_with(&[ + ("sketch.create", json!({"plane": "XY", "name": "Post path"})), + ("sketch.options", json!({"sketch_3d": true})), + ("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 300]]})), + ("sketch.finish", json!({})), + ("frame.member", json!({"sketch": "Post path", "body_name": "Post", "profile": tube})), + ]); + let end = |app: &SolveApp, z: f64| { + let st = app.session.model.state(); + let b = st.body("Post").unwrap(); + let i = (0..b.body.face_count()) + .find(|i| b.body.planar_face(*i).is_some_and(|pl| pl.normal().z.abs() > 0.999 && (pl.origin.z - z).abs() < 1e-6)) + .unwrap(); + Sel::Face { body: "Post".into(), index: i, point: solidcore_record::Vec3::new(18.5, 0.0, z) } + }; + let (top, bottom) = (end(&app, 300.0), end(&app, 0.0)); + let faces: Vec = [&top, &bottom] + .iter() + .map(|s| match s { + Sel::Face { body, index, point } => json!({"body": body, "index": index, "face": point}), + _ => Value::Null, + }) + .collect(); + app.session.execute("frame.end_cap", &json!({"faces": faces, "thickness": 6})).unwrap(); + let kind = app.session.doc.find_feature("EndCap1").unwrap().kind.clone(); + let (crate::dialogs::Kind::EndCap(c), inputs, extra) = crate::dialogs_end_cap::for_feature(&app, &kind).unwrap() else { panic!() }; + assert!(c.unresolved.is_empty() && inputs[0].items.len() == 2, "{c:?}"); + assert!(crate::dialogs_end_cap::commands(&app, &c, &inputs, &extra).is_ok()); + // The second end could not be found: nothing is picked, and OK says which end is missing. + let c = crate::dialogs_end_cap::EndCap { unresolved: vec![2], ..c }; + let mut inputs = inputs; + inputs[0].items.clear(); + let e = crate::dialogs_end_cap::commands(&app, &c, &inputs, &extra).unwrap_err(); + assert!(e.contains('2'), "{e}"); + // Picked again, the remaining end alone is a deliberate choice, as are both. + inputs[0].items = vec![top.clone()]; + assert!(crate::dialogs_end_cap::commands(&app, &c, &inputs, &extra).is_ok()); + inputs[0].items = vec![top, bottom]; + assert!(crate::dialogs_end_cap::commands(&app, &c, &inputs, &extra).is_ok()); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47744e02f8c..d2783383174 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -39,6 +39,7 @@ pub mod dialogs; pub mod dialogs_appearance; pub mod dialogs_assembly; pub mod dialogs_coupling; +pub mod dialogs_end_cap; pub mod dialogs_frame; mod dialogs_hole; pub mod dialogs_insert_drawing; diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index ef3793b6867..da4af1d29f7 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -259,6 +259,7 @@ pub(crate) fn icon_of(k: &FeatureKind) -> &'static str { FeatureKind::Remove { .. } => "delete", FeatureKind::BoundingSolid { .. } => "bounding_solid", FeatureKind::Pipe { .. } => "pipe", + FeatureKind::FrameEndCap { .. } => "end_cap", FeatureKind::FrameMember { .. } => "frame_member", FeatureKind::Emboss { .. } => "emboss", FeatureKind::ReplaceFace { .. } => "replace_face", diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index b183bcb7129..0c4d6b460f6 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -323,7 +323,7 @@ pub const SECTIONS: &[Section] = &[ Section { tab: "SHEET METAL", panel: "CONFIGURE", promoted: 2, ids: CONFIGURE }, // A frame starts from a sketch of its lines; its profile sizes are often parameters. Section { tab: "WELDMENTS", panel: "SKETCH", promoted: 1, ids: &["sketch.create"] }, - Section { tab: "WELDMENTS", panel: "CREATE", promoted: 1, ids: &["frame.member"] }, + Section { tab: "WELDMENTS", panel: "CREATE", promoted: 2, ids: &["frame.member", "frame.end_cap"] }, Section { tab: "WELDMENTS", panel: "CONFIGURE", promoted: 2, ids: CONFIGURE }, ]; @@ -616,7 +616,7 @@ pub fn frame_body(app: &crate::SolveApp) -> Option { let name = active_body(app, &state)?; let body = state.bodies.iter().find(|b| b.name == name)?; let made_by = app.session.doc.feature(body.feature)?; - matches!(made_by.kind, FeatureKind::FrameMember { .. }).then(|| body.name.clone()) + matches!(made_by.kind, FeatureKind::FrameMember { .. } | FeatureKind::FrameEndCap { .. }).then(|| body.name.clone()) } /// The design tabs following the general-purpose tabs in the ribbon. @@ -998,14 +998,14 @@ mod tests { let specs = solidcraft_engine::command_specs(); assert_eq!(panels("WELDMENTS"), ["SKETCH", "CREATE", "CONFIGURE"]); let (create, n) = layout("WELDMENTS", "CREATE", &specs).unwrap(); - assert_eq!(create.iter().take(n).map(|c| c.id).collect::>(), ["frame.member"]); + assert_eq!(create.iter().take(n).map(|c| c.id).collect::>(), ["frame.member", "frame.end_cap"]); assert!(!panel_ids("MODEL", &specs).contains(&"frame.member"), "Frame Member's home is Weldments"); let mut h = crate::scenario::Harness::new(); h.step(&json!({"click":{"handle":"tab:WELDMENTS"}})).unwrap(); h.frames(2); assert_eq!(h.app.ui.tab, "WELDMENTS"); - for id in ["sketch.create", "frame.member", "parameters.change"] { + for id in ["sketch.create", "frame.member", "frame.end_cap", "parameters.change"] { assert!(crate::scenario::handle_at(&format!("button:{id}")).is_some(), "{id} is a button on the Weldments tab"); } h.step(&json!({"click":{"handle":"button:frame.member"}})).unwrap(); diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md index 8ae060be1ea..296b4296838 100644 --- a/docs/book/src/reference/glossary.md +++ b/docs/book/src/reference/glossary.md @@ -225,6 +225,19 @@ A dimension can drive the sketch, or be driven by it and only show the value. - **Elsewhere:** dimension, dimensional constraint, driving dimension. - **For translators:** not a drawing dimension and not a measured value. +### end cap + +A plate that closes the open end of a frame member, shaped like the member profile's outer outline +and set in from its edge. + +An end cap is a separate body named after its member. Compare a mounting plate, which is +rectangular or round and need not follow the profile. + +- **In SolidCraft:** `frame.end_cap`; the `frame_end_cap` design-file key. +- **Don't use:** plug, lid, blank (for the plate). +- **Elsewhere:** end cap, end plate, cap plate. +- **For translators:** a closing plate on a tube's end, not a cap of a sketch or surface. + ### equation curve A sketch curve whose shape comes from formulas over a range of one variable. diff --git a/docs/frames.md b/docs/frames.md index f0655e6d992..4f0607f5d1a 100644 --- a/docs/frames.md +++ b/docs/frames.md @@ -2,7 +2,7 @@ Frames and weldments (#4003) are structural members (tube, angle, channel, beam, an aluminium extrusion of your own) laid along the lines of a frame sketch. This page covers what has landed: -members and their profiles. Corners, trims, end caps, gussets, welds and the cut list follow. +members and their profiles, and end caps. Corners, trims, gussets, welds and the cut list follow. ## The workflow @@ -24,7 +24,7 @@ members and their profiles. Corners, trims, end caps, gussets, welds and the cut Members are ordinary bodies: mirror, pattern, move, drill and combine them with the usual commands. Where members meet they overlap until corner treatments land. -The **Weldments** ribbon tab gathers the frame commands: New Sketch, Frame Member and +The **Weldments** ribbon tab gathers the frame commands: New Sketch, Frame Member, End Cap and Parameters. Like Sheet Metal it is always there, and it selects itself when a frame member is the selected body (or the last body of the active component). @@ -74,6 +74,43 @@ Every built-in profile is SolidCraft's own parametric definition, built in code dimensions of the stock you buy. Any other section, a vendor's aluminium extrusion for example, comes from a sketch: draw it or insert the vendor's DXF. +## End caps + +**End Cap** (WELDMENTS › CREATE, `frame.end_cap`) closes open ends of members with plates, one +separate body per end, named after the member (`Post End Cap`). Pick the end faces in the view: +each must be a flat end of a frame member, square to its line. + +- The plate covers the outside of the profile: on a closed section (a square or rectangular + tube, a pipe, a bar) it is the profile's outer outline; on an open section (an angle, a + channel, a beam, an extrusion with slots) it is the profile's outside edges with their rounds + and chamfers, and each inward stretch (a slot, between flanges) is closed straight across + along the rectangle round the profile, so the whole end is closed. +- **Offset** sets the plate in from that outside edge: tick it, then give the inset as a + **Ratio of thickness** (0.5 puts a 6 mm cap 3 mm in from the edge) or a **Length**. Unticked, + the plate is flush with the outside of the profile. A rounded corner keeps its rounding less + the inset; a corner rounded less than the inset becomes sharp. +- **Thickness** is the plate's thickness. **Outward** puts it past the end, so the frame gets + longer by the thickness; **Inward** cuts the member back by the thickness and puts the plate + where the end was, so the frame keeps its length. +- **Corner Chamfer** cuts each outside corner along both edges, measured from where the edges meet. On a + rounded corner it must be at least the rounding, which it cuts away; a round cap has no corners + to chamfer. +- Caps follow the member: change its profile, its line or the frame sketch and they move and + resize with it. Renaming the member keeps them. A cap whose member or face is gone reports an + error instead of picking another end. +- Caps follow any outline of lines and arcs. On an open section the chamfer cuts the + plate's outside corners. An inset that leaves no plate is refused, as is a chamfer longer than its + edges allow. + +```json +{"command": "frame.end_cap", "params": {"faces": [{"face": [18.5, 0, 300], "body": "Post", "index": 7}], "thickness": 6}} +{"command": "frame.end_cap", "params": {"faces": [{"face": [18.5, 0, 0], "body": "Post", "index": 6}], "thickness": "cap_t", "offset": 2, "chamfer": 4, "direction": "inward"}} +``` + +`faces` are picks as the view makes them: a world point on the face, its body and face index +(`path` for a face in another occurrence). Give the inset as `offset` (a length) or `ratio`, not +both. **Edit Feature** reopens the dialog with the faces and values. + ## Built-in profiles A profile is JSON with a `kind` and its dimensions, each a number in the design's units or a diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index 04508618966..72042db43a0 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -83,6 +83,7 @@ file.save_as saving the design file.save_mesh saving a display mesh file.send_to_slicer hands the file to a slicer file.slicers a listing of slicers +frame.end_cap plates on member ends; tested in crates/engine/src/cmd/frame_tests.rs frame.profile.list a listing of the profile library frame.profile.properties a profile's section properties from the library inspect.accessibility display analysis: shading From 57075d31d37d3316141cb589ee3ea7c36f6c16ce Mon Sep 17 00:00:00 2001 From: Karl Von Richter Date: Tue, 10 Nov 2026 15:08:02 +1000 Subject: [PATCH 2/2] ui(test): use shared text lookup in dialog assertions Use solidcraft_ui_text::tr_label for selection-picker accessibility labels, matching the dialog renderer after the translation API moved out of ui-egui. This fixes the End Cap merge-queue build against current main while preserving both message IDs and legacy English labels. Signed-off-by: Karl Von Richter --- crates/ui-egui/src/dialogs_all_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index f571c73c110..abc7dfe3d53 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -363,7 +363,7 @@ fn check_form(command: &str, labels: &[&str]) { for input in &d.inputs { assert!(scenario::rect_of(&format!("dialog:field:{}", input.label)).is_some(), "{command}: selection field {}", input.label); assert!( - nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::Button && n.label() == Some(crate::i18n::tr(input.label))), + nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::Button && n.label() == Some(solidcraft_ui_text::tr_label(input.label))), "{command}: picker {} is a button", input.label );