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 @@
+
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 @@
+
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 @@
+
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