Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Cut tool (Line, Lasso, Rectangle, Polyline; Away, In, Add), Mask Front faces only, Duplicate Part shortcut
islandmed7f47a11a286e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5607791..a8b0732c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,16 @@ All notable changes to SculptForge are listed here. The format follows## [Unreleased]+### Added+- Cut (#101, #91): one tool that cuts the active Part with a Line, Lasso, Rectangle or Polyline drawn on the screen,+ in the Ctrl+Shift brush picker and in Tool > Cut. Away removes what the shape covers through the whole Part and+ closes the cut with a flat cap (a face group of its own), In cuts a flat-bottomed pocket Depth deep, Add extrudes+ the shape out of the surface (boolean union). An exact boolean in screen space: the uncut surface and its mask,+ colours, UVs and layers are kept, and the result is watertight. Follows X/Y/Z and radial symmetry; one undo step.+ Scriptable as the `cut` command.+- Mask Lasso and Mask Rectangle: Front faces only (#91), also `front_faces_only` on mask_lasso / mask_rect.+- Duplicate Part shortcut: Ctrl+Shift+D (also Duplicate Part in the command palette).+## [0.10.8] - 2026-11-02### Fixeddiff --git a/CMakeLists.txt b/CMakeLists.txtindex dd947ce2..5c7b2751 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -67,6 +67,7 @@ add_library(sculptforge_core STATICsrc/core/Voxel.cppsrc/core/EnginePresets.cppsrc/core/Masking.cpp+ src/core/Cut.cppsrc/core/BrushAlpha.cppsrc/core/Stroke.cppsrc/core/PathStroke.cpp@@ -287,6 +288,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/UserGuide.cppsrc/app/AssetLibrary.cppsrc/app/PanelMasking.cpp+ src/app/PanelCut.cppsrc/app/PanelPolygroups.cppsrc/app/PanelSelectionSets.cppsrc/app/Selection.cppdiff --git a/REPLY.md b/REPLY.mdnew file mode 100644index 00000000..0dd60825--- /dev/null+++ b/REPLY.md@@ -0,0 +1,10 @@+# Replies (drafts; post after the 0.10.9 release)++**GitHub #101 (lostpackets)**+Cut is in 0.10.9: one tool with Line, Lasso, Rectangle and Polyline shapes. Hold Ctrl+Shift and pick a Cut shape (or open Tool > Cut). Away cuts through the Part and closes it with a flat cap, In cuts a flat-bottomed pocket, and Add raises the shape out of the surface. The result stays watertight and follows symmetry. Guide: Cut (Help > User Guide). Please reopen if something you use trimming for is missing.++**GitHub #91 (Devon0209)**+Two of your items are in 0.10.9. (1) Cut: Line, Lasso, Rectangle and Polyline, with Away (trim plus a flat cap), In (pocket) and Add (union). Ctrl+Shift picks the shape, Tool > Cut picks the mode. (3) Tool > Masking > Front faces only: Mask Lasso and Mask Rectangle leave the far side alone. X-ray (2) and the colour palette with an eyedropper (4) are still queued; I'll update here when they're scheduled.++**Discord #ideas (ABHITAR, Duplicate Part shortcut)**+Done for 0.10.9: Ctrl+Shift+D duplicates the active Part. It's also Duplicate Part in the command palette (F3) and still in the Parts list's right-click menu. You can rebind it like any other shortcut.diff --git a/TESTERS.md b/TESTERS.mdnew file mode 100644index 00000000..abf0dc4d--- /dev/null+++ b/TESTERS.md@@ -0,0 +1,7 @@+# Testers: Cut, Front faces only, Duplicate Part (0.10.9 preview)++- **Cut, any OS, mouse and pen:** load a sphere or your own sculpt. Hold Ctrl+Shift, open the brush picker and try Cut Line, Cut Lasso, Cut Rectangle, and Cut Polyline (click the points, then click the first one again to close, or double-click to end it open). Try each with Tool > Cut > Away, In and Add. Good: it matches the orange preview, the cap is flat, Ctrl+Z undoes it in one step, and the model stays closed (no holes along the cut).+- **Cut with symmetry on (X) and with two Parts:** only the active Part is cut, and the mirror side matches. Good: no holes, no stray slivers along the cut, and the other Part is unchanged.+- **Windows display scaling 125/150/175 % and a display tablet (Wacom, Huion, XP-Pen):** draw a Cut Polyline with the pen. Good: points land where the pen taps, the close circle around the first point is easy to hit, Enter or a double-tap ends it, and Esc drops it.+- **Masking > Front faces only:** with Mask Lasso, mask across the whole model with the option on, then rotate. Good: the back stays unmasked; with the option off, the back is masked as before.+- **Ctrl+Shift+D:** duplicates the active Part (it shows as "<name> copy" under the original). Good: it doesn't fire while you type in a text field, and Blender-style keys still work.diff --git a/docs/guide/cut.md b/docs/guide/cut.mdnew file mode 100644index 00000000..746f80e5--- /dev/null+++ b/docs/guide/cut.md@@ -0,0 +1,57 @@+# Cut: line, lasso, rectangle and polyline++**Cut** cuts the active Part with a shape you draw on the screen. The shape is pushed straight into the view, so+what you see inside it is what gets cut, front and back. Every cut is one undo step, and a closed Part stays+closed (watertight), so you can keep sculpting, remeshing or 3D printing it.++## Pick a shape++Hold <kbd>Ctrl</kbd>+<kbd>Shift</kbd> and click the brush tile on the shelf (or press <kbd>B</kbd>) to pick a Cut+shape next to **Select Rectangle** and **Select Lasso**, or use the shape buttons at the top of **Tool > Cut**:++| Shape | How to draw it |+| --- | --- |+| **Cut Line** | <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+drag a straight line. The shaded side is cut; hold <kbd>Alt</kbd> as you let go to cut the other side. |+| **Cut Lasso** | <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+drag a free-hand outline. Its inside is cut. A lasso that crosses itself keeps its biggest loop. |+| **Cut Rectangle** | <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+drag a rectangle. Its inside is cut. |+| **Cut Polyline** | <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+click point after point. Click the first point again to cut the polygon; double-click or press <kbd>Enter</kbd> to cut along the open, bent line (the shaded side; <kbd>Alt</kbd> for the other); <kbd>Esc</kbd> drops it. |++While a Cut shape is picked, <kbd>Ctrl</kbd>+<kbd>Shift</kbd> cuts instead of hiding; pick **Select Rectangle**+or **Select Lasso** again to hide parts of the model.++## Pick a mode++**Tool > Cut** has three modes:++| Mode | What it does |+| --- | --- |+| **Away** | Removes everything the shape covers, through the whole Part, and closes the cut with a flat cap. A line slices the Part in two and keeps one side; a lasso or rectangle drawn inside the outline cuts a hole right through. |+| **In** | Cuts a flat-bottomed pocket where the shape covers the Part. **Depth** sets how deep, measured from the nearest point under the shape. |+| **Add** | Adds the shape, extruded towards you by **Depth** and joined to the Part (a boolean union): panels, ridges, buttons, sockets. |++**Depth** is a share of the Part's size (0.10 = a tenth of its largest side), so it means the same on a small or+large model.++## What the cut keeps++- The surface outside the cut is kept exactly, with its mask, vertex colours, UVs, face groups and sculpt layers;+ only the triangles the shape crosses are split.+- The cap (and the walls of a pocket or added shape) are a **face group of their own**, so you can select, mask or+ hide them in one click ([Face Groups](face-groups.md)).+- The caps are flat with long triangles. To sculpt on them, give the Part even topology first:+ **Tool > Remesh** or Dynamic topology ([Subdivide, remesh, decimate and LODs](geometry.md)).+- Only the active Part is cut; the other [Parts](parts.md) are untouched. Cut each Part on its own, or merge them+ first.+- With symmetry on (**X**, **Y**, **Z** or radial on the top shelf), the mirror image of the shape cuts too.++An open Part (a plane, a scan with holes) is trimmed without a cap. **Add** needs a closed Part. Forge Spheres+and Parts with a micro level must be made into a plain mesh first.++> **ZBrush:** this covers what the trim, clip and slice curve brushes and Live Boolean are used for, as one tool.+> SculptForge is not affiliated with Maxon or ZBrush.++## Scripting++The `cut` command takes the shape (`line`, `lasso`, `rect`, `polyline`), its `points` in normalised screen+coordinates, the `mode` (`away`, `in`, `add`), `depth`, `flip`, `closed` and an optional `view_proj` matrix; see+[Scripting](scripting.md).diff --git a/docs/guide/index.md b/docs/guide/index.mdindex ded3451a..afb69ab3 100644--- a/docs/guide/index.md+++ b/docs/guide/index.md@@ -42,6 +42,7 @@ You can read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<23. [Sculpt Timeline and timelapse](timeline.md)24. [Moving, rotating and posing (Gizmo)](gizmo.md)25. [Subdivide, remesh, decimate and LODs](geometry.md)+ - [Cut: line, lasso, rectangle and polyline](cut.md)26. [Quad retopology and detail projection](retopology.md)## AI and capturediff --git a/docs/guide/masking.md b/docs/guide/masking.mdindex 2042302b..d9766d35 100644--- a/docs/guide/masking.md+++ b/docs/guide/masking.md@@ -65,6 +65,10 @@ mask stroke mirrors. A shape that covers none of the model clears the mask inste**Mask Strength** sets how much a selection masks or unmasks, and each selection is one undo step. A lasso thatcrosses itself leaves out the areas it encloses twice.+Turn on **Front faces only** (under the shape buttons, shown for Mask Lasso and Mask Rectangle) to mask only what+faces you: the far side of the model and folds turned away from you are left as they are. It follows the mirror+image too when symmetry is on.+The cursor turns into a small cross while <kbd>Ctrl</kbd> is held, since the brush size doesn't matter for aselection.diff --git a/docs/guide/parts.md b/docs/guide/parts.mdindex 326adbf2..b2074d71 100644--- a/docs/guide/parts.md+++ b/docs/guide/parts.md@@ -34,7 +34,7 @@ and they catch up a moment after you stop changing a Part (not during a stroke).| Select a Part | Click its row, or <kbd>Alt</kbd>+click it in the viewport; triple-click another Part in the viewport to select it and frame it || Rename it | Double-click the row (or right-click > **Rename**), type, press <kbd>Enter</kbd> || Hide or show it | Click the eye at the end of the row |-| Duplicate or delete it | Right-click the row > **Duplicate** or **Delete...** |+| Duplicate or delete it | Right-click the row > **Duplicate** (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>D</kbd>) or **Delete...** || See its vertex and triangle counts | Point at the row for a moment |The list shows six rows and scrolls when there are more. Names are kept unique: renaming a Part to a name that@@ -74,7 +74,8 @@ You can also add files as Parts from elsewhere:- In the [Library](interface.md) **Tool** tab, <kbd>Shift</kbd>+double-click a model, or right-click itand choose **Append as Part**.-> **Tip:** **Duplicate** copies the active Part with its layers and attributes, names it `<name> copy` and puts it+> **Tip:** **Duplicate** (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>D</kbd>, also in the command palette as+> **Duplicate Part**) copies the active Part with its layers and attributes, names it `<name> copy` and puts it> right under the original. Use it to keep a safe copy before a destructive step such as a remesh.## Show, hide and solodiff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.mdindex d8920df6..ac597509 100644--- a/docs/guide/whats-new.md+++ b/docs/guide/whats-new.md@@ -5,6 +5,16 @@ chapter opens by itself the first time you start a new version; you can always f**Help > What's New**. Every detail is in the[changelog](https://github.com/islandmed/SculptForge/blob/main/CHANGELOG.md).+## Version 0.10.9++- **Cut**: one tool that cuts the active Part with a **Line**, **Lasso**, **Rectangle** or **Polyline**. **Away**+ removes what the shape covers and closes the cut with a flat cap, **In** cuts a flat-bottomed pocket and **Add**+ raises the shape out of the surface. The result stays watertight and follows the symmetry. Hold+ <kbd>Ctrl</kbd>+<kbd>Shift</kbd> and pick a Cut shape, or open **Tool > Cut**. See [Cut](cut.md) (#101, #91).+- **Mask: Front faces only**: Mask Lasso and Mask Rectangle can leave the far side alone+ ([Masking](masking.md#mask-with-a-lasso-or-rectangle), #91).+- **Duplicate Part** has a shortcut: <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>D</kbd> ([Parts](parts.md)).+## Version 0.10.8- **Tablets in mouse mode work again**: on some Windows tablets with **Mouse mode** on (Preferences > Tablet) thediff --git a/src/app/App.cpp b/src/app/App.cppindex 08c6194c..01159ac5 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -1583,6 +1583,7 @@ void App::onMouseUp() {}void App::onKey(SDL_Keycode key, SDL_Keymod mod) {+ if (cutPolylineKey(key)) return; // Enter ends a Cut Polyline, Esc drops it (PanelCut.cpp)if (key == SDLK_ESCAPE && radial_.menu >= 0) {closeRadialMenu();return;diff --git a/src/app/App.h b/src/app/App.hindex 34fbdfa2..1ea16793 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -529,10 +529,25 @@ private:bool polygroupMouseDown(float x, float y, SDL_Keymod mod); // true if it took the clickvoid polygroupMouseUp();void drawPolygroupsSection();+ // Cut (PanelCut.cpp, core/Cut.h): Ctrl+Shift with a Cut shape. Line, Lasso and Rectangle are dragged; Polyline+ // is clicked point by point (click the first point to close it, double-click or Enter to end it open, Esc drops it).+ void cutMouseUp();+ bool cutPolylineMouseDown(float x, float y, SDL_Keymod mod); // true if it took the click+ bool cutPolylineKey(SDL_Keycode key); // Enter / Esc while placing points+ void finishCutPolyline(bool closed);+ void runCut(const char* shape, const std::vector<ImVec2>& path, bool closed, bool flip);+ void drawCutOverlay();+ void drawCutSection();+ bool maskFrontFacesOnly_ = false; // Mask Lasso / Rectangle: only vertices facing the viewer (#91.3)+ int cutMode_ = 0; // 0 Away, 1 In, 2 Add (core/Cut.h)+ float cutDepth_ = 0.1f; // In / Add: fraction of the Part's size+ std::vector<ImVec2> cutPolyline_; // window pixels of the Polyline being placed// Screen selections (Selection.cpp): the rectangle or lasso dragged for// visibility (Ctrl+Shift, ZBrush SelectRect / SelectLasso) or for the mask// (Ctrl, MaskRect / MaskLasso). Pen is the mask's brush-stroke mode.- enum class SelectShape { Pen, Lasso, Rect };+ // The Cut shapes share the Ctrl+Shift drag with SelectRect / SelectLasso (PanelCut.cpp).+ enum class SelectShape { Pen, Lasso, Rect, CutLine, CutLasso, CutRect, CutPolyline };+ static bool isCutShape(SelectShape s) { return s >= SelectShape::CutLine; }enum class SelectTarget { Hide, Mask };void beginSelection(float x, float y, SelectTarget target, SelectShape shape);void selectionMove(float x, float y);diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 7174c9cf..c5e5bf0e 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -365,6 +365,10 @@ void App::initActions() {"Write the micro level as a 32-bit EXR displacement map over the base UVs (next to the project).");add("geometry.micro_noise", "Micro Surface Noise", "Tool > Geometry", nullptr, [this] { runCommand("micro_noise"); }, nullptr,"micro_noise", nullptr, [this] { return hasMicro(doc_.mesh); });+ add("subtool.duplicate", "Duplicate Part", "Tool > Parts", "Ctrl+Shift+D", [this] { runCommand("subtool_duplicate"); },+ ICON_LC_COPY, "subtool_duplicate", nullptr, nullptr,+ "Copy the active Part, with its layers and attributes, and make the copy active (also in the Parts list's "+ "right-click menu).");// Tool > SubTool > Extract, Tool > Geometry > Modify Topology, Tool > Deformation (PanelExtract.cpp).add("subtool.extract", "Extract", "Tool > Parts", nullptr, [this] { runExtract(); }, nullptr, "extract", nullptr,[this] { return doc_.mesh.hasMask(); },diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 64f74029..8c25210e 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -204,6 +204,13 @@ constexpr Entry kSpanish[] = {{"Pressure > Size", "Presión > Tamaño"},{"Pressure > Strength", "Presión > Fuerza"},{"Front faces only", "Solo caras frontales"},+ {"Ctrl+Shift+drag with a Cut shape (Alt flips a line)", "Ctrl+Mayús+arrastrar con una forma de Corte (Alt cambia el lado de la línea)"},+ {"Depth %.2f", "Profundidad %.2f"},+ {"Copy the active Part (%s)", "Copiar la Parte activa (%s)"},+ {"Mask Lasso and Mask Rectangle mask only what faces you: the far side and folds turned away stay as they are.",+ "Mask Lasso y Mask Rectangle enmascaran solo lo que mira hacia ti: el lado de atrás y los pliegues que no te miran no cambian."},+ {"How deep Cut In goes, or how far Cut Add stands out, as a share of the Part's size.",+ "Cuánto entra Cut In, o cuánto sobresale Cut Add, como fracción del tamaño de la Parte."},{"Invert (Alt)", "Invertir (Alt)"},{"Invert", "Invertir"},{"Smooth keeps volume", "Smooth conserva el volumen"},diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 36025693..1407354e 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -766,6 +766,10 @@ void App::drawPalette_Tool() {drawDeformationContents(); // Mirror (PanelExtract.cpp)Demo::popScope();}+ if (subpalette("tool.cut", "Cut")) {+ tray::Section section;+ drawCutSection(); // PanelCut.cpp+ }if (subpalette("tool.masking", "Masking")) {tray::Section section;drawMaskingSection();diff --git a/src/app/PanelCut.cpp b/src/app/PanelCut.cppnew file mode 100644index 00000000..e8237da2--- /dev/null+++ b/src/app/PanelCut.cpp@@ -0,0 +1,183 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Cut (#101, #91; core/Cut.h): the Cut shapes sit in the Ctrl+Shift brush picker next to Select Rectangle and+// Select Lasso. Ctrl+Shift+drag a line, lasso or rectangle (Alt turns a line round); Cut Polyline places points+// with Ctrl+Shift+click. Tool > Cut picks the mode (Away, In, Add) and the depth. Each cut is one "cut" command+// with the shape in normalised device coordinates and the current view, mirrored by the symmetry.+#include "app/App.h"+#include "app/I18n.h"+#include "app/Ui.h"++#include <cmath>+#include <cstdio>++namespace sf {++namespace {++constexpr float kCloseRadiusPx = 9.0f; // a Polyline click this close to its first point closes it++const char* modeName(int mode) { return mode == 1 ? "in" : mode == 2 ? "add" : "away"; }++// Which side of a -> b a line (or the first segment of an open polyline) cuts: the left in NDC (y up), which is the+// left on the screen too; `flip` takes the right.+ImVec2 sideOf(ImVec2 a, ImVec2 b, bool flip) {+ const float dx = b.x - a.x, dy = b.y - a.y, len = std::max(std::hypot(dx, dy), 1e-3f);+ // Screen y runs down: the left of the drawing direction is (dy, -dx).+ return flip ? ImVec2(-dy / len, dx / len) : ImVec2(dy / len, -dx / len);+}++} // namespace++void App::runCut(const char* shape, const std::vector<ImVec2>& path, bool closed, bool flip) {+ const CanvasRect c = canvasRect();+ if (c.w <= 0.0f || c.h <= 0.0f || path.size() < 2) return;+ std::string points;+ char buf[48];+ for (const ImVec2& p : path) {+ std::snprintf(buf, sizeof buf, "%s%.5f %.5f", points.empty() ? "" : " ", double((p.x - c.x) / c.w * 2.0f - 1.0f),+ double(1.0f - (p.y - c.y) / c.h * 2.0f));+ points += buf;+ }+ const glm::mat4 vp = camera_.projection() * camera_.view();+ std::string matrix;+ for (int i = 0; i < 16; ++i) {+ std::snprintf(buf, sizeof buf, "%s%.9g", i ? " " : "", double(vp[i / 4][i % 4]));+ matrix += buf;+ }+ runCommand("cut", withSymmetryArgs({{"shape", std::string(shape)},+ {"points", points},+ {"mode", std::string(modeName(cutMode_))},+ {"depth", double(cutDepth_)},+ {"closed", closed},+ {"flip", flip},+ {"view_proj", matrix}}));+}++void App::cutMouseUp() {+ if (!selectMoved_) return; // a click cuts nothing+ const bool alt = (inputMods() & SDL_KMOD_ALT) != 0;+ std::vector<ImVec2> path = selectPath_;+ const ImVec2 mouse(mouseX_, mouseY_);+ switch (selectShape_) {+ case SelectShape::CutLine: runCut("line", {path.front(), mouse}, false, alt); break;+ case SelectShape::CutRect: runCut("rect", {path.front(), mouse}, false, false); break;+ case SelectShape::CutLasso:+ path.push_back(mouse);+ if (path.size() >= 3) runCut("lasso", path, true, false);+ break;+ default: break;+ }+}++bool App::cutPolylineMouseDown(float x, float y, SDL_Keymod mod) {+ const bool ctrlShift = (mod & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) && (mod & SDL_KMOD_SHIFT);+ if (cutPolyline_.empty() && (!ctrlShift || hideShape_ != SelectShape::CutPolyline || previewLod_ >= 0)) return false;+ if (cutPolyline_.size() >= 3 && std::hypot(x - cutPolyline_.front().x, y - cutPolyline_.front().y) < kCloseRadiusPx * uiScale_) {+ finishCutPolyline(true);+ return true;+ }+ if (!cutPolyline_.empty() && mouseClicks_ >= 2) { // double-click: end it open, at this point+ finishCutPolyline(false);+ return true;+ }+ if (cutPolyline_.empty() || std::hypot(x - cutPolyline_.back().x, y - cutPolyline_.back().y) > 2.0f)+ cutPolyline_.push_back(ImVec2(x, y));+ status_ = "Cut Polyline: click to add points, the first point to close, double-click or Enter to end, Esc to drop";+ return true;+}++bool App::cutPolylineKey(SDL_Keycode key) {+ if (cutPolyline_.empty()) return false;+ if (key == SDLK_ESCAPE) {+ cutPolyline_.clear();+ status_ = "Cut Polyline dropped";+ return true;+ }+ if (key == SDLK_RETURN || key == SDLK_KP_ENTER) {+ finishCutPolyline(false);+ return true;+ }+ return false;+}++void App::finishCutPolyline(bool closed) {+ std::vector<ImVec2> path;+ path.swap(cutPolyline_);+ if (path.size() < (closed ? 3u : 2u)) return;+ runCut("polyline", path, closed, (inputMods() & SDL_KMOD_ALT) != 0);+}++void App::drawCutOverlay() {+ const bool dragging = drag_ == Drag::Select && selectMoved_ && !selectPath_.empty() && isCutShape(selectShape_);+ if (!dragging && cutPolyline_.empty()) return;+ const bool alt = (inputMods() & SDL_KMOD_ALT) != 0;+ // Orange: what the cut takes away (Away, In) or adds (Add).+ const ImU32 line = cutMode_ == 2 ? IM_COL32(120, 220, 255, 235) : IM_COL32(255, 150, 70, 235);+ const ImU32 fill = cutMode_ == 2 ? IM_COL32(120, 220, 255, 45) : IM_COL32(255, 150, 70, 45);+ ImDrawList* dl = ImGui::GetForegroundDrawList();+ const CanvasRect c = canvasRect();+ dl->PushClipRect(ImVec2(c.x, c.y), ImVec2(c.x + c.w, c.y + c.h), true);+ const ImVec2 mouse(mouseX_, mouseY_);+ const float far = (c.w + c.h) * 2.0f;+ // A line or open polyline: the path, and the side it cuts shaded out to the canvas edge.+ auto openPath = [&](std::vector<ImVec2> path, bool flip) {+ if (path.size() < 2) return;+ const ImVec2 s = sideOf(path[0], path[1], flip), e = sideOf(path[path.size() - 2], path.back(), flip);+ const ImVec2 d0(path[1].x - path[0].x, path[1].y - path[0].y), d1(path.back().x - path[path.size() - 2].x,+ path.back().y - path[path.size() - 2].y);+ const float l0 = std::max(std::hypot(d0.x, d0.y), 1e-3f), l1 = std::max(std::hypot(d1.x, d1.y), 1e-3f);+ const ImVec2 start(path[0].x - d0.x / l0 * far, path[0].y - d0.y / l0 * far);+ const ImVec2 end(path.back().x + d1.x / l1 * far, path.back().y + d1.y / l1 * far);+ std::vector<ImVec2> poly{start};+ poly.insert(poly.end(), path.begin(), path.end());+ poly.push_back(end);+ poly.push_back(ImVec2(end.x + e.x * far, end.y + e.y * far));+ poly.push_back(ImVec2(start.x + s.x * far, start.y + s.y * far));+ dl->AddConcavePolyFilled(poly.data(), int(poly.size()), fill);+ dl->AddPolyline(path.data(), int(path.size()), line, ImDrawFlags_None, 2.0f);+ };+ if (!cutPolyline_.empty()) {+ std::vector<ImVec2> path = cutPolyline_;+ path.push_back(mouse);+ const bool closing = cutPolyline_.size() >= 3 &&+ std::hypot(mouse.x - cutPolyline_.front().x, mouse.y - cutPolyline_.front().y) < kCloseRadiusPx * uiScale_;+ if (closing) {+ path.back() = cutPolyline_.front();+ dl->AddConcavePolyFilled(path.data(), int(path.size()), fill);+ dl->AddPolyline(path.data(), int(path.size()), line, ImDrawFlags_Closed, 2.0f);+ } else {+ openPath(path, alt);+ }+ for (const ImVec2& p : cutPolyline_) dl->AddCircleFilled(p, 3.5f * uiScale_, line);+ dl->AddCircle(cutPolyline_.front(), kCloseRadiusPx * uiScale_, line, 0, 1.0f);+ } else if (selectShape_ == SelectShape::CutLine) {+ openPath({selectPath_.front(), mouse}, alt);+ } else if (selectShape_ == SelectShape::CutRect) {+ const ImVec2 a = selectPath_.front();+ const ImVec2 p0(std::fmin(a.x, mouse.x), std::fmin(a.y, mouse.y)), p1(std::fmax(a.x, mouse.x), std::fmax(a.y, mouse.y));+ dl->AddRectFilled(p0, p1, fill);+ dl->AddRect(p0, p1, line, 0.0f, 0, 2.0f);+ } else {+ std::vector<ImVec2> path = selectPath_;+ path.push_back(mouse);+ dl->AddConcavePolyFilled(path.data(), int(path.size()), fill);+ dl->AddPolyline(path.data(), int(path.size()), line, ImDrawFlags_Closed, 2.0f);+ }+ dl->PopClipRect();+}++void App::drawCutSection() {+ ImGui::TextDisabled("%s", tr("Ctrl+Shift+drag with a Cut shape (Alt flips a line)"));+ ui::Segmented(*this, {"cut.line", "cut.lasso", "cut.rect", "cut.polyline"});+ ui::Segmented(*this, {"cut.away", "cut.in", "cut.add"});+ if (cutMode_ != 0) {+ ImGui::SetNextItemWidth(-1);+ ui::SliderInside("##cutdepth", &cutDepth_, 0.01f, 1.0f, tr("Depth %.2f"));+ ui::HelpText("Depth", nullptr, tr("How deep Cut In goes, or how far Cut Add stands out, as a share of the Part's size."),+ "Tool > Cut");+ }+}++} // namespace sfdiff --git a/src/app/PanelMasking.cpp b/src/app/PanelMasking.cppindex 31f79612..6c7890b9 100644--- a/src/app/PanelMasking.cpp+++ b/src/app/PanelMasking.cpp@@ -133,7 +133,8 @@ void App::maskSelectMouseUp() {// Mask the inside, or unmask it with Alt (Mask Strength sets how much), mirrored by the symmetry like a mask// stroke (#51). A shape that covers none of the model clears the mask instead (ZBrush).runSelection("mask_rect", "mask_lasso",- withSymmetryArgs({{"unmask", alt}, {"strength", double(maskStrength_)}, {"clear_outside", !alt}}));+ withSymmetryArgs({{"unmask", alt}, {"strength", double(maskStrength_)}, {"clear_outside", !alt},+ {"front_faces_only", maskFrontFacesOnly_}}));}App::HeldBrush App::heldBrush() const {@@ -149,7 +150,11 @@ std::vector<App::HeldBrushItem> App::heldBrushItems(HeldBrush held) {{"mask.rect", "Mask Rectangle", "Rect", ICON_LC_SQUARE_DASHED, SelectShape::Rect}};if (held == HeldBrush::Select)return {{"select.rect", "Select Rectangle", "Rect", ICON_LC_SQUARE_DASHED, SelectShape::Rect},- {"select.lasso", "Select Lasso", "Lasso", ICON_LC_LASSO, SelectShape::Lasso}};+ {"select.lasso", "Select Lasso", "Lasso", ICON_LC_LASSO, SelectShape::Lasso},+ {"cut.line", "Cut Line", "Line", ICON_LC_SLASH, SelectShape::CutLine},+ {"cut.lasso", "Cut Lasso", "Lasso", ICON_LC_SCISSORS, SelectShape::CutLasso},+ {"cut.rect", "Cut Rectangle", "Rect", ICON_LC_SQUARE_DASHED, SelectShape::CutRect},+ {"cut.polyline", "Cut Polyline", "Polyline", ICON_LC_WAYPOINTS, SelectShape::CutPolyline}};return {};}@@ -183,7 +188,8 @@ bool App::drawHeldBrushGrid(HeldBrush held, bool strokes) {}const std::string help = strokes ? std::string("Stroke of ") + it.brush + ". " + (a ? a->description : ""): (a ? a->description : std::string());- ui::HelpText(label, nullptr, help.c_str(), held == HeldBrush::Mask ? "Tool > Masking" : "Tool > Visibility");+ ui::HelpText(label, nullptr, help.c_str(),+ held == HeldBrush::Mask ? "Tool > Masking" : isCutShape(it.shape) ? "Tool > Cut" : "Tool > Visibility");}return picked;}@@ -194,6 +200,13 @@ void App::drawMaskingSection() {ImGui::TextDisabled("%s", tr(maskShape_ == SelectShape::Pen ? "(Ctrl paints, Ctrl+Alt erases)": "(Ctrl masks, Ctrl+Alt unmasks)"));ui::Segmented(*this, {"mask.pen", "mask.lasso", "mask.rect"});+ if (maskShape_ != SelectShape::Pen) { // #91.3+ ImGui::Checkbox(tr("Front faces only##mask"), &maskFrontFacesOnly_);+ ui::HelpText("Front faces only", nullptr,+ tr("Mask Lasso and Mask Rectangle mask only what faces you: the far side and folds turned away "+ "stay as they are."),+ "Tool > Masking");+ }ImGui::SetNextItemWidth(-1);ui::SliderInside("##maskstrength", &maskStrength_, 0.01f, 1.0f, "Mask Strength %.2f");diff --git a/src/app/PanelPolygroups.cpp b/src/app/PanelPolygroups.cppindex b1f4ce80..9b812b87 100644--- a/src/app/PanelPolygroups.cpp+++ b/src/app/PanelPolygroups.cpp@@ -24,6 +24,7 @@ bool ctrlShiftDown(SDL_Keymod mod) {} // namespacebool App::polygroupMouseDown(float x, float y, SDL_Keymod mod) {+ if (cutPolylineMouseDown(x, y, mod)) return true; // Cut Polyline places points (PanelCut.cpp)if (!ctrlShiftDown(mod) || previewLod_ >= 0) return false;beginSelection(x, y, SelectTarget::Hide, hideShape_);return true;diff --git a/src/app/PanelSubTools.cpp b/src/app/PanelSubTools.cppindex 81d0c9d0..325393d7 100644--- a/src/app/PanelSubTools.cpp+++ b/src/app/PanelSubTools.cpp@@ -278,7 +278,7 @@ void App::drawSubToolsContents() {focusRename_ = true;std::snprintf(renameBuffer_, sizeof renameBuffer_, "%s", s.name.c_str());}- if (ImGui::MenuItem(tr("Duplicate"))) duplicateIndex = i;+ if (ImGui::MenuItem(tr("Duplicate"), actions_.shortcutText("subtool.duplicate").c_str())) duplicateIndex = i;if (ImGui::MenuItem(tr("Delete..."), nullptr, false, count > 1)) deleteIndex = i;ImGui::EndPopup();}@@ -409,6 +409,7 @@ void App::drawSubToolsContents() {}ImGui::SameLine();if (ImGui::Button(tr("Duplicate"), ImVec2(third, 0))) runCommand("subtool_duplicate");+ if (ImGui::IsItemHovered()) ImGui::SetTooltip(tr("Copy the active Part (%s)"), actions_.shortcutText("subtool.duplicate").c_str());ImGui::SameLine();ImGui::BeginDisabled(count < 2);if (ImGui::Button(tr("Delete..."), ImVec2(third, 0)))diff --git a/src/app/Selection.cpp b/src/app/Selection.cppindex c1fccdfe..e6b75d04 100644--- a/src/app/Selection.cpp+++ b/src/app/Selection.cpp@@ -67,13 +67,15 @@ void App::selectionMove(float x, float y) {const ImVec2 start = selectPath_.front();if (!selectMoved_ && std::abs(x - start.x) < kClickSlopPx && std::abs(y - start.y) < kClickSlopPx) return;selectMoved_ = true;- if (selectShape_ != SelectShape::Lasso) return; // a rectangle only needs the cursor+ if (selectShape_ != SelectShape::Lasso && selectShape_ != SelectShape::CutLasso) return; // a rectangle or line only needs the cursorconst ImVec2 last = selectPath_.back();if (std::hypot(x - last.x, y - last.y) >= kLassoSpacingPx) selectPath_.push_back(ImVec2(x, y));}void App::selectionMouseUp() {- if (selectTarget_ == SelectTarget::Hide)+ if (isCutShape(selectShape_))+ cutMouseUp(); // PanelCut.cpp+ else if (selectTarget_ == SelectTarget::Hide)polygroupMouseUp();elsemaskSelectMouseUp();@@ -111,7 +113,8 @@ bool App::runSelection(const char* rectCommand, const char* lassoCommand, Args a}void App::drawSelectionOverlay() {- if (drag_ != Drag::Select || !selectMoved_ || selectPath_.empty()) return;+ drawCutOverlay(); // the Cut shapes draw their own (PanelCut.cpp)+ if (drag_ != Drag::Select || !selectMoved_ || selectPath_.empty() || isCutShape(selectShape_)) return;// Visibility: green keeps the inside, red hides it (Alt). Mask: a dark veil masks, blue unmasks (Alt).const bool alt = (inputMods() & SDL_KMOD_ALT) != 0;ImU32 line, fill;diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex e947616f..dc9c30c2 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -430,6 +430,24 @@ void App::registerShellActions() {"Ctrl+Shift+drag a rectangle to keep what's inside and hide the rest; add Alt to hide the inside.");shape("select.lasso", "Select Lasso", "Tool > Visibility", &hideShape_, SelectShape::Lasso,"Ctrl+Shift+drag a lasso to keep what's inside and hide the rest; add Alt to hide the inside.");+ // Cut (PanelCut.cpp, core/Cut.h): the same Ctrl+Shift drag, cutting instead of hiding.+ shape("cut.line", "Cut Line", "Tool > Cut", &hideShape_, SelectShape::CutLine,+ "Ctrl+Shift+drag a line: the shaded side is cut (Alt: the other side). Away removes it through the whole "+ "Part and closes the cut flat; In steps it down by Depth; Add raises it.");+ shape("cut.lasso", "Cut Lasso", "Tool > Cut", &hideShape_, SelectShape::CutLasso,+ "Ctrl+Shift+drag a lasso: Away cuts a hole through the Part, In a pocket Depth deep, Add raises the shape.");+ shape("cut.rect", "Cut Rectangle", "Tool > Cut", &hideShape_, SelectShape::CutRect,+ "Ctrl+Shift+drag a rectangle: Away cuts a hole through the Part, In a pocket Depth deep, Add a block.");+ shape("cut.polyline", "Cut Polyline", "Tool > Cut", &hideShape_, SelectShape::CutPolyline,+ "Ctrl+Shift+click points: click the first point to cut the polygon, double-click or Enter to cut along an "+ "open bent line (Alt: the other side), Esc to drop it.");+ auto cutMode = [this](std::string id, std::string label, int mode, std::string description) {+ actions_.add({std::move(id), std::move(label), nullptr, std::move(description), "Tool > Cut", "", "",+ [this, mode] { cutMode_ = mode; }, [this, mode] { return cutMode_ == mode; }, nullptr});+ };+ cutMode("cut.away", "Away", 0, "Remove what the shape covers, through the whole Part, and close the cut with a flat cap.");+ cutMode("cut.in", "In", 1, "Cut a flat-bottomed pocket Depth deep where the shape covers the Part.");+ cutMode("cut.add", "Add", 2, "Add the shape, extruded Depth out of the surface, joined to the Part.");flag("draw.pressure_strength", "Pressure > Strength", nullptr, "Draw > Tablet", "", &pressureStrength_,"Pen pressure scales the brush strength.");flag("draw.pressure_size", "Pressure > Size", nullptr, "Draw > Tablet", "", &pressureSize_,diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 02ae0080..c5a24f40 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -18,6 +18,7 @@#include "core/HardwareProfile.h"#include "core/ImageTo3D.h"#include "core/Masking.h"+#include "core/Cut.h"#include "core/Multires.h"#include "core/Micro.h"#include "core/MeshTransform.h"@@ -804,6 +805,7 @@ CommandRegistry::CommandRegistry() {}});registerMaskingCommands(*this);+ registerCutCommands(*this); // cut (core/Cut.h)registerPolygroupCommands(*this);registerSelectionSetCommands(*this); // selection_set_* (core/SelectionSets.h)registerSubToolCommands(*this);@@ -830,7 +832,7 @@ CommandRegistry::CommandRegistry() {void CommandRegistry::add(Command cmd) {// The commands that follow the brushes' symmetry take radial and local symmetry too (#63).static const char* const kSymmetric[] = {"stroke", "vdm_stamp", "mask_rect", "mask_lasso", "hide_rect",- "hide_lasso", "insert_primitive", "insert_mesh"};+ "hide_lasso", "insert_primitive", "insert_mesh", "cut"};for (const char* name : kSymmetric)if (cmd.name == name)for (ParamSpec& p : radialSymmetryParams()) cmd.params.push_back(std::move(p));diff --git a/src/core/Cut.cpp b/src/core/Cut.cppnew file mode 100644index 00000000..e92ab05b--- /dev/null+++ b/src/core/Cut.cpp@@ -0,0 +1,1336 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Cut: an exact boolean between a mesh and a screen polygon extruded along the view (see Cut.h).+//+// Everything happens in normalised device coordinates (doubles), where the extrusion is a straight prism: walls+// standing on the polygon's edges and two caps at constant depth. Each wall and cap is a "face" of the prism.+// Intersection points come in two kinds, keyed so both sides of every edge find the same one:+// A - a mesh edge crossing a prism face (key: the edge's vertices and the face),+// B - a prism edge piercing a mesh triangle (key: the prism edge and the triangle).+// The segments where a triangle meets a face join those points. Each cut triangle and each prism face is then+// split along its segments into regions (a planar graph, holes bridged, ear-clipped), and every region is kept or+// dropped by which side of the other surface it lies on, read off locally at one of its segments. A mesh vertex+// lying exactly on the prism makes the arrangement degenerate, so the prism is nudged by a tiny random amount (and+// again, a bit more, whenever a test lands too close to call).+#include "core/Cut.h"++#include "core/Commands.h"+#include "core/Masking.h"+#include "core/PaintLayer.h"+#include "core/ScreenSelect.h"+#include "core/Sculpt.h"+#include "core/Document.h"++#include <glm/gtc/matrix_inverse.hpp>++#include <algorithm>+#include <array>+#include <cstdlib>+#include <memory>+#include <cmath>+#include <numeric>+#include <random>+#include <unordered_map>++namespace sf {++const char* cutShapeName(CutShape s) {+ switch (s) {+ case CutShape::Line: return "line";+ case CutShape::Lasso: return "lasso";+ case CutShape::Rect: return "rect";+ case CutShape::Polyline: return "polyline";+ }+ return "lasso";+}++const char* cutModeName(CutMode m) {+ switch (m) {+ case CutMode::Away: return "away";+ case CutMode::In: return "in";+ case CutMode::Add: return "add";+ }+ return "away";+}++bool parseCutShape(const std::string& name, CutShape& out) {+ for (CutShape s : {CutShape::Line, CutShape::Lasso, CutShape::Rect, CutShape::Polyline})+ if (name == cutShapeName(s)) {+ out = s;+ return true;+ }+ if (name == "rectangle") {+ out = CutShape::Rect;+ return true;+ }+ return false;+}++bool parseCutMode(const std::string& name, CutMode& out) {+ for (CutMode m : {CutMode::Away, CutMode::In, CutMode::Add})+ if (name == cutModeName(m)) {+ out = m;+ return true;+ }+ return false;+}++namespace {++using glm::dvec2;+using glm::dvec3;+using glm::dvec4;++double cross2(dvec2 a, dvec2 b) { return a.x * b.y - a.y * b.x; }+double orient2(dvec2 a, dvec2 b, dvec2 c) { return cross2(b - a, c - a); }++double signedArea(const std::vector<dvec2>& p) {+ double a = 0.0;+ for (size_t i = 0; i < p.size(); ++i) a += cross2(p[i], p[(i + 1) % p.size()]);+ return 0.5 * a;+}++// Proper crossing of segments ab and cd (not at their ends); `t` = where along ab.+bool segmentsCross(dvec2 a, dvec2 b, dvec2 c, dvec2 d, double& t) {+ const double d1 = orient2(c, d, a), d2 = orient2(c, d, b), d3 = orient2(a, b, c), d4 = orient2(a, b, d);+ if (!(((d1 > 0) != (d2 > 0)) && ((d3 > 0) != (d4 > 0)))) return false;+ if (d1 == 0 || d2 == 0 || d3 == 0 || d4 == 0) return false;+ t = d1 / (d1 - d2);+ return true;+}++// Removes near-duplicate points, then cuts a self-crossing outline at its first crossing and keeps the larger+// loop, until it is simple. Counter-clockwise on return.+bool simplifyOutline(std::vector<dvec2>& p) {+ std::vector<dvec2> q;+ for (const dvec2& v : p)+ if (q.empty() || glm::length(v - q.back()) > 1e-7) q.push_back(v);+ while (q.size() > 1 && glm::length(q.front() - q.back()) <= 1e-7) q.pop_back();+ p.swap(q);+ for (size_t guard = 0; guard < 4096 && p.size() >= 3; ++guard) {+ const size_t n = p.size();+ bool crossed = false;+ for (size_t i = 0; i < n && !crossed; ++i)+ for (size_t j = i + 2; j < n && !crossed; ++j) {+ if (i == 0 && j == n - 1) continue; // neighbours through the closing edge+ double t;+ if (!segmentsCross(p[i], p[(i + 1) % n], p[j], p[(j + 1) % n], t)) continue;+ const dvec2 x = p[i] + (p[(i + 1) % n] - p[i]) * t;+ std::vector<dvec2> a{x}, b{x};+ for (size_t k = i + 1; k <= j; ++k) a.push_back(p[k]);+ for (size_t k = j + 1; k < n; ++k) b.push_back(p[k]);+ for (size_t k = 0; k <= i; ++k) b.push_back(p[k]);+ p = std::abs(signedArea(a)) >= std::abs(signedArea(b)) ? a : b;+ crossed = true;+ }+ if (!crossed) break;+ }+ if (p.size() < 3) return false;+ if (signedArea(p) < 0) std::reverse(p.begin(), p.end());+ return std::abs(signedArea(p)) > 1e-10;+}++// A simple polygon with an even-odd inside test, edges bucketed into horizontal bands.+struct Poly2 {+ std::vector<dvec2> p;+ dvec2 lo{0.0}, hi{0.0};+ double bandH = 1.0;+ std::vector<std::vector<uint32_t>> bands;++ explicit Poly2(std::vector<dvec2> pts) : p(std::move(pts)) {+ lo = hi = p[0];+ for (const dvec2& v : p) {+ lo = glm::min(lo, v);+ hi = glm::max(hi, v);+ }+ const size_t nb = std::clamp<size_t>(p.size(), 1, 1024);+ bandH = std::max((hi.y - lo.y) / double(nb), 1e-300);+ bands.resize(nb);+ for (uint32_t i = 0; i < p.size(); ++i) {+ const dvec2 a = p[i], b = p[(i + 1) % p.size()];+ const size_t b0 = band(std::min(a.y, b.y)), b1 = band(std::max(a.y, b.y));+ for (size_t k = b0; k <= b1; ++k) bands[k].push_back(i);+ }+ }+ size_t band(double y) const {+ return size_t(std::clamp((y - lo.y) / bandH, 0.0, double(bands.size() - 1)));+ }+ bool contains(dvec2 q) const {+ if (q.x < lo.x || q.x > hi.x || q.y < lo.y || q.y > hi.y) return false;+ bool in = false;+ for (uint32_t i : bands[band(q.y)]) {+ const dvec2 a = p[i], b = p[(i + 1) % p.size()];+ if ((a.y > q.y) != (b.y > q.y) && q.x < a.x + (q.y - a.y) / (b.y - a.y) * (b.x - a.x)) in = !in;+ }+ return in;+ }+};++// --- Planar regions: a polygon split by segments, holes bridged to it --------------------------------------++struct PEdge {+ uint32_t a, b;+ int32_t tag; // what made the edge (the other surface), -1 = the polygon's own outline or a bridge+};++struct PRegion {+ std::vector<uint32_t> cycle; // counter-clockwise, interior on the left+ std::vector<int32_t> tags; // tag of edge cycle[i] -> cycle[i + 1]+};++bool planarRegions(const std::vector<dvec2>& p, std::vector<PEdge> edges, std::vector<PRegion>& out) {+ out.clear();+ const uint32_t n = uint32_t(p.size());+ // Drop repeats (keeping a tagged copy) and loops.+ {+ std::unordered_map<uint64_t, size_t> seen;+ std::vector<PEdge> unique;+ for (const PEdge& e : edges) {+ if (e.a == e.b) continue;+ const uint64_t key = (uint64_t(std::min(e.a, e.b)) << 32) | std::max(e.a, e.b);+ auto [it, fresh] = seen.emplace(key, unique.size());+ if (fresh) unique.push_back(e);+ else if (unique[it->second].tag < 0) unique[it->second].tag = e.tag;+ }+ edges.swap(unique);+ }+ // Connected pieces; every piece but the outline's (vertex 0) is a hole to bridge.+ std::vector<uint32_t> parent(n);+ std::iota(parent.begin(), parent.end(), 0u);+ auto find = [&](uint32_t x) {+ while (parent[x] != x) x = parent[x] = parent[parent[x]];+ return x;+ };+ for (const PEdge& e : edges) parent[find(e.a)] = find(e.b);+ std::vector<uint8_t> hasEdge(n, 0);+ for (const PEdge& e : edges) hasEdge[e.a] = hasEdge[e.b] = 1;+ const uint32_t outer = find(0);+ std::unordered_map<uint32_t, uint32_t> leftmost; // piece -> its leftmost vertex+ for (uint32_t v = 0; v < n; ++v) {+ if (!hasEdge[v] || find(v) == outer) continue;+ auto [it, fresh] = leftmost.emplace(find(v), v);+ if (!fresh && (p[v].x < p[it->second].x || (p[v].x == p[it->second].x && p[v].y < p[it->second].y))) it->second = v;+ }+ std::vector<uint32_t> holes;+ for (auto& [piece, v] : leftmost) holes.push_back(v);+ std::sort(holes.begin(), holes.end(), [&](uint32_t a, uint32_t b) { return p[a].x < p[b].x; });+ std::vector<uint8_t> joined(n, 0);+ for (uint32_t v = 0; v < n; ++v) joined[v] = hasEdge[v] && find(v) == outer;+ for (uint32_t h : holes) {+ // Ray to the left: the nearest joined edge it hits, then the vertex there that h sees (as earcut does).+ const dvec2 hp = p[h];+ double bestX = -1e300;+ int best = -1;+ for (size_t i = 0; i < edges.size(); ++i) {+ const PEdge& e = edges[i];+ if (!joined[e.a]) continue;+ const dvec2 a = p[e.a], b = p[e.b];+ if ((a.y > hp.y) == (b.y > hp.y)) continue;+ const double x = a.x + (hp.y - a.y) / (b.y - a.y) * (b.x - a.x);+ if (x <= hp.x && x > bestX) {+ bestX = x;+ best = int(i);+ }+ }+ if (best < 0) return false;+ uint32_t m = p[edges[best].a].x < p[edges[best].b].x ? edges[best].a : edges[best].b;+ const dvec2 q(bestX, hp.y), mp = p[m];+ double bestTan = 1e300;+ for (uint32_t v = 0; v < n; ++v) {+ if (!joined[v] || v == m) continue;+ const dvec2 vp = p[v];+ if (vp.x < mp.x || vp.x > hp.x) continue;+ const double o1 = orient2(hp, q, vp), o2 = orient2(q, mp, vp), o3 = orient2(mp, hp, vp);+ const bool inside = (o1 >= 0 && o2 >= 0 && o3 >= 0) || (o1 <= 0 && o2 <= 0 && o3 <= 0);+ if (!inside) continue;+ const double tan = std::abs(hp.y - vp.y) / std::max(hp.x - vp.x, 1e-300);+ if (tan < bestTan || (tan == bestTan && vp.x > p[m].x)) {+ bestTan = tan;+ m = v;+ }+ }+ edges.push_back({h, m, -1});+ const uint32_t piece = find(h);+ for (uint32_t v = 0; v < n; ++v)+ if (hasEdge[v] && find(v) == piece) joined[v] = 1;+ }+ // Half-edges, sorted by angle around each vertex; walking "next clockwise from the twin" traces each region+ // counter-clockwise.+ struct Half {+ uint32_t to;+ int32_t tag;+ double angle;+ };+ std::vector<std::vector<Half>> around(n);+ for (const PEdge& e : edges) {+ around[e.a].push_back({e.b, e.tag, std::atan2(p[e.b].y - p[e.a].y, p[e.b].x - p[e.a].x)});+ around[e.b].push_back({e.a, e.tag, std::atan2(p[e.a].y - p[e.b].y, p[e.a].x - p[e.b].x)});+ }+ for (auto& list : around) std::sort(list.begin(), list.end(), [](const Half& a, const Half& b) { return a.angle < b.angle; });+ std::vector<std::vector<uint8_t>> used(n);+ for (uint32_t v = 0; v < n; ++v) used[v].assign(around[v].size(), 0);+ auto indexOf = [&](uint32_t from, uint32_t to) {+ for (size_t i = 0; i < around[from].size(); ++i)+ if (around[from][i].to == to) return i;+ return size_t(0);+ };+ for (uint32_t v0 = 0; v0 < n; ++v0)+ for (size_t i0 = 0; i0 < around[v0].size(); ++i0) {+ if (used[v0][i0]) continue;+ PRegion r;+ uint32_t v = v0;+ size_t i = i0;+ for (size_t guard = 0; guard < 4 * edges.size() + 8 && !used[v][i]; ++guard) {+ used[v][i] = 1;+ const Half& h = around[v][i];+ r.cycle.push_back(v);+ r.tags.push_back(h.tag);+ const uint32_t w = h.to;+ const size_t twin = indexOf(w, v), deg = around[w].size();+ i = (twin + deg - 1) % deg;+ v = w;+ }+ double area = 0.0;+ for (size_t k = 0; k < r.cycle.size(); ++k) area += cross2(p[r.cycle[k]], p[r.cycle[(k + 1) % r.cycle.size()]]);+ if (area > 0 && r.cycle.size() >= 3) out.push_back(std::move(r));+ }+ return true;+}++// Ear clipping of a (weakly) simple counter-clockwise cycle. Never adds vertices, so the outline's edges are+// exactly the triangles' boundary even where the geometry is near-degenerate.+void earClip(const std::vector<dvec2>& p, const std::vector<uint32_t>& cyc, std::vector<std::array<uint32_t, 3>>& out) {+ const size_t n = cyc.size();+ if (n < 3) return;+ std::vector<size_t> prev(n), next(n);+ for (size_t i = 0; i < n; ++i) {+ prev[i] = (i + n - 1) % n;+ next[i] = (i + 1) % n;+ }+ auto pt = [&](size_t i) { return p[cyc[i]]; };+ auto isEar = [&](size_t b) {+ const size_t a = prev[b], c = next[b];+ const dvec2 pa = pt(a), pb = pt(b), pc = pt(c);+ if (orient2(pa, pb, pc) <= 0) return false;+ for (size_t j = next[c]; j != a; j = next[j]) {+ const uint32_t id = cyc[j];+ if (id == cyc[a] || id == cyc[b] || id == cyc[c]) continue;+ const dvec2 q = pt(j);+ if (orient2(pt(prev[j]), q, pt(next[j])) > 0) continue; // only reflex vertices can block an ear+ if (orient2(pa, pb, q) >= 0 && orient2(pb, pc, q) >= 0 && orient2(pc, pa, q) >= 0) return false;+ }+ return true;+ };+ size_t count = n, i = 0, stall = 0;+ while (count > 3) {+ if (isEar(i) || stall > count) {+ if (stall > count) { // nothing clean left (near-degenerate): clip the most convex corner+ size_t bestI = i;+ double best = -1e300;+ size_t j = i;+ for (size_t k = 0; k < count; ++k, j = next[j]) {+ const double o = orient2(pt(prev[j]), pt(j), pt(next[j]));+ if (o > best) {+ best = o;+ bestI = j;+ }+ }+ i = bestI;+ }+ out.push_back({cyc[prev[i]], cyc[i], cyc[next[i]]});+ next[prev[i]] = next[i];+ prev[next[i]] = prev[i];+ i = prev[i];+ --count;+ stall = 0;+ } else {+ i = next[i];+ ++stall;+ }+ }+ out.push_back({cyc[prev[i]], cyc[i], cyc[next[i]]});+}++// --- The boolean -------------------------------------------------------------------------------------------++enum : uint8_t { kVertex, kA, kB, kCorner };++struct Pt {+ dvec3 ndc{0.0};+ uint8_t kind = kVertex;+ uint32_t u = 0, v = 0; // A: the edge (u < v); B: v = triangle; corner: u = prism corner id+ uint32_t e = 0; // B: the prism edge+ double lam = 0.0; // A: world-space position along u -> v+ dvec3 bary{0.0}; // B: world-space barycentric coordinates in triangle v+};++struct Seg {+ uint32_t p, q; // global point ids+ uint32_t other; // the prism face (on a triangle) or the triangle (on a face)+};++struct AKeyHash {+ size_t operator()(const std::pair<uint64_t, uint32_t>& k) const {+ return std::hash<uint64_t>()(k.first * 0x9E3779B97F4A7C15ull ^ k.second);+ }+};++struct Cutter {+ // Inputs.+ const Mesh& mesh;+ glm::dmat4 vp, inv;+ double s = 1.0; // orientation of the world -> NDC map+ std::vector<dvec2> r;+ double z0 = 0.0, z1 = 0.0;+ bool unionMode = false, caps = true;++ // State.+ uint32_t nv = 0, n = 0;+ std::vector<dvec3> N; // NDC of each vertex+ std::vector<double> W; // clip w of each vertex+ std::vector<Pt> pts; // the points that aren't mesh vertices (id nv + i)+ std::unordered_map<std::pair<uint64_t, uint32_t>, int64_t, AKeyHash> amap; // A key -> point id or -1+ std::unordered_map<uint32_t, std::vector<Seg>> triSegs;+ std::vector<std::vector<Seg>> faceSegs;+ bool degenerate = false;+ double eps = 1e-12, baryEps = 1e-11;+ // Wall grid.+ int G = 1;+ dvec2 glo{0.0}, ghi{0.0};+ std::vector<std::vector<uint32_t>> cells;+ std::unique_ptr<Poly2> poly;++ // Output: triangles as global ids, with the mesh triangle they came from (-1 = prism).+ std::vector<std::array<uint32_t, 3>> outTris;+ std::vector<int64_t> outParent;+ std::vector<uint8_t> splitParent; // per mesh triangle: it was cut+ size_t removedTriangles = 0, prismTriangles = 0;++ explicit Cutter(const Mesh& m) : mesh(m) {}++ uint32_t faceCount() const { return n + 2; }+ dvec3 ndcOf(uint32_t g) const { return g < nv ? N[g] : pts[g - nv].ndc; }+ dvec3 outward(uint32_t f) const {+ if (f == n) return {0, 0, -1};+ if (f == n + 1) return {0, 0, 1};+ const dvec2 e = glm::normalize(r[(f + 1) % n] - r[f]);+ return {e.y, -e.x, 0.0};+ }+ // Signed distance to face f's plane, positive towards the prism's inside.+ double dist(uint32_t f, const dvec3& x) const {+ if (f == n) return x.z - z0;+ if (f == n + 1) return z1 - x.z;+ const dvec2 a = r[f], e = r[(f + 1) % n] - a;+ return cross2(e, dvec2(x) - a) / glm::length(e);+ }+ // Whether a point on face f's plane lies on the face.+ bool onFace(uint32_t f, const dvec3& x) {+ if (f >= n) return poly->contains(dvec2(x));+ const dvec2 a = r[f], e = r[(f + 1) % n] - a;+ const double t = glm::dot(dvec2(x) - a, e) / glm::dot(e, e);+ const double te = baryEps;+ if (std::abs(t) < te || std::abs(t - 1) < te || std::abs(x.z - z0) < eps || std::abs(x.z - z1) < eps) degenerate = true;+ return t > 0 && t < 1 && x.z > z0 && x.z < z1;+ }+ bool insidePrism(const dvec3& x) const { return x.z > z0 && x.z < z1 && poly->contains(dvec2(x)); }+ // Prism edges: vertical k at corner k, bottom n + k and top 2n + k along wall k. Corners: bottom k, top n + k.+ uint32_t cornerId(uint32_t k, bool top) const { return nv + (top ? n : 0) + k % n; }+ std::pair<uint32_t, uint32_t> edgeEnds(uint32_t e) const {+ if (e < n) return {cornerId(e, false), cornerId(e, true)};+ if (e < 2 * n) return {cornerId(e - n, false), cornerId(e - n + 1, false)};+ return {cornerId(e - 2 * n, true), cornerId(e - 2 * n + 1, true)};+ }+ dvec3 unproject(const dvec3& ndc) const {+ const dvec4 w = inv * dvec4(ndc, 1.0);+ return dvec3(w) / w.w;+ }+ uint32_t addPoint(const Pt& p) {+ pts.push_back(p);+ return nv + uint32_t(pts.size() - 1);+ }++ int cell(double x, double lo, double hi) const {+ return std::clamp(int((x - lo) / std::max(hi - lo, 1e-300) * G), 0, G - 1);+ }++ // The A point where mesh edge (a, b) crosses face f's plane: its id, or -1 when the crossing is off the face.+ int64_t aPoint(uint32_t a, uint32_t b, uint32_t f, dvec3& pos) {+ const uint32_t u = std::min(a, b), v = std::max(a, b);+ const double du = dist(f, N[u]), dv = dist(f, N[v]);+ const double t = du / (du - dv);+ pos = N[u] + (N[v] - N[u]) * t;+ const auto key = std::make_pair((uint64_t(u) << 32) | v, f);+ if (auto it = amap.find(key); it != amap.end()) return it->second;+ int64_t id = -1;+ if (onFace(f, pos)) {+ Pt p;+ p.ndc = pos;+ p.kind = kA;+ p.u = u;+ p.v = v;+ p.lam = t * W[u] / ((1 - t) * W[v] + t * W[u]); // perspective-correct+ id = addPoint(p);+ }+ amap.emplace(key, id);+ return id;+ }++ void processTriangle(uint32_t t) {+ const glm::uvec3 tri = mesh.triangles[t];+ const dvec3 a = N[tri.x], b = N[tri.y], c = N[tri.z];+ const dvec2 lo = glm::min(glm::min(dvec2(a), dvec2(b)), dvec2(c)), hi = glm::max(glm::max(dvec2(a), dvec2(b)), dvec2(c));+ const double zmin = std::min({a.z, b.z, c.z}), zmax = std::max({a.z, b.z, c.z});+ if (zmax < z0 || zmin > z1 || hi.x < poly->lo.x || lo.x > poly->hi.x || hi.y < poly->lo.y || lo.y > poly->hi.y) return;+ // Candidate walls from the grid, then the caps the triangle straddles.+ std::vector<uint32_t> faces;+ const int x0 = cell(lo.x, glo.x, ghi.x), x1 = cell(hi.x, glo.x, ghi.x);+ const int y0 = cell(lo.y, glo.y, ghi.y), y1 = cell(hi.y, glo.y, ghi.y);+ for (int y = y0; y <= y1; ++y)+ for (int x = x0; x <= x1; ++x)+ for (uint32_t k : cells[size_t(y) * G + x]) faces.push_back(k);+ std::sort(faces.begin(), faces.end());+ faces.erase(std::unique(faces.begin(), faces.end()), faces.end());+ const size_t walls = faces.size();+ if (zmin < z0 && zmax > z0) faces.push_back(n);+ if (zmin < z1 && zmax > z1) faces.push_back(n + 1);+ if (faces.empty()) return;+ const dvec3 rn = glm::cross(b - a, c - a);+ const double rn2 = glm::dot(rn, rn);+ if (rn2 <= 0) return;+ // B points: the prism edges of the candidate walls that pierce the triangle.+ std::vector<std::pair<uint32_t, uint32_t>> pierced; // (prism edge, point id)+ std::vector<uint32_t> tried;+ auto pierce = [&](uint32_t e) {+ if (std::find(tried.begin(), tried.end(), e) != tried.end()) return;+ tried.push_back(e);+ const auto [i0, i1] = edgeEnds(e);+ const dvec3 p0 = pts[i0 - nv].ndc, p1 = pts[i1 - nv].ndc;+ const double d0 = glm::dot(rn, p0 - a), d1 = glm::dot(rn, p1 - a);+ const double scale = std::sqrt(rn2) * eps;+ if (std::abs(d0) < scale || std::abs(d1) < scale) {+ // A prism corner on the triangle's plane: only a problem when it is on the triangle.+ const dvec3 x = std::abs(d0) < scale ? p0 : p1;+ const double l0 = glm::dot(glm::cross(b - x, c - x), rn) / rn2, l1 = glm::dot(glm::cross(c - x, a - x), rn) / rn2;+ if (l0 > -baryEps && l1 > -baryEps && 1 - l0 - l1 > -baryEps) degenerate = true;+ return;+ }+ if ((d0 > 0) == (d1 > 0)) return;+ const dvec3 x = p0 + (p1 - p0) * (d0 / (d0 - d1));+ const double l0 = glm::dot(glm::cross(b - x, c - x), rn) / rn2;+ const double l1 = glm::dot(glm::cross(c - x, a - x), rn) / rn2;+ const double l2 = 1.0 - l0 - l1;+ if (std::abs(l0) < baryEps || std::abs(l1) < baryEps || std::abs(l2) < baryEps) degenerate = true;+ if (l0 <= 0 || l1 <= 0 || l2 <= 0) return;+ Pt p;+ p.ndc = x;+ p.kind = kB;+ p.e = e;+ p.v = t;+ const dvec3 wl(l0 / W[tri.x], l1 / W[tri.y], l2 / W[tri.z]);+ p.bary = wl / (wl.x + wl.y + wl.z);+ pierced.push_back({e, addPoint(p)});+ };+ for (size_t i = 0; i < walls; ++i) {+ const uint32_t k = faces[i];+ for (uint32_t e : {k, (k + 1) % n, n + k, 2 * n + k}) pierce(e);+ }+ const uint32_t vi[3] = {tri.x, tri.y, tri.z};+ for (uint32_t f : faces) {+ double d[3];+ for (int i = 0; i < 3; ++i) {+ d[i] = dist(f, N[vi[i]]);+ if (std::abs(d[i]) < eps) degenerate = true;+ }+ if ((d[0] > 0) == (d[1] > 0) && (d[1] > 0) == (d[2] > 0)) continue;+ // The two triangle edges the plane crosses.+ struct X {+ dvec3 pos;+ int64_t id;+ } xs[2];+ int nx = 0;+ for (int i = 0; i < 3 && nx < 2; ++i) {+ const int j = (i + 1) % 3;+ if ((d[i] > 0) == (d[j] > 0)) continue;+ xs[nx].id = aPoint(vi[i], vi[j], f, xs[nx].pos);+ ++nx;+ }+ if (nx != 2) {+ degenerate = true;+ return;+ }+ // The face's own edges through the triangle.+ std::vector<std::pair<double, uint32_t>> bs;+ const dvec3 dir = xs[1].pos - xs[0].pos;+ const double dd = glm::dot(dir, dir);+ for (const auto& [e, id] : pierced) {+ const bool mine = f < n ? (e == f || e == (f + 1) % n || e == n + f || e == 2 * n + f)+ : (f == n ? (e >= n && e < 2 * n) : e >= 2 * n);+ if (mine) bs.push_back({dd > 0 ? glm::dot(pts[id - nv].ndc - xs[0].pos, dir) / dd : 0.0, id});+ }+ if (xs[0].id < 0 && xs[1].id < 0 && bs.empty()) continue;+ std::sort(bs.begin(), bs.end());+ bool in = xs[0].id >= 0;+ uint32_t cur = in ? uint32_t(xs[0].id) : 0;+ auto seg = [&](uint32_t p, uint32_t q) {+ triSegs[t].push_back({p, q, f});+ faceSegs[f].push_back({p, q, t});+ };+ for (const auto& [param, id] : bs) {+ if (in) seg(cur, id);+ else cur = id;+ in = !in;+ }+ if (in != (xs[1].id >= 0)) {+ degenerate = true;+ return;+ }+ if (in) seg(cur, uint32_t(xs[1].id));+ }+ }++ // Splits one mesh triangle along its segments; keeps the regions outside the prism.+ void splitTriangle(uint32_t t, const std::vector<Seg>& segs) {+ const glm::uvec3 tri = mesh.triangles[t];+ const uint32_t vi[3] = {tri.x, tri.y, tri.z};+ const dvec3 rn = glm::cross(N[tri.y] - N[tri.x], N[tri.z] - N[tri.x]);+ // 2D frame: drop the normal's largest axis, keeping counter-clockwise = rn.+ int axis = 0;+ if (std::abs(rn.y) > std::abs(rn[axis])) axis = 1;+ if (std::abs(rn.z) > std::abs(rn[axis])) axis = 2;+ int ia = (axis + 1) % 3, ib = (axis + 2) % 3;+ if (rn[axis] < 0) std::swap(ia, ib);+ std::vector<uint32_t> ids;+ std::unordered_map<uint32_t, uint32_t> local;+ auto loc = [&](uint32_t g) {+ auto [it, fresh] = local.emplace(g, uint32_t(ids.size()));+ if (fresh) ids.push_back(g);+ return it->second;+ };+ for (uint32_t v : vi) loc(v);+ std::vector<PEdge> edges;+ // Outline: each side with the A points on it, in order.+ for (int i = 0; i < 3; ++i) {+ const uint32_t u = vi[i], w = vi[(i + 1) % 3];+ std::vector<std::pair<double, uint32_t>> on;+ for (const Seg& s : segs)+ for (uint32_t g : {s.p, s.q})+ if (g >= nv && pts[g - nv].kind == kA && pts[g - nv].u == std::min(u, w) && pts[g - nv].v == std::max(u, w))+ on.push_back({glm::dot(pts[g - nv].ndc - N[u], N[w] - N[u]), g});+ std::sort(on.begin(), on.end());+ on.erase(std::unique(on.begin(), on.end()), on.end());+ uint32_t prev = loc(u);+ for (const auto& [param, g] : on) {+ const uint32_t l = loc(g);+ edges.push_back({prev, l, -1});+ prev = l;+ }+ edges.push_back({prev, loc(w), -1});+ }+ for (const Seg& s : segs) edges.push_back({loc(s.p), loc(s.q), int32_t(s.other)});+ std::vector<dvec2> p2(ids.size());+ for (size_t i = 0; i < ids.size(); ++i) {+ const dvec3 x = ndcOf(ids[i]);+ p2[i] = {x[ia], x[ib]};+ }+ std::vector<PRegion> regions;+ if (!planarRegions(p2, edges, regions)) {+ degenerate = true;+ return;+ }+ std::vector<std::array<uint32_t, 3>> tris;+ for (const PRegion& reg : regions) {+ int which = -1;+ for (size_t k = 0; k < reg.tags.size() && which < 0; ++k)+ if (reg.tags[k] >= 0) which = int(k);+ if (which < 0) {+ degenerate = true;+ return;+ }+ const dvec3 P = ndcOf(ids[reg.cycle[which]]), Q = ndcOf(ids[reg.cycle[(which + 1) % reg.cycle.size()]]);+ const bool inside = glm::dot(glm::cross(rn, Q - P), outward(uint32_t(reg.tags[which]))) < 0;+ if (inside) continue;+ tris.clear();+ earClip(p2, reg.cycle, tris);+ for (const auto& tr : tris) {+ outTris.push_back({ids[tr[0]], ids[tr[1]], ids[tr[2]]});+ outParent.push_back(t);+ }+ }+ }++ // Face f's outline: its prism edges in order (counter-clockwise around its outward normal), with direction.+ std::vector<std::pair<uint32_t, bool>> faceEdges(uint32_t f) const {+ std::vector<std::pair<uint32_t, bool>> out; // (edge, forward)+ if (f < n) {+ out = {{n + f, true}, {(f + 1) % n, true}, {2 * n + f, false}, {f, false}};+ } else if (f == n + 1) {+ for (uint32_t k = 0; k < n; ++k) out.push_back({2 * n + k, true});+ } else {+ for (uint32_t k = n; k-- > 0;) out.push_back({n + k, false});+ }+ return out;+ }+ dvec2 face2d(uint32_t f, const dvec3& x) const {+ if (f == n + 1) return {x.x, x.y};+ if (f == n) return {x.x, -x.y};+ const dvec2 a = r[f], e = glm::normalize(r[(f + 1) % n] - a);+ return {glm::dot(dvec2(x) - a, e), x.z};+ }++ // Splits face f along its segments. Returns, per prism edge on its outline with no B points, the status of the+ // region along it (1 inside the mesh, 0 outside) in `edgeStatus`. Keeps the regions the mode wants.+ void splitFace(uint32_t f, std::vector<int8_t>& edgeStatus) {+ const std::vector<Seg>& segs = faceSegs[f];+ std::vector<uint32_t> ids;+ std::unordered_map<uint32_t, uint32_t> local;+ auto loc = [&](uint32_t g) {+ auto [it, fresh] = local.emplace(g, uint32_t(ids.size()));+ if (fresh) ids.push_back(g);+ return it->second;+ };+ std::vector<PEdge> edges;+ std::vector<std::pair<uint64_t, uint32_t>> plainEdges; // (local a, local b) -> prism edge, for edgeStatus+ const auto outline = faceEdges(f);+ loc(outline.empty() ? 0 : (outline[0].second ? edgeEnds(outline[0].first).first : edgeEnds(outline[0].first).second));+ for (const auto& [e, fwd] : outline) {+ const auto [e0, e1] = edgeEnds(e);+ const uint32_t from = fwd ? e0 : e1, to = fwd ? e1 : e0;+ const dvec3 A = pts[from - nv].ndc, B = pts[to - nv].ndc;+ std::vector<std::pair<double, uint32_t>> on;+ for (const Seg& s : segs)+ for (uint32_t g : {s.p, s.q})+ if (g >= nv && pts[g - nv].kind == kB && pts[g - nv].e == e) on.push_back({glm::dot(pts[g - nv].ndc - A, B - A), g});+ std::sort(on.begin(), on.end());+ on.erase(std::unique(on.begin(), on.end()), on.end());+ uint32_t prev = loc(from);+ for (const auto& [param, g] : on) {+ const uint32_t l = loc(g);+ edges.push_back({prev, l, -1});+ prev = l;+ }+ edges.push_back({prev, loc(to), -1});+ if (on.empty()) plainEdges.push_back({(uint64_t(loc(from)) << 32) | loc(to), e});+ }+ for (const Seg& s : segs) edges.push_back({loc(s.p), loc(s.q), int32_t(s.other)});+ std::vector<dvec2> p2(ids.size());+ for (size_t i = 0; i < ids.size(); ++i) p2[i] = face2d(f, ndcOf(ids[i]));+ std::vector<PRegion> regions;+ if (!planarRegions(p2, edges, regions)) {+ degenerate = true;+ return;+ }+ const dvec3 out = outward(f);+ std::vector<std::array<uint32_t, 3>> tris;+ for (const PRegion& reg : regions) {+ int which = -1;+ for (size_t k = 0; k < reg.tags.size() && which < 0; ++k)+ if (reg.tags[k] >= 0) which = int(k);+ if (which < 0) {+ degenerate = true;+ return;+ }+ const uint32_t t = uint32_t(reg.tags[which]);+ const glm::uvec3 tri = mesh.triangles[t];+ const dvec3 nt = s * glm::cross(N[tri.y] - N[tri.x], N[tri.z] - N[tri.x]);+ const dvec3 P = ndcOf(ids[reg.cycle[which]]), Q = ndcOf(ids[reg.cycle[(which + 1) % reg.cycle.size()]]);+ const bool insideMesh = glm::dot(glm::cross(out, Q - P), nt) < 0;+ for (size_t k = 0; k < reg.cycle.size(); ++k) {+ const uint64_t key = (uint64_t(reg.cycle[k]) << 32) | reg.cycle[(k + 1) % reg.cycle.size()];+ for (const auto& [pk, e] : plainEdges)+ if (pk == key) edgeStatus[e] = insideMesh ? 1 : 0;+ }+ if (insideMesh == unionMode) continue;+ tris.clear();+ earClip(p2, reg.cycle, tris);+ emitPrism(ids, tris);+ }+ }++ void emitPrism(const std::vector<uint32_t>& ids, const std::vector<std::array<uint32_t, 3>>& tris) {+ // Counter-clockwise around the outward normal in NDC; the world winding flips with s, and a difference+ // keeps the prism's inside-out surface.+ const bool flip = unionMode ? s < 0 : s > 0;+ for (const auto& tr : tris) {+ if (flip) outTris.push_back({ids[tr[0]], ids[tr[2]], ids[tr[1]]});+ else outTris.push_back({ids[tr[0]], ids[tr[1]], ids[tr[2]]});+ outParent.push_back(-1);+ ++prismTriangles;+ }+ }++ // Winding number of the mesh around an NDC point (1 inside a closed mesh, 0 outside).+ double winding(const dvec3& x) const {+ double sum = 0.0;+ for (const glm::uvec3& tri : mesh.triangles) {+ const dvec3 A = N[tri.x] - x, B = N[tri.y] - x, C = N[tri.z] - x;+ const double la = glm::length(A), lb = glm::length(B), lc = glm::length(C);+ const double num = glm::dot(A, glm::cross(B, C));+ const double den = la * lb * lc + glm::dot(A, B) * lc + glm::dot(B, C) * la + glm::dot(C, A) * lb;+ sum += 2.0 * std::atan2(num, den);+ }+ return s * sum / (4.0 * 3.14159265358979323846);+ }++ // One attempt; false when degenerate (try again with another nudge).+ bool run() {+ pts.clear();+ amap.clear();+ triSegs.clear();+ outTris.clear();+ outParent.clear();+ degenerate = false;+ removedTriangles = prismTriangles = 0;+ n = uint32_t(r.size());+ poly = std::make_unique<Poly2>(r);+ faceSegs.assign(faceCount(), {});+ for (uint32_t k = 0; k < 2 * n; ++k) {+ Pt p;+ p.kind = kCorner;+ p.u = k;+ p.ndc = dvec3(r[k % n], k < n ? z0 : z1);+ addPoint(p);+ }+ // Wall grid over the shape's box, clipped to the mesh's.+ dvec2 mlo(1e300), mhi(-1e300);+ for (const dvec3& x : N) {+ mlo = glm::min(mlo, dvec2(x));+ mhi = glm::max(mhi, dvec2(x));+ }+ glo = glm::max(poly->lo, mlo);+ ghi = glm::min(poly->hi, mhi);+ G = std::clamp(int(std::sqrt(double(n)) * 2.0), 4, 256);+ cells.assign(size_t(G) * G, {});+ for (uint32_t k = 0; k < n; ++k) {+ const dvec2 a = r[k], b = r[(k + 1) % n];+ const int x0 = cell(std::min(a.x, b.x), glo.x, ghi.x), x1 = cell(std::max(a.x, b.x), glo.x, ghi.x);+ const int y0 = cell(std::min(a.y, b.y), glo.y, ghi.y), y1 = cell(std::max(a.y, b.y), glo.y, ghi.y);+ if (std::max(a.x, b.x) < glo.x || std::min(a.x, b.x) > ghi.x || std::max(a.y, b.y) < glo.y || std::min(a.y, b.y) > ghi.y)+ continue;+ for (int y = y0; y <= y1; ++y)+ for (int x = x0; x <= x1; ++x) cells[size_t(y) * G + x].push_back(k);+ }+ const uint32_t nt = uint32_t(mesh.triangleCount());+ for (uint32_t t = 0; t < nt && !degenerate; ++t) processTriangle(t);+ if (degenerate) return false;++ splitParent.assign(nt, 0);+ for (auto& [t, segs] : triSegs) {+ splitParent[t] = 1;+ ++removedTriangles; // counted again below if a piece survives; only used to tell "nothing happened"+ splitTriangle(t, segs);+ if (degenerate) return false;+ }+ const bool anySegments = !triSegs.empty();+ // Untouched triangles: entirely on one side.+ for (uint32_t t = 0; t < nt; ++t) {+ if (splitParent[t]) continue;+ const glm::uvec3 tri = mesh.triangles[t];+ if (insidePrism((N[tri.x] + N[tri.y] + N[tri.z]) / 3.0)) {+ ++removedTriangles;+ continue;+ }+ outTris.push_back({tri.x, tri.y, tri.z});+ outParent.push_back(t);+ }+ if (!caps) return true;+ // Prism faces: split the cut ones; the rest take the status of a neighbour across an uncut edge.+ std::vector<int8_t> edgeStatus(3 * n, -1);+ std::vector<int8_t> faceStatus(faceCount(), -1);+ for (uint32_t f = 0; f < faceCount(); ++f)+ if (!faceSegs[f].empty()) {+ splitFace(f, edgeStatus);+ if (degenerate) return false;+ faceStatus[f] = 2; // done+ }+ if (!anySegments) {+ const int8_t st = winding(pts[0].ndc) > 0.5 ? 1 : 0;+ std::fill(faceStatus.begin(), faceStatus.end(), st);+ }+ for (bool changed = true; changed;) {+ changed = false;+ for (uint32_t f = 0; f < faceCount(); ++f) {+ if (faceStatus[f] != -1) continue;+ for (const auto& [e, fwd] : faceEdges(f))+ if (edgeStatus[e] >= 0) {+ faceStatus[f] = edgeStatus[e];+ changed = true;+ break;+ }+ if (faceStatus[f] >= 0)+ for (const auto& [e, fwd] : faceEdges(f)) edgeStatus[e] = faceStatus[f];+ }+ }+ for (uint32_t f = 0; f < faceCount(); ++f) {+ if (faceStatus[f] == 2) continue;+ if (faceStatus[f] < 0) return false;+ if ((faceStatus[f] == 1) == unionMode) continue;+ std::vector<uint32_t> ids, cyc;+ std::vector<dvec2> p2;+ for (const auto& [e, fwd] : faceEdges(f)) {+ const auto [e0, e1] = edgeEnds(e);+ ids.push_back(fwd ? e0 : e1);+ cyc.push_back(uint32_t(cyc.size()));+ p2.push_back(face2d(f, pts[ids.back() - nv].ndc));+ }+ std::vector<std::array<uint32_t, 3>> tris;+ earClip(p2, cyc, tris);+ emitPrism(ids, tris);+ }+ return true;+ }+};++bool closedMesh(const Mesh& mesh) {+ std::unordered_map<uint64_t, int> count;+ count.reserve(mesh.triangleCount() * 3);+ for (const glm::uvec3& t : mesh.triangles)+ for (int i = 0; i < 3; ++i) {+ const uint32_t a = t[i], b = t[(i + 1) % 3];+ count[(uint64_t(a) << 32) | b] += 1;+ }+ for (const auto& [key, c] : count) {+ const uint64_t twin = (key << 32) | (key >> 32);+ auto it = count.find(twin);+ if (c != 1 || it == count.end() || it->second != 1) return false;+ }+ return !mesh.triangles.empty();+}++} // namespace++bool isWatertight(const Mesh& mesh) { return closedMesh(mesh); }++bool cutRegion(CutShape shape, const std::vector<glm::vec2>& points, bool flip, bool closed,+ std::vector<glm::dvec2>& region, std::string& error) {+ region.clear();+ constexpr double kFar = 1000.0; // NDC: far beyond any visible model+ auto side = [&](dvec2 d) { return flip ? dvec2(d.y, -d.x) : dvec2(-d.y, d.x); };+ if (shape == CutShape::Line || (shape == CutShape::Polyline && !closed)) {+ std::vector<dvec2> p;+ for (const glm::vec2& v : points)+ if (p.empty() || glm::length(dvec2(v) - p.back()) > 1e-6) p.push_back(dvec2(v));+ if (shape == CutShape::Line && p.size() > 2) p = {p.front(), p.back()};+ if (p.size() < 2) {+ error = "Cut: draw a line (two different points)";+ return false;+ }+ const dvec2 d0 = glm::normalize(p[1] - p[0]), d1 = glm::normalize(p.back() - p[p.size() - 2]);+ const dvec2 start = p.front() - d0 * kFar, end = p.back() + d1 * kFar;+ region.push_back(start);+ if (shape == CutShape::Polyline) region.insert(region.end(), p.begin(), p.end()); // (a line's are on the way)+ region.push_back(end);+ region.push_back(end + side(d1) * kFar);+ region.push_back(start + side(d0) * kFar);+ } else {+ for (const glm::vec2& v : points) region.push_back(dvec2(v));+ if (shape == CutShape::Rect && region.size() == 2) {+ const dvec2 a = region[0], b = region[1];+ region = {a, {b.x, a.y}, b, {a.x, b.y}};+ }+ if (region.size() < 3) {+ error = "Cut: the shape needs at least three points";+ return false;+ }+ }+ if (!simplifyOutline(region)) {+ error = "Cut: the shape encloses no area";+ return false;+ }+ return true;+}++bool cutMesh(const Mesh& mesh, const glm::mat4& viewProj, const std::vector<glm::dvec2>& region, CutMode mode,+ float depth, Mesh& out, std::string& error) {+ if (mesh.triangleCount() == 0) {+ error = "Cut: the Part is empty";+ return false;+ }+ if (region.size() < 3) {+ error = "Cut: the shape needs at least three points";+ return false;+ }+ Cutter c(mesh);+ c.vp = glm::dmat4(viewProj);+ c.inv = glm::inverse(c.vp);+ c.s = glm::determinant(c.vp) < 0 ? -1.0 : 1.0;+ c.nv = uint32_t(mesh.vertexCount());+ c.N.resize(c.nv);+ c.W.resize(c.nv);+ double zmin = 1e300, zmax = -1e300;+ dvec2 lo(1e300), hi(-1e300);+ for (uint32_t v = 0; v < c.nv; ++v) {+ const dvec4 clip = c.vp * dvec4(dvec3(mesh.positions[v]), 1.0);+ if (clip.w <= 1e-12) {+ error = "Cut: part of the Part is behind the camera; step back and try again";+ return false;+ }+ c.W[v] = clip.w;+ c.N[v] = dvec3(clip) / clip.w;+ zmin = std::min(zmin, c.N[v].z);+ zmax = std::max(zmax, c.N[v].z);+ lo = glm::min(lo, dvec2(c.N[v]));+ hi = glm::max(hi, dvec2(c.N[v]));+ }+ const double extent = std::max({hi.x - lo.x, hi.y - lo.y, 1e-9});+ c.eps = 1e-12 * std::max(1.0, extent);+ const bool closed = closedMesh(mesh);+ c.unionMode = mode == CutMode::Add;+ c.caps = closed;+ if (c.unionMode && !closed) {+ error = "Cut Add needs a closed (watertight) Part; remesh it first";+ return false;+ }+ // Depth range of the extrusion.+ const Poly2 shape(region);+ double zFront = 1e300, zBack = -1e300;+ dvec3 frontHit(0.0), backHit(0.0); // world points of the nearest and farthest surface under the shape+ for (uint32_t v = 0; v < c.nv; ++v)+ if (shape.contains(dvec2(c.N[v]))) {+ if (c.N[v].z < zFront) {+ zFront = c.N[v].z;+ frontHit = dvec3(mesh.positions[v]);+ }+ if (c.N[v].z > zBack) {+ zBack = c.N[v].z;+ backHit = dvec3(mesh.positions[v]);+ }+ }+ // A shape inside one big triangle covers no vertex: also sample the surface under the shape's corners and+ // centre (front and back hits, interpolated in the triangles there).+ {+ std::vector<dvec2> samples;+ const size_t stride = std::max<size_t>(1, region.size() / 48);+ dvec2 centre(0.0);+ for (size_t i = 0; i < region.size(); ++i) {+ centre += region[i];+ if (i % stride == 0 && shape.contains(region[i] * 0.999 + region[(i + 1) % region.size()] * 0.0005 ++ region[(i + region.size() - 1) % region.size()] * 0.0005))+ samples.push_back(region[i]);+ }+ centre /= double(region.size());+ if (shape.contains(centre)) samples.push_back(centre);+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {+ const glm::uvec3 tri = mesh.triangles[t];+ const dvec3 a = c.N[tri.x], b = c.N[tri.y], cc = c.N[tri.z];+ const double area = orient2(dvec2(a), dvec2(b), dvec2(cc));+ if (area == 0.0) continue;+ const dvec2 tlo = glm::min(glm::min(dvec2(a), dvec2(b)), dvec2(cc)), thi = glm::max(glm::max(dvec2(a), dvec2(b)), dvec2(cc));+ for (const dvec2& q : samples) {+ if (q.x < tlo.x || q.x > thi.x || q.y < tlo.y || q.y > thi.y) continue;+ const double l0 = orient2(dvec2(b), dvec2(cc), q) / area, l1 = orient2(dvec2(cc), dvec2(a), q) / area;+ const double l2 = 1.0 - l0 - l1;+ if (l0 < 0 || l1 < 0 || l2 < 0) continue;+ const double z = l0 * a.z + l1 * b.z + l2 * cc.z;+ if (z < zFront) {+ zFront = z;+ frontHit = c.unproject(dvec3(q, z));+ }+ if (z > zBack) {+ zBack = z;+ backHit = c.unproject(dvec3(q, z));+ }+ }+ }+ }+ const double margin = 1e-3 * std::max(zmax - zmin, 1e-6);+ double z0 = zmin - margin, z1 = zmax + margin;+ if (mode != CutMode::Away) {+ AABB box;+ for (const glm::vec3& p : mesh.positions) box.expand(p);+ const double size = double(std::max({box.extent().x, box.extent().y, box.extent().z}));+ const double d = std::clamp(double(depth), 1e-4, 4.0) * size;+ const dvec3 forward = glm::normalize(c.unproject({0, 0, 0.5}) - c.unproject({0, 0, -0.5}));+ auto ndcZ = [&](const dvec3& p, bool& ok) {+ const dvec4 clip = c.vp * dvec4(p, 1.0);+ ok = clip.w > 1e-12;+ return clip.z / clip.w;+ };+ bool ok = true;+ if (zFront > 1e299) {+ if (mode == CutMode::In) {+ error = "Cut: the shape misses the Part";+ return false;+ }+ const dvec3 mid = dvec3(box.center());+ z0 = ndcZ(mid - forward * (d * 0.5), ok);+ z1 = ndcZ(mid + forward * (d * 0.5), ok);+ } else if (mode == CutMode::In) {+ z1 = ndcZ(frontHit + forward * d, ok);+ } else {+ const dvec3 pf = frontHit, pb = backHit;+ z0 = ndcZ(pf - forward * d, ok);+ z1 = std::max(ndcZ((pf + pb) * 0.5, ok), ndcZ(pf + forward * (d * 0.25), ok));+ }+ if (!ok || !(z1 > z0)) {+ error = "Cut: the depth reaches past the camera; lower Depth or step back";+ return false;+ }+ }+ std::mt19937 rng(12345);+ for (int attempt = 0; attempt < 8; ++attempt) {+ const double amp = 1e-7 * extent * std::pow(3.0, attempt); // at most ~2e-4 of the view+ std::uniform_real_distribution<double> jitter(-amp, amp);+ c.r = region;+ for (dvec2& p : c.r) p += dvec2(jitter(rng), jitter(rng));+ c.z0 = z0 + jitter(rng) * 1e-3;+ c.z1 = z1 + jitter(rng) * 1e-3;+ if (!c.run()) continue;+ // Output vertices: every id the triangles use, in order.+ std::vector<uint32_t> remap(c.nv + c.pts.size(), ~0u), used;+ for (const auto& t : c.outTris)+ for (uint32_t g : t)+ if (remap[g] == ~0u) {+ remap[g] = uint32_t(used.size());+ used.push_back(g);+ }+ const bool changed = c.prismTriangles > 0 || c.outTris.size() != mesh.triangleCount() || used.size() != mesh.vertexCount();+ if (!changed) {+ error = "Cut: the shape misses the Part";+ return false;+ }+ if (c.outTris.empty()) {+ error = "Cut: that would remove the whole Part";+ return false;+ }+ Mesh m;+ const size_t nvOut = used.size(), ntOut = c.outTris.size();+ m.positions.resize(nvOut);+ const bool hasLayers = !mesh.layers.empty();+ if (hasLayers) {+ m.base.resize(nvOut);+ m.layers = mesh.layers;+ for (SculptLayer& l : m.layers) l.delta.assign(nvOut, glm::vec3(0.0f));+ }+ if (mesh.hasMask()) m.mask.assign(nvOut, 0.0f);+ glm::vec3 capColor(1.0f);+ if (mesh.hasColors()) {+ m.colors.assign(nvOut, glm::vec3(1.0f));+ glm::dvec3 sum(0.0);+ size_t k = 0;+ for (const Pt& p : c.pts)+ if (p.kind == kA) {+ sum += dvec3(glm::mix(mesh.colors[p.u], mesh.colors[p.v], float(p.lam)));+ ++k;+ }+ if (k) capColor = glm::vec3(sum / double(k));+ }+ std::vector<uint32_t> kept(nvOut, 0);+ // Weights of the source vertices for each output vertex.+ auto weights = [&](uint32_t g, std::array<std::pair<uint32_t, float>, 3>& w) {+ if (g < c.nv) {+ w = {{{g, 1.0f}, {g, 0.0f}, {g, 0.0f}}};+ return true;+ }+ const Pt& p = c.pts[g - c.nv];+ if (p.kind == kA) {+ w = {{{p.u, float(1 - p.lam)}, {p.v, float(p.lam)}, {p.v, 0.0f}}};+ return true;+ }+ if (p.kind == kB) {+ const glm::uvec3 tri = mesh.triangles[p.v];+ w = {{{tri.x, float(p.bary.x)}, {tri.y, float(p.bary.y)}, {tri.z, float(p.bary.z)}}};+ return true;+ }+ return false;+ };+ const std::vector<glm::vec3>& base = mesh.basePositions();+ for (size_t i = 0; i < nvOut; ++i) {+ const uint32_t g = used[i];+ std::array<std::pair<uint32_t, float>, 3> w;+ if (!weights(g, w)) { // a prism corner+ m.positions[i] = glm::vec3(c.unproject(c.pts[g - c.nv].ndc));+ if (hasLayers) m.base[i] = m.positions[i];+ if (mesh.hasColors()) m.colors[i] = capColor;+ continue;+ }+ glm::dvec3 pos(0.0), bp(0.0);+ float best = -1.0f;+ for (const auto& [v, wt] : w) {+ pos += dvec3(mesh.positions[v]) * double(wt);+ if (hasLayers) bp += dvec3(base[v]) * double(wt);+ if (wt > best) {+ best = wt;+ kept[i] = v;+ }+ }+ m.positions[i] = glm::vec3(pos);+ if (hasLayers) {+ m.base[i] = glm::vec3(bp);+ for (size_t l = 0; l < m.layers.size(); ++l) {+ glm::vec3 d(0.0f);+ for (const auto& [v, wt] : w) d += mesh.layers[l].delta[v] * wt;+ m.layers[l].delta[i] = d;+ }+ }+ if (mesh.hasMask()) {+ float mk = 0.0f;+ for (const auto& [v, wt] : w) mk += mesh.mask[v] * wt;+ m.mask[i] = mk;+ }+ if (mesh.hasColors()) {+ glm::vec3 col(0.0f);+ for (const auto& [v, wt] : w) col += mesh.colors[v] * wt;+ m.colors[i] = col;+ }+ }+ m.triangles.resize(ntOut);+ uint32_t capGroup = 0;+ if (c.prismTriangles > 0) {+ for (uint32_t gid : mesh.polygroups) capGroup = std::max(capGroup, gid);+ capGroup += 1;+ m.ensurePolygroups(0);+ } else if (mesh.hasPolygroups()) {+ m.polygroups.resize(ntOut);+ }+ if (mesh.hasHidden()) m.hidden.assign(ntOut, 0);+ if (mesh.hasUvs()) m.uvs.assign(ntOut * 3, glm::vec2(0.0f));+ if (mesh.hasUvFlags()) m.uvFlags.assign(ntOut * 3, 0);+ std::vector<uint32_t> newIndex(mesh.triangleCount(), Mesh::kNoQuad);+ for (size_t t = 0; t < ntOut; ++t) {+ const auto& tr = c.outTris[t];+ m.triangles[t] = glm::uvec3(remap[tr[0]], remap[tr[1]], remap[tr[2]]);+ const int64_t parent = c.outParent[t];+ if (parent < 0) {+ if (!m.polygroups.empty()) m.polygroups[t] = capGroup;+ continue;+ }+ const uint32_t pt = uint32_t(parent);+ if (!m.polygroups.empty()) m.polygroups[t] = mesh.polygroupAt(pt);+ if (mesh.hasHidden()) m.hidden[t] = mesh.hidden[pt];+ if (!c.splitParent[pt]) {+ newIndex[pt] = uint32_t(t);+ if (mesh.hasUvs())+ for (int k = 0; k < 3; ++k) m.uvs[t * 3 + k] = mesh.uvs[pt * 3 + k];+ if (mesh.hasUvFlags())+ for (int k = 0; k < 3; ++k) m.uvFlags[t * 3 + k] = mesh.uvFlags[pt * 3 + k];+ continue;+ }+ if (mesh.hasUvs()) {+ const glm::uvec3 src = mesh.triangles[pt];+ for (int k = 0; k < 3; ++k) {+ std::array<std::pair<uint32_t, float>, 3> w;+ if (!weights(tr[k], w)) continue;+ glm::vec2 uv(0.0f);+ for (const auto& [v, wt] : w)+ for (int j = 0; j < 3; ++j)+ if (src[j] == v) uv += mesh.uvs[pt * 3 + j] * wt;+ m.uvs[t * 3 + k] = uv;+ }+ }+ }+ if (mesh.hasQuads()) remapQuads(mesh, newIndex, m);+ m.texture = mesh.texture;+ m.paintToTexture = mesh.paintToTexture;+ m.selectionSets = mesh.selectionSets;+ if (!mesh.paintLayers.empty()) copyPaintLayers(mesh, m, kept);+ m.rebuildTopology();+ m.recomputeAllNormals();+ m.sanitizeAttributes();+ if (closed && !closedMesh(m)) continue; // a crack: try again with another nudge+ out = std::move(m);+ return true;+ }+ error = "Cut: the shape runs too close to the Part's vertices; draw it again slightly differently";+ return false;+}++// --- Command -----------------------------------------------------------------------------------------------++void registerCutCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ registry.add(+ {"cut",+ "Cut the active Part with a shape drawn on the screen (Line, Lasso, Rectangle or Polyline), extruded along "+ "the view. Modes: away (remove what the shape covers, through the whole Part, and close it with a flat cap), "+ "in (cut a flat-bottomed pocket `depth` deep), add (add the shape extruded `depth` out of the surface). The "+ "result stays watertight. Coordinates are normalised (-1..1, y up) in the given view; without a view the "+ "shape is drawn on the Part seen from the front (+Z).",+ {{"shape", T::String, "line, lasso, rect or polyline. Default lasso.", false},+ {"points", T::String, "The shape's points \"x0 y0 x1 y1 ...\": two for a line (or a rect's corners), three or "+ "more for a lasso, two or more for a polyline.", true},+ {"mode", T::String, "away, in or add. Default away.", false},+ {"depth", T::Number, "In and add: how deep or tall, as a fraction of the Part's size (0.001-4). Default 0.1.", false},+ {"flip", T::Bool, "Line and open polyline: cut the right side instead of the left. Default false.", false},+ {"closed", T::Bool, "Polyline: a closed polygon (cuts its inside) instead of a bent line. Default false.", false},+ {"view_proj", T::String, "Optional 16 numbers: column-major view-projection matrix.", false},+ {"symmetry", T::String, "Mirror axes, e.g. \"x\": the mirror image of the shape cuts too (default none).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (doc.mesh.triangleCount() == 0) return {false, "The Part is empty"};+ if (!doc.mesh.zspheres.empty()) return {false, "Cut: make Forge Spheres into a mesh first"};+ if (doc.mesh.micro) return {false, "Cut: apply or remove the micro level first"};+ CutShape shape = CutShape::Lasso;+ CutMode mode = CutMode::Away;+ if (!parseCutShape(argString(a, "shape", "lasso"), shape)) return {false, "Cut: shape is line, lasso, rect or polyline"};+ if (!parseCutMode(argString(a, "mode", "away"), mode)) return {false, "Cut: mode is away, in or add"};+ std::vector<glm::vec2> points;+ {+ const std::string text = argString(a, "points");+ std::vector<float> nums;+ const char* s = text.c_str();+ char* end = nullptr;+ for (float v = std::strtof(s, &end); end != s; v = std::strtof(s, &end)) {+ nums.push_back(v);+ s = end;+ }+ for (size_t i = 0; i + 1 < nums.size(); i += 2) points.push_back({nums[i], nums[i + 1]});+ if (nums.size() % 2) return {false, "Cut: points are x y pairs"};+ }+ std::string error;+ glm::mat4 vp;+ if (!viewProjArg(doc.mesh, a, vp, error)) return {false, error};+ std::vector<SymCopy> copies;+ if (!symmetryCopiesArg(a, doc.mesh, copies, error)) return {false, error};+ if (copies.empty()) copies.push_back(SymCopy{});+ std::vector<glm::dvec2> region;+ if (!cutRegion(shape, points, argBool(a, "flip", false), argBool(a, "closed", false), region, error))+ return {false, error};+ const float depth = float(argNumber(a, "depth", 0.1));+ // A mirror image of the shape that lands on the shape itself (a rectangle across the mirror plane) would+ // cut the same prism twice: skip it.+ auto sameCutter = [&](const glm::mat4& a, const glm::mat4& b) {+ const glm::dmat4 A(a), invB = glm::inverse(glm::dmat4(b));+ for (const glm::dvec2& r : region)+ for (double z : {-0.5, 0.5}) {+ const glm::dvec4 w = invB * glm::dvec4(r, z, 1.0);+ const glm::dvec4 q = A * (w / w.w);+ const glm::dvec3 n = glm::dvec3(q) / q.w;+ bool found = false;+ for (const glm::dvec2& s : region)+ found = found || (glm::length(glm::dvec2(n) - s) < 1e-5 * (1.0 + glm::length(s)) &&+ std::abs(n.z - z) < 1e-5);+ if (!found) return false;+ }+ return true;+ };+ Mesh current;+ const Mesh* src = &doc.mesh;+ size_t applied = 0;+ std::string lastError;+ std::vector<glm::mat4> done;+ for (const SymCopy& copy : copies) {+ // The copy of the shape: points p with copy^-1(p) inside the original.+ glm::mat4 inv(glm::transpose(copy.m));+ inv[3] = glm::vec4(copy.pivot - glm::transpose(copy.m) * copy.pivot, 1.0f);+ const glm::mat4 view = vp * inv;+ if (std::any_of(done.begin(), done.end(), [&](const glm::mat4& d) { return sameCutter(d, view); })) continue;+ done.push_back(view);+ Mesh next;+ if (!cutMesh(*src, view, region, mode, depth, next, lastError)) continue;+ current = std::move(next);+ src = ¤t;+ ++applied;+ }+ if (applied == 0) {+ if (lastError.find("misses") != std::string::npos) return {true, lastError};+ return {false, lastError};+ }+ const size_t before = doc.mesh.triangleCount();+ doc.replaceMeshUndoable(std::move(current), "Cut");+ const char* verb = mode == CutMode::Add ? "Cut Add" : mode == CutMode::In ? "Cut In" : "Cut Away";+ return {true, std::string(verb) + ": " + std::to_string(before) + " -> " ++ std::to_string(doc.mesh.triangleCount()) + " triangles"};+ }});+}++} // namespace sfdiff --git a/src/core/Cut.h b/src/core/Cut.hnew file mode 100644index 00000000..1dab44a9--- /dev/null+++ b/src/core/Cut.h@@ -0,0 +1,54 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Cut (#101, #91): one tool that cuts the active Part with a shape drawn on the screen. Shapes: Line (the+// half of the screen on one side of it), Lasso, Rectangle and Polyline (open: a bent line; closed: a polygon).+// Modes, each an exact boolean between the Part and the shape extruded along the view:+// Away - removes everything the shape covers, through the whole Part, and closes the cut with a flat cap;+// In - boolean difference with the shape pushed `depth` into the surface (a flat-bottomed pocket);+// Add - boolean union with the shape extruded `depth` out of the surface (anchored halfway into the Part).+// The result is watertight when the Part is (open Parts are trimmed without a cap; Add needs a closed one).+// The boolean runs in normalised device coordinates, where the extrusion is a straight prism: intersection+// points are shared by the Part's triangles and the prism's faces, so no cracks; the Part's surface is kept+// exactly where it isn't cut, with its attributes interpolated onto the new vertices. The cap gets a face group+// of its own.+#pragma once++#include "core/Mesh.h"++#include <glm/glm.hpp>++#include <string>+#include <vector>++namespace sf {++class CommandRegistry;++enum class CutShape : uint8_t { Line, Lasso, Rect, Polyline };+enum class CutMode : uint8_t { Away, In, Add };+const char* cutShapeName(CutShape s); // "line", "lasso", "rect", "polyline"+const char* cutModeName(CutMode m); // "away", "in", "add"+bool parseCutShape(const std::string& name, CutShape& out);+bool parseCutMode(const std::string& name, CutMode& out);++// The screen region (NDC, counter-clockwise, simple) a shape cuts. Line: two points, the side to the left of+// a -> b (`flip`: the right). Polyline: open (2+ points) cuts the left side like a bent line; `closed` (3+)+// cuts the inside. Lasso and Rectangle: the inside (a lasso that crosses itself keeps its biggest loop).+// False, saying why, for too few or degenerate points.+bool cutRegion(CutShape shape, const std::vector<glm::vec2>& points, bool flip, bool closed,+ std::vector<glm::dvec2>& region, std::string& error);++// Cuts `mesh` with `region` (from cutRegion) extruded along the view of `viewProj`. `depth` (In, Add) is a+// fraction of the mesh's largest side. False with `error` when nothing could be cut (the shape misses the mesh,+// the result would be empty, part of the mesh is behind the camera); `out` is the result otherwise.+bool cutMesh(const Mesh& mesh, const glm::mat4& viewProj, const std::vector<glm::dvec2>& region, CutMode mode,+ float depth, Mesh& out, std::string& error);++// Every edge of `mesh` is shared by exactly two triangles, wound opposite ways (a closed, manifold surface).+bool isWatertight(const Mesh& mesh);++// Registers "cut".+void registerCutCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/Masking.cpp b/src/core/Masking.cppindex 04048b72..11094634 100644--- a/src/core/Masking.cpp+++ b/src/core/Masking.cpp@@ -290,22 +290,33 @@ namespace {// Vertex v, or one of its mirror images, projects inside the shape.bool inShape(const Mesh& mesh, const glm::mat4& viewProj, const ScreenPolygon& shape,- const std::vector<SymCopy>& mirrors, uint32_t v) {+ const std::vector<SymCopy>& mirrors, uint32_t v, const glm::mat4* invViewProj = nullptr) {+ // With `invViewProj` (Front faces only), the point's normal must face the viewer: against the view ray+ // through it, which works for perspective and orthographic views alike.+ auto facing = [&](const glm::vec3& n, glm::vec2 ndc) {+ if (!invViewProj || v >= mesh.normals.size()) return true;+ const glm::vec4 a = *invViewProj * glm::vec4(ndc, -1.0f, 1.0f), b = *invViewProj * glm::vec4(ndc, 1.0f, 1.0f);+ return glm::dot(n, glm::vec3(b) / b.w - glm::vec3(a) / a.w) < 0.0f;+ };glm::vec2 ndc;- if (projectToNdc(viewProj, mesh.positions[v], ndc) && shape.contains(ndc)) return true;+ const glm::vec3 n = v < mesh.normals.size() ? mesh.normals[v] : glm::vec3(0.0f);+ if (projectToNdc(viewProj, mesh.positions[v], ndc) && shape.contains(ndc) && facing(n, ndc)) return true;for (const SymCopy& m : mirrors)- if (!m.identity() && projectToNdc(viewProj, m.point(mesh.positions[v]), ndc) && shape.contains(ndc)) return true;+ if (!m.identity() && projectToNdc(viewProj, m.point(mesh.positions[v]), ndc) && shape.contains(ndc) &&+ facing(m.dir(n), ndc))+ return true;return false;}} // namespacebool maskInShape(Mesh& mesh, const glm::mat4& viewProj, const ScreenPolygon& shape, float strength, bool unmask,- const std::vector<SymCopy>& mirrors) {+ const std::vector<SymCopy>& mirrors, bool frontFacesOnly) {if (mesh.vertexCount() == 0 || !shape.valid()) return false;const float s = std::clamp(strength, 0.0f, 1.0f);+ const glm::mat4 inv = glm::inverse(viewProj);return maskPass(mesh, [&](const std::vector<float>& m, uint32_t v) {- if (!inShape(mesh, viewProj, shape, mirrors, v)) return m[v];+ if (!inShape(mesh, viewProj, shape, mirrors, v, frontFacesOnly ? &inv : nullptr)) return m[v];return unmask ? m[v] * (1.0f - s) : m[v] + (1.0f - m[v]) * s;});}@@ -458,6 +469,10 @@ void registerMaskingCommands(CommandRegistry& registry) {"When the shape covers none of the model, clear the mask instead (ZBrush: Ctrl+drag on ""the background). Default false.",false};+ const ParamSpec frontFaces{"front_faces_only", T::Bool,+ "Only vertices facing the viewer: the far side of the model, and folds turned away, "+ "are left as they are (#91.3). Default false.",+ false};auto selection = [®istry](std::string name, std::string description, std::vector<ParamSpec> params,std::function<bool(const Args&, std::vector<glm::vec2>&, std::string&)> shape) {registry.add(@@ -481,7 +496,8 @@ void registerMaskingCommands(CommandRegistry& registry) {}const std::string label = unmask ? "Unmask" : "Mask";UndoRecord record = UndoRecord::captureMask(doc.mesh, label);- if (!maskInShape(doc.mesh, vp, polygon, float(argNumber(a, "strength", 1.0)), unmask, mirrors))+ if (!maskInShape(doc.mesh, vp, polygon, float(argNumber(a, "strength", 1.0)), unmask, mirrors,+ argBool(a, "front_faces_only", false)))return {true, label + ": mask unchanged"};doc.undo.push(std::move(record));doc.modified = true;@@ -501,7 +517,8 @@ void registerMaskingCommands(CommandRegistry& registry) {strength,viewProj,symmetry,- clearOutside},+ clearOutside,+ frontFaces},[](const Args& a, std::vector<glm::vec2>& points, std::string&) {const float x0 = float(argNumber(a, "x0", -1)), y0 = float(argNumber(a, "y0", -1));const float x1 = float(argNumber(a, "x1", 1)), y1 = float(argNumber(a, "y1", 1));@@ -518,7 +535,8 @@ void registerMaskingCommands(CommandRegistry& registry) {strength,viewProj,symmetry,- clearOutside},+ clearOutside,+ frontFaces},lassoArg);}diff --git a/src/core/Masking.h b/src/core/Masking.hindex afe125dc..7fae910f 100644--- a/src/core/Masking.h+++ b/src/core/Masking.h@@ -60,8 +60,9 @@ bool maskBorder(Mesh& mesh, int rings, bool polygroups, bool soft, float strengt// camera count as outside; the far side of the model is selected too.// `mirrors` (Sculptor::copies of the symmetry) also selects each vertex whose// mirror image or radial copy projects inside, as the brushes mirror (#51, #63); empty = none.+// `frontFacesOnly` (#91.3): only vertices whose normal faces the viewer (for a mirror image, its mirrored normal).bool maskInShape(Mesh& mesh, const glm::mat4& viewProj, const ScreenPolygon& shape, float strength, bool unmask,- const std::vector<SymCopy>& mirrors = {});+ const std::vector<SymCopy>& mirrors = {}, bool frontFacesOnly = false);// Whether any visible vertex (or, with `mirrors`, its mirror image) projects// inside `shape`: a selection that covers none of the model clears the mask// instead (ZBrush: Ctrl+drag on the background).diff --git a/tests/test_cut.cpp b/tests/test_cut.cppnew file mode 100644index 00000000..2369087f--- /dev/null+++ b/tests/test_cut.cpp@@ -0,0 +1,298 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Cut (#101, #91): every shape and mode on a sphere, a low-poly cube and a two-Part scene; watertight results,+// attributes, symmetry, perspective views, open meshes and undo. Also Mask Lasso "Front faces only" (#91.3).+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Cut.h"+#include "core/Masking.h"+#include "core/Primitives.h"+#include "core/ScreenSelect.h"++#include <glm/gtc/matrix_transform.hpp>++#include <cmath>+#include <cstdio>++using namespace sf;++namespace {++const CommandRegistry& registry() {+ static CommandRegistry r;+ return r;+}++double volume(const Mesh& m) {+ double v = 0.0;+ for (const glm::uvec3& t : m.triangles)+ v += glm::dot(glm::dvec3(m.positions[t.x]), glm::cross(glm::dvec3(m.positions[t.y]), glm::dvec3(m.positions[t.z])));+ return v / 6.0;+}++CommandResult cut(Document& d, const std::string& shape, const std::string& points, const std::string& mode,+ Args extra = {}) {+ extra["shape"] = shape;+ extra["points"] = points;+ extra["mode"] = mode;+ return registry().execute(d, "cut", extra);+}++std::string matrixString(const glm::mat4& m) {+ std::string s;+ char buf[32];+ for (int i = 0; i < 16; ++i) {+ std::snprintf(buf, sizeof buf, "%s%.9g", i ? " " : "", double(m[i / 4][i % 4]));+ s += buf;+ }+ return s;+}++// Vertices inside an axis box of x, y (the front view's NDC is world x, y for a unit sphere) and above z.+size_t countIn(const Mesh& m, float x0, float x1, float y0, float y1, float zAbove = -1e9f) {+ size_t n = 0;+ for (const glm::vec3& p : m.positions)+ if (p.x > x0 && p.x < x1 && p.y > y0 && p.y < y1 && p.z > zAbove) ++n;+ return n;+}++const double kSphere = 4.0 / 3.0 * 3.14159265358979;++} // namespace++TEST(cut_command_registered) {+ CHECK(registry().find("cut") != nullptr);+ CHECK(registry().toolSchemaJson().find("\"cut\"") != std::string::npos);+ CutShape s;+ CutMode m;+ CHECK(parseCutShape("polyline", s) && s == CutShape::Polyline);+ CHECK(parseCutMode("add", m) && m == CutMode::Add);+ CHECK(!parseCutMode("trim", m));+}++TEST(cut_line_away_halves_sphere) {+ Document d = makeDoc(makeIcosphere(4));+ CHECK(isWatertight(d.mesh));+ const double v0 = volume(d.mesh);+ // A vertical line upwards: the left (-x) half goes, a flat cap closes the right half.+ const CommandResult r = cut(d, "line", "0.013 -2 0.013 2", "away");+ CHECK(r.ok);+ CHECK(isWatertight(d.mesh));+ size_t left = 0, onCap = 0;+ for (const glm::vec3& p : d.mesh.positions) {+ if (p.x < 0.013f - 1e-4f) ++left;+ if (std::abs(p.x - 0.013f) < 1e-4f) ++onCap;+ }+ CHECK(left == 0);+ CHECK(onCap > 20);+ const double v1 = volume(d.mesh);+ CHECK(v1 > 0.4 * v0 && v1 < 0.5 * v0); // a bit under half: the line is right of centre+ // The cap is a face group of its own.+ CHECK(d.mesh.hasPolygroups());+ // Flip keeps the other half.+ Document e = makeDoc(makeIcosphere(4));+ CHECK(cut(e, "line", "0.013 -2 0.013 2", "away", {{"flip", true}}).ok);+ CHECK(isWatertight(e.mesh));+ for (const glm::vec3& p : e.mesh.positions) CHECK(p.x < 0.013f + 1e-4f);+ CHECK(std::abs(volume(e.mesh) + v1 - v0) < 0.02 * v0);+ // Undo brings the sphere back.+ CHECK(registry().execute(d, "undo").ok);+ CHECK(std::abs(volume(d.mesh) - v0) < 1e-6);+}++TEST(cut_every_shape_away_through_sphere) {+ struct Case {+ const char* shape;+ const char* points;+ bool closed;+ } cases[] = {+ {"rect", "-0.31 -0.29 0.33 0.27", false},+ {"lasso", "-0.5 -0.47 0.52 -0.45 0.03 0.61", false},+ {"polyline", "-0.5 -0.47 0.52 -0.45 0.03 0.61", true},+ };+ for (const Case& c : cases) {+ Document d = makeDoc(makeIcosphere(4));+ const double v0 = volume(d.mesh);+ const CommandResult r = cut(d, c.shape, c.points, "away", {{"closed", c.closed}});+ CHECK(r.ok);+ CHECK(isWatertight(d.mesh)); // a tunnel through the sphere+ CHECK(volume(d.mesh) < 0.9 * v0);+ CHECK(countIn(d.mesh, -0.1f, 0.1f, -0.2f, 0.1f) == 0);+ }+ // Open polyline: a bent line, cutting the top-left away.+ Document d = makeDoc(makeIcosphere(4));+ CHECK(cut(d, "polyline", "-2 0.21 0.02 0.21 0.53 -2", "away").ok);+ CHECK(isWatertight(d.mesh));+ CHECK(countIn(d.mesh, -2.0f, -0.05f, 0.25f, 2.0f) == 0);+ CHECK(countIn(d.mesh, -2.0f, -0.05f, -2.0f, 0.15f) > 0);+}++TEST(cut_in_and_add_on_sphere) {+ // In: a flat-bottomed pocket 0.4 deep (depth 0.2 of the size 2) in the front.+ Document d = makeDoc(makeIcosphere(4));+ const double v0 = volume(d.mesh);+ CHECK(cut(d, "rect", "-0.31 -0.29 0.33 0.27", "in", {{"depth", 0.2}}).ok);+ CHECK(isWatertight(d.mesh));+ CHECK(volume(d.mesh) < v0 && volume(d.mesh) > 0.8 * v0);+ float bottom = 1e9f;+ for (const glm::vec3& p : d.mesh.positions)+ if (std::abs(p.x) < 0.4f && std::abs(p.y) < 0.4f && p.z > 0.3f) bottom = std::min(bottom, p.z); // floor corners+ CHECK(bottom > 0.5f && bottom < 0.62f); // the pocket floor: front (~0.95) minus 0.4+ CHECK(countIn(d.mesh, -0.2f, 0.2f, -0.2f, 0.2f, bottom + 0.01f) == 0);+ CHECK(countIn(d.mesh, -0.2f, 0.2f, -0.2f, 0.2f) > 0); // the back of the sphere is still there++ // Add: the rectangle extruded 0.4 towards the viewer, anchored in the sphere.+ Document a = makeDoc(makeIcosphere(4));+ CHECK(cut(a, "rect", "-0.31 -0.29 0.33 0.27", "add", {{"depth", 0.2}}).ok);+ CHECK(isWatertight(a.mesh));+ CHECK(volume(a.mesh) > v0 * 1.02);+ CHECK(a.mesh.bounds().max.z > 1.3f);+ for (const char* shape : {"lasso", "polyline"}) {+ Document b = makeDoc(makeIcosphere(4));+ CHECK(cut(b, shape, "-0.5 -0.47 0.52 -0.45 0.03 0.61", "add", {{"depth", 0.1}, {"closed", true}}).ok);+ CHECK(isWatertight(b.mesh));+ CHECK(volume(b.mesh) > v0);+ Document c = makeDoc(makeIcosphere(4));+ CHECK(cut(c, shape, "-0.5 -0.47 0.52 -0.45 0.03 0.61", "in", {{"depth", 0.1}, {"closed", true}}).ok);+ CHECK(isWatertight(c.mesh));+ CHECK(volume(c.mesh) < v0);+ }+ // Line In: a step cut off the front.+ Document l = makeDoc(makeIcosphere(4));+ CHECK(cut(l, "line", "0.013 -2 0.013 2", "in", {{"depth", 0.3}}).ok);+ CHECK(isWatertight(l.mesh));+ CHECK(volume(l.mesh) < v0);+}++TEST(cut_low_poly_cube_hole_inside_one_triangle) {+ // A small lasso inside one face of a 12-triangle cube: the cut's outline sits inside a triangle (a hole to bridge).+ Document d = makeDoc(makeCube(1));+ const size_t t0 = d.mesh.triangleCount();+ CHECK(cut(d, "lasso", "-0.21 -0.18 0.23 -0.2 0.27 0.22 -0.19 0.24", "in", {{"depth", 0.25}}).ok);+ CHECK(isWatertight(d.mesh));+ CHECK(d.mesh.triangleCount() > t0);+ CHECK(std::abs(volume(d.mesh) - (8.0 - 0.44 * 0.43 * 0.5)) < 0.1);+ Document a = makeDoc(makeCube(1));+ CHECK(cut(a, "rect", "-0.21 -0.18 0.23 0.24", "add", {{"depth", 0.25}}).ok);+ CHECK(isWatertight(a.mesh));+ CHECK(volume(a.mesh) > 8.0);+ Document w = makeDoc(makeCube(1));+ CHECK(cut(w, "rect", "-0.21 -0.18 0.23 0.24", "away").ok);+ CHECK(isWatertight(w.mesh));+ CHECK(std::abs(volume(w.mesh) - (8.0 - 2.0 * 0.44 * 0.42)) < 0.05);+}++TEST(cut_perspective_view_and_symmetry) {+ Document d = makeDoc(makeIcosphere(4));+ const glm::mat4 vp = glm::perspective(glm::radians(40.0f), 1.3f, 0.1f, 100.0f) *+ glm::lookAt(glm::vec3(0.7f, 0.9f, 4.0f), glm::vec3(0.0f), glm::vec3(0, 1, 0));+ const double v0 = volume(d.mesh);+ CHECK(cut(d, "lasso", "-0.1 -0.1 0.12 -0.08 0.02 0.15", "away", {{"view_proj", matrixString(vp)}}).ok);+ CHECK(isWatertight(d.mesh));+ CHECK(volume(d.mesh) < v0);+ CHECK(cut(d, "rect", "-0.05 -0.4 0.05 0.4", "add", {{"view_proj", matrixString(vp)}, {"depth", 0.1}}).ok);+ CHECK(isWatertight(d.mesh));++ // X symmetry: a rectangle on the right also cuts its mirror image on the left.+ Document s = makeDoc(makeIcosphere(4));+ CHECK(cut(s, "rect", "0.31 -0.19 0.61 0.21", "away", {{"symmetry", std::string("x")}}).ok);+ CHECK(isWatertight(s.mesh));+ CHECK(countIn(s.mesh, 0.36f, 0.56f, -0.14f, 0.16f) == 0);+ CHECK(countIn(s.mesh, -0.56f, -0.36f, -0.14f, 0.16f) == 0);+ CHECK(countIn(s.mesh, -0.2f, 0.2f, -0.14f, 0.16f) > 0);+}++TEST(cut_two_part_scene_cuts_active_part_only) {+ Document d = makeDoc(makeIcosphere(4));+ CHECK(registry().execute(d, "subtool_append", {{"type", std::string("sphere")}}).ok);+ CHECK(d.subtools.size() == 2 && d.activeSubtool == 1);+ const Mesh other = d.subtoolMesh(0);+ const double v0 = volume(d.mesh);+ const AABB b = d.mesh.bounds();+ // The default view frames the active Part: a line through its middle.+ CHECK(cut(d, "line", "0.013 -2 0.013 2", "away").ok);+ CHECK(isWatertight(d.mesh));+ CHECK(volume(d.mesh) < 0.6 * v0);+ for (const glm::vec3& p : d.mesh.positions) CHECK(p.x > b.center().x - 0.01f * b.extent().x);+ // The other Part is untouched.+ CHECK(d.subtoolMesh(0).triangleCount() == other.triangleCount());+ CHECK(d.subtoolMesh(0).positions == other.positions);+ // Undo and redo.+ CHECK(registry().execute(d, "undo").ok);+ CHECK(std::abs(volume(d.mesh) - v0) < 1e-6);+ CHECK(registry().execute(d, "redo").ok);+ CHECK(volume(d.mesh) < 0.6 * v0);+ // Every mode on the other Part too.+ CHECK(registry().execute(d, "subtool_select", {{"index", 0.0}}).ok);+ for (const char* mode : {"away", "in", "add"}) {+ const size_t before = d.undo.undoCount();+ CHECK(cut(d, "rect", "-0.31 -0.29 0.33 0.27", mode, {{"depth", 0.15}}).ok);+ CHECK(isWatertight(d.mesh));+ CHECK(d.undo.undoCount() == before + 1);+ }+}++TEST(cut_attributes_misses_and_open_meshes) {+ Document d = makeDoc(makeIcosphere(4));+ d.mesh.ensureMask(1.0f);+ d.mesh.ensureColors(glm::vec3(0.2f, 0.4f, 0.6f));+ CHECK(cut(d, "line", "0.013 -2 0.013 2", "away").ok);+ size_t masked = 0;+ for (float m : d.mesh.mask) masked += m > 0.99f;+ CHECK(masked > d.mesh.vertexCount() / 2); // the kept surface keeps its mask; only the cap's inner corners are free+ for (const glm::vec3& c : d.mesh.colors) CHECK(glm::length(c - glm::vec3(0.2f, 0.4f, 0.6f)) < 1e-3f);++ // A shape off the Part changes nothing and adds no undo step.+ Document m = makeDoc(makeIcosphere(3));+ const size_t steps = m.undo.undoCount();+ const CommandResult miss = cut(m, "rect", "3 3 4 4", "away");+ CHECK(miss.ok && miss.message.find("misses") != std::string::npos);+ CHECK(m.undo.undoCount() == steps);+ // Covering all of it is refused.+ CHECK(!cut(m, "rect", "-5 -5 5 5", "away").ok);+ // Bad arguments.+ CHECK(!cut(m, "line", "0 0", "away").ok);+ CHECK(!cut(m, "lasso", "0 0 1 1", "away").ok);+ CHECK(!cut(m, "lasso", "0 0 1 1 0.5 0.5", "sideways").ok);++ // An open plane is trimmed without a cap; Add needs a closed Part.+ Document p = makeDoc(makePlane(16));+ const size_t t0 = p.mesh.triangleCount();+ const glm::mat4 top = glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, 0.1f, 10.0f) *+ glm::lookAt(glm::vec3(0, 5, 0), glm::vec3(0.0f), glm::vec3(0, 0, -1));+ const AABB pb = p.mesh.bounds();+ const bool flat = pb.extent().y < 1e-4f; // makePlane lies in XZ+ const std::string view = flat ? matrixString(top) : std::string();+ Args a{{"view_proj", view}};+ if (view.empty()) a.erase("view_proj");+ CHECK(cut(p, "line", "0.013 -2 0.013 2", "away", a).ok);+ CHECK(p.mesh.triangleCount() < t0);+ CHECK(!isWatertight(p.mesh));+ CHECK(!cut(p, "rect", "-0.3 -0.3 0.3 0.3", "add", a).ok);+}++TEST(mask_lasso_front_faces_only) {+ Document d = makeDoc(makeIcosphere(3));+ // The whole sphere seen from the front: only the half facing the viewer (+Z) is masked.+ CHECK(registry().execute(d, "mask_rect", {{"x0", -2.0}, {"y0", -2.0}, {"x1", 2.0}, {"y1", 2.0}, {"front_faces_only", true}}).ok);+ size_t wrong = 0, masked = 0;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {+ const float z = d.mesh.normals[v].z;+ const bool m = d.mesh.mask[v] > 0.5f;+ masked += m;+ if (std::abs(z) > 0.05f && m != (z > 0.0f)) ++wrong;+ }+ CHECK(wrong == 0);+ CHECK(masked > 0 && masked < d.mesh.vertexCount());+ CHECK(registry().execute(d, "mask_clear").ok);+ CHECK(registry().execute(d, "mask_lasso", {{"points", std::string("-2 -2 2 -2 0 2")}, {"front_faces_only", true}}).ok);+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v)+ if (d.mesh.normals[v].z < -0.05f) CHECK(d.mesh.mask[v] == 0.0f);+ // Without the option the back is masked too.+ CHECK(registry().execute(d, "mask_lasso", {{"points", std::string("-2 -2 2 -2 0 2")}}).ok);+ size_t back = 0;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) back += d.mesh.normals[v].z < -0.5f && d.mesh.mask[v] > 0.5f;+ CHECK(back > 0);+}diff --git a/tests/ui/cut_tool.sfui b/tests/ui/cut_tool.sfuinew file mode 100644index 00000000..8a1a3a75--- /dev/null+++ b/tests/ui/cut_tool.sfui@@ -0,0 +1,62 @@+# Cut (#101, #91): the Cut shapes in the Ctrl+Shift brush picker, Tool > Cut's modes, one undo step per cut; and+# Duplicate Part's shortcut (Ctrl+Shift+D).+run new_sphere subdivisions=5+remember triangles full+hold ctrl+shift+click "##tile.brush"+wait 0.1+expect "Cut Rectangle##held.cut.rect"+hover "Cut Rectangle##held.cut.rect"+expect_help "rectangle"+shot cut-brush-picker+click "Cut Rectangle##held.cut.rect"+hold none+expect_value hide_shape == 5++# Away: a hole through the sphere (with X symmetry the rectangle mirrors onto itself).+hold ctrl+shift+drag_path 0.38 0.36 0.62 0.6 keep+wait 0.1+shot cut-rect-dragging+hold none+wait 0.2+expect_value hidden == 0+expect_value can_undo == 1+shot cut-rect-away+key ctrl+z+expect_value triangles == $full++# Tool > Cut: Add raises a rectangle, In cuts a pocket with a lasso.+click "Cut"+click "Add##cut.add"+shot cut-panel+hold ctrl+shift+drag_path 0.4 0.4 0.6 0.55+hold none+wait 0.2+expect_value can_undo == 1+shot cut-rect-add+key ctrl+z+click "In##cut.in"+click "Cut Lasso##cut.lasso"+expect_value hide_shape == 4+hold ctrl+shift+drag_path 0.4 0.4 0.6 0.42 0.55 0.6 0.42 0.58+hold none+wait 0.2+expect_value can_undo == 1+shot cut-lasso-in++# Back to Select Rectangle: Ctrl+Shift hides again.+click "Away##cut.away"+hold ctrl+shift+click "##tile.brush"+wait 0.1+click "Select Rectangle##held.select.rect"+hold none+expect_value hide_shape == 2++# Duplicate Part: Ctrl+Shift+D.+expect_value subtools == 1+key ctrl+shift+d+expect_value subtools == 2