Skip to content

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

Surface trim: projected curves, several kept regions, mutual trim (#767) (#1466)

Irakli Kourtis1cd9983c8fc5
diff --git a/ROADMAP.md b/ROADMAP.md
index 471240bb77..fc02e7f623 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -57,7 +57,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings.
| M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 |
| M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 |
| M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 |
-| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), loft guide rails (#201; sweep guide rails and two-rail sweeps are done, #771), and every remaining #757–#772 item | deferred | — |
+| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), loft guide rails (#201; sweep guide rails and two-rail sweeps are done, #771), and every remaining #757–#772 item | deferred | — |
| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 |
| M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 |
| M11 | 2D drawings | deferred | — |
diff --git a/assets/locales/cs.json b/assets/locales/cs.json
index 9df1715f95..e70007ab6d 100644
--- a/assets/locales/cs.json
+++ b/assets/locales/cs.json
@@ -98,6 +98,7 @@
"Export Current View as DXF…": "Exportovat aktuální pohled do DXF…",
"Export DXF…": "Exportovat DXF…",
"Export hidden edges as dashed lines": "Exportovat skryté hrany čárkovaně",
+ "Extend to meet": "Prodloužit k protnutí",
"Extents": "Rozsahy",
"Face": "Plocha",
"Face attachment lost": "Připojení k ploše ztraceno",
@@ -126,7 +127,9 @@
"Interferes": "Koliduje",
"Issue title": "Název hlášení",
"Joint Origin1": "Počátek kloubu1",
+ "Keep (points on it)": "Ponechat (body na ní)",
"Keep Tools": "Ponechat nástroje",
+ "Keep of the other surface": "Ponechat z druhé plochy",
"Later": "Později",
"Leave it": "Nechat být",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Starší typ připojení k ploše. Novým navázáním na ověřenou plochu vznikne přesné připojení.",
@@ -162,6 +165,7 @@
"Open GitHub draft": "Otevřít koncept na GitHubu",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametrický 3D CAD v jazyce Rust. Licence MIT OR Apache-2.0.",
"Other side": "Druhá strana",
+ "Other surface (mutual trim)": "Druhá plocha (vzájemné oříznutí)",
"Outside": "Vně",
"Overall length": "Celková délka",
"Parameter values": "Hodnoty parametrů",
@@ -245,9 +249,12 @@
"Stand this part up?": "Postavit tento díl?",
"Step": "Krok",
"Steps": "Kroky",
+ "Stitch the kept pieces": "Sešít ponechané části",
"Style": "Styl",
"Suppressed": "Potlačeno",
+ "Surface": "Plocha",
"Swap Ends": "Prohodit konce",
+ "TRIM": "OŘÍZNOUT",
"Tangent (G1)": "Tečně (G1)",
"Tangent Chain": "Tečný řetězec",
"Tear": "Roztržení",
@@ -264,6 +271,7 @@
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Tato plocha nemůže poskytnout trvalé připojení. Zvolte jinou plochu nebo výslovně použijte pevnou rovinu.",
"To Offset": "Odsazení k objektu",
"Tolerance": "Tolerance",
+ "Trimming tool (plane, face or curves)": "Ořezávací nástroj (rovina, plocha nebo křivky)",
"Turn off section analysis before exporting the view.": "Před exportem pohledu vypněte analýzu řezu.",
"Type": "Typ",
"UNTRIM": "ZRUŠIT OŘEZ",
diff --git a/assets/locales/de.json b/assets/locales/de.json
index 78bbe8d255..4f2e2f2bf1 100644
--- a/assets/locales/de.json
+++ b/assets/locales/de.json
@@ -39,6 +39,7 @@
"Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…",
"Export DXF…": "DXF exportieren…",
"Export hidden edges as dashed lines": "Verdeckte Kanten gestrichelt exportieren",
+ "Extend to meet": "Verlängern, bis sie sich treffen",
"Face": "Fläche",
"Faces": "Flächen",
"Find in Browser": "Im Browser suchen",
@@ -49,6 +50,8 @@
"In place (surfaces)": "An Ort und Stelle (Flächen)",
"In plane": "In der Ebene",
"Inside": "Innen",
+ "Keep (points on it)": "Behalten (Punkte darauf)",
+ "Keep of the other surface": "Vom anderen Flächenkörper behalten",
"Length": "Länge",
"Max": "Max",
"Min": "Min",
@@ -58,6 +61,7 @@
"None": "Keine",
"Normal to sketch": "Normal zur Skizze",
"Notch": "Ausklinkung",
+ "Other surface (mutual trim)": "Anderer Flächenkörper (gegenseitig trimmen)",
"Outside": "Außen",
"Overall length": "Gesamtlänge",
"Pass through": "Durch Punkte",
@@ -87,12 +91,16 @@
"Sketch geometry and profiles": "Skizzengeometrie und Profile",
"Sketch points": "Skizzenpunkte",
"Slot width": "Langlochbreite",
+ "Stitch the kept pieces": "Behaltene Teile vernähen",
"Study": "Untersuchung",
+ "Surface": "Flächenkörper",
+ "TRIM": "TRIMMEN",
"Tangent (G1)": "Tangente (G1)",
"Tear": "Reißen",
"Thickness Outside": "Dicke außen",
"Thin": "Dünnwandig",
"Thin Extrude": "Dünnwandig extrudieren",
+ "Trimming tool (plane, face or curves)": "Trimmwerkzeug (Ebene, Fläche oder Kurven)",
"Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.",
"Type": "Typ",
"UNTRIM": "TRIMMEN AUFHEBEN",
diff --git a/assets/locales/en.json b/assets/locales/en.json
index d3c74c2b04..708ac23f06 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -107,6 +107,7 @@
"Export Current View as DXF…": "Export Current View as DXF…",
"Export DXF…": "Export DXF…",
"Export hidden edges as dashed lines": "Export hidden edges as dashed lines",
+ "Extend to meet": "Extend to meet",
"Extents": "Extents",
"Face": "Face",
"Face attachment lost": "Face attachment lost",
@@ -135,7 +136,9 @@
"Interferes": "Interferes",
"Issue title": "Issue title",
"Joint Origin1": "Joint Origin1",
+ "Keep (points on it)": "Keep (points on it)",
"Keep Tools": "Keep Tools",
+ "Keep of the other surface": "Keep of the other surface",
"Later": "Later",
"Leave it": "Leave it",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Legacy face attachment. Rebinding to a certified face creates an exact attachment.",
@@ -173,6 +176,7 @@
"Open GitHub draft": "Open GitHub draft",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.",
"Other side": "Other side",
+ "Other surface (mutual trim)": "Other surface (mutual trim)",
"Outside": "Outside",
"Overall length": "Overall length",
"Parameter values": "Parameter values",
@@ -260,10 +264,13 @@
"Stand this part up?": "Stand this part up?",
"Step": "Step",
"Steps": "Steps",
+ "Stitch the kept pieces": "Stitch the kept pieces",
"Study": "Study",
"Style": "Style",
"Suppressed": "Suppressed",
+ "Surface": "Surface",
"Swap Ends": "Swap Ends",
+ "TRIM": "TRIM",
"Tangent (G1)": "Tangent (G1)",
"Tangent Chain": "Tangent Chain",
"Tear": "Tear",
@@ -281,6 +288,7 @@
"To Offset": "To Offset",
"Tolerance": "Tolerance",
"Too close": "Too close",
+ "Trimming tool (plane, face or curves)": "Trimming tool (plane, face or curves)",
"Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.",
"Type": "Type",
"UNTRIM": "UNTRIM",
diff --git a/assets/locales/es.json b/assets/locales/es.json
index 1750c89665..a8939d7e29 100644
--- a/assets/locales/es.json
+++ b/assets/locales/es.json
@@ -105,6 +105,7 @@
"Export Current View as DXF…": "Exportar vista actual como DXF…",
"Export DXF…": "Exportar DXF…",
"Export hidden edges as dashed lines": "Exportar aristas ocultas como líneas discontinuas",
+ "Extend to meet": "Extender hasta encontrarla",
"Extents": "Extensión",
"Face": "Cara",
"Face attachment lost": "Se ha perdido la vinculación de la cara",
@@ -133,7 +134,9 @@
"Interferes": "Interfiere",
"Issue title": "Título de la incidencia",
"Joint Origin1": "Origen de unión1",
+ "Keep (points on it)": "Conservar (puntos sobre ella)",
"Keep Tools": "Conservar herramientas",
+ "Keep of the other surface": "Conservar de la otra superficie",
"Later": "Más tarde",
"Leave it": "Dejar como está",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Vinculación antigua de cara. Volver a vincularla a una cara verificada crea una vinculación exacta.",
@@ -171,6 +174,7 @@
"Open GitHub draft": "Abrir borrador de GitHub",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código abierto desarrollado en Rust. Licencia MIT O Apache-2.0.",
"Other side": "Lado opuesto",
+ "Other surface (mutual trim)": "Otra superficie (recorte mutuo)",
"Outside": "Exterior",
"Overall length": "Longitud total",
"Parameter values": "Valores de parámetros",
@@ -258,10 +262,13 @@
"Stand this part up?": "¿Poner esta pieza en vertical?",
"Step": "Paso",
"Steps": "Pasos",
+ "Stitch the kept pieces": "Coser las piezas conservadas",
"Study": "Estudio",
"Style": "Estilo",
"Suppressed": "Suprimido",
+ "Surface": "Superficie",
"Swap Ends": "Intercambiar extremos",
+ "TRIM": "RECORTAR",
"Tangent (G1)": "Tangencia (G1)",
"Tangent Chain": "Cadena tangente",
"Tear": "Desgarro",
@@ -279,6 +286,7 @@
"To Offset": "Hasta desfase",
"Tolerance": "Tolerancia",
"Too close": "Demasiado cerca",
+ "Trimming tool (plane, face or curves)": "Herramienta de recorte (plano, cara o curvas)",
"Turn off section analysis before exporting the view.": "Desactiva el análisis de sección antes de exportar la vista.",
"Type": "Tipo",
"UNTRIM": "ANULAR RECORTE",
diff --git a/assets/locales/fr.json b/assets/locales/fr.json
index 276e9dc21a..6e2feab66e 100644
--- a/assets/locales/fr.json
+++ b/assets/locales/fr.json
@@ -105,6 +105,7 @@
"Export Current View as DXF…": "Exporter la vue actuelle en DXF…",
"Export DXF…": "Exporter en DXF…",
"Export hidden edges as dashed lines": "Exporter les arêtes cachées en tirets",
+ "Extend to meet": "Prolonger jusqu'à la rencontre",
"Extents": "Étendues",
"Face": "Face",
"Face attachment lost": "Rattachement à la face perdu",
@@ -133,7 +134,9 @@
"Interferes": "Interfère",
"Issue title": "Titre du ticket",
"Joint Origin1": "Origine de liaison1",
+ "Keep (points on it)": "À conserver (points dessus)",
"Keep Tools": "Conserver les outils",
+ "Keep of the other surface": "À conserver de l'autre surface",
"Later": "Plus tard",
"Leave it": "Laisser tel quel",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Rattachement à la face hérité. Le relier à une face certifiée crée un rattachement exact.",
@@ -171,6 +174,7 @@
"Open GitHub draft": "Ouvrir le brouillon GitHub",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAO 3D paramétrique open source en Rust. Sous licence MIT OR Apache-2.0.",
"Other side": "Autre côté",
+ "Other surface (mutual trim)": "Autre surface (ajustement mutuel)",
"Outside": "Extérieur",
"Overall length": "Longueur hors tout",
"Parameter values": "Valeurs des paramètres",
@@ -258,10 +262,13 @@
"Stand this part up?": "Redresser cette pièce ?",
"Step": "Étape",
"Steps": "Étapes",
+ "Stitch the kept pieces": "Coudre les parties conservées",
"Study": "Étude",
"Style": "Style",
"Suppressed": "Désactivé",
+ "Surface": "Surface",
"Swap Ends": "Permuter les extrémités",
+ "TRIM": "AJUSTER",
"Tangent (G1)": "Tangence (G1)",
"Tangent Chain": "Chaîne tangente",
"Tear": "Déchirure",
@@ -279,6 +286,7 @@
"To Offset": "Jusqu'au décalage",
"Tolerance": "Tolérance",
"Too close": "Trop proches",
+ "Trimming tool (plane, face or curves)": "Outil d'ajustement (plan, face ou courbes)",
"Turn off section analysis before exporting the view.": "Désactivez l'analyse de coupe avant d'exporter la vue.",
"Type": "Type",
"UNTRIM": "ANNULER L'AJUSTEMENT",
diff --git a/assets/locales/gl.json b/assets/locales/gl.json
index d7a2196608..b0960fee8e 100644
--- a/assets/locales/gl.json
+++ b/assets/locales/gl.json
@@ -98,6 +98,7 @@
"Export Current View as DXF…": "Exportar a vista actual como DXF…",
"Export DXF…": "Exportar DXF…",
"Export hidden edges as dashed lines": "Exportar as arestas ocultas como liñas descontinuas",
+ "Extend to meet": "Estender ata atopala",
"Extents": "Extensións",
"Face": "Cara",
"Face attachment lost": "Perdeuse a ancoraxe á cara",
@@ -126,7 +127,9 @@
"Interferes": "Interfire",
"Issue title": "Título da incidencia",
"Joint Origin1": "Orixe da unión1",
+ "Keep (points on it)": "Manter (puntos sobre ela)",
"Keep Tools": "Manter as ferramentas",
+ "Keep of the other surface": "Manter da outra superficie",
"Later": "Máis tarde",
"Leave it": "Deixalo",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Ancoraxe á cara antiga. Volver vincular a unha cara certificada crea unha ancoraxe exacta.",
@@ -162,6 +165,7 @@
"Open GitHub draft": "Abrir o borrador de GitHub",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto en Rust. Con licenza MIT OR Apache-2.0.",
"Other side": "Outro lado",
+ "Other surface (mutual trim)": "Outra superficie (recorte mutuo)",
"Outside": "Fóra",
"Overall length": "Lonxitude total",
"Parameter values": "Valores dos parámetros",
@@ -245,9 +249,12 @@
"Stand this part up?": "Poñer esta peza de pé?",
"Step": "Paso",
"Steps": "Pasos",
+ "Stitch the kept pieces": "Coser as pezas mantidas",
"Style": "Estilo",
"Suppressed": "Suprimida",
+ "Surface": "Superficie",
"Swap Ends": "Intercambiar os extremos",
+ "TRIM": "RECORTAR",
"Tangent (G1)": "Tanxente (G1)",
"Tangent Chain": "Cadea tanxente",
"Tear": "Rasgado",
@@ -264,6 +271,7 @@
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta cara non pode ofrecer unha ancoraxe duradeira. Escolle outra cara ou usa expresamente un plano fixo.",
"To Offset": "Ata o desprazamento",
"Tolerance": "Tolerancia",
+ "Trimming tool (plane, face or curves)": "Ferramenta de recorte (plano, cara ou curvas)",
"Turn off section analysis before exporting the view.": "Desactiva a análise de sección antes de exportar a vista.",
"Type": "Tipo",
"UNTRIM": "DESRECORTAR",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index a1c8c9f4a3..eeb2011c9f 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -107,6 +107,7 @@
"Export Current View as DXF…": "現在の表示をDXFでエクスポート…",
"Export DXF…": "DXFをエクスポート…",
"Export hidden edges as dashed lines": "点線で出力",
+ "Extend to meet": "交わるまで延長",
"Extents": "範囲",
"Face": "面",
"Face attachment lost": "面アタッチメントが失われました",
@@ -135,7 +136,9 @@
"Interferes": "干渉あり",
"Issue title": "Issueタイトル",
"Joint Origin1": "ジョイント原点1",
+ "Keep (points on it)": "残す部分(その上の点)",
"Keep Tools": "ツールボディを保持",
+ "Keep of the other surface": "相手のサーフェスで残す部分",
"Later": "後で",
"Leave it": "そのままにする",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "従来の面アタッチメントです。確定された面に再バインドすると正確なアタッチメントが作成されます。",
@@ -173,6 +176,7 @@
"Open GitHub draft": "GitHubの下書きを開く",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust製オープンソース・パラメトリック3D CAD。ライセンス: MIT または Apache-2.0。",
"Other side": "反対側",
+ "Other surface (mutual trim)": "相手のサーフェス(相互トリム)",
"Outside": "外側",
"Overall length": "全長",
"Parameter values": "パラメータ値",
@@ -260,10 +264,13 @@
"Stand this part up?": "このパーツを正立させますか?",
"Step": "ステップ",
"Steps": "ステップ数",
+ "Stitch the kept pieces": "残した部分をステッチ",
"Study": "スタディ",
"Style": "スタイル",
"Suppressed": "抑制",
+ "Surface": "サーフェス",
"Swap Ends": "端点を入れ替え",
+ "TRIM": "トリム",
"Tangent (G1)": "接線 (G1)",
"Tangent Chain": "正接チェーン",
"Tear": "引き裂き",
@@ -281,6 +288,7 @@
"To Offset": "オフセットまで",
"Tolerance": "公差",
"Too close": "近すぎる",
+ "Trimming tool (plane, face or curves)": "トリムツール(平面、面、または曲線)",
"Turn off section analysis before exporting the view.": "断面解析をオフにしてからエクスポートしてください。",
"Type": "タイプ",
"UNTRIM": "トリム解除",
diff --git a/assets/locales/ko.json b/assets/locales/ko.json
index e4a4fbef48..ba118b7989 100644
--- a/assets/locales/ko.json
+++ b/assets/locales/ko.json
@@ -39,6 +39,7 @@
"Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…",
"Export DXF…": "DXF 내보내기…",
"Export hidden edges as dashed lines": "숨겨진 모서리를 파선으로 내보내기",
+ "Extend to meet": "만날 때까지 연장",
"Face": "면",
"Faces": "면",
"Find in Browser": "브라우저에서 찾기",
@@ -49,6 +50,8 @@
"In place (surfaces)": "제자리에서 (서피스)",
"In plane": "평면 내",
"Inside": "안쪽",
+ "Keep (points on it)": "유지할 부분(그 위의 점)",
+ "Keep of the other surface": "다른 곡면에서 유지할 부분",
"Length": "길이",
"Max": "최대",
"Min": "최소",
@@ -58,6 +61,7 @@
"None": "없음",
"Normal to sketch": "스케치에 수직",
"Notch": "노치",
+ "Other surface (mutual trim)": "다른 곡면(상호 트림)",
"Outside": "바깥쪽",
"Overall length": "전체 길이",
"Pass through": "통과점",
@@ -87,12 +91,16 @@
"Sketch geometry and profiles": "스케치 기하 및 프로파일",
"Sketch points": "스케치 점",
"Slot width": "슬롯 폭",
+ "Stitch the kept pieces": "유지한 부분 재봉",
"Study": "연구",
+ "Surface": "곡면",
+ "TRIM": "트림",
"Tangent (G1)": "접선 (G1)",
"Tear": "찢김",
"Thickness Outside": "바깥쪽 두께",
"Thin": "얇은 벽",
"Thin Extrude": "얇은 벽 돌출",
+ "Trimming tool (plane, face or curves)": "트림 도구(평면, 면 또는 곡선)",
"Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.",
"Type": "유형",
"UNTRIM": "트림 해제",
diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json
index da4c5c4e5e..4e33285500 100644
--- a/assets/locales/pt-BR.json
+++ b/assets/locales/pt-BR.json
@@ -98,6 +98,7 @@
"Export Current View as DXF…": "Exportar vista atual como DXF…",
"Export DXF…": "Exportar DXF…",
"Export hidden edges as dashed lines": "Exportar arestas ocultas como linhas tracejadas",
+ "Extend to meet": "Estender até encontrar",
"Extents": "Extensões",
"Face": "Face",
"Face attachment lost": "Fixação à face perdida",
@@ -126,7 +127,9 @@
"Interferes": "Interfere",
"Issue title": "Título da issue",
"Joint Origin1": "Origem da junta1",
+ "Keep (points on it)": "Manter (pontos sobre ela)",
"Keep Tools": "Manter ferramentas",
+ "Keep of the other surface": "Manter da outra superfície",
"Later": "Depois",
"Leave it": "Deixar assim",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Fixação de face antiga. Vincular novamente a uma face certificada cria uma fixação exata.",
@@ -162,6 +165,7 @@
"Open GitHub draft": "Abrir rascunho no GitHub",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto em Rust. Licenciado sob MIT OU Apache-2.0.",
"Other side": "Outro lado",
+ "Other surface (mutual trim)": "Outra superfície (aparo mútuo)",
"Outside": "Fora",
"Overall length": "Comprimento total",
"Parameter values": "Valores dos parâmetros",
@@ -245,9 +249,12 @@
"Stand this part up?": "Colocar esta peça em pé?",
"Step": "Passo",
"Steps": "Passos",
+ "Stitch the kept pieces": "Costurar as partes mantidas",
"Style": "Estilo",
"Suppressed": "Suprimido",
+ "Surface": "Superfície",
"Swap Ends": "Trocar extremidades",
+ "TRIM": "APARAR",
"Tangent (G1)": "Tangente (G1)",
"Tangent Chain": "Cadeia tangente",
"Tear": "Rasgo",
@@ -264,6 +271,7 @@
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta face não pode fornecer uma fixação duradoura. Escolha outra face ou use explicitamente um plano fixo.",
"To Offset": "Deslocamento final",
"Tolerance": "Tolerância",
+ "Trimming tool (plane, face or curves)": "Ferramenta de aparo (plano, face ou curvas)",
"Turn off section analysis before exporting the view.": "Desative a análise de seção antes de exportar a vista.",
"Type": "Tipo",
"UNTRIM": "DESAPARAR",
diff --git a/assets/locales/ru.json b/assets/locales/ru.json
index bcfadce6ee..7cc15552eb 100644
--- a/assets/locales/ru.json
+++ b/assets/locales/ru.json
@@ -88,6 +88,7 @@
"Enabled": "Включено",
"Explode": "Разобрать",
"Export Animation…": "Экспортировать анимацию…",
+ "Extend to meet": "Продлить до пересечения",
"Extents": "Пределы",
"Face attachment lost": "Привязка к грани потеряна",
"Faces": "Грани",
@@ -110,7 +111,9 @@
"Interferes": "Пересекается",
"Issue title": "Заголовок Issue",
"Joint Origin1": "Точка сопряжения1",
+ "Keep (points on it)": "Оставить (точки на нём)",
"Keep Tools": "Оставить инструменты",
+ "Keep of the other surface": "Оставить от другой поверхности",
"Later": "Позже",
"Leave it": "Оставить как есть",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Устаревшая привязка к грани. Перепривязка к сертифицированной грани создаёт точную привязку.",
@@ -142,6 +145,7 @@
"Open GitHub draft": "Открыть черновик на GitHub",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Открытая параметрическая 3D CAD на Rust. Лицензия MIT OR Apache-2.0.",
"Other side": "Другая сторона",
+ "Other surface (mutual trim)": "Другая поверхность (взаимная обрезка)",
"Parameter values": "Значения параметров",
"Pass through": "Через точки",
"Path": "Траектория",
@@ -218,10 +222,13 @@
"Stand this part up?": "Поставить эту деталь вертикально?",
"Step": "Шаг",
"Steps": "Шаги",
+ "Stitch the kept pieces": "Сшить оставленные части",
"Study": "Исследование",
"Style": "Стиль",
"Suppressed": "Подавлено",
+ "Surface": "Поверхность",
"Swap Ends": "Поменять концы",
+ "TRIM": "ОБРЕЗКА",
"Tangent (G1)": "Касание (G1)",
"Tangent Chain": "Касательная цепочка",
"Tear": "Разрыв",
@@ -235,6 +242,7 @@
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Эта грань не может обеспечить надёжную привязку. Выберите другую грань или явно используйте фиксированную плоскость.",
"To Offset": "До смещения",
"Tolerance": "Допуск",
+ "Trimming tool (plane, face or curves)": "Инструмент обрезки (плоскость, грань или кривые)",
"Type": "Тип",
"Updating the preview": "Обновление предпросмотра",
"Use active author placement": "Использовать активное исходное положение",
diff --git a/assets/locales/tr.json b/assets/locales/tr.json
index 513250cd16..861dd5fc57 100644
--- a/assets/locales/tr.json
+++ b/assets/locales/tr.json
@@ -92,6 +92,7 @@
"Enabled": "Etkin",
"Explode": "Patlat",
"Export Animation…": "Animasyonu dışa aktar…",
+ "Extend to meet": "Buluşana kadar uzat",
"Extents": "Kapsamlar",
"Face": "Yüz",
"Face attachment lost": "Yüze bağlama kayboldu",
@@ -119,7 +120,9 @@
"Interferes": "Girişim var",
"Issue title": "Sorun başlığı",
"Joint Origin1": "Bağlantı orijini1",
+ "Keep (points on it)": "Koru (üzerindeki noktalar)",
"Keep Tools": "Araçları koru",
+ "Keep of the other surface": "Diğer yüzeyden korunacak",
"Later": "Daha sonra",
"Leave it": "Olduğu gibi bırak",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Eski tip yüz bağlaması. Doğrulanmış bir yüze yeniden bağlamak tam bir bağlama oluşturur.",
@@ -154,6 +157,7 @@
"Open GitHub draft": "GitHub taslağını aç",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust ile yazılmış açık kaynaklı parametrik 3D CAD. Lisans: MIT OR Apache-2.0.",
"Other side": "Diğer taraf",
+ "Other surface (mutual trim)": "Diğer yüzey (karşılıklı kırpma)",
"Outside": "Dış",
"Overall length": "Toplam uzunluk",
"Parameter values": "Parametre değerleri",
@@ -236,10 +240,13 @@
"Stand this part up?": "Bu parça dik çevrilsin mi?",
"Step": "Adım",
"Steps": "Adımlar",
+ "Stitch the kept pieces": "Korunan parçaları dik",
"Study": "Etüt",
"Style": "Stil",
"Suppressed": "Bastırılmış",
+ "Surface": "Yüzey",
"Swap Ends": "Uçları değiştir",
+ "TRIM": "KIRP",
"Tangent Chain": "Teğet zincir",
"The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Kesikli eskiz, kaydedilmiş bir düzlem kılavuzudur. Bağlamayı onarmak için yeni bir yüz seçin.",
"The saved author occurrence is missing. Select a valid author placement before rebinding.": "Kaydedilmiş kaynak örnek eksik. Yeniden bağlamadan önce geçerli bir kaynak yerleşimi seçin.",
@@ -254,6 +261,7 @@
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Bu yüz kalıcı bir bağlama sağlayamaz. Başka bir yüz seçin veya açıkça sabit bir düzlem kullanın.",
"To Offset": "Ofsete kadar",
"Tolerance": "Tolerans",
+ "Trimming tool (plane, face or curves)": "Kırpma aracı (düzlem, yüz veya eğriler)",
"Type": "Tür",
"UNTRIM": "KIRPMAYI KALDIR",
"Updating the preview": "Önizleme güncelleniyor",
diff --git a/assets/locales/uk.json b/assets/locales/uk.json
index 898789df4a..2a936339ba 100644
--- a/assets/locales/uk.json
+++ b/assets/locales/uk.json
@@ -103,6 +103,7 @@
"Export Current View as DXF…": "Експортувати поточний вид як DXF…",
"Export DXF…": "Експорт DXF…",
"Export hidden edges as dashed lines": "Експортувати приховані ребра як штрихові лінії",
+ "Extend to meet": "Подовжити до перетину",
"Extents": "Межі",
"Face": "Грань",
"Face attachment lost": "Втрачено прив'язку до грані",
@@ -131,7 +132,9 @@
"Interferes": "Перетинається",
"Issue title": "Заголовок повідомлення",
"Joint Origin1": "Початок з'єднання1",
+ "Keep (points on it)": "Залишити (точки на ньому)",
"Keep Tools": "Зберегти інструменти",
+ "Keep of the other surface": "Залишити від іншої поверхні",
"Later": "Пізніше",
"Leave it": "Залишити як є",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Застаріла прив'язка до грані. Повторна прив'язка до перевіреної грані створює точну прив'язку.",
@@ -168,6 +171,7 @@
"Open GitHub draft": "Відкрити чернетку GitHub",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Параметричний 3D-CAD з відкритим вихідним кодом на Rust. Ліцензовано за MIT OR Apache-2.0.",
"Other side": "Інший бік",
+ "Other surface (mutual trim)": "Інша поверхня (взаємне обрізання)",
"Outside": "Назовні",
"Overall length": "Загальна довжина",
"Parameter values": "Значення параметрів",
@@ -254,10 +258,13 @@
"Stand this part up?": "Вирівняти цю деталь?",
"Step": "Крок",
"Steps": "Кроки",
+ "Stitch the kept pieces": "Зшити залишені частини",
"Study": "Дослідження",
"Style": "Стиль",
"Suppressed": "Придушено",
+ "Surface": "Поверхня",
"Swap Ends": "Поміняти кінці місцями",
+ "TRIM": "ОБРІЗАННЯ",
"Tangent (G1)": "Дотик (G1)",
"Tangent Chain": "Дотичний ланцюг",
"Tear": "Розрив",
@@ -274,6 +281,7 @@
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Ця грань не може забезпечити надійну прив'язку. Виберіть іншу грань або явно використайте фіксовану площину.",
"To Offset": "До зсуву",
"Tolerance": "Допуск",
+ "Trimming tool (plane, face or curves)": "Інструмент обрізання (площина, грань або криві)",
"Turn off section analysis before exporting the view.": "Вимкніть аналіз перерізу перед експортом виду.",
"Type": "Тип",
"UNTRIM": "ЗНЯТИ ОБРІЗАННЯ",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index 8daee673e4..96b2405e02 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -107,6 +107,7 @@
"Export Current View as DXF…": "将当前视图导出为DXF…",
"Export DXF…": "导出DXF…",
"Export hidden edges as dashed lines": "以虚线导出隐藏线",
+ "Extend to meet": "延伸至相交",
"Extents": "范围",
"Face": "面",
"Face attachment lost": "面附着丢失",
@@ -135,7 +136,9 @@
"Interferes": "发生干涉",
"Issue title": "Issue 标题",
"Joint Origin1": "接头原点1",
+ "Keep (points on it)": "保留(其上的点)",
"Keep Tools": "保留工具",
+ "Keep of the other surface": "另一曲面保留的部分",
"Later": "稍后",
"Leave it": "保持原样",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "旧版面附着。重新绑定到经验证的面可创建精确附着。",
@@ -173,6 +176,7 @@
"Open GitHub draft": "打开 GitHub 草稿",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "使用 Rust 编写的开源参数化 3D CAD。基于 MIT OR Apache-2.0 许可。",
"Other side": "另一侧",
+ "Other surface (mutual trim)": "另一曲面(相互修剪)",
"Outside": "外侧",
"Overall length": "总长",
"Parameter values": "参数值",
@@ -260,10 +264,13 @@
"Stand this part up?": "立起此零件?",
"Step": "步骤",
"Steps": "步数",
+ "Stitch the kept pieces": "缝合保留的部分",
"Study": "研究",
"Style": "样式",
"Suppressed": "已抑制",
+ "Surface": "曲面",
"Swap Ends": "交换端点",
+ "TRIM": "修剪",
"Tangent (G1)": "相切 (G1)",
"Tangent Chain": "相切链",
"Tear": "撕裂",
@@ -281,6 +288,7 @@
"To Offset": "偏移",
"Tolerance": "公差",
"Too close": "过近",
+ "Trimming tool (plane, face or curves)": "修剪工具(平面、面或曲线)",
"Turn off section analysis before exporting the view.": "请关闭截面分析后再导出视图。",
"Type": "类型",
"UNTRIM": "取消修剪",
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index a661404b56..1ec44993b5 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -1511,14 +1511,31 @@ pub enum FeatureKind {
#[walk(length = "Tolerance")]
tolerance: Expr,
},
- /// A surface body trimmed by a plane, or by a face of a body (`tool`), keeping the side of
- /// `keep`.
+ /// A surface body trimmed by a plane, by a face of a body (`tool`, its surface extended) or
+ /// by sketch curves swept onto it (`curves`), keeping the side of `keep`; with `keep_more`,
+ /// the regions (pieces that hang together once cut) `keep` and those points pick instead.
+ /// With `with`, a mutual trim: `body` and `with` (one face each) cut each other, `with`
+ /// keeping the side of its one `keep_with` point or the regions of several; `extend`
+ /// extends one that stops short of the other to meet it, and `stitch` sews the two kept
+ /// pieces into `body` (`with` is then gone).
SurfaceTrim {
body: BodyName,
plane: PlaneRef,
#[serde(default, skip_serializing_if = "Option::is_none")]
tool: Option<FaceAt>,
keep: Position,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ keep_more: Vec<Position>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ curves: Option<TrimCurves>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ with: Option<BodyName>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ keep_with: Vec<Position>,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ stitch: bool,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ extend: bool,
},
Move {
bodies: Vec<BodyName>,
@@ -1689,6 +1706,18 @@ impl FilletStyle {
}
}
+/// Sketch curves a trim cuts with: chains of the curves `curves` (every curve of the sketch
+/// that is not construction geometry when empty) swept along `direction` (the sketch's normal
+/// when none) onto the surface.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
+pub struct TrimCurves {
+ pub sketch: SketchId,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub curves: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub direction: Option<Dir>,
+}
+
/// A face picked by a point on it, on a named body.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
pub struct FaceAt {
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 195280f6c7..153b2561fb 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -5019,7 +5019,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
if curves.is_empty() {
return Err(DocError::Invalid(format!("sketch `{}` has no curves to split with", ss.name)));
}
- kernel::split_faces(&mb.body, &picked, &kernel::SplitTool::Curves { plane: ss.plane, curves })?
+ kernel::split_faces(&mb.body, &picked, &kernel::SplitTool::Curves { plane: ss.plane, curves, along: None })?
}
(None, None) => {
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs
index 227a126a71..b59d557fc4 100644
--- a/crates/doc/src/eval_surface.rs
+++ b/crates/doc/src/eval_surface.rs
@@ -67,20 +67,46 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature,
}
apply_op(st, f, tools, *operation, &crate::plain(targets))
}
- FeatureKind::SurfaceTrim { body, plane, tool, keep } => {
+ FeatureKind::SurfaceTrim { body, plane, tool, keep, keep_more, curves, with, keep_with, stitch, extend } => {
let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
- let trimmed = match tool {
- Some(t) => {
+ let picks: Vec<Vec3> = std::iter::once(keep.0).chain(keep_more.iter().map(|p| p.0)).collect();
+ let keeps = if keep_more.is_empty() { kernel::TrimKeep::Side(keep.0) } else { kernel::TrimKeep::Regions(&picks) };
+ if let Some(other) = with {
+ return mutual_trim(st, i, other, keeps, &crate::plain(keep_with), *stitch, *extend);
+ }
+ let trimmed = match (tool, curves) {
+ (Some(t), _) => {
let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?;
let face = crate::appearance::face_index_at(tb, t.point.0)
.ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the tool point", t.body)))?;
- kernel::trim(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face }, keep.0)?
+ kernel::trim_keep(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face }, keeps)?
+ }
+ (None, Some(c)) => {
+ let ss = st
+ .sketch(c.sketch.0)
+ .ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", c.sketch)))?;
+ let ss = sketch_in_feature_frame(doc, ss, f.component)?;
+ let ids: Vec<String> = if c.curves.is_empty() {
+ ss.sketch.curves.iter().filter(|k| !k.construction).map(|k| k.id.clone()).collect()
+ } else {
+ c.curves.clone()
+ };
+ let chains = curve_chains(&ss, &ids)?;
+ if chains.is_empty() {
+ return Err(DocError::Invalid(format!("sketch `{}` has no curves to trim with", ss.name)));
+ }
+ kernel::trim_keep(
+ &mb.body,
+ &kernel::SplitTool::Curves { plane: ss.plane, curves: chains, along: c.direction.map(|d| d.0) },
+ keeps,
+ )?
}
- None => kernel::trim(&mb.body, &kernel::SplitTool::Plane(doc.resolve_plane_in(vals, plane, 0, Some(st))?), keep.0)?,
+ (None, None) => kernel::trim_keep(&mb.body, &kernel::SplitTool::Plane(doc.resolve_plane_in(vals, plane, 0, Some(st))?), keeps)?,
};
+ let made = Traced::step(trimmed, &[&mb.traced()]);
if let Some(slot) = st.bodies.get_mut(i) {
- *slot = ModelBody::new(mb.name, trimmed, mb.feature);
+ *slot = ModelBody::traced_new(mb.name, made, mb.feature);
}
Ok(())
}
@@ -669,6 +695,43 @@ fn boundary_frames(
Ok(out)
}
+/// Mutual Trim: the body at `i` and `other` trimmed by each other (each keeping its picks), the
+/// kept pieces sewn into the first when `stitch`; their faces named after the faces they are
+/// pieces of.
+fn mutual_trim(st: &mut ModelState, i: usize, other: &str, keeps: kernel::TrimKeep, keep_with: &[Vec3], stitch: bool, extend: bool) -> Result<()> {
+ let j = st.bodies.iter().position(|b| b.name == other).ok_or_else(|| DocError::Unknown(format!("body `{other}`")))?;
+ if i == j {
+ return Err(DocError::Invalid("a surface can't trim itself: pick another surface".into()));
+ }
+ let (Some(a), Some(b)) = (st.bodies.get(i).cloned(), st.bodies.get(j).cloned()) else { return Err(DocError::Invalid("body".into())) };
+ let keeps_with = match keep_with {
+ [] => return Err(DocError::Invalid(format!("pick the side of `{other}` to keep"))),
+ [p] => kernel::TrimKeep::Side(*p),
+ ps => kernel::TrimKeep::Regions(ps),
+ };
+ let (ta, tb) = kernel::mutual_trim(&a.body, &b.body, keeps, keeps_with, extend)?;
+ let (ta, tb) = (Traced::step(ta, &[&a.traced()]), Traced::step(tb, &[&b.traced()]));
+ if stitch {
+ let sewn = kernel::stitch(&[&ta.body, &tb.body], 0.0)?;
+ if sewn.edge_count() >= ta.body.edge_count() + tb.body.edge_count() {
+ return Err(DocError::Invalid("the trimmed surfaces don't meet along an edge: they can't be stitched".into()));
+ }
+ let sewn = Traced::step(sewn, &[&ta, &tb]);
+ if let Some(slot) = st.bodies.get_mut(i) {
+ *slot = ModelBody::traced_new(a.name, sewn, a.feature);
+ }
+ st.bodies.retain(|x| x.name != other);
+ } else {
+ if let Some(slot) = st.bodies.get_mut(i) {
+ *slot = ModelBody::traced_new(a.name, ta, a.feature);
+ }
+ if let Some(slot) = st.bodies.get_mut(j) {
+ *slot = ModelBody::traced_new(b.name, tb, b.feature);
+ }
+ }
+ Ok(())
+}
+
/// What a surface builder sweeps: the boundary loops of the picked profiles, then the picked
/// curves chained end to end.
fn sheet_chains(ss: &SolvedSketch, profiles: Option<&ProfileSel>, curves: &[String]) -> Result<Vec<Vec<Seg2>>> {
diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs
index 71cecf9b30..ba9d31fdbd 100644
--- a/crates/doc/src/feature_walk_tests/fixtures.rs
+++ b/crates/doc/src/feature_walk_tests/fixtures.rs
@@ -188,6 +188,15 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
"direction": [0, 0, 1], "face": [1, 0, 0]}),
),
("surface_trim", json!({"type": "surface_trim", "body": "B", "plane": plane("trim"), "keep": o})),
+ (
+ "surface_trim_curves",
+ json!({"type": "surface_trim", "body": "B", "plane": plane("trim"), "keep": o, "keep_more": [o],
+ "curves": {"sketch": 1, "curves": ["l1"], "direction": [0, 0, 1]}}),
+ ),
+ (
+ "surface_trim_mutual",
+ json!({"type": "surface_trim", "body": "B", "plane": plane("trim"), "keep": o, "with": "B", "keep_with": [o, o], "stitch": true, "extend": true}),
+ ),
("move", json!({"type": "move", "bodies": ["B"], "translate": ["move.x", "move.y", "move.z"], "angle": "move.angle"})),
("import", json!({"type": "import", "file": "a.step", "step": ""})),
("mesh_convert", json!({"type": "mesh_convert", "body": "B", "tolerance": "mesh_convert.tolerance"})),
diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt
index d898714722..5a4f9da2e3 100644
--- a/crates/doc/src/feature_walk_tests/golden_exprs.txt
+++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt
@@ -375,6 +375,16 @@ surface_trim
Angle = trim.angle (Angle)
Offset = trim.offset (Length)
expressions: trim.angle, trim.offset
+surface_trim_curves
+ inputs:
+ Angle = trim.angle (Angle)
+ Offset = trim.offset (Length)
+ expressions: trim.angle, trim.offset
+surface_trim_mutual
+ inputs:
+ Angle = trim.angle (Angle)
+ Offset = trim.offset (Length)
+ expressions: trim.angle, trim.offset
move
inputs:
X distance = move.x (Length)
diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt
index 314c4607f2..af2ef727d4 100644
--- a/crates/doc/src/feature_walk_tests/golden_geometry.txt
+++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt
@@ -183,6 +183,10 @@ surface_ruled
face points: [1, 0, 0]
surface_trim
moves: keep[0], keep[1], keep[2], plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2], tool.point[0], tool.point[1], tool.point[2]
+surface_trim_curves
+ moves: curves.direction[0], curves.direction[2], keep[0], keep[1], keep[2], keep_more[0][0], keep_more[0][1], keep_more[0][2], plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2]
+surface_trim_mutual
+ moves: keep[0], keep[1], keep[2], keep_with[0][0], keep_with[0][1], keep_with[0][2], keep_with[1][0], keep_with[1][1], keep_with[1][2], plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2]
move
moves: rotate_axis[1], rotate_axis[2]
import
diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt
index 386158c4e0..5eeaff4219 100644
--- a/crates/doc/src/feature_walk_tests/golden_refs.txt
+++ b/crates/doc/src/feature_walk_tests/golden_refs.txt
@@ -208,6 +208,13 @@ surface_ruled
surface_trim
remap_refs: plane.base.base.name
remap_bodies: body, tool.body
+surface_trim_curves
+ sketches: [1]
+ remap_refs: curves.sketch, plane.base.base.name
+ remap_bodies: body
+surface_trim_mutual
+ remap_refs: plane.base.base.name
+ remap_bodies: body, with
move
remap_bodies: bodies[0]
import
diff --git a/crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs b/crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs
new file mode 100644
index 0000000000..7fb3ba86f3
--- /dev/null
+++ b/crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs
@@ -0,0 +1,6 @@
+//! A `SurfaceTrim` can keep several regions (`keep_more`: more points; with them, the pieces that
+//! hang together once cut that `keep` and these points pick are kept instead of the side of
+//! `keep`), cut with sketch curves swept onto the surface (`curves`: `sketch`, optional `curves`
+//! ids and `direction`), or trim another surface and be trimmed by it (`with`, `keep_with` points,
+//! optional `stitch` and `extend`). Older designs need no transformation: a trim without them
+//! saves as before; 0.14.x asks for an update instead of ignoring them and trimming by the plane.
diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs
index ea161f8e9e..32fb50bc17 100644
--- a/crates/engine/src/cmd/surface.rs
+++ b/crates/engine/src/cmd/surface.rs
@@ -4,7 +4,7 @@
use serde_json::Value;
use solidcraft_doc::{
BlendSide, EdgeContinuity, Expr, ExtendMode, ExtendTo, FaceAt, FeatureKind, PatchContinuity, PlaneRef, ProfileSel, RuledCorners, RuledMode,
- expr::Kind,
+ TrimCurves, expr::Kind,
};
use solidcraft_doc::{BodyName, SketchId};
use solidcraft_doc::{Dir, FacePick, Position};
@@ -35,7 +35,7 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("surface.trim", "Trim", trim)
.at("SURFACE", "MODIFY")
.icon("surface_trim")
- .params("body: surface name; plane: XY|XZ|YZ|plane name|{origin, normal} or tool: {body, point} (a face, its surface extended); keep: [x,y,z] (a point on the side to keep)"),
+ .params("body: surface name; plane: XY|XZ|YZ|plane name|{origin, normal} or tool: {body, point} (a face, its surface extended) or curves: {sketch, curves?: [curve ids] (chains of curves meeting end to end; default every curve), direction?: normal|[x,y,z] (swept onto the surface along the sketch's normal, the default, or this direction)}; keep: [x,y,z] (a point on the side to keep) or [[x,y,z], ...] (points on the regions to keep: the pieces that hang together once cut). Mutual trim: with: another surface (one face each; leave out plane, tool and curves), keep_with: [x,y,z] or [[x,y,z], ...] (what to keep of it); each is cut where the other's surface (extended) meets it; extend?: bool (a surface that stops short of the other is extended to meet it); stitch?: bool (the kept pieces sewn into `body`; `with` is then gone)"),
CommandSpec::new("surface.extrude", "Surface Extrude", surface_extrude)
.at("SURFACE", "CREATE")
.icon("surface_extrude")
@@ -595,22 +595,117 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {
)
}
+/// Points to keep: one `[x, y, z]`, or a list of them (at most 10 000).
+fn keep_points(v: Option<&Value>, cmd: &str, key: &str) -> Result<Vec<solidcraft_geom::Vec3>> {
+ let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
+ if let Some(p) = vec3(v) {
+ return Ok(vec![p]);
+ }
+ let list = v
+ .as_array()
+ .filter(|a| !a.is_empty() && a.len() <= 10_000)
+ .ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, z] or a list of them")))?;
+ list.iter().map(|q| vec3(q).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, z] or a list of them")))).collect()
+}
+
fn trim(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "surface.trim";
let body = str_(p, "body").ok_or_else(|| bad(cmd, "`body` is required"))?.to_string();
if s.model.state().body(&body).is_none() {
return Err(bad(cmd, format!("no body `{body}`")));
}
- let keep = p.get("keep").and_then(vec3).ok_or_else(|| bad(cmd, "`keep` must be [x, y, z] on the side to keep"))?;
- let (plane, tool) = match p.get("tool").filter(|t| !t.is_null()) {
- Some(t) => {
+ let picks = keep_points(p.get("keep"), cmd, "keep")?;
+ let Some((&keep, more)) = picks.split_first() else {
+ return Err(bad(cmd, "`keep` must be [x, y, z] on the side to keep (or a list of points on the regions to keep)"));
+ };
+ let keep_more = more.to_vec();
+ let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
+ let xy = || PlaneRef::Origin { name: "XY".into() };
+ if let Some(w) = p.get("with").filter(|v| !v.is_null()) {
+ let with = w.as_str().ok_or_else(|| bad(cmd, "`with` must name a surface body"))?.to_string();
+ if with == body {
+ return Err(bad(cmd, "`with` must be another surface body"));
+ }
+ if s.model.state().body(&with).is_none() {
+ return Err(bad(cmd, format!("no body `{with}`")));
+ }
+ if given("plane") || given("tool") || given("curves") {
+ return Err(bad(cmd, "a mutual trim cuts each surface with the other: leave out `plane`, `tool` and `curves`"));
+ }
+ let keep_with = keep_points(p.get("keep_with"), cmd, "keep_with")?;
+ if keep_with.is_empty() {
+ return Err(bad(cmd, "`keep_with` must be [x, y, z] on the side of the other surface to keep"));
+ }
+ let (stitch, extend) = (bool_(p, "stitch").unwrap_or(false), bool_(p, "extend").unwrap_or(false));
+ let kind = FeatureKind::SurfaceTrim {
+ body: BodyName(body),
+ plane: xy(),
+ tool: None,
+ keep: Position(keep),
+ keep_more: keep_more.into_iter().map(Position).collect(),
+ curves: None,
+ with: Some(BodyName(with)),
+ keep_with: keep_with.into_iter().map(Position).collect(),
+ stitch,
+ extend,
+ };
+ return add_feature(s, p, kind);
+ }
+ if given("keep_with") || given("stitch") || given("extend") {
+ return Err(bad(cmd, "`keep_with`, `stitch` and `extend` belong to a mutual trim (`with`)"));
+ }
+ let (plane, tool, curves) = match (p.get("tool").filter(|t| !t.is_null()), p.get("curves").filter(|c| !c.is_null())) {
+ (Some(_), Some(_)) => return Err(bad(cmd, "give `tool` or `curves`, not both")),
+ (Some(t), None) => {
let tb = t.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`tool.body` must name a body"))?.to_string();
let point = t.get("point").and_then(vec3).ok_or_else(|| bad(cmd, "`tool.point` must be [x, y, z] on the tool face"))?;
- (PlaneRef::Origin { name: "XY".into() }, Some(FaceAt { body: BodyName(tb), point: Position(point) }))
+ (xy(), Some(FaceAt { body: BodyName(tb), point: Position(point) }), None)
}
- None => (plane_param(s, p.get("plane"), cmd)?, None),
+ (None, Some(c)) => {
+ let sketch = sketch_id(s, c.get("sketch"), cmd, "curves.sketch")?;
+ let ids = match c.get("curves").filter(|v| !v.is_null()) {
+ None => Vec::new(),
+ Some(v) => {
+ let a = v.as_array().filter(|a| a.len() <= 1000).ok_or_else(|| bad(cmd, "`curves.curves` must list curve ids"))?;
+ a.iter()
+ .map(|x| x.as_str().map(str::to_string).ok_or_else(|| bad(cmd, "`curves.curves` must list curve ids")))
+ .collect::<Result<Vec<_>>>()?
+ }
+ };
+ let direction = match c.get("direction").filter(|v| !v.is_null()) {
+ None => None,
+ Some(Value::String(d)) if d.trim() == "normal" => None,
+ Some(Value::String(d)) if d.trim() == "face_normal" => {
+ return Err(bad(
+ cmd,
+ "not supported yet: projecting curves along the surface's normal (#767); project along the sketch's normal or a direction",
+ ));
+ }
+ Some(v) => {
+ let d = vec3(v).ok_or_else(|| bad(cmd, "`curves.direction` must be normal or [x, y, z]"))?;
+ if !(d.len() > 1e-12) {
+ return Err(bad(cmd, "`curves.direction` must not be zero"));
+ }
+ Some(d)
+ }
+ };
+ (xy(), None, Some(TrimCurves { sketch: SketchId(sketch), curves: ids, direction: direction.map(Dir) }))
+ }
+ (None, None) => (plane_param(s, p.get("plane"), cmd)?, None, None),
+ };
+ let kind = FeatureKind::SurfaceTrim {
+ body: BodyName(body),
+ plane,
+ tool,
+ keep: Position(keep),
+ keep_more: keep_more.into_iter().map(Position).collect(),
+ curves,
+ with: None,
+ keep_with: Vec::new(),
+ stitch: false,
+ extend: false,
};
- add_feature(s, p, FeatureKind::SurfaceTrim { body: BodyName(body), plane, tool, keep: Position(keep) })
+ add_feature(s, p, kind)
}
/// `surface.fair`: the B-spline faces of a body faired in place. The tolerance a caller leaves
@@ -1284,6 +1379,193 @@ mod tests {
assert_eq!(s.doc.features.len(), before, "a planned command changed the design");
}
+ /// A rectangle patch in a plane (`plane`: a sketch plane name), corners (u0, v0) and (u1, v1)
+ /// in its coordinates.
+ fn sheet(s: &mut Session, plane: &str, name: &str, p0: [f64; 2], p1: [f64; 2]) {
+ let sk = format!("{name} sketch");
+ run(s, "sketch.create", json!({"plane": plane, "name": sk}));
+ run(s, "sketch.rectangle.two_point", json!({"p0": p0, "p1": p1}));
+ run(s, "sketch.finish", json!({}));
+ run(s, "surface.patch", json!({"sketch": sk, "body_name": name}));
+ }
+
+ fn names(s: &Session, body: &str) -> Vec<String> {
+ solidcraft_doc::naming::face_names(s.model.state().body(body).unwrap()).to_vec()
+ }
+
+ fn exact(s: &Session, body: &str, i: usize) -> bool {
+ solidcraft_doc::naming::face_name_exact(s.model.state().body(body).unwrap(), i)
+ }
+
+ /// Two 20 × 10 sheets crossing at right angles (z = 0 and x = 0, both y = 0…10), trimmed by
+ /// each other and stitched: an L of two faces sharing one edge (7 edges), 200 in area; each
+ /// face named after the sheet it is a piece of. Undo, redo and reopening rebuild it.
+ #[test]
+ fn mutual_trim_stitches_crossing_sheets_into_an_l() {
+ let mut s = Session::default();
+ sheet(&mut s, "XY", "Floor", [-10.0, 0.0], [10.0, 10.0]);
+ // YZ sketches have u along Y and v along Z.
+ sheet(&mut s, "YZ", "Wall", [0.0, -10.0], [10.0, 10.0]);
+ let (floor, wall) = (names(&s, "Floor"), names(&s, "Wall"));
+ // (A patch's face is named from geometry; its pieces inherit that, no surer.)
+ let sure = exact(&s, "Floor", 0);
+ run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [5, 5, 0], "with": "Wall", "keep_with": [0, 5, 5], "stitch": true}));
+ let st = s.world_state();
+ assert!(st.body("Wall").is_none(), "sewn into the floor");
+ let l = &st.body("Floor").unwrap().body;
+ assert!(l.is_surface());
+ assert_eq!((l.face_count(), l.edge_count()), (2, 7), "one connected sheet");
+ assert!((area(&s, "Floor") - 200.0).abs() < 1e-9, "{}", area(&s, "Floor"));
+ let bb = solidcraft_kernel::measure(l).unwrap().bbox;
+ assert!(bb.min.x.abs() < 1e-9 && bb.min.z.abs() < 1e-9 && (bb.max.x - 10.0).abs() < 1e-9 && (bb.max.z - 10.0).abs() < 1e-9, "{bb:?}");
+ let mut got = names(&s, "Floor");
+ got.sort();
+ let mut want = vec![floor[0].clone(), wall[0].clone()];
+ want.sort();
+ assert_eq!(got, want, "each face named after its sheet");
+ assert!(exact(&s, "Floor", 0) == sure && exact(&s, "Floor", 1) == sure);
+ let saved = s.doc.to_json();
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.world_state().body("Wall").is_some() && (area(&s, "Floor") - 200.0).abs() < 1e-9);
+ run(&mut s, "edit.redo", json!({}));
+ let cold = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());
+ assert!((area(&cold, "Floor") - 200.0).abs() < 1e-9 && cold.world_state().body("Wall").is_none());
+ // Without stitching, each keeps its half under its own name.
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [-5, 5, 0], "with": "Wall", "keep_with": [0, 5, -5]}));
+ assert!((area(&s, "Floor") - 100.0).abs() < 1e-9 && (area(&s, "Wall") - 100.0).abs() < 1e-9);
+ let bb = solidcraft_kernel::measure(&s.world_state().body("Wall").unwrap().body).unwrap().bbox;
+ assert!((bb.max.z).abs() < 1e-9, "the wall's lower half: {bb:?}");
+ }
+
+ /// A wall that stops 3 short of the floor is refused until `extend` brings it down to meet
+ /// it; then the two make the L.
+ #[test]
+ fn mutual_trim_extends_a_short_sheet() {
+ let mut s = Session::default();
+ sheet(&mut s, "XY", "Floor", [-10.0, 0.0], [10.0, 10.0]);
+ sheet(&mut s, "YZ", "Wall", [0.0, 3.0], [10.0, 10.0]);
+ let mutual = json!({"body": "Floor", "keep": [5, 5, 0], "with": "Wall", "keep_with": [0, 5, 5], "stitch": true});
+ let e = s.execute("surface.trim", &mutual).unwrap_err().to_string();
+ assert!(e.contains("extend"), "{e}");
+ let mut asked = mutual.clone();
+ asked["extend"] = json!(true);
+ run(&mut s, "surface.trim", asked);
+ let st = s.world_state();
+ let l = &st.body("Floor").unwrap().body;
+ assert_eq!((l.face_count(), l.edge_count()), (2, 7));
+ assert!((area(&s, "Floor") - 200.0).abs() < 1e-6, "{}", area(&s, "Floor"));
+ }
+
+ /// The slot |x| ≤ 3, round ends at z = 12 and 28 (overall 9…31), drawn on XZ and swept along
+ /// its normal onto a half cylinder (radius 10 about Z, y ≥ 0, 40 high): the piece inside is
+ /// ∫∫ R / √(R² − x²) dx dz over the slot, the straight run 16 · 2R·asin(3/R) and the round
+ /// ends one disc (Simpson in φ, x = 3 sin φ). Picking the inside region gives the same
+ /// piece; a direction along the face's normal is not supported yet.
+ #[test]
+ fn trim_a_cylinder_by_a_projected_slot() {
+ let pi = std::f64::consts::PI;
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
+ let arc = run(&mut s, "sketch.arc.three_point", json!({"start": [10, 0], "end": [-10, 0], "through": [0, 10]}))["created"]["curves"][0]
+ .as_str()
+ .unwrap()
+ .to_string();
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": [arc], "distance": 40, "body_name": "Half"}));
+ let source = names(&s, "Half");
+ // XZ sketches have v along −Z.
+ run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Slot"}));
+ run(&mut s, "sketch.slot.overall", json!({"p0": [0, -9], "p1": [0, -31], "width": 6}));
+ run(&mut s, "sketch.finish", json!({}));
+ let (r, a): (f64, f64) = (10.0, 3.0);
+ let n = 4000;
+ let f = |phi: f64| 2.0 * a * a * phi.cos().powi(2) * r / (r * r - (a * phi.sin()).powi(2)).sqrt();
+ let h = pi / n as f64;
+ let ends = (0..=n)
+ .map(|k| {
+ (if k == 0 || k == n {
+ 1.0
+ } else if k % 2 == 1 {
+ 4.0
+ } else {
+ 2.0
+ }) * f(-pi / 2.0 + h * k as f64)
+ })
+ .sum::<f64>()
+ * h
+ / 3.0;
+ let inside = 16.0 * 2.0 * r * (a / r).asin() + ends;
+ run(&mut s, "surface.trim", json!({"body": "Half", "curves": {"sketch": "Slot"}, "keep": [0, 10, 20]}));
+ // (Measured on meshes.)
+ assert!((area(&s, "Half") - inside).abs() < inside * 1e-3, "{} vs {inside}", area(&s, "Half"));
+ assert_eq!(names(&s, "Half"), source, "the piece is the cylinder's face");
+ assert!(exact(&s, "Half", 0));
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "surface.trim", json!({"body": "Half", "curves": {"sketch": "Slot", "direction": "normal"}, "keep": [[0, 10, 20]]}));
+ assert!((area(&s, "Half") - inside).abs() < inside * 1e-3, "{}", area(&s, "Half"));
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "surface.trim", json!({"body": "Half", "curves": {"sketch": "Slot"}, "keep": [10, 0, 20]}));
+ let rest = pi * r * 40.0 - inside;
+ assert!((area(&s, "Half") - rest).abs() < rest * 1e-3, "{} vs {rest}", area(&s, "Half"));
+ run(&mut s, "edit.undo", json!({}));
+ let e = s
+ .execute("surface.trim", &json!({"body": "Half", "curves": {"sketch": "Slot", "direction": "face_normal"}, "keep": [0, 10, 20]}))
+ .unwrap_err();
+ assert!(e.to_string().contains("not supported yet"), "{e}");
+ }
+
+ /// A U-shaped sheet (legs at x = 0 and 10, 10 high; base along y = 0; 10 deep) cut by the
+ /// plane y = 5: one point keeps its side (both legs' tops, 100), a list of points the regions
+ /// they pick (one leg's top, 50; the base region, 200).
+ #[test]
+ fn trim_keeps_several_regions() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "U"}));
+ let created = run(&mut s, "sketch.line", json!({"points": [[0, 10], [0, 0], [10, 0], [10, 10]]}));
+ let ids: Vec<String> = created["created"]["curves"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "surface.extrude", json!({"sketch": "U", "curves": ids, "distance": 10, "body_name": "U"}));
+ let cut = json!({"origin": [0, 5, 0], "normal": [0, 1, 0]});
+ run(&mut s, "surface.trim", json!({"body": "U", "plane": cut, "keep": [0, 8, 5]}));
+ assert!((area(&s, "U") - 100.0).abs() < 1e-9, "{}", area(&s, "U"));
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "surface.trim", json!({"body": "U", "plane": cut, "keep": [[0, 8, 5], [0, 9, 1]]}));
+ assert!((area(&s, "U") - 50.0).abs() < 1e-9, "{}", area(&s, "U"));
+ let saved = s.doc.to_json();
+ assert!(saved.contains("\"keep_more\""), "the other points are saved");
+ let cold = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());
+ assert!((area(&cold, "U") - 50.0).abs() < 1e-9);
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "surface.trim", json!({"body": "U", "plane": cut, "keep": [[5, 0, 5], [10, 1, 5]]}));
+ assert!((area(&s, "U") - 200.0).abs() < 1e-9, "{}", area(&s, "U"));
+ }
+
+ /// Trim requests that make no sense are refused and leave the design as it was.
+ #[test]
+ fn trim_refuses_bad_requests() {
+ let mut s = Session::default();
+ sheet(&mut s, "XY", "Floor", [-10.0, 0.0], [10.0, 10.0]);
+ sheet(&mut s, "YZ", "Wall", [0.0, -10.0], [10.0, 10.0]);
+ let before = s.doc.features.len();
+ for p in [
+ json!({"body": "Floor", "with": "Floor", "keep": [5, 5, 0], "keep_with": [5, 5, 0]}),
+ json!({"body": "Floor", "with": "Nope", "keep": [5, 5, 0], "keep_with": [0, 5, 5]}),
+ json!({"body": "Floor", "with": "Wall", "keep": [5, 5, 0]}),
+ json!({"body": "Floor", "with": "Wall", "keep": [5, 5, 0], "keep_with": [0, 5, 5], "plane": "YZ"}),
+ json!({"body": "Floor", "plane": "YZ", "keep": [5, 5, 0], "stitch": true}),
+ json!({"body": "Floor", "plane": "YZ", "keep": []}),
+ json!({"body": "Floor", "plane": "YZ", "keep": [[5, 5]]}),
+ json!({"body": "Floor", "tool": {"body": "Wall", "point": [0, 5, 5]}, "curves": {"sketch": "Wall sketch"}, "keep": [5, 5, 0]}),
+ json!({"body": "Floor", "curves": {"sketch": "Nope"}, "keep": [5, 5, 0]}),
+ json!({"body": "Floor", "curves": {"sketch": "Wall sketch", "curves": ["nope"]}, "keep": [5, 5, 0]}),
+ json!({"body": "Floor", "curves": {"sketch": "Wall sketch", "direction": [0, 0, 0]}, "keep": [5, 5, 0]}),
+ ] {
+ assert!(s.execute("surface.trim", &p).is_err(), "{p}");
+ }
+ assert_eq!(s.doc.features.len(), before);
+ }
+
/// A trim keeps its construction plane when the plane is renamed.
#[test]
fn renaming_a_plane_keeps_a_surface_trim_on_it() {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 23b107875f..e65bd328d8 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -810,6 +810,11 @@ fn hostile_params_never_panic() {
"faces",
"u",
"v",
+ "keep",
+ "with",
+ "keep_with",
+ "stitch",
+ "extend",
];
// Commands are independent; worker threads take them one at a time (their costs vary a lot).
let ids: Vec<&str> = command_specs()
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index 046eb469cc..ae37c34483 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -127,6 +127,7 @@ mod surface_offset;
mod surface_ruled;
#[cfg(test)]
mod surface_second_derivative_tests;
+mod surface_trim;
mod surface_untrim;
mod surfaces;
mod sweep_path;
@@ -203,10 +204,11 @@ pub use surface_extend::{ExtendLimit, ExtendMode, ExtendOptions, extend_surface}
pub use surface_kind::{EdgeCircle, FaceSurface, edge_circle, face_surface};
pub use surface_offset::offset_surface;
pub use surface_ruled::{Ruled, RuledCorners, RuledMode, ruled_surface};
+pub use surface_trim::{TrimKeep, mutual_trim, trim, trim_keep};
pub use surface_untrim::{UntrimHoles, untrim};
pub use surfaces::{
copy_faces, extend, extrude_sheet, loft_sheet, patch_edges, patch_region, remove_faces, reverse_faces, revolve_sheet, stitch, sweep_sheet,
- sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, trim, unstitch,
+ sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, unstitch,
};
pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_path_with};
pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at};
diff --git a/crates/kernel/src/smooth_edges.rs b/crates/kernel/src/smooth_edges.rs
index bb24f50736..90460e3e91 100644
--- a/crates/kernel/src/smooth_edges.rs
+++ b/crates/kernel/src/smooth_edges.rs
@@ -151,6 +151,12 @@ fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec<bool>, Vec<bool>)
boundaries.push(None);
continue;
}
+ // Mapping rebuilds each edge through a check that refuses one starting and ending at
+ // the same vertex (a loop of one closed edge: a hole a closed curve cut).
+ if wires.iter().flat_map(|w| w.edge_iter()).any(|e| e.front().id() == e.back().id()) {
+ boundaries.push(None);
+ continue;
+ }
let mapped = face.try_mapped(|_| Some(()), |_| Some(()), |surface| ruled(surface, face.orientation(), &mut work));
boundaries.push(mapped.map(|face| face.surface()));
}
@@ -243,6 +249,27 @@ mod tests {
crate::extrude(&Plane::XY, &[Region2 { outer: circle(10., count), holes: vec![circle(9., count).reversed()] }], 0., 3.).unwrap().remove(0)
}
+ /// A square sheet with a round hole a closed curve cut (its loop one closed edge) is
+ /// classified without a check refusing the closed edge (a panic the guard would catch).
+ #[test]
+ fn a_hole_of_one_closed_edge_is_classified() {
+ let sheet = crate::patch_region(
+ &Plane::XY,
+ &Region2 {
+ outer: Loop2::polygon(&[Vec2::new(-10., -10.), Vec2::new(10., -10.), Vec2::new(10., 10.), Vec2::new(-10., 10.)]),
+ holes: vec![],
+ },
+ )
+ .unwrap();
+ let ring: Vec<Seg2> = circle(4., 8).segs;
+ let tool = crate::SplitTool::Curves { plane: Plane::XY, curves: vec![ring], along: None };
+ let holed = crate::trim(&sheet, &tool, Vec3::new(9., 9., 0.)).unwrap();
+ assert!(holed.solid.edge_iter().any(|e| e.front().id() == e.back().id()), "a closed edge");
+ let mesh = holed.tessellate(0.02).unwrap();
+ let (smooth, sharp) = classify(&holed, &mesh, WORK);
+ assert_eq!((smooth.len(), sharp.len()), (mesh.edges.len(), mesh.edges.len()));
+ }
+
#[test]
fn periodic_ring_hides_only_whole_smooth_wall_joins() {
let body = ring(256);
diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs
index 9afee86167..cab1c21104 100644
--- a/crates/kernel/src/splitface.rs
+++ b/crates/kernel/src/splitface.rs
@@ -24,10 +24,11 @@ pub enum SplitTool<'a> {
Plane(Plane),
/// The surface of another body's face (`face` in that body's face order), extended.
Face { body: &'a Body, face: usize },
- /// Sketch curves (chains of segments in `plane`) swept along the plane's normal; each curve
- /// splits on its own, extended past its ends. A single line or arc splits exactly (a plane
- /// or a cylinder); longer chains and splines follow the curve.
- Curves { plane: Plane, curves: Vec<Vec<Seg2>> },
+ /// Sketch curves (chains of segments in `plane`) swept along `along` (none: the plane's
+ /// normal); each curve splits on its own, an open one extended past its ends. A single line
+ /// splits exactly (a plane), and so does a single arc swept along the normal (a cylinder);
+ /// longer chains, splines and arcs swept aslant follow the curve.
+ Curves { plane: Plane, curves: Vec<Vec<Seg2>>, along: Option<Vec3> },
}
/// Which side of the tool a point is on (zero on the tool).
@@ -45,9 +46,13 @@ enum Field {
r: f64,
out: f64,
},
+ /// A chain of points in `plane`, swept along `along` (the plane's normal when none). A
+ /// closed chain is positive inside it; an open one on its left, its end segments extended.
Curve {
plane: Plane,
pts: Vec<Vec2>,
+ closed: bool,
+ along: Option<Vec3>,
},
}
@@ -68,9 +73,28 @@ impl Field {
let radial = v - *axis * v.dot(*axis);
*out * (radial.len() - *r)
}
- Field::Curve { plane, pts } => {
+ Field::Curve { plane, pts, closed, along } => {
+ // Where p's line along the sweep direction meets the plane.
+ let p = match along {
+ Some(d) => p - *d * ((p - plane.origin).dot(plane.normal()) / d.dot(plane.normal())),
+ None => p,
+ };
let q = plane.to_local(p);
let q = Vec2::new(q.x, q.y);
+ if *closed {
+ // Distance to the loop, positive inside it.
+ let d = (0..pts.len().saturating_sub(1))
+ .filter_map(|i| Some((*pts.get(i)?, *pts.get(i + 1)?)))
+ .map(|(a, b)| {
+ let d = b - a;
+ let l2 = d.dot(d);
+ let t = if l2 > 0.0 { ((q - a).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 };
+ (q - (a + d * t)).len()
+ })
+ .fold(f64::INFINITY, f64::min);
+ let uv: Vec<(f64, f64)> = pts.iter().map(|p| (p.x, p.y)).collect();
+ return if inside(&uv, (q.x, q.y)) { d } else { -d };
+ }
// Signed distance to the polyline, its end segments extended as lines.
let n = pts.len();
let mut best = (f64::INFINITY, 0.0);
@@ -119,6 +143,11 @@ struct Chain {
/// Mesh tolerance for tracing a face.
fn trace_tol(face: &mt::Face, size: f64) -> f64 {
let _ = face;
+ trace_tol_of(size)
+}
+
+/// Mesh tolerance for tracing on a body of this size.
+fn trace_tol_of(size: f64) -> f64 {
(size * 2e-3).max(1e-4)
}
@@ -989,18 +1018,36 @@ fn fields(tool: &SplitTool) -> Result<Vec<Field>> {
let f = other.solid.face_iter().nth(*face).ok_or_else(|| KernelError::Invalid(format!("the tool body has no face {face}")))?;
vec![surface_field(&f.oriented_surface())]
}
- SplitTool::Curves { plane, curves } => {
+ SplitTool::Curves { plane, curves, along } => {
+ let n = plane.normal();
+ // The sweep direction, turned to the plane's side (a direction along the plane sweeps
+ // nothing).
+ let along = match along {
+ None => None,
+ Some(d) => {
+ let d = d
+ .normalized()
+ .filter(|d| d.is_finite())
+ .ok_or_else(|| KernelError::Invalid("the projection direction must be a nonzero vector".into()))?;
+ if d.dot(n).abs() < 1e-6 {
+ return Err(KernelError::Invalid("the projection direction runs along the sketch plane".into()));
+ }
+ let d = if d.dot(n) < 0.0 { -d } else { d };
+ (d.cross(n).len() > 1e-12).then_some(d)
+ }
+ };
+ let sweep = along.unwrap_or(n);
let mut out = Vec::new();
for c in curves {
out.push(match c.as_slice() {
[Seg2::Line { a, b }] => {
let (wa, wb) = (plane.to_world(*a), plane.to_world(*b));
- let n = plane.normal().cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?;
+ let n = sweep.cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?;
Field::Plane { o: wa, n }
}
- [Seg2::Arc { center, radius, .. }] if radius.is_finite() && *radius > 0.0 => Field::Cylinder {
+ [Seg2::Arc { center, radius, .. }] if along.is_none() && radius.is_finite() && *radius > 0.0 => Field::Cylinder {
o: plane.to_world(*center),
- axis: plane.normal().unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?,
+ axis: n.unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?,
r: *radius,
out: 1.0,
},
@@ -1016,7 +1063,9 @@ fn fields(tool: &SplitTool) -> Result<Vec<Field>> {
if pts.len() < 2 || pts.iter().any(|p| !(p.x.is_finite() && p.y.is_finite())) || pts.len() > 1_000_000 {
return Err(KernelError::Invalid("split curves need finite segments".into()));
}
- Field::Curve { plane: *plane, pts }
+ let span = pts.iter().fold(0.0f64, |m, p| m.max(p.len()));
+ let closed = pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| (*a - *b).len() <= span * 1e-9 + 1e-9);
+ Field::Curve { plane: *plane, pts, closed, along }
}
});
}
@@ -1193,6 +1242,62 @@ fn chain_loops(edges: &[mt::Edge]) -> Result<Vec<Vec<mt::Edge>>> {
Ok(out)
}
+/// The regions of a body cut by a tool: for each face (in face order), the region it lies in,
+/// and how many there are. Faces are in one region when they meet at an edge the tool does not
+/// run along; an edge along the tool (a split line) parts them.
+pub(crate) fn regions(split: &Body, tool: &SplitTool) -> Result<(Vec<usize>, usize)> {
+ let fields = fields(tool)?;
+ let tol = trace_tol_of(split.size());
+ let faces: Vec<&mt::Face> = split.solid.face_iter().collect();
+ let mut along_tool: HashMap<mt::EdgeID, bool> = HashMap::new();
+ let mut by_edge: HashMap<mt::EdgeID, Vec<usize>> = HashMap::new();
+ for (i, f) in faces.iter().enumerate() {
+ for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) {
+ by_edge.entry(e.id()).or_default().push(i);
+ along_tool.entry(e.id()).or_insert_with(|| {
+ let c = e.curve();
+ let (t0, t1) = c.range_tuple();
+ let at: Vec<Vec3> = [0.25, 0.5, 0.75].iter().map(|s| from_p3(c.subs(t0 + (t1 - t0) * s))).collect();
+ fields.iter().any(|g| at.iter().all(|p| g.eval(*p).abs() <= tol))
+ });
+ }
+ }
+ let mut region = vec![usize::MAX; faces.len()];
+ let mut count = 0;
+ for s in 0..faces.len() {
+ if region.get(s) != Some(&usize::MAX) {
+ continue;
+ }
+ if let Some(r) = region.get_mut(s) {
+ *r = count;
+ }
+ let mut stack = vec![s];
+ while let Some(i) = stack.pop() {
+ let Some(f) = faces.get(i) else { continue };
+ for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) {
+ if along_tool.get(&e.id()).copied().unwrap_or(false) {
+ continue;
+ }
+ for &j in by_edge.get(&e.id()).into_iter().flatten() {
+ if let Some(r) = region.get_mut(j)
+ && *r == usize::MAX
+ {
+ *r = count;
+ stack.push(j);
+ }
+ }
+ }
+ }
+ count += 1;
+ }
+ Ok((region, count))
+}
+
+/// How many fields a tool is (a sketch tool: one per curve).
+pub(crate) fn field_count(tool: &SplitTool) -> Result<usize> {
+ Ok(fields(tool)?.len())
+}
+
/// Faces grouped by shared edges (in face order).
fn components(faces: Vec<mt::Face>) -> Vec<Vec<mt::Face>> {
let n = faces.len();
@@ -1484,7 +1589,7 @@ mod tests {
let side = c.faces(0.01).unwrap().iter().position(|f| f.plane_normal.is_none()).unwrap();
// A horizontal line seen from the front (XZ sketch) at z = 5, swept along y.
let xz = Plane { y: Vec3::Z, ..Plane::XZ };
- let tool = SplitTool::Curves { plane: xz, curves: vec![vec![Seg2::Line { a: Vec2::new(-20.0, 5.0), b: Vec2::new(20.0, 5.0) }]] };
+ let tool = SplitTool::Curves { plane: xz, curves: vec![vec![Seg2::Line { a: Vec2::new(-20.0, 5.0), b: Vec2::new(20.0, 5.0) }]], along: None };
let s = split_faces(&c, &[side], &tool).unwrap();
let m = measure(&s).unwrap();
// (Measured on meshes: curved faces agree to about 1e-4.)
@@ -1566,7 +1671,7 @@ mod tests {
let t = top(&b, 30.0);
let arc = Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: 6.0, start: 0.0, sweep: std::f64::consts::FRAC_PI_2 };
let plane = Plane { origin: Vec3::new(0.0, 0.0, 30.0), ..Plane::XY };
- let tool = SplitTool::Curves { plane, curves: vec![vec![arc]] };
+ let tool = SplitTool::Curves { plane, curves: vec![vec![arc]], along: None };
let (s, map) = split_faces_with_map(&b, &[t], &tool).unwrap();
assert_eq!(map.len(), s.face_count());
assert_eq!(map.iter().filter(|o| **o == t).count(), 2);
diff --git a/crates/kernel/src/surface_trim.rs b/crates/kernel/src/surface_trim.rs
new file mode 100644
index 0000000000..06b22abaa4
--- /dev/null
+++ b/crates/kernel/src/surface_trim.rs
@@ -0,0 +1,398 @@
+//! Trim: a surface body cut where a tool meets it (a plane, another body's face, or sketch
+//! curves swept onto it), keeping the side of a point or the regions points pick; and Mutual
+//! Trim: two surfaces cut by each other, each keeping its picked side, extended to meet first
+//! when one stops short of the other.
+
+use solidcraft_geom::Vec3;
+use truck_modeling as mt;
+
+use crate::body::Body;
+use crate::record::{Rebuild, rebuilt_body};
+use crate::splitface::{SplitTool, ToolSide};
+use crate::surface_extend::{ExtendLimit, ExtendMode, ExtendOptions};
+use crate::surfaces::surface_body;
+use crate::{KernelError, Result, guard};
+
+/// Most points one trim picks with.
+const MAX_PICKS: usize = 10_000;
+
+/// What a trim keeps.
+#[derive(Clone, Copy, Debug)]
+pub enum TrimKeep<'a> {
+ /// Every piece on the side of the tool this point is on. A tool of several sketch curves
+ /// has no one side: the region the point picks is kept.
+ Side(Vec3),
+ /// The regions the points pick (a region: the pieces that hang together once the tool has
+ /// cut the body, each picked by the piece nearest a point).
+ Regions(&'a [Vec3]),
+}
+
+impl TrimKeep<'_> {
+ fn points(&self) -> &[Vec3] {
+ match self {
+ TrimKeep::Side(p) => std::slice::from_ref(p),
+ TrimKeep::Regions(at) => at,
+ }
+ }
+
+ fn check(&self) -> Result<()> {
+ let at = self.points();
+ if at.is_empty() {
+ return Err(KernelError::Invalid("pick what to keep".into()));
+ }
+ if at.len() > MAX_PICKS {
+ return Err(KernelError::Invalid("too many points to keep".into()));
+ }
+ if at.iter().any(|p| !p.is_finite()) {
+ return Err(KernelError::Invalid("a point to keep is not finite".into()));
+ }
+ Ok(())
+ }
+}
+
+/// A surface body trimmed by a tool: its faces are cut where the tool meets them and the
+/// pieces on the side of `keep` are kept. The result's history is over `[body]`.
+pub fn trim(body: &Body, tool: &SplitTool, keep: Vec3) -> Result<Body> {
+ trim_keep(body, tool, TrimKeep::Side(keep))
+}
+
+/// A surface body trimmed by a tool, keeping what `keep` says. Each kept face is the face it is
+/// a piece of (its history is over `[body]`).
+pub fn trim_keep(body: &Body, tool: &SplitTool, keep: TrimKeep) -> Result<Body> {
+ body.require_brep("trim")?;
+ keep.check()?;
+ let total = body.solid.face_iter().count();
+ let all: Vec<usize> = (0..total).collect();
+ let (split, _) = crate::splitface::split_any(body, &all, tool)?;
+ let one_side = match keep {
+ TrimKeep::Side(p) if crate::splitface::field_count(tool)? == 1 => Some(crate::splitface::side_of_point(tool, p)?),
+ _ => None,
+ };
+ let picked = match one_side {
+ Some(_) => Vec::new(),
+ None => nearest_faces(&split, keep.points())?,
+ };
+ guard("trim", || {
+ let mut kept = Vec::new();
+ match one_side {
+ Some(side) => {
+ for f in split.solid.face_iter() {
+ let x = crate::splitface::face_side(f, tool, split.size())?;
+ if (x >= 0.0) == (side >= 0.0) {
+ kept.push(f.clone());
+ }
+ }
+ }
+ None => {
+ let (region, count) = crate::splitface::regions(&split, tool)?;
+ let mut wanted = vec![false; count];
+ for f in &picked {
+ if let Some(w) = region.get(*f).and_then(|r| wanted.get_mut(*r)) {
+ *w = true;
+ }
+ }
+ for (f, r) in split.solid.face_iter().zip(&region) {
+ if wanted.get(*r).copied().unwrap_or(false) {
+ kept.push(f.clone());
+ }
+ }
+ }
+ }
+ if kept.is_empty() {
+ return Err(KernelError::Invalid("nothing is left on that side of the tool".into()));
+ }
+ // The kept pieces are the split's own; its history carries them back to `body`.
+ let trimmed = rebuilt_body(surface_body(kept), &[&split.solid], &Rebuild::default());
+ Ok(crate::record::after(trimmed, &split, &crate::record::counts(&[body])))
+ })
+}
+
+/// For each point, the face of `body` nearest it (over one tessellation).
+fn nearest_faces(body: &Body, at: &[Vec3]) -> Result<Vec<usize>> {
+ let m = body.tessellate(body.size() * 2e-3)?;
+ at.iter()
+ .map(|p| {
+ let mut best: Option<(f64, u32)> = None;
+ for (t, f) in m.triangles.iter().zip(&m.tri_face) {
+ let Some([a, b, c]) = m.tri(t) else { continue };
+ let d = ((a + b + c) / 3.0).dist(*p).min(a.dist(*p)).min(b.dist(*p)).min(c.dist(*p));
+ if best.is_none_or(|(x, _)| d < x) {
+ best = Some((d, *f));
+ }
+ }
+ best.map(|(_, f)| f as usize).ok_or_else(|| KernelError::Invalid("no face there".into()))
+ })
+ .collect()
+}
+
+/// Two surface bodies trimmed by each other: `a` cut where `b`'s surface (extended) meets it,
+/// keeping what `keep_a` says, and `b` by `a`'s, keeping `keep_b`. A surface that stops short of
+/// the other is extended to meet it when `extend` is set (naturally, its nearest boundary edge
+/// up to the other's surface), else that is an error; one that ends on the other is kept whole.
+/// Each body must be one face (its surface is the other's tool). The results' histories are over
+/// `[a]` and `[b]`.
+pub fn mutual_trim(a: &Body, b: &Body, keep_a: TrimKeep, keep_b: TrimKeep, extend: bool) -> Result<(Body, Body)> {
+ for (x, name) in [(a, "first"), (b, "second")] {
+ x.require_brep("trim")?;
+ if !x.is_surface() {
+ return Err(KernelError::Invalid(format!("the {name} body is a solid: a mutual trim takes two surfaces")));
+ }
+ if x.face_count() != 1 {
+ return Err(KernelError::Invalid(format!(
+ "not supported yet: a mutual trim of a surface of more than one face (the {name} body has {}; trim it by one face instead)",
+ x.face_count()
+ )));
+ }
+ }
+ keep_a.check()?;
+ keep_b.check()?;
+ let ta = cut_by(a, &SplitTool::Face { body: b, face: 0 }, keep_a, extend, "first")?;
+ let tb = cut_by(b, &SplitTool::Face { body: a, face: 0 }, keep_b, extend, "second")?;
+ Ok((ta, tb))
+}
+
+/// `x` trimmed by `tool` where the tool crosses it; whole where it ends on the tool; extended to
+/// the tool first (when `extend`) where it stops short of it.
+fn cut_by(x: &Body, tool: &SplitTool, keep: TrimKeep, extend: bool, name: &str) -> Result<Body> {
+ let side = ToolSide::of(tool)?;
+ let size = x.size();
+ let touch = size * 1e-6 + 1e-9;
+ let m = x.tessellate(size * 2e-3)?;
+ let (mut lo, mut hi, mut near) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY);
+ for p in &m.positions {
+ let v = side.at(*p);
+ if !v.is_finite() {
+ return Err(KernelError::Failed("the other surface cannot be evaluated over this one".into()));
+ }
+ lo = lo.min(v);
+ hi = hi.max(v);
+ near = near.min(v.abs());
+ }
+ if lo < -touch && hi > touch {
+ return trim_keep(x, tool, keep);
+ }
+ if near <= touch {
+ return Ok(crate::boolean_record::operand(x, 0, &crate::record::counts(&[x])));
+ }
+ if !extend {
+ return Err(KernelError::Invalid(format!("the {name} surface does not reach the other one: extend it to meet")));
+ }
+ let edge = nearest_boundary_edge(x, &side)?;
+ let opts = ExtendOptions { mode: ExtendMode::Natural, limit: ExtendLimit::UpTo(tool), neighbours: true };
+ crate::extend_surface(x, &[edge], &opts)
+}
+
+/// A point in the middle of the boundary edge of `x` nearest the tool.
+fn nearest_boundary_edge(x: &Body, side: &ToolSide) -> Result<Vec3> {
+ guard("trim", || {
+ let mut uses: std::collections::HashMap<mt::EdgeID, (usize, mt::Edge)> = std::collections::HashMap::new();
+ for f in x.solid.face_iter() {
+ for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) {
+ uses.entry(e.id()).or_insert((0, e.clone())).0 += 1;
+ }
+ }
+ let mut best: Option<(f64, Vec3)> = None;
+ for (count, e) in uses.values() {
+ if *count != 1 {
+ continue;
+ }
+ use mt::{BoundedCurve, ParametricCurve};
+ let c = e.curve();
+ let (t0, t1) = c.range_tuple();
+ let mid = crate::body::from_p3(c.subs(0.5 * (t0 + t1)));
+ let d = side.at(mid).abs();
+ if d.is_finite() && best.is_none_or(|(b, _)| d < b) {
+ best = Some((d, mid));
+ }
+ }
+ best.map(|(_, p)| p).ok_or_else(|| KernelError::Invalid("the surface has no boundary edge to extend".into()))
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::history::{Change, FaceOrigin};
+ use crate::{extrude_sheet, measure, patch_region, stitch};
+ use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2};
+ use std::f64::consts::PI;
+
+ fn rel(a: f64, b: f64) -> f64 {
+ (a - b).abs() / b.abs().max(1e-12)
+ }
+
+ fn rect(plane: &Plane, u0: f64, v0: f64, u1: f64, v1: f64) -> Body {
+ let outer = Loop2::polygon(&[Vec2::new(u0, v0), Vec2::new(u1, v0), Vec2::new(u1, v1), Vec2::new(u0, v1)]);
+ patch_region(plane, &Region2 { outer, holes: vec![] }).unwrap()
+ }
+
+ fn area(b: &Body) -> f64 {
+ measure(b).unwrap().area
+ }
+
+ /// A U-shaped sheet (legs x = 0 and x = 10, 10 high, a base along y = 0, 10 deep in z) cut
+ /// by the plane y = 5: one side keeps both legs' tops, one region pick only one of them, two
+ /// picks both again.
+ #[test]
+ fn regions_keep_what_the_points_pick() {
+ let chain = vec![
+ Seg2::Line { a: Vec2::new(0.0, 10.0), b: Vec2::new(0.0, 0.0) },
+ Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) },
+ Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 10.0) },
+ ];
+ let u = extrude_sheet(&Plane::XY, &[chain], 0.0, 10.0).unwrap();
+ let cut = SplitTool::Plane(Plane::new(Vec3::new(0.0, 5.0, 0.0), Vec3::X, Vec3::Z).unwrap());
+ let side = trim(&u, &cut, Vec3::new(0.0, 8.0, 5.0)).unwrap();
+ assert!(rel(area(&side), 100.0) < 1e-9, "{}", area(&side));
+ let one = trim_keep(&u, &cut, TrimKeep::Regions(&[Vec3::new(0.0, 8.0, 5.0)])).unwrap();
+ assert!(rel(area(&one), 50.0) < 1e-9, "{}", area(&one));
+ let both = trim_keep(&u, &cut, TrimKeep::Regions(&[Vec3::new(0.0, 8.0, 5.0), Vec3::new(10.0, 9.0, 2.0)])).unwrap();
+ assert!(rel(area(&both), 100.0) < 1e-9, "{}", area(&both));
+ // The base side is one region: its three faces hang together.
+ let base = trim_keep(&u, &cut, TrimKeep::Regions(&[Vec3::new(5.0, 0.0, 5.0)])).unwrap();
+ assert!(rel(area(&base), 200.0) < 1e-9 && base.face_count() == 3, "{}", area(&base));
+ // Each kept face is a piece of the face it was cut from.
+ let h = one.history().unwrap();
+ assert_eq!(h.operands, 1);
+ assert!(
+ h.faces.iter().all(|f| f.change == Change::Modified && matches!(f.origins.as_slice(), [FaceOrigin::Face { operand: 0, .. }])),
+ "{h:?}"
+ );
+ }
+
+ /// A 10 × 10 square cut by two sketch lines (x = 3 and x = 7): a side is no answer for two
+ /// curves, so a point picks its region; two picks keep the two outer strips.
+ #[test]
+ fn several_curves_cut_regions() {
+ let sq = rect(&Plane::XY, 0.0, 0.0, 10.0, 10.0);
+ let lines = vec![
+ vec![Seg2::Line { a: Vec2::new(3.0, -5.0), b: Vec2::new(3.0, 15.0) }],
+ vec![Seg2::Line { a: Vec2::new(7.0, -5.0), b: Vec2::new(7.0, 15.0) }],
+ ];
+ let tool = SplitTool::Curves { plane: Plane { origin: Vec3::new(0.0, 0.0, 5.0), ..Plane::XY }, curves: lines, along: None };
+ let mid = trim(&sq, &tool, Vec3::new(5.0, 5.0, 0.0)).unwrap();
+ assert!(rel(area(&mid), 40.0) < 1e-9, "{}", area(&mid));
+ let outer = trim_keep(&sq, &tool, TrimKeep::Regions(&[Vec3::new(1.0, 5.0, 0.0), Vec3::new(9.0, 5.0, 0.0)])).unwrap();
+ assert!(rel(area(&outer), 60.0) < 1e-9 && outer.face_count() == 2, "{}", area(&outer));
+ }
+
+ /// A line sketched 10 above a 20 × 20 sheet at x = 5, swept along (1, 0, −1): it meets the
+ /// sheet at x = 15, so the side of x = 0 keeps 15 × 20. A direction along the sketch plane
+ /// is refused.
+ #[test]
+ fn curves_swept_aslant() {
+ let sq = rect(&Plane::XY, 0.0, 0.0, 20.0, 20.0);
+ let plane = Plane { origin: Vec3::new(0.0, 0.0, 10.0), ..Plane::XY };
+ let curves = vec![vec![Seg2::Line { a: Vec2::new(5.0, -5.0), b: Vec2::new(5.0, 25.0) }]];
+ let tool = SplitTool::Curves { plane, curves: curves.clone(), along: Some(Vec3::new(1.0, 0.0, -1.0)) };
+ let t = trim(&sq, &tool, Vec3::new(1.0, 5.0, 0.0)).unwrap();
+ assert!(rel(area(&t), 300.0) < 1e-9, "{}", area(&t));
+ let flat = SplitTool::Curves { plane, curves, along: Some(Vec3::X) };
+ assert!(trim(&sq, &flat, Vec3::new(1.0, 5.0, 0.0)).is_err());
+ }
+
+ /// The slot |x| ≤ 3 (a straight run z = 12…28 and round ends) sketched in front of a half
+ /// cylinder (radius 10 about Z, y ≥ 0, 40 high) and swept along the sketch's normal: the
+ /// piece inside it is ∫∫ R / √(R² − x²) dx dz over the slot (the straight run 16 · 2R·asin(3/R),
+ /// the two round ends one disc), the piece outside the rest of 10π · 40.
+ #[test]
+ fn a_slot_projected_onto_a_cylinder() {
+ let r: f64 = 10.0;
+ let half = extrude_sheet(&Plane::XY, &[vec![Seg2::Arc { center: Vec2::ZERO, radius: r, start: 0.0, sweep: PI }]], 0.0, 40.0).unwrap();
+ let a: f64 = 3.0;
+ let slot = vec![
+ Seg2::Line { a: Vec2::new(a, 12.0), b: Vec2::new(a, 28.0) },
+ Seg2::Arc { center: Vec2::new(0.0, 28.0), radius: a, start: 0.0, sweep: PI },
+ Seg2::Line { a: Vec2::new(-a, 28.0), b: Vec2::new(-a, 12.0) },
+ Seg2::Arc { center: Vec2::new(0.0, 12.0), radius: a, start: PI, sweep: PI },
+ ];
+ let front = Plane { y: Vec3::Z, ..Plane::XZ };
+ let tool = SplitTool::Curves { plane: front, curves: vec![slot], along: None };
+ // The round ends: x = a·sin φ, the disc's height 2a·cos φ, dx = a·cos φ dφ (Simpson).
+ let n = 4000;
+ let f = |phi: f64| 2.0 * a * a * phi.cos().powi(2) * r / (r * r - (a * phi.sin()).powi(2)).sqrt();
+ let h = PI / n as f64;
+ let ends = (0..=n)
+ .map(|k| {
+ let w = if k == 0 || k == n {
+ 1.0
+ } else if k % 2 == 1 {
+ 4.0
+ } else {
+ 2.0
+ };
+ w * f(-PI / 2.0 + h * k as f64)
+ })
+ .sum::<f64>()
+ * h
+ / 3.0;
+ let inside = 16.0 * 2.0 * r * (a / r).asin() + ends;
+ let on = Vec3::new(0.0, r, 20.0);
+ let kept = trim(&half, &tool, on).unwrap();
+ eprintln!("slot on the cylinder: {} measured, {inside} analytic", area(&kept));
+ // (Measured on meshes.)
+ assert!(rel(area(&kept), inside) < 1e-3, "{} vs {inside}", area(&kept));
+ let rest = trim(&half, &tool, Vec3::new(r, 0.0, 20.0)).unwrap();
+ let all = PI * r * 40.0;
+ assert!(rel(area(&rest), all - inside) < 1e-3, "{} vs {}", area(&rest), all - inside);
+ let picked = trim_keep(&half, &tool, TrimKeep::Regions(&[on])).unwrap();
+ assert!(rel(area(&picked), area(&kept)) < 1e-9);
+ }
+
+ /// Two 20 × 10 sheets crossing at right angles (z = 0 and x = 0, both y = 0…10) trimmed by
+ /// each other, each keeping its x > 0 / z > 0 half, and stitched: an L of two faces sharing
+ /// their edge, 200 in area.
+ #[test]
+ fn crossing_sheets_trim_each_other_into_an_l() {
+ let a = rect(&Plane::XY, -10.0, 0.0, 10.0, 10.0);
+ let yz = Plane::new(Vec3::ZERO, Vec3::Y, Vec3::Z).unwrap();
+ let b = rect(&yz, 0.0, -10.0, 10.0, 10.0);
+ let (ta, tb) = mutual_trim(&a, &b, TrimKeep::Side(Vec3::new(5.0, 5.0, 0.0)), TrimKeep::Side(Vec3::new(0.0, 5.0, 5.0)), false).unwrap();
+ assert!(rel(area(&ta), 100.0) < 1e-9 && rel(area(&tb), 100.0) < 1e-9);
+ let l = stitch(&[&ta, &tb], 0.0).unwrap();
+ assert_eq!((l.face_count(), l.edge_count()), (2, 7), "one shared edge");
+ assert!(rel(area(&l), 200.0) < 1e-9);
+ assert!(l.is_surface());
+ let bb = measure(&l).unwrap().bbox;
+ assert!(bb.min.x.abs() < 1e-9 && bb.min.z.abs() < 1e-9 && (bb.max.x - 10.0).abs() < 1e-9 && (bb.max.z - 10.0).abs() < 1e-9, "{bb:?}");
+ // The pieces are the sheets' faces.
+ for t in [&ta, &tb] {
+ let h = t.history().unwrap();
+ assert!(matches!(h.faces[0].origins.as_slice(), [FaceOrigin::Face { operand: 0, face: 0 }]) && h.faces[0].change == Change::Modified);
+ }
+ }
+
+ /// A sheet that stops 3 short of the other (x = 0, z = 3…10) is refused until extended to
+ /// meet it; extended, the two still make the L.
+ #[test]
+ fn a_short_sheet_is_extended_to_meet() {
+ let a = rect(&Plane::XY, -10.0, 0.0, 10.0, 10.0);
+ let yz = Plane::new(Vec3::ZERO, Vec3::Y, Vec3::Z).unwrap();
+ let b = rect(&yz, 0.0, 3.0, 10.0, 10.0);
+ let (ka, kb) = (TrimKeep::Side(Vec3::new(5.0, 5.0, 0.0)), TrimKeep::Side(Vec3::new(0.0, 5.0, 5.0)));
+ let e = mutual_trim(&a, &b, ka, kb, false).unwrap_err().to_string();
+ assert!(e.contains("extend"), "{e}");
+ let (ta, tb) = mutual_trim(&a, &b, ka, kb, true).unwrap();
+ assert!(rel(area(&ta), 100.0) < 1e-9 && rel(area(&tb), 100.0) < 1e-6, "{} {}", area(&ta), area(&tb));
+ let l = stitch(&[&ta, &tb], 0.0).unwrap();
+ assert_eq!((l.face_count(), l.edge_count()), (2, 7));
+ }
+
+ #[test]
+ fn hostile_trims_are_refused() {
+ let a = rect(&Plane::XY, 0.0, 0.0, 10.0, 10.0);
+ let cut = SplitTool::Plane(Plane::new(Vec3::new(3.0, 0.0, 0.0), Vec3::Y, Vec3::Z).unwrap());
+ assert!(trim_keep(&a, &cut, TrimKeep::Regions(&[])).is_err());
+ assert!(trim_keep(&a, &cut, TrimKeep::Regions(&[Vec3::new(f64::NAN, 0.0, 0.0)])).is_err());
+ assert!(trim(&a, &cut, Vec3::new(f64::INFINITY, 0.0, 0.0)).is_err());
+ let many = vec![Vec3::ZERO; MAX_PICKS + 1];
+ assert!(trim_keep(&a, &cut, TrimKeep::Regions(&many)).is_err());
+ let solid = crate::box_solid(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0)).unwrap();
+ assert!(mutual_trim(&a, &solid, TrimKeep::Side(Vec3::ZERO), TrimKeep::Side(Vec3::ZERO), true).is_err());
+ let chain =
+ vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(5.0, 0.0) }, Seg2::Line { a: Vec2::new(5.0, 0.0), b: Vec2::new(5.0, 5.0) }];
+ let two = extrude_sheet(&Plane::XY, &[chain], 0.0, 5.0).unwrap();
+ let e = mutual_trim(&a, &two, TrimKeep::Side(Vec3::ZERO), TrimKeep::Side(Vec3::ZERO), true).unwrap_err().to_string();
+ assert!(e.contains("not supported yet"), "{e}");
+ }
+}
diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs
index b7c0ed0157..6031f4859a 100644
--- a/crates/kernel/src/surfaces.rs
+++ b/crates/kernel/src/surfaces.rs
@@ -1098,31 +1098,6 @@ pub fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result<Body> {
})
}
-/// A surface body trimmed by a tool: its faces are cut where the tool meets them and the
-/// pieces on the side of `keep` are kept. The result's history is over `[body]`.
-pub fn trim(body: &Body, tool: &crate::SplitTool, keep: Vec3) -> Result<Body> {
- body.require_brep("trim")?;
- let total = body.solid.face_iter().count();
- let all: Vec<usize> = (0..total).collect();
- let (split, _) = crate::splitface::split_any(body, &all, tool)?;
- let side = crate::splitface::side_of_point(tool, keep)?;
- guard("trim", || {
- let mut kept = Vec::new();
- for f in split.solid.face_iter() {
- let x = crate::splitface::face_side(f, tool, split.size())?;
- if (x >= 0.0) == (side >= 0.0) {
- kept.push(f.clone());
- }
- }
- if kept.is_empty() {
- return Err(KernelError::Invalid("nothing is left on that side of the tool".into()));
- }
- // The kept pieces are the split's own; its history carries them back to `body`.
- let trimmed = rebuilt_body(surface_body(kept), &[&split.solid], &Rebuild::default());
- Ok(crate::record::after(trimmed, &split, &crate::record::counts(&[body])))
- })
-}
-
/// A planar surface extended: the chosen straight edges (picked by points on them) move
/// outward in the face's plane by `distance`, their neighbours lengthened to meet them. The
/// result's history is over `[body]`: the face and each edge the one it was moved from.
@@ -1196,7 +1171,7 @@ pub fn extend(body: &Body, at: &[Vec3], distance: f64) -> Result<Body> {
#[cfg(test)]
mod tests {
use super::*;
- use crate::{box_solid, cylinder, measure};
+ use crate::{box_solid, cylinder, measure, trim};
use solidcraft_geom::{Loop2, Vec2};
fn rel(a: f64, b: f64) -> f64 {
diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs
index a984cf3e23..397ce0fa87 100644
--- a/crates/ui-egui/src/dialogs_surface.rs
+++ b/crates/ui-egui/src/dialogs_surface.rs
@@ -5,7 +5,7 @@
use serde_json::{Map, Value, json};
use solidcraft_engine::Sel;
use solidcraft_engine::doc::expr::Kind as ValueKind;
-use solidcraft_engine::doc::{AxisRef, Direction, FaceAt, FeatureKind, Mat, PlaneRef, ProfileSel, RuledCorners, RuledMode};
+use solidcraft_engine::doc::{AxisRef, Direction, FaceAt, FeatureKind, Mat, PlaneRef, Position, ProfileSel, RuledCorners, RuledMode};
use solidcraft_engine::geom::Vec3;
use crate::SolveApp;
@@ -65,7 +65,12 @@ pub enum Surf {
Extend {
distance: String,
},
- Trim,
+ /// `direction`: the stored sweep direction of trimming curves (none: the sketch's normal).
+ Trim {
+ extend: bool,
+ stitch: bool,
+ direction: Option<Vec3>,
+ },
/// `holes`: an index into [`UNTRIM_HOLES`].
Untrim {
holes: usize,
@@ -91,7 +96,7 @@ impl Surf {
Surf::Stitch { .. } => "STITCH",
Surf::Thicken { .. } => "THICKEN",
Surf::Extend { .. } => "EXTEND",
- Surf::Trim => "TRIM",
+ Surf::Trim { .. } => "TRIM",
Surf::Untrim { .. } => "UNTRIM",
Surf::SplitFace => "SPLIT FACE",
}
@@ -151,10 +156,12 @@ fn inputs(k: &Surf) -> Vec<SelInput> {
Surf::Stitch { .. } => vec![SelInput::new("Surfaces", BODIES, true)],
Surf::Thicken { .. } => vec![SelInput::new("Surfaces", BODIES, true)],
Surf::Extend { .. } => vec![SelInput::new("Edges", EDGES, true)],
- Surf::Trim => vec![
+ Surf::Trim { .. } => vec![
SelInput::new("Surface", BODIES, false),
- SelInput::new("Trimming tool", PLANES | FACES, false),
- SelInput::new("Side to keep", FACES, false),
+ SelInput::new("Trimming tool (plane, face or curves)", PLANES | FACES | CURVES, true),
+ SelInput::new("Keep (points on it)", FACES, true).places(),
+ SelInput::new("Other surface (mutual trim)", BODIES, false),
+ SelInput::new("Keep of the other surface", FACES, true).places(),
],
Surf::Untrim { .. } => vec![SelInput::new("Face", FACES, false), SelInput::new("Holes (edges on them)", EDGES, true)],
Surf::SplitFace => vec![SelInput::new("Faces to split", FACES, true), SelInput::new("Splitting tool", PLANES | FACES, false)],
@@ -177,7 +184,7 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
"surface.stitch" => Surf::Stitch { tolerance: String::new() },
"surface.thicken" => Surf::Thicken { thickness: "2 mm".into(), symmetric: false, operation: 0 },
"surface.extend" => Surf::Extend { distance: "10 mm".into() },
- "surface.trim" => Surf::Trim,
+ "surface.trim" => Surf::Trim { extend: false, stitch: false, direction: None },
"surface.untrim" => Surf::Untrim { holes: 0, outer: false, in_place: false },
"solid.split_face" => Surf::SplitFace,
_ => return None,
@@ -288,8 +295,16 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool {
*join = op == 1;
ui.end_row();
}
+ Surf::Trim { extend, stitch, .. } => {
+ row_label(ui, "Extend to meet");
+ ui.checkbox(extend, "");
+ ui.end_row();
+ row_label(ui, "Stitch the kept pieces");
+ ui.checkbox(stitch, "");
+ ui.end_row();
+ }
Surf::Sweep(opts) => enter |= crate::dialogs_sweep::rows(ui, opts, "ss"),
- Surf::Trim | Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {}
+ Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {}
}
enter
}
@@ -673,18 +688,52 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map<Strin
items(inputs, 0).iter().filter_map(|x| if let Sel::Edge { point, .. } = x { Some(pt(*point)) } else { None }).collect();
("surface.extend", json!({"body": body, "edges": edges, "distance": distance}))
}
- Surf::Trim => {
+ Surf::Trim { extend, stitch, direction } => {
need(0, "the surface to trim")?;
- need(1, "the trimming tool")?;
- need(2, "the side to keep (a point on it)")?;
+ need(2, "what to keep (points on it)")?;
let body = bodies(inputs, 0).into_iter().next().unwrap_or_default();
- let (key, t) = tool(app, items(inputs, 1).first())?;
- let keep = items(inputs, 2)
- .first()
- .and_then(|x| if let Sel::Face { point, .. } = x { Some(pt(*point)) } else { None })
- .ok_or("pick the side to keep")?;
- let mut p = json!({"body": body, "keep": keep});
- p[key] = t;
+ // One point keeps its side, several the regions they pick.
+ let points = |i: usize| -> Option<Value> {
+ let pts: Vec<Value> =
+ items(inputs, i).iter().filter_map(|x| if let Sel::Face { point, .. } = x { Some(pt(*point)) } else { None }).collect();
+ match pts.as_slice() {
+ [] => None,
+ [one] => Some(one.clone()),
+ _ => Some(json!(pts)),
+ }
+ };
+ let mut p = json!({"body": body, "keep": points(2).ok_or("pick what to keep")?});
+ if let Some(other) = bodies(inputs, 3).into_iter().next() {
+ need(4, "what to keep of the other surface")?;
+ p["with"] = json!(other);
+ p["keep_with"] = points(4).ok_or("pick what to keep of the other surface")?;
+ if *extend {
+ p["extend"] = json!(true);
+ }
+ if *stitch {
+ p["stitch"] = json!(true);
+ }
+ } else {
+ need(1, "the trimming tool")?;
+ let picks = items(inputs, 1);
+ let curves: Vec<String> =
+ picks.iter().filter_map(|x| if let Sel::SketchCurve { id } = x { Some(id.clone()) } else { None }).collect();
+ if curves.is_empty() {
+ let [one] = picks else { return Err("pick one plane or face as the tool, or sketch curves".into()) };
+ let (key, t) = tool(app, Some(one))?;
+ p[key] = t;
+ } else {
+ if curves.len() != picks.len() {
+ return Err("trim by sketch curves, or by one plane or face".into());
+ }
+ let sketch = crate::dialogs::curves_sketch(app, &curves, None).ok_or("the curves must be in one sketch")?;
+ let mut c = json!({"sketch": sketch, "curves": curves});
+ if let Some(d) = direction {
+ c["direction"] = pt(*d);
+ }
+ p["curves"] = c;
+ }
+ }
("surface.trim", p)
}
Surf::Untrim { holes, outer, in_place } => {
@@ -950,14 +999,30 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K
}
return Some((Kind::Surface(k), ins, extra));
}
- FeatureKind::SurfaceTrim { body, plane, tool, keep } => (
- Surf::Trim,
- vec![
- vec![Sel::Body { name: body.to_string() }],
- tool_sel(app, plane, tool.as_ref()).into_iter().collect(),
- crate::dialogs::face_sel(s, keep.0).into_iter().collect(),
- ],
- ),
+ FeatureKind::SurfaceTrim { body, plane, tool, keep, keep_more, curves, with, keep_with, stitch, extend } => {
+ let faces = |pts: &mut dyn Iterator<Item = &Position>| -> Vec<Sel> { pts.filter_map(|p| crate::dialogs::face_sel(s, p.0)).collect() };
+ let tools: Vec<Sel> = match (with, curves) {
+ (Some(_), _) => Vec::new(),
+ (None, Some(c)) if c.curves.is_empty() => {
+ let st = s.world_state();
+ st.sketch(c.sketch.0)
+ .map(|ss| ss.sketch.curves.iter().filter(|k| !k.construction).map(|k| Sel::SketchCurve { id: k.id.clone() }).collect())
+ .unwrap_or_default()
+ }
+ (None, Some(c)) => c.curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect(),
+ (None, None) => tool_sel(app, plane, tool.as_ref()).into_iter().collect(),
+ };
+ (
+ Surf::Trim { extend: *extend, stitch: *stitch, direction: curves.as_ref().and_then(|c| c.direction.map(|d| d.0)) },
+ vec![
+ vec![Sel::Body { name: body.to_string() }],
+ tools,
+ faces(&mut std::iter::once(keep).chain(keep_more)),
+ with.iter().map(|n| Sel::Body { name: n.to_string() }).collect(),
+ faces(&mut keep_with.iter()),
+ ],
+ )
+ }
FeatureKind::SurfaceUntrim { face, holes, outer, in_place } => {
let (index, picked) = match holes {
None => (0, Vec::new()),
diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs
index bfb7471286..d2ca0d5482 100644
--- a/crates/ui-egui/src/preselect_tests.rs
+++ b/crates/ui-egui/src/preselect_tests.rs
@@ -1544,6 +1544,59 @@ fn ruled_surface_dialog_takes_edges_a_face_and_a_direction() {
assert_eq!((&p["params"]["mode"], &p["params"]["direction"]), (&json!("direction"), &json!([0.0, 0.0, 1.0])), "{p}");
}
+#[test]
+fn trim_dialog_takes_curves_several_keep_points_and_another_surface() {
+ // Two 20 × 10 sheets crossing at x = 0 / z = 0 and a sketch line x = 3 on XY.
+ let mut app = app_with(json!([
+ {"command": "sketch.create", "params": {"plane": "XY", "name": "F"}},
+ {"command": "sketch.rectangle.two_point", "params": {"p0": [-10, 0], "p1": [10, 10]}},
+ {"command": "sketch.finish", "params": {}},
+ {"command": "surface.patch", "params": {"sketch": "F", "body_name": "Floor"}},
+ {"command": "sketch.create", "params": {"plane": "YZ", "name": "W"}},
+ {"command": "sketch.rectangle.two_point", "params": {"p0": [0, -10], "p1": [10, 10]}},
+ {"command": "sketch.finish", "params": {}},
+ {"command": "surface.patch", "params": {"sketch": "W", "body_name": "Wall"}},
+ {"command": "sketch.create", "params": {"plane": "XY", "name": "Cut"}},
+ {"command": "sketch.line", "params": {"points": [[3, -5], [3, 15]], "ids": ["c1"]}},
+ {"command": "sketch.finish", "params": {}}
+ ]));
+ let face = |body: &str, p: [f64; 3]| Sel::Face { body: body.into(), index: 0, point: Vec3::new(p[0], p[1], p[2]) };
+ let mut d = start(&mut app, vec![], "surface.trim");
+ assert_eq!(d.inputs.len(), 5);
+ d.inputs[0].items = vec![Sel::Body { name: "Floor".into() }];
+ d.inputs[1].items = vec![Sel::SketchCurve { id: "c1".into() }];
+ // Two places on the one face both count (a face pick would toggle the face off).
+ d.inputs[2].toggle(vec![face("Floor", [1.0, 5.0, 0.0])]);
+ d.inputs[2].toggle(vec![face("Floor", [-5.0, 5.0, 0.0])]);
+ assert_eq!(d.inputs[2].items.len(), 2);
+ let (id, p) = apply_commands(&app, &d).unwrap().remove(0);
+ assert_eq!(p["curves"]["curves"], json!(["c1"]), "{p}");
+ assert_eq!(p["keep"], json!([[1.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]), "{p}");
+ app.session.execute(&id, &p).unwrap();
+ let area = |app: &SolveApp, n: &str| app.session.world_state().body(n).unwrap().mesh().measure().area;
+ assert!((area(&app, "Floor") - 130.0).abs() < 1e-6, "{}", area(&app, "Floor"));
+ app.session.execute("edit.undo", &json!({})).unwrap();
+ // Mutual: the other surface replaces the tool; stitched into an L.
+ d.inputs[1].items.clear();
+ d.inputs[2].items = vec![face("Floor", [5.0, 5.0, 0.0])];
+ d.inputs[3].items = vec![Sel::Body { name: "Wall".into() }];
+ assert!(apply_commands(&app, &d).is_err(), "nothing kept of the wall yet");
+ d.inputs[4].items = vec![face("Wall", [0.0, 5.0, 5.0])];
+ if let Kind::Surface(crate::dialogs_surface::Surf::Trim { stitch, .. }) = &mut d.kind {
+ *stitch = true;
+ }
+ let (id, p) = apply_commands(&app, &d).unwrap().remove(0);
+ assert_eq!((&p["with"], &p["keep_with"], &p["stitch"]), (&json!("Wall"), &json!([0.0, 5.0, 5.0]), &json!(true)), "{p}");
+ assert!(p.get("extend").is_none() && p.get("plane").is_none(), "{p}");
+ app.session.execute(&id, &p).unwrap();
+ assert!((area(&app, "Floor") - 200.0).abs() < 1e-6 && app.session.world_state().body("Wall").is_none());
+ let fid = app.session.doc.features.last().unwrap().id;
+ let back = crate::dialogs::for_feature(&app, fid, None).unwrap();
+ assert!(matches!(back.kind, Kind::Surface(crate::dialogs_surface::Surf::Trim { stitch: true, extend: false, direction: None })));
+ let counts: Vec<usize> = back.inputs.iter().map(|i| i.items.len()).collect();
+ assert_eq!(counts, [1, 0, 1, 1, 1]);
+}
+
#[test]
fn untrim_dialog_takes_a_face_its_holes_and_the_outer_boundary() {
// A 40 × 20 × 2 plate with three holes: its top untrimmed (every hole) is the whole 800 mm²
diff --git a/crates/ui-egui/src/selection.rs b/crates/ui-egui/src/selection.rs
index e4480ea137..e9f460f4bf 100644
--- a/crates/ui-egui/src/selection.rs
+++ b/crates/ui-egui/src/selection.rs
@@ -46,12 +46,21 @@ pub struct SelInput {
pub accept: Accept,
/// Many items (clicks toggle them), or one (a click replaces it).
pub multi: bool,
+ /// Face picks are places on the face, not the face: several on one face add up (a click on
+ /// the very spot of one takes it out). For points that pick pieces a face is cut into.
+ pub places: bool,
pub items: Vec<Sel>,
}
impl SelInput {
pub fn new(label: &'static str, accept: Accept, multi: bool) -> SelInput {
- SelInput { label, accept, multi, items: Vec::new() }
+ SelInput { label, accept, multi, places: false, items: Vec::new() }
+ }
+
+ /// This input with face picks as places (see [`SelInput::places`]).
+ pub fn places(mut self) -> SelInput {
+ self.places = true;
+ self
}
/// The selection a hit stands for, if this input accepts it.
@@ -85,11 +94,17 @@ impl SelInput {
return;
}
// A pick of something already in (or a chain fully in) takes it out.
- if picked.iter().all(|p| self.items.iter().any(|x| same_item(x, p))) {
- self.items.retain(|x| !picked.iter().any(|p| same_item(x, p)));
+ let places = self.places;
+ // Whether two picks are the same item of this input.
+ let same = |a: &Sel, b: &Sel| match (a, b) {
+ (Sel::Face { point: p, .. }, Sel::Face { point: q, .. }) if places => same_item(a, b) && p.dist(*q) <= 1e-9,
+ _ => same_item(a, b),
+ };
+ if picked.iter().all(|p| self.items.iter().any(|x| same(x, p))) {
+ self.items.retain(|x| !picked.iter().any(|p| same(x, p)));
} else {
for p in picked {
- if !self.items.iter().any(|x| same_item(x, &p)) {
+ if !self.items.iter().any(|x| same(x, &p)) {
self.items.push(p);
}
}