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
Parts tools (@foirgairwolf): Split hidden / masked / unmasked into a new Part, Delete masked, per-Part shading in the Parts list, Merge by Distance, Check Mesh with per-issue Fix and Fix all
islandmed143a4348c527
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 09f7b670..e18b1a28 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -97,6 +97,7 @@ add_library(sculptforge_core STATICsrc/core/Masking.cppsrc/core/Cut.cppsrc/core/CloseHoles.cpp+ src/core/MeshCheck.cppsrc/core/BrushAlpha.cppsrc/core/Stencil.cppsrc/core/Stroke.cpp@@ -461,6 +462,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/PanelIntegrations.cppsrc/app/WhatsNewPopup.cppsrc/app/PanelExtract.cpp+ src/app/PanelMeshCheck.cppsrc/app/PanelTimeline.cppsrc/app/ProofMode.cppsrc/app/BenchVideo.cppdiff --git a/assets/fonts/NotoSansSC-UI.otf b/assets/fonts/NotoSansSC-UI.otfindex 8d50de07..fddeba34 100644Binary files a/assets/fonts/NotoSansSC-UI.otf and b/assets/fonts/NotoSansSC-UI.otf differdiff --git a/assets/fonts/NotoSansTC-UI.otf b/assets/fonts/NotoSansTC-UI.otfindex b8fc6182..1e5897bf 100644Binary files a/assets/fonts/NotoSansTC-UI.otf and b/assets/fonts/NotoSansTC-UI.otf differdiff --git a/changes/feat-parts-tools.md b/changes/feat-parts-tools.mdnew file mode 100644index 00000000..827c6e27--- /dev/null+++ b/changes/feat-parts-tools.md@@ -0,0 +1,39 @@+---+whats_new: **Split > Hidden / Masked / Unmasked** (**Tool > Parts**): move the hidden, masked or unmasked triangles+ of a Part into a new Part just below it, in one undo step. Asked for by @foirgairwolf.+whats_new: **Delete masked** (**Tool > Visibility**) deletes what is masked, as **Delete hidden** does for what is+ hidden. Undoable.+whats_new: **Smooth or flat per Part, right in the list**: click the mark left of a Part's eye to go from the scene's+ shading to Smooth to Flat.+highlight: Split masked, hidden or unmasked into a new Part+added: **Split > Hidden / Masked / Unmasked** (Tool > Parts; `part_split_hidden`, `part_split_masked`,+ `part_split_unmasked`): the triangles leave the active Part for a new Part below it (same folder, visibility and+ shading), one undo step that also removes the new Part. A triangle is masked when its corners' average mask is+ above 50%. UVs, face groups, vertex paint and sculpt layers carry over; subdivision levels are cut at the current+ level (undo restores them). Thanks @foirgairwolf.+added: **Delete masked** (Tool > Visibility; `delete_masked`), the mirror of Delete hidden. Thanks @foirgairwolf.+added: A per-Part shading mark in the Parts list (Scene / Smooth / Flat; `part_shading`). Thanks @foirgairwolf.+whats_new: **Merge by Distance** (**Tool > Geometry**): merge points closer than a distance, with a live count and the+ points shown on the model before you click. For unwelded imports. Asked for by @foirgairwolf.+whats_new: **Check Mesh** (**Tool > Geometry**): counts non-manifold edges, holes, duplicate, degenerate, zero-area and+ flipped triangles and isolated points, with a **Fix** per row and **Fix all**. Checking never changes the mesh.+added: **Merge by Distance** (Tool > Geometry; `weld_points distance=... preview=true`): the points of the active Part+ within the distance merge into the nearest kept one; collapsed triangles go; one undo step. The count follows the+ slider and the points that would merge show in orange. Thanks @foirgairwolf.+added: **Check Mesh** (Tool > Geometry; `mesh_check`, `mesh_fix issue=...`): non-manifold edges (Fix loosens the extra+ triangles), holes (capped as Close Holes), duplicate and degenerate triangles (deleted), zero-area triangles+ (shortest edge collapsed), flipped triangles and inside-out closed pieces (rewound), isolated points (removed).+ Fix all fixes everything except holes, as one undo step. Thanks @foirgairwolf.+testers:+ - Any OS: mask half a sphere, Tool > Parts > Split > Masked: a new "<name> masked" Part below, unmasked; Ctrl+Z+ once puts the half back and removes the Part.+ - Hide part of a Part (Ctrl+Shift+drag), Split > Hidden: the new Part shows those triangles.+ - Tool > Visibility > Delete masked, then Ctrl+Z.+ - Parts list: click the mark left of the eye three times: Scene (dim), Smooth (disc), Flat (hexagon), back.+ - Open tests/data/check_mesh_cube.obj (each face has its own points): Tool > Geometry > Merge by Distance shows+ "16 points will merge" and orange dots at the corners; Merge leaves 8 points. Ctrl+Z.+ - Check Mesh on a clean sphere: "No problems found". On a broken import: rows with counts; Fix one row, it goes;+ Fix all, then Ctrl+Z once brings every problem back.+ - Windows at 150% scaling: the Check Mesh rows' counts and Fix buttons line up at the right edge.+---+The Discord #ideas request (1568553579323588630) by @foirgairwolf: Geometry / Parts panel additions.diff --git a/docs/guide/face-groups.md b/docs/guide/face-groups.mdindex c62da524..8a30109e 100644--- a/docs/guide/face-groups.md+++ b/docs/guide/face-groups.md@@ -92,8 +92,9 @@ Open **Tool > Visibility**:| **Show all** | Show every hidden part again. Available when something is hidden. | `show_all` || **Invert visible** | Hide what is visible and show what is hidden. | `invert_visibility` || **Delete hidden** | Permanently remove the hidden triangles from the mesh. Undoable. | `delete_hidden` |+| **Delete masked** | Remove the masked triangles (their corners' average mask above 50%). Undoable. Available when something is masked. | `delete_masked` |-**Delete hidden** keeps every attribute of what remains (mask, vertex paint, face groups, UVs and sculpt layers).+**Delete hidden** and **Delete masked** keep every attribute of what remains (mask, vertex paint, face groups, UVs and sculpt layers).Use it to cut away parts of a scan or a generated model, or to remove the inside of a mesh after you isolatedthe outside.diff --git a/docs/guide/geometry.md b/docs/guide/geometry.mdindex cfeea40b..baa5d276 100644--- a/docs/guide/geometry.md+++ b/docs/guide/geometry.md@@ -182,6 +182,41 @@ without symmetry, to finish a half model, or to repair a model whose sides havesurface still facing outward. Face Groups, vertex paint, UVs and layers come along; subdivision levels are removed(undo restores them). `mirror pivot=center` flips it in place about its own centre instead.+## Merge by Distance++**Tool > Geometry > Merge by Distance** merges the points of the active Part that are closer together than the+**Distance** slider into one. Use it on an import whose triangles don't share their points (an STL, or a model+another program split at its seams): until they are merged, every triangle is loose and a brush tears the surface+apart.++- The line under the slider counts the points that will merge, and those points show on the model in orange while+ the section is open. On meshes with more than 1.5 million points the count updates when you let go of the slider.+- **0** merges only points exactly on top of each other. The slider goes up to 2% of the Part's size; scripts can use+ any distance.+- Points are taken in order: each one within the distance of a point kept before it merges into the nearest of them+ and takes its position, mask, vertex paint and sculpt layer offsets. Triangles that collapse (two corners on one+ point) are removed, and so are points no triangle uses.+- One undo step. Subdivision levels are removed (undo restores them).++## Check Mesh++**Tool > Geometry > Check Mesh** looks for what makes a mesh hard to sculpt, remesh, 3D print or export. **Check**+counts the problems; it changes nothing. Each problem found gets a row with its count and a **Fix** button that+changes only what that row names, as one undo step.++| Row | What it is | What Fix does |+|---|---|---|+| **Non-manifold edges** | Edges shared by three or more triangles (a fin, a wall inside the mesh) | Each triangle past the first two gets its own copy of the edge, so it comes loose; nothing is deleted |+| **Holes** | Open boundary loops | Caps each with a patch, as [Close Holes](#close-holes) does |+| **Duplicate triangles** | Triangles on the same three points as another, either way round | Deletes the copies |+| **Degenerate triangles** | Triangles that use one point twice | Deletes them |+| **Zero-area triangles** | Three different points in one line (a sliver) | Collapses each one's shortest edge |+| **Flipped triangles** | Triangles wound against their neighbours, or a closed piece that is inside out | Turns them to match the rest of their piece, and closed pieces right way out |+| **Isolated points** | Points no triangle uses | Removes them |++**Fix all** fixes every row except **Holes**, in one undo step: a mesh can be open on purpose (a cloth panel, a+mask, a relief), so holes are only capped when you click their own **Fix**. After a fix the list checks again.+## LOD chainsA level-of-detail chain is a series of lighter copies of the model for game engines: LOD0 is the full sculpt, and@@ -214,7 +249,8 @@ See [Exporting](exporting.md) for these exports and their options.## Undo and safety-Subdivide, remesh, Quad Remesh, decimate, Mirror And Weld, Mirror and delete hidden are single undo steps on the+Subdivide, remesh, Quad Remesh, decimate, Mirror And Weld, Mirror, Merge by Distance, every Check Mesh fix and+delete hidden are single undo steps on theactive Part. They can use a lot of memory on dense meshes, and undo keeps a full copy of the previous mesh foreach of them. Before a big change on a heavy sculpt:@@ -233,6 +269,9 @@ each of them. Before a big change on a heavy sculpt:| `close_holes` | `max_edges` closes only holes with at most that many boundary edges (default 0: all); `refine` (default true; false: as few triangles as possible); `new_group` (default true) || `mirror_and_weld` | `axis` x, y, z or several, e.g. `xz` (default x); `side` positive (default) or negative || `mirror` | `axis` (default x); `pivot` origin (default) or center |+| `weld_points` | `distance` in scene units (0: only exactly coincident points); `preview=true` only counts them |+| `mesh_check` | Lists the problems, e.g. `holes=2 flipped=14` |+| `mesh_fix` | `issue` non_manifold, holes, duplicate, degenerate, zero_area, flipped, isolated or all (all but holes) || `export_lods` | `path` (base name), `levels` 1-8 including LOD0 (default 4), `ratio` 0.1-0.9 (default 0.5) |```shdiff --git a/docs/guide/parts.md b/docs/guide/parts.mdindex f2e8a653..a1774712 100644--- a/docs/guide/parts.md+++ b/docs/guide/parts.md@@ -12,8 +12,8 @@ hiding, reordering, merging and splitting Parts, and how they travel through fil[sculpt layers](layers.md).- Each Part has its own undo history. <kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes the last change in the activePart, and switching Parts doesn't lose the history of the others.-- Adding, deleting, reordering, merging and splitting Parts are **not undoable**. Merges and- deletes ask for confirmation first.+- Adding, deleting, reordering, merging and splitting Parts are **not undoable**, except **Split hidden**,+ **Split masked** and **Split unmasked** (one undo step each). Merges and deletes ask for confirmation first.- The Parts list highlights the active Part. In the Classic layout the title strip also shows it and its placein the list, for example `Part Helmet (2/5)`.@@ -23,7 +23,7 @@ The list is in **Tool > Parts**, which is open in the right tray by default.-Each row shows a small picture of the Part, its name, its triangle count and an eye. The pictures are drawn from+Each row shows a small picture of the Part, its name, its triangle count, its shading and an eye. The pictures are drawn fromthe model the viewport already has on the graphics card, so they cost almost nothing even on very dense Parts,and they catch up a moment after you stop changing a Part (not during a stroke).@@ -33,6 +33,7 @@ and they catch up a moment after you stop changing a Part (not during a stroke).| Sculpt the Part under the cursor | Point at it and press <kbd>Alt</kbd>+<kbd>Q</kbd> (every input style, as in Blender): it becomes the active Part, the view stays put and each Part keeps its mask || 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 |+| Shade it smooth or flat | Click the mark left of the eye: it goes from **as the scene** (dim) to **Smooth** (a disc) to **Flat** (a faceted hexagon) and back. Only this Part changes; the scene's own setting is **Render > Materials > Shading** || 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 |@@ -167,6 +168,24 @@ meshes the Auto UV takes a while. Scripts can skip it with `keep_texture=false`,Both replace the active Part with the pieces. Because a merge keeps each original mesh in its own face group,**Split groups** undoes a merge.+### Split hidden, masked or unmasked++The **Split** row (**Hidden**, **Masked**, **Unmasked**) takes part of the active Part out into a **new Part just below it**, in the same folder, shown+as the source is and shaded the same way. Each is **one undo step**: <kbd>Ctrl</kbd>+<kbd>Z</kbd> puts the+triangles back and removes the new Part.++| Button | Moves into the new Part | Command |+|---|---|---|+| **Split > Hidden** | the hidden triangles; they are shown in the new Part | `part_split_hidden` |+| **Split > Masked** | the masked triangles; the new Part starts unmasked | `part_split_masked` |+| **Split > Unmasked** | the triangles that are not masked; the masked ones stay | `part_split_unmasked` |++A triangle counts as **masked when the average mask of its three corners is above 50%**, so a soft mask edge+splits along its middle and a single masked corner doesn't take its neighbours. UVs, face groups, vertex paint and+sculpt layers carry over to both sides. [Subdivision levels](subdivision-levels.md) can't be cut: the split is+made at the level the Part is on, which becomes its base (undo brings the levels back). To delete instead of+split, use **Delete hidden** or **Delete masked** in **Tool > Visibility**.+## Extract a shell**Extract**, in **Tool > Parts**, makes a new Part from the masked part of the active one: a helmet from the@@ -236,6 +255,8 @@ used.| `transform translate=0,0.1,0 folder=true` | Transform the visible Parts in the active Part's folder || `part_merge_down` / `part_merge_visible` | Merge || `part_split_groups` / `part_split_parts` | Split |+| `part_split_hidden` / `part_split_masked` / `part_split_unmasked` | Split off into a new Part (undoable) |+| `part_shading mode=flat` | Shade a Part `default` (as the scene), `smooth` or `flat` || `extract thickness=0.02 smooth=5 double=false` | Preview an Extract shell from the mask; `tcorne` / `tborder` for a triangle rim; `accept=true` keeps it at once || `extract_accept` / `extract_cancel` | Keep or remove the Extract preview |diff --git a/src/app/App.cpp b/src/app/App.cppindex 765f9f38..d783be49 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -3050,6 +3050,7 @@ void App::drawUi() {drawGizmo(); // Transform gizmo handles and panel (Gizmo.cpp)drawQRemeshGuides(); // QRemesh Guides curves (PanelRetopo.cpp)drawUvEditorOverlay(); // UV seams on the model, the Seam tool's cursor (PanelUvEditor.cpp)+ drawWeldPreviewOverlay(); // the points Merge by Distance would merge (PanelMeshCheck.cpp)drawForgeSphereOverlay(); // the sphere under the cursor (PanelForge Spheres.cpp)drawForgeSphereMenu(); // a right click on a spheredrawFaceOverlay(); // facial landmarks (PanelFace.cpp)diff --git a/src/app/App.h b/src/app/App.hindex b4c35602..e26ed534 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -33,6 +33,7 @@#include "core/DiscordPresence.h"#include "core/Face.h"#include "core/GeneratedRemesh.h"+#include "core/MeshCheck.h"#include "core/MeshTransform.h"#include "app/Wintab.h"#include "core/PenPredictor.h"@@ -1788,6 +1789,20 @@ private:void drawExtractContents();void drawModifyTopologyContents();void drawDeformationContents();+ // PanelMeshCheck.cpp: Tool > Geometry > Merge by Distance (weld_points) and Check Mesh (mesh_check / mesh_fix),+ // and the points a weld would merge drawn on the model while the section shows.+ void drawMeshCheckContents();+ void drawWeldPreviewOverlay();+ uint64_t meshCheckKey() const; // changes with the active Part's mesh+ float weldDistance_ = -1.0f; // scene units; < 0 until the section first shows (then a default from the Part's size)+ bool weldShown_ = false; // the section was drawn this frame (the preview shows)+ uint64_t weldKey_ = 0; // meshCheckKey() and distance the count below is for+ float weldKeyDistance_ = -1.0f;+ size_t weldCount_ = 0;+ std::vector<glm::vec3> weldPoints_; // a sample (<= 20000) of the points that would merge, for the preview+ MeshReport meshReport_;+ uint64_t meshReportKey_ = 0; // 0 = not checked yet+ void runMeshCheck();void runExtract(); // Extract with the palette's settings (a preview; Accept keeps it)static std::string axesText(const bool axes[3]); // "x", "xz", "" (the axis argument of mirror commands)float extractThick_ = 0.015f; // Thick: fraction of the Part's sizediff --git a/src/app/Config.cpp b/src/app/Config.cppindex 973f378a..e05bc460 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -467,6 +467,20 @@ void App::initActions() {ICON_LC_COPY, "part_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).");+ add("part.split_hidden", "Split Hidden", "Tool > Parts", nullptr, [this] { runCommand("part_split_hidden"); }, nullptr,+ "part_split_hidden", nullptr, [this] { return doc_.mesh.hasHidden(); },+ "Move the hidden triangles of the active Part into a new Part just below it, shown. One undo step.");+ add("part.split_masked", "Split Masked", "Tool > Parts", nullptr, [this] { runCommand("part_split_masked"); }, nullptr,+ "part_split_masked", nullptr, [this] { return doc_.mesh.hasMask(); },+ "Move the masked triangles (the average mask of their corners above 50%) into a new, unmasked Part just "+ "below. One undo step.");+ add("part.split_unmasked", "Split Unmasked", "Tool > Parts", nullptr, [this] { runCommand("part_split_unmasked"); },+ nullptr, "part_split_unmasked", nullptr, [this] { return doc_.mesh.hasMask(); },+ "Move the triangles that are not masked into a new Part just below; the masked ones stay. One undo step.");+ add("geometry.delete_masked", "Delete Masked", "Tool > Visibility", nullptr, [this] { runCommand("delete_masked"); },+ nullptr, "delete_masked", nullptr, [this] { return doc_.mesh.hasMask(); },+ "Delete the masked triangles (the average mask of their corners above 50%) of the active Part. Ctrl+Z "+ "brings them back.");add("part.sculpt_under_cursor", "Sculpt the Part under the cursor", "Tool > Parts", "Alt+Q",[this] { sculptPartUnderCursor(); }, ICON_LC_MOUSE_POINTER_CLICK, nullptr, nullptr, nullptr,"Make the Part under the pointer the one you sculpt, without moving the view (each Part keeps its mask). "diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cppindex eafaf004..ada3d5c7 100644--- a/src/app/I18nSimplifiedChinese.cpp+++ b/src/app/I18nSimplifiedChinese.cpp@@ -4342,6 +4342,58 @@ constexpr Entry kSimplifiedChinese[] = {"旋转模板,以逆时针度数表示;Ctrl+点击以输入。"},{"Centre the Stencil again, upright, 80% of the view's height.","将模板重新居中、摆正,高度为视图的 80%。"},+ {"%s: flat shading. Click: as the scene", "%s:平面着色。单击:跟随场景"},+ {"%s: shading as the scene (%s). Click: Smooth", "%s:着色跟随场景(%s)。单击:平滑"},+ {"%s: smooth shading. Click: Flat", "%s:平滑着色。单击:平面"},+ {"Delete Masked", "删除遮罩部分"},+ {"Delete masked", "删除遮罩部分"},+ {"Delete the masked triangles (average mask above 50%); undo brings them back", "删除遮罩的三角形(平均遮罩高于 50%);撤销可恢复"},+ {"Delete the masked triangles (the average mask of their corners above 50%) of the active Part. Ctrl+Z brings them back.", "删除活动部件的遮罩三角形(顶点平均遮罩高于 50%)。Ctrl+Z 可恢复。"},+ {"Move the hidden triangles of the active Part into a new Part just below it, shown. One undo step.", "将活动部件的隐藏三角形移到其正下方的新部件,并显示出来。一个撤销步骤。"},+ {"Move the masked triangles (the average mask of their corners above 50%) into a new, unmasked Part just below. One undo step.", "将遮罩的三角形(顶点平均遮罩高于 50%)移到正下方一个没有遮罩的新部件。一个撤销步骤。"},+ {"Move the triangles that are not masked into a new Part just below; the masked ones stay. One undo step.", "将没有遮罩的三角形移到正下方的新部件;遮罩的留下。一个撤销步骤。"},+ {"Split Hidden", "分离隐藏部分"},+ {"Split Masked", "分离遮罩部分"},+ {"Split Unmasked", "分离未遮罩部分"},+ {"flat", "平面"},+ {"smooth", "平滑"},+ {"Hidden", "隐藏"},+ {"Masked", "遮罩"},+ {"Unmasked", "未遮罩"},+ {"Split hidden: the hidden triangles become a new Part", "分离隐藏:隐藏的三角形成为新部件"},+ {"Split masked: the masked triangles (average mask above 50%) become a new Part", "分离遮罩:遮罩的三角形(平均遮罩高于 50%)成为新部件"},+ {"Split unmasked: the unmasked triangles become a new Part; the masked ones stay", "分离未遮罩:未遮罩的三角形成为新部件;遮罩的留下"},+ {"%zu point will merge", "%zu 个点将合并"},+ {"%zu points will merge", "%zu 个点将合并"},+ {"Check", "检查"},+ {"Check Mesh", "检查网格"},+ {"Degenerate triangles", "退化三角形"},+ {"Distance", "距离"},+ {"Duplicate triangles", "重复三角形"},+ {"Edges shared by three or more triangles. Fix gives each extra triangle its own copy of the edge, so it comes loose; nothing is deleted.", "由三个以上三角形共用的边。修复会让每个多出的三角形有自己的一份边,使它分离出来;不会删除任何东西。"},+ {"Fix", "修复"},+ {"Fix all", "全部修复"},+ {"Fix every problem listed except holes, as one undo step. Holes stay open: a mesh can be open on purpose (use their own Fix to cap them).", "修复列表中除孔洞以外的所有问题,作为一个撤销步骤。孔洞保持开放:网格可能是有意开放的(用孔洞自己的修复来封闭)。"},+ {"Flipped triangles", "翻转的三角形"},+ {"Holes", "孔洞"},+ {"Isolated points", "孤立点"},+ {"Let go of the slider to count", "松开滑块即可计数"},+ {"Look for what makes a mesh hard to sculpt, remesh, print or export. Checking changes nothing; each Fix changes only what its row names, as one undo step.", "找出让网格难以雕刻、重新拓扑、打印或导出的问题。检查不会改变任何东西;每个修复只改变该行所指的内容,作为一个撤销步骤。"},+ {"Merge", "合并"},+ {"Merge by Distance", "按距离合并"},+ {"Merge the points of the active Part that are closer than the distance into one (an unwelded import, seams left by another program). Triangles that collapse are removed. One undo step.", "将活动部件里比距离更近的点合并为一个(未焊接的导入、其他程序留下的接缝)。塌陷的三角形会被移除。一个撤销步骤。"},+ {"No problems found", "没有发现问题"},+ {"Non-manifold edges", "非流形边"},+ {"Not checked yet", "尚未检查"},+ {"Open boundaries. Fix caps each one with a patch, as Close Holes does.", "开放的边界。修复会像封闭孔洞一样,用补片封住每一个。"},+ {"Points no triangle uses. Fix removes them.", "没有三角形使用的点。修复会移除它们。"},+ {"Points this close (in scene units) or closer merge. 0 merges only points exactly on top of each other. The points that would merge show on the model in orange.", "距离在此值(场景单位)以内的点会合并。0 只合并完全重叠的点。将合并的点会在模型上以橙色显示。"},+ {"The mesh changed: check again", "网格已更改:请重新检查"},+ {"Triangles on the same three points as another. Fix deletes the copies.", "与另一个三角形使用相同三个点的三角形。修复会删除副本。"},+ {"Triangles that use one point twice. Fix deletes them.", "重复使用同一个点的三角形。修复会删除它们。"},+ {"Triangles whose three points are in one line. Fix collapses their shortest edge.", "三个点在同一直线上的三角形。修复会塌陷其最短的边。"},+ {"Triangles wound against their neighbours, or whole closed pieces inside out. Fix turns them to match.", "与相邻三角形方向相反的三角形,或整个内外颠倒的封闭部分。修复会将它们翻转成一致。"},+ {"Zero-area triangles", "零面积三角形"},};} // namespacediff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 8a63ea2a..f0df6555 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -4816,6 +4816,58 @@ constexpr Entry kSpanish[] = {"Barra superior"},{"Status bar","Barra de estado"},+ {"%s: flat shading. Click: as the scene", "%s: sombreado plano. Clic: como la escena"},+ {"%s: shading as the scene (%s). Click: Smooth", "%s: sombreado como la escena (%s). Clic: Suave"},+ {"%s: smooth shading. Click: Flat", "%s: sombreado suave. Clic: Plano"},+ {"Delete Masked", "Eliminar enmascarado"},+ {"Delete masked", "Eliminar enmascarados"},+ {"Delete the masked triangles (average mask above 50%); undo brings them back", "Elimina los triángulos enmascarados (máscara media por encima del 50%); deshacer los recupera"},+ {"Delete the masked triangles (the average mask of their corners above 50%) of the active Part. Ctrl+Z brings them back.", "Elimina los triángulos enmascarados (la máscara media de sus vértices por encima del 50%) de la pieza activa. Ctrl+Z los recupera."},+ {"Move the hidden triangles of the active Part into a new Part just below it, shown. One undo step.", "Mueve los triángulos ocultos de la pieza activa a una pieza nueva justo debajo, visibles. Un solo paso de deshacer."},+ {"Move the masked triangles (the average mask of their corners above 50%) into a new, unmasked Part just below. One undo step.", "Mueve los triángulos enmascarados (la máscara media de sus vértices por encima del 50%) a una pieza nueva sin máscara justo debajo. Un solo paso de deshacer."},+ {"Move the triangles that are not masked into a new Part just below; the masked ones stay. One undo step.", "Mueve los triángulos sin máscara a una pieza nueva justo debajo; los enmascarados se quedan. Un solo paso de deshacer."},+ {"Split Hidden", "Separar ocultos"},+ {"Split Masked", "Separar enmascarados"},+ {"Split Unmasked", "Separar no enmascarados"},+ {"flat", "plano"},+ {"smooth", "suave"},+ {"Hidden", "Ocultos"},+ {"Masked", "Enmascarados"},+ {"Unmasked", "Sin máscara"},+ {"Split hidden: the hidden triangles become a new Part", "Separar ocultos: los triángulos ocultos pasan a una pieza nueva"},+ {"Split masked: the masked triangles (average mask above 50%) become a new Part", "Separar enmascarados: los triángulos enmascarados (máscara media por encima del 50%) pasan a una pieza nueva"},+ {"Split unmasked: the unmasked triangles become a new Part; the masked ones stay", "Separar sin máscara: los triángulos sin máscara pasan a una pieza nueva; los enmascarados se quedan"},+ {"%zu point will merge", "%zu punto se fusionará"},+ {"%zu points will merge", "%zu puntos se fusionarán"},+ {"Check", "Comprobar"},+ {"Check Mesh", "Comprobar malla"},+ {"Degenerate triangles", "Triángulos degenerados"},+ {"Distance", "Distancia"},+ {"Duplicate triangles", "Triángulos duplicados"},+ {"Edges shared by three or more triangles. Fix gives each extra triangle its own copy of the edge, so it comes loose; nothing is deleted.", "Aristas compartidas por tres o más triángulos. Corregir da a cada triángulo de más su propia copia de la arista, así queda suelto; no se elimina nada."},+ {"Fix", "Corregir"},+ {"Fix all", "Corregir todo"},+ {"Fix every problem listed except holes, as one undo step. Holes stay open: a mesh can be open on purpose (use their own Fix to cap them).", "Corrige todos los problemas de la lista salvo los agujeros, en un solo paso de deshacer. Los agujeros quedan abiertos: una malla puede estar abierta a propósito (usa su propio Corregir para taparlos)."},+ {"Flipped triangles", "Triángulos invertidos"},+ {"Holes", "Agujeros"},+ {"Isolated points", "Puntos aislados"},+ {"Let go of the slider to count", "Suelta el deslizador para contar"},+ {"Look for what makes a mesh hard to sculpt, remesh, print or export. Checking changes nothing; each Fix changes only what its row names, as one undo step.", "Busca lo que hace difícil esculpir, remallar, imprimir o exportar una malla. Comprobar no cambia nada; cada Corregir cambia solo lo que nombra su fila, en un solo paso de deshacer."},+ {"Merge", "Fusionar"},+ {"Merge by Distance", "Fusionar por distancia"},+ {"Merge the points of the active Part that are closer than the distance into one (an unwelded import, seams left by another program). Triangles that collapse are removed. One undo step.", "Fusiona en uno los puntos de la pieza activa que están más cerca que la distancia (una importación sin soldar, costuras que dejó otro programa). Los triángulos que colapsan se eliminan. Un solo paso de deshacer."},+ {"No problems found", "No se encontraron problemas"},+ {"Non-manifold edges", "Aristas no múltiples"},+ {"Not checked yet", "Aún sin comprobar"},+ {"Open boundaries. Fix caps each one with a patch, as Close Holes does.", "Bordes abiertos. Corregir tapa cada uno con un parche, como Cerrar agujeros."},+ {"Points no triangle uses. Fix removes them.", "Puntos que ningún triángulo usa. Corregir los elimina."},+ {"Points this close (in scene units) or closer merge. 0 merges only points exactly on top of each other. The points that would merge show on the model in orange.", "Se fusionan los puntos a esta distancia (en unidades de escena) o menos. 0 fusiona solo los puntos exactamente superpuestos. Los puntos que se fusionarían se ven en naranja sobre el modelo."},+ {"The mesh changed: check again", "La malla cambió: vuelve a comprobar"},+ {"Triangles on the same three points as another. Fix deletes the copies.", "Triángulos sobre los mismos tres puntos que otro. Corregir elimina las copias."},+ {"Triangles that use one point twice. Fix deletes them.", "Triángulos que usan un punto dos veces. Corregir los elimina."},+ {"Triangles whose three points are in one line. Fix collapses their shortest edge.", "Triángulos cuyos tres puntos están en una línea. Corregir colapsa su arista más corta."},+ {"Triangles wound against their neighbours, or whole closed pieces inside out. Fix turns them to match.", "Triángulos orientados al revés que sus vecinos, o piezas cerradas enteras del revés. Corregir los gira para que coincidan."},+ {"Zero-area triangles", "Triángulos de área cero"},};} // namespacediff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cppindex 6fc3b2fa..8821ad9b 100644--- a/src/app/I18nTraditionalChinese.cpp+++ b/src/app/I18nTraditionalChinese.cpp@@ -4340,6 +4340,58 @@ constexpr Entry kTraditionalChinese[] = {"旋轉模板,以逆時針度數表示;Ctrl+點擊以輸入。"},{"Centre the Stencil again, upright, 80% of the view's height.","將模板重新置中、擺正,高度為視圖的 80%。"},+ {"%s: flat shading. Click: as the scene", "%s:平面著色。按一下:依場景"},+ {"%s: shading as the scene (%s). Click: Smooth", "%s:著色依場景(%s)。按一下:平滑"},+ {"%s: smooth shading. Click: Flat", "%s:平滑著色。按一下:平面"},+ {"Delete Masked", "刪除遮罩部分"},+ {"Delete masked", "刪除遮罩部分"},+ {"Delete the masked triangles (average mask above 50%); undo brings them back", "刪除遮罩的三角形(平均遮罩高於 50%);復原可找回"},+ {"Delete the masked triangles (the average mask of their corners above 50%) of the active Part. Ctrl+Z brings them back.", "刪除作用中部件的遮罩三角形(頂點平均遮罩高於 50%)。Ctrl+Z 可找回。"},+ {"Move the hidden triangles of the active Part into a new Part just below it, shown. One undo step.", "將作用中部件的隱藏三角形移到其正下方的新部件,並顯示出來。一個復原步驟。"},+ {"Move the masked triangles (the average mask of their corners above 50%) into a new, unmasked Part just below. One undo step.", "將遮罩的三角形(頂點平均遮罩高於 50%)移到正下方一個沒有遮罩的新部件。一個復原步驟。"},+ {"Move the triangles that are not masked into a new Part just below; the masked ones stay. One undo step.", "將沒有遮罩的三角形移到正下方的新部件;遮罩的留下。一個復原步驟。"},+ {"Split Hidden", "分離隱藏部分"},+ {"Split Masked", "分離遮罩部分"},+ {"Split Unmasked", "分離未遮罩部分"},+ {"flat", "平面"},+ {"smooth", "平滑"},+ {"Hidden", "隱藏"},+ {"Masked", "遮罩"},+ {"Unmasked", "未遮罩"},+ {"Split hidden: the hidden triangles become a new Part", "分離隱藏:隱藏的三角形成為新部件"},+ {"Split masked: the masked triangles (average mask above 50%) become a new Part", "分離遮罩:遮罩的三角形(平均遮罩高於 50%)成為新部件"},+ {"Split unmasked: the unmasked triangles become a new Part; the masked ones stay", "分離未遮罩:未遮罩的三角形成為新部件;遮罩的留下"},+ {"%zu point will merge", "%zu 個點將合併"},+ {"%zu points will merge", "%zu 個點將合併"},+ {"Check", "檢查"},+ {"Check Mesh", "檢查網格"},+ {"Degenerate triangles", "退化三角形"},+ {"Distance", "距離"},+ {"Duplicate triangles", "重複三角形"},+ {"Edges shared by three or more triangles. Fix gives each extra triangle its own copy of the edge, so it comes loose; nothing is deleted.", "由三個以上三角形共用的邊。修正會讓每個多出的三角形有自己的一份邊,使它分離出來;不會刪除任何東西。"},+ {"Fix", "修正"},+ {"Fix all", "全部修正"},+ {"Fix every problem listed except holes, as one undo step. Holes stay open: a mesh can be open on purpose (use their own Fix to cap them).", "修正清單中除孔洞以外的所有問題,作為一個復原步驟。孔洞保持開放:網格可能是刻意開放的(用孔洞自己的修正來封閉)。"},+ {"Flipped triangles", "翻轉的三角形"},+ {"Holes", "孔洞"},+ {"Isolated points", "孤立點"},+ {"Let go of the slider to count", "放開滑桿即可計數"},+ {"Look for what makes a mesh hard to sculpt, remesh, print or export. Checking changes nothing; each Fix changes only what its row names, as one undo step.", "找出讓網格難以雕刻、重新拓撲、列印或匯出的問題。檢查不會改變任何東西;每個修正只改變該列所指的內容,作為一個復原步驟。"},+ {"Merge", "合併"},+ {"Merge by Distance", "依距離合併"},+ {"Merge the points of the active Part that are closer than the distance into one (an unwelded import, seams left by another program). Triangles that collapse are removed. One undo step.", "將作用中部件裡比距離更近的點合併為一個(未焊接的匯入、其他程式留下的接縫)。塌陷的三角形會被移除。一個復原步驟。"},+ {"No problems found", "沒有發現問題"},+ {"Non-manifold edges", "非流形邊"},+ {"Not checked yet", "尚未檢查"},+ {"Open boundaries. Fix caps each one with a patch, as Close Holes does.", "開放的邊界。修正會像封閉孔洞一樣,用補片封住每一個。"},+ {"Points no triangle uses. Fix removes them.", "沒有三角形使用的點。修正會移除它們。"},+ {"Points this close (in scene units) or closer merge. 0 merges only points exactly on top of each other. The points that would merge show on the model in orange.", "距離在此值(場景單位)以內的點會合併。0 只合併完全重疊的點。將合併的點會在模型上以橘色顯示。"},+ {"The mesh changed: check again", "網格已變更:請重新檢查"},+ {"Triangles on the same three points as another. Fix deletes the copies.", "與另一個三角形使用相同三個點的三角形。修正會刪除副本。"},+ {"Triangles that use one point twice. Fix deletes them.", "重複使用同一個點的三角形。修正會刪除它們。"},+ {"Triangles whose three points are in one line. Fix collapses their shortest edge.", "三個點在同一直線上的三角形。修正會塌陷其最短的邊。"},+ {"Triangles wound against their neighbours, or whole closed pieces inside out. Fix turns them to match.", "與相鄰三角形方向相反的三角形,或整個內外顛倒的封閉部分。修正會將它們翻轉成一致。"},+ {"Zero-area triangles", "零面積三角形"},};} // namespacediff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex b8069ba1..f35fe9bc 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -914,6 +914,7 @@ void App::drawPalette_Tool() {drawQRemeshContents(); // quad retopology (PanelRetopo.cpp)Demo::popScope();drawModifyTopologyContents(); // Mirror And Weld (PanelExtract.cpp)+ drawMeshCheckContents(); // Merge by Distance, Check Mesh (PanelMeshCheck.cpp)}if (subpalette("tool.remesh", "Remesh")) {tray::Section section;diff --git a/src/app/PanelFaceGroups.cpp b/src/app/PanelFaceGroups.cppindex aa9845d6..e2822839 100644--- a/src/app/PanelFaceGroups.cpp+++ b/src/app/PanelFaceGroups.cpp@@ -102,11 +102,17 @@ void App::drawVisibilitySection() {ImGui::SameLine();if (ImGui::Button(tr("Invert visible"), ImVec2(half, 0))) runCommand("invert_visibility");ImGui::BeginDisabled(!doc_.mesh.hasHidden());- if (ImGui::Button(tr("Delete hidden"), ImVec2(-1, 0))) runCommand("delete_hidden");+ if (ImGui::Button(tr("Delete hidden"), ImVec2(half, 0))) runCommand("delete_hidden");ImGui::EndDisabled();if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))ImGui::SetTooltip("%s", tr("Ctrl+Shift+click a group to isolate it, +Alt to hide it, on the background to show all.\n""Ctrl+Shift+drag hides outside the rectangle or lasso (Alt: inside)."));+ ImGui::SameLine();+ ImGui::BeginDisabled(!doc_.mesh.hasMask());+ if (ImGui::Button(tr("Delete masked"), ImVec2(half, 0))) runCommand("delete_masked");+ ImGui::EndDisabled();+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))+ ImGui::SetTooltip("%s", tr("Delete the masked triangles (average mask above 50%); undo brings them back"));}} // namespace sfdiff --git a/src/app/PanelMeshCheck.cpp b/src/app/PanelMeshCheck.cppnew file mode 100644index 00000000..6c6015a6--- /dev/null+++ b/src/app/PanelMeshCheck.cpp@@ -0,0 +1,163 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Tool > Geometry > Merge by Distance and Check Mesh (@foirgairwolf). The work is done by the weld_points,+// mesh_check and mesh_fix commands (core/MeshCheck.h); this is their panel and the weld's preview on the model.+#include "app/App.h"+#include "app/Demo.h"+#include "app/I18n.h"+#include "app/Palettes.h"+#include "app/Theme.h"+#include "app/Ui.h"++#include <algorithm>+#include <string>+#include <utility>++namespace sf {++namespace {++// The count follows the slider live up to this many points; above it, when the slider is let go.+constexpr size_t kLiveWeldPoints = 1500000;+constexpr size_t kWeldPreviewPoints = 20000;++} // namespace++uint64_t App::meshCheckKey() const {+ const Mesh& m = doc_.mesh;+ return (uint64_t(doc_.activePartInfo().id) << 48) ^ (doc_.undo.revision() * 0x9E3779B97F4A7C15ull) ^+ (uint64_t(m.triangleCount()) << 20) ^ uint64_t(m.vertexCount()) ^ uint64_t(reinterpret_cast<uintptr_t>(m.positions.data()));+}++void App::runMeshCheck() {+ meshReport_ = checkMesh(doc_.mesh);+ meshReportKey_ = meshCheckKey() | 1; // (never 0: checked)+}++void App::drawMeshCheckContents() {+ const Mesh& m = doc_.mesh;+ const ImGuiStyle& style = ImGui::GetStyle();+ const float diag = m.vertexCount() ? glm::length(m.bounds().extent()) : 1.0f;+ const uint64_t key = meshCheckKey() | 1;+ weldShown_ = true;++ Demo::pushScope("Merge by Distance");+ tray::GroupLabel(*this, "Merge by Distance");+ if (weldDistance_ < 0.0f) weldDistance_ = diag * 1e-4f; // a ten-thousandth of the Part's size+ const float hi = std::max(diag * 0.02f, weldDistance_);+ const float button = ImGui::CalcTextSize(tr("Merge")).x + 2.0f * style.FramePadding.x + ImGui::GetFrameHeight();+ ImGui::BeginDisabled(weldCount_ == 0 || weldKey_ != key || weldKeyDistance_ != weldDistance_);+ if (ImGui::Button(tr("Merge##weld_points"), ImVec2(button, 0))) {+ runCommand("weld_points", {{"distance", double(weldDistance_)}});+ weldKey_ = 0;+ }+ ImGui::EndDisabled();+ ui::HelpText("Merge", nullptr,+ "Merge the points of the active Part that are closer than the distance into one (an unwelded import, "+ "seams left by another program). Triangles that collapse are removed. One undo step.",+ "Tool > Geometry > Merge by Distance");+ ImGui::SameLine();+ ImGui::SetNextItemWidth(-1);+ ui::SliderInside("##weld_distance", &weldDistance_, 0.0f, hi, "Distance %.5f", ImGuiSliderFlags_Logarithmic);+ const bool dragging = ImGui::IsItemActive();+ ui::HelpText("Distance", nullptr,+ "Points this close (in scene units) or closer merge. 0 merges only points exactly on top of each "+ "other. The points that would merge show on the model in orange.",+ "Tool > Geometry > Merge by Distance");+ // The count (and the preview's points) for this mesh and distance: live while dragging on smaller meshes.+ if ((weldKey_ != key || weldKeyDistance_ != weldDistance_) && (!dragging || m.vertexCount() <= kLiveWeldPoints)) {+ std::vector<uint32_t> target = weldTargets(m, weldDistance_, &weldCount_);+ weldPoints_.clear();+ const size_t step = std::max<size_t>(1, weldCount_ / kWeldPreviewPoints);+ size_t seen = 0;+ for (uint32_t v = 0; v < target.size(); ++v)+ if (target[v] != v && seen++ % step == 0) weldPoints_.push_back(m.positions[v]);+ weldKey_ = key;+ weldKeyDistance_ = weldDistance_;+ }+ if (weldKey_ == key && weldKeyDistance_ == weldDistance_)+ ImGui::TextDisabled(weldCount_ == 1 ? tr("%zu point will merge") : tr("%zu points will merge"), weldCount_);+ else+ ImGui::TextDisabled("%s", tr("Let go of the slider to count"));+ Demo::popScope();++ Demo::pushScope("Check Mesh");+ tray::GroupLabel(*this, "Check Mesh");+ const float half = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) * 0.5f;+ const bool current = meshReportKey_ == key;+ if (ImGui::Button(tr("Check##mesh_check"), ImVec2(half, 0))) runMeshCheck();+ ui::HelpText("Check", nullptr,+ "Look for what makes a mesh hard to sculpt, remesh, print or export. Checking changes nothing; each "+ "Fix changes only what its row names, as one undo step.",+ "Tool > Geometry > Check Mesh");+ ImGui::SameLine();+ size_t fixable = 0;+ for (int i = 0; i < kMeshIssueCount; ++i)+ if (MeshIssue(i) != MeshIssue::Holes) fixable += meshReport_.count[i];+ ImGui::BeginDisabled(!current || fixable == 0);+ if (ImGui::Button(tr("Fix all##mesh_fix"), ImVec2(-1, 0))) {+ runCommand("mesh_fix", {{"issue", std::string("all")}});+ runMeshCheck();+ }+ ImGui::EndDisabled();+ ui::HelpText("Fix all", nullptr,+ "Fix every problem listed except holes, as one undo step. Holes stay open: a mesh can be open on "+ "purpose (use their own Fix to cap them).",+ "Tool > Geometry > Check Mesh");+ if (meshReportKey_ == 0) {+ ImGui::TextDisabled("%s", tr("Not checked yet"));+ } else if (!current) {+ ImGui::TextDisabled("%s", tr("The mesh changed: check again"));+ } else if (meshReport_.total() == 0) {+ ImGui::TextColored(theme::text, "%s", tr("No problems found"));+ } else {+ // Per MeshIssue: the row's name and what it means / what its Fix does.+ const char* const rows[kMeshIssueCount][2] = {+ {tr("Non-manifold edges"), tr("Edges shared by three or more triangles. Fix gives each extra triangle its "+ "own copy of the edge, so it comes loose; nothing is deleted.")},+ {tr("Holes"), tr("Open boundaries. Fix caps each one with a patch, as Close Holes does.")},+ {tr("Duplicate triangles"), tr("Triangles on the same three points as another. Fix deletes the copies.")},+ {tr("Degenerate triangles"), tr("Triangles that use one point twice. Fix deletes them.")},+ {tr("Zero-area triangles"), tr("Triangles whose three points are in one line. Fix collapses their shortest edge.")},+ {tr("Flipped triangles"), tr("Triangles wound against their neighbours, or whole closed pieces inside out. "+ "Fix turns them to match.")},+ {tr("Isolated points"), tr("Points no triangle uses. Fix removes them.")}};+ const float fixW = ImGui::CalcTextSize(tr("Fix")).x + 2.0f * style.FramePadding.x + ImGui::GetFrameHeight() * 0.5f;+ for (int i = 0; i < kMeshIssueCount; ++i) {+ if (!meshReport_.count[i]) continue;+ ImGui::PushID(i);+ ImGui::AlignTextToFramePadding();+ ImGui::Text("%s", rows[i][0]);+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal)) ImGui::SetTooltip("%s", rows[i][1]);+ const std::string n = std::to_string(meshReport_.count[i]);+ ImGui::SameLine(ImGui::GetContentRegionMax().x - fixW - style.ItemSpacing.x - ImGui::CalcTextSize(n.c_str()).x);+ ImGui::TextColored(theme::accent, "%s", n.c_str());+ ImGui::SameLine(ImGui::GetContentRegionMax().x - fixW);+ if (ImGui::Button(tr("Fix"), ImVec2(fixW, 0))) {+ runCommand("mesh_fix", {{"issue", std::string(meshIssueName(MeshIssue(i)))}});+ runMeshCheck();+ }+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal)) ImGui::SetTooltip("%s", rows[i][1]);+ ImGui::PopID();+ }+ }+ Demo::popScope();+}++void App::drawWeldPreviewOverlay() {+ const bool shown = std::exchange(weldShown_, false);+ if (!shown || weldPoints_.empty() || weldKey_ != (meshCheckKey() | 1) || !doc_.activePartInfo().visible) return;+ ImDrawList* dl = ImGui::GetBackgroundDrawList();+ const CanvasRect cr = canvasRect();+ dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);+ const ImU32 col = theme::u32(theme::accent);+ const float r = 2.0f * uiScale_;+ for (const glm::vec3& p : weldPoints_) {+ ImVec2 s;+ if (gizmoProject(p, s)) dl->AddCircleFilled(s, r, col, 6);+ }+ dl->PopClipRect();+}++} // namespace sfdiff --git a/src/app/PanelParts.cpp b/src/app/PanelParts.cppindex 959e34eb..ffd650c2 100644--- a/src/app/PanelParts.cpp+++ b/src/app/PanelParts.cpp@@ -15,6 +15,7 @@#include <IconsLucide.h>#include <cctype>+#include <cmath>#include <cstring>#include <imgui_internal.h>@@ -79,6 +80,25 @@ void drawEye(ImDrawList* dl, ImVec2 c, float size, bool open, ImU32 col) {}}+// Shading mark: a shaded disc (smooth) or a faceted hexagon (flat).+void drawShadeMark(ImDrawList* dl, ImVec2 c, float size, bool flat, ImU32 col) {+ const float r = size * 0.5f, t = std::max(1.0f, size * 0.11f);+ if (!flat) {+ dl->AddCircle(c, r, col, 0, t);+ dl->AddCircleFilled(ImVec2(c.x - r * 0.3f, c.y - r * 0.3f), r * 0.32f, col);+ return;+ }+ ImVec2 p[6];+ for (int k = 0; k < 6; ++k) {+ const float a = 3.14159265f / 3.0f * float(k) + 3.14159265f / 6.0f;+ p[k] = ImVec2(c.x + r * std::cos(a), c.y + r * std::sin(a));+ }+ dl->AddPolyline(p, 6, col, ImDrawFlags_Closed, t);+ dl->AddLine(c, p[1], col, t * 0.8f);+ dl->AddLine(c, p[3], col, t * 0.8f);+ dl->AddLine(c, p[5], col, t * 0.8f);+}+} // namespaceint App::pickPart(float x, float y, RayHit* out) {@@ -248,8 +268,8 @@ void App::drawPartsContents() {const int active = doc_.activePart;const ImGuiStyle& style = ImGui::GetStyle();- // The list: eye, name, triangles. Row actions run after the loop (they change the list).- int selectIndex = -1, toggleIndex = -1, deleteIndex = -1, duplicateIndex = -1, renameIndex = -1;+ // The list: name, levels, triangles, shading, eye. Row actions run after the loop (they change the list).+ int selectIndex = -1, toggleIndex = -1, shadeIndex = -1, deleteIndex = -1, duplicateIndex = -1, renameIndex = -1;std::string renameTo;// Folders (#96): pending actions on one, by name; a Part put into a folder ("" = out of its folder).PartFolderActions fa;@@ -298,7 +318,7 @@ void App::drawPartsContents() {ImGui::PushStyleColor(ImGuiCol_Header, kRowSelected);ImGui::PushStyleColor(ImGuiCol_HeaderHovered, kRowHover);ImGui::PushStyleColor(ImGuiCol_HeaderActive, kRowPressed);- if (ImGui::BeginTable("##parts", 4, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_PadOuterX, ImVec2(-1, listH))) {+ if (ImGui::BeginTable("##parts", 5, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_PadOuterX, ImVec2(-1, listH))) {const float eyeW = ImGui::GetTextLineHeight() * 1.2f;ImGui::TableSetupColumn("name", ImGuiTableColumnFlags_WidthStretch);// Subdivision levels lists them ("SDiv 3/5"); empty for meshes without levels.@@ -306,6 +326,7 @@ void App::drawPartsContents() {for (int i = 0; i < count && !anyLevels; ++i) anyLevels = subdivLevelCount(doc_.partMesh(i)) > 0;ImGui::TableSetupColumn("sdiv", ImGuiTableColumnFlags_WidthFixed, anyLevels ? ImGui::CalcTextSize("SDiv 8/8").x : 0.0f);ImGui::TableSetupColumn("tris", ImGuiTableColumnFlags_WidthFixed, ImGui::CalcTextSize("0.00M").x);+ ImGui::TableSetupColumn("shade", ImGuiTableColumnFlags_WidthFixed, eyeW);ImGui::TableSetupColumn("eye", ImGuiTableColumnFlags_WidthFixed, eyeW);// A Part dropped on a row: into that folder, or (on a Part outside folders) out of its folder.for (const Row& row : rows) {@@ -438,6 +459,26 @@ void App::drawPartsContents() {ImGui::TextColored(trisCol, "%s", tris.c_str());ImGui::TableSetColumnIndex(3);ImGui::SetCursorPosY(ImGui::GetCursorPosY() + textDy);+ {+ // Smooth / flat shading of this Part: click cycles Scene -> Smooth -> Flat (part_shading).+ const ImVec2 at = ImGui::GetCursorScreenPos();+ const ImVec2 size(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeight());+ if (ImGui::InvisibleButton(("##shade " + s.name).c_str(), size)) shadeIndex = i;+ const bool hovered = ImGui::IsItemHovered();+ const bool flat = s.shading == Shading::Flat || (s.shading == Shading::Default && renderSettings_.flatShading);+ if (hovered)+ ImGui::SetTooltip(tr(s.shading == Shading::Default ? "%s: shading as the scene (%s). Click: Smooth"+ : s.shading == Shading::Smooth ? "%s: smooth shading. Click: Flat"+ : "%s: flat shading. Click: as the scene"),+ s.name.c_str(), tr(renderSettings_.flatShading ? "flat" : "smooth"));+ const ImU32 col = ImGui::GetColorU32(hovered ? style.Colors[ImGuiCol_ButtonHovered]+ : s.shading != Shading::Default ? style.Colors[ImGuiCol_Text]+ : style.Colors[ImGuiCol_TextDisabled]);+ drawShadeMark(ImGui::GetWindowDrawList(), ImVec2(at.x + size.x * 0.5f, at.y + size.y * 0.5f),+ ImGui::GetTextLineHeight() * 0.7f, flat, col);+ }+ ImGui::TableSetColumnIndex(4);+ ImGui::SetCursorPosY(ImGui::GetCursorPosY() + textDy);const ImVec2 eyePos = ImGui::GetCursorScreenPos();const ImVec2 eyeSize(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeight());if (ImGui::InvisibleButton(("##eye " + s.name).c_str(), eyeSize)) toggleIndex = i;@@ -462,6 +503,11 @@ void App::drawPartsContents() {partSelected("Parts list");}if (toggleIndex >= 0) runCommand("part_visibility", {{"index", double(toggleIndex)}});+ if (shadeIndex >= 0) {+ const Shading now = doc_.parts[size_t(shadeIndex)].shading;+ const Shading next = now == Shading::Default ? Shading::Smooth : now == Shading::Smooth ? Shading::Flat : Shading::Default;+ runCommand("part_shading", {{"index", double(shadeIndex)}, {"mode", std::string(shadingName(next))}});+ }if (duplicateIndex >= 0) runCommand("part_duplicate", {{"index", double(duplicateIndex)}});if (newFolderPart >= 0) {runCommand("part_folder_new", {{"index", double(newFolderPart)}});@@ -666,6 +712,30 @@ void App::drawPartsContents() {ImGui::EndDisabled();if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_DelayNormal))ImGui::SetTooltip("%s", tr("One Part per disconnected piece"));+ // Split off what is hidden, masked or not masked into a new Part below (one undo step each): "Split" and three+ // short buttons, so the row fits the narrowest tray.+ {+ ImGui::AlignTextToFramePadding();+ ImGui::TextDisabled("%s", tr("Split"));+ ImGui::SameLine();+ const float third = (ImGui::GetContentRegionAvail().x - 2.0f * style.ItemSpacing.x) / 3.0f;+ const bool masked = doc_.mesh.hasMask();+ auto splitButton = [&](const char* label, const char* command, bool enabled, const char* tip) {+ ImGui::BeginDisabled(!enabled);+ if (ImGui::Button(tr(label), ImVec2(third, 0))) runCommand(command);+ ImGui::EndDisabled();+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_DelayNormal))+ ImGui::SetTooltip("%s", tr(tip));+ };+ splitButton("Hidden##part_split", "part_split_hidden", doc_.mesh.hasHidden(),+ "Split hidden: the hidden triangles become a new Part");+ ImGui::SameLine();+ splitButton("Masked##part_split", "part_split_masked", masked,+ "Split masked: the masked triangles (average mask above 50%) become a new Part");+ ImGui::SameLine();+ splitButton("Unmasked##part_split", "part_split_unmasked", masked,+ "Split unmasked: the unmasked triangles become a new Part; the masked ones stay");+ }if (fontSmall_) ImGui::PushFont(fontSmall_);ImGui::TextDisabled("%s", tr("Alt+click a Part to select it"));if (fontSmall_) ImGui::PopFont();@@ -791,7 +861,7 @@ void App::drawPartFolderRow(int fi, float rowH, ImVec2 cellPad, PartFolderActionImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(t.c_str()).x);ImGui::TextDisabled("%s", t.c_str());}- ImGui::TableSetColumnIndex(3);+ ImGui::TableSetColumnIndex(4);ImGui::SetCursorPosY(ImGui::GetCursorPosY() + textDy);const ImVec2 eyePos = ImGui::GetCursorScreenPos();const ImVec2 eyeSize(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeight());diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex d7ec570c..53583fae 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -25,6 +25,7 @@#include "core/Multires.h"#include "core/Micro.h"#include "core/MeshTransform.h"+#include "core/MeshCheck.h"#include "core/PathStroke.h"#include "core/FaceGroups.h"#include "core/SelectionSets.h"@@ -878,6 +879,7 @@ CommandRegistry::CommandRegistry() {registerSculptableCommands(*this); // splat_to_mesh, face_guides (core/Sculptable.h)registerTransformCommands(*this); // transform (core/MeshTransform.h)registerExtractMirrorCommands(*this); // extract, mirror_and_weld, mirror (core/ExtractMirror.h)+ registerMeshCheckCommands(*this); // weld_points, mesh_check, mesh_fix (core/MeshCheck.h)registerPerformanceCommands(*this); // perf_info, set_multithreading (core/Benchmark.cpp)registerHardwareProfileCommands(*this); // performance_profile, calibrate, set_performance_override (core/HardwareProfile.cpp)registerTimelineCommands(*this); // timeline_info / seek / select / retune / save / load (core/Timeline.h)diff --git a/src/core/FaceGroups.cpp b/src/core/FaceGroups.cppindex e028ce1c..40c1e652 100644--- a/src/core/FaceGroups.cpp+++ b/src/core/FaceGroups.cpp@@ -292,31 +292,60 @@ Mesh deleteHiddenTriangles(const Mesh& mesh) {return extractTriangles(mesh, keep);}-Mesh extractTriangles(const Mesh& mesh, const std::vector<uint8_t>& keep) {- const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();- std::vector<uint32_t> remap(nv, kUnassigned);- std::vector<uint32_t> kept;+std::vector<uint8_t> trianglesIn(const Mesh& mesh, TriangleSet set, size_t* count) {+ const size_t nt = mesh.triangleCount();+ std::vector<uint8_t> in(nt, uint8_t(0));+ size_t n = 0;+ if (set == TriangleSet::Hidden) {+ for (size_t t = 0; t < nt && t < mesh.hidden.size(); ++t) n += in[t] = mesh.hidden[t] != 0;+ } else {+ const bool masked = set == TriangleSet::Masked;+ const size_t nv = mesh.mask.size();+ for (size_t t = 0; t < nt; ++t) {+ const glm::uvec3 v = mesh.triangles[t];+ float sum = 0.0f;+ if (nv) sum = (v.x < nv ? mesh.mask[v.x] : 0.0f) + (v.y < nv ? mesh.mask[v.y] : 0.0f) + (v.z < nv ? mesh.mask[v.z] : 0.0f);+ n += in[t] = (sum > 3.0f * kMaskedThreshold) == masked;+ }+ }+ if (count) *count = n;+ return in;+}++Mesh extractTriangles(const Mesh& mesh, const std::vector<uint8_t>& keep) { return rebuildTriangles(mesh, keep, {}); }++Mesh rebuildTriangles(const Mesh& mesh, const std::vector<uint8_t>& keep, const TriangleRebuild& how) {+ const size_t nt = mesh.triangleCount();+ const size_t ids = how.source ? how.source->size() : mesh.vertexCount();+ std::vector<uint32_t> remap(ids, kUnassigned);+ std::vector<uint32_t> kept; // the source vertex of each new vertexMesh out;bool anyHidden = false;std::vector<uint32_t> newTriangle(mesh.hasQuads() ? nt : 0, Mesh::kNoQuad);for (uint32_t t = 0; t < nt; ++t) {if (t >= keep.size() || !keep[t]) continue;if (!newTriangle.empty()) newTriangle[t] = uint32_t(out.triangles.size());+ const glm::uvec3 c = how.corners ? (*how.corners)[t] : mesh.triangles[t];+ const bool flip = how.flip && (*how.flip)[t];glm::uvec3 tri;for (int k = 0; k < 3; ++k) {- uint32_t& r = remap[mesh.triangles[t][k]];+ uint32_t& r = remap[c[k]];if (r == kUnassigned) {r = static_cast<uint32_t>(kept.size());- kept.push_back(mesh.triangles[t][k]);+ kept.push_back(how.source ? (*how.source)[c[k]] : c[k]);}tri[k] = r;}+ if (flip) std::swap(tri.y, tri.z);out.triangles.push_back(tri);out.hidden.push_back(mesh.triangleHidden(t) ? 1 : 0);anyHidden |= mesh.triangleHidden(t);if (mesh.hasFaceGroups()) out.facegroups.push_back(mesh.facegroups[t]);- if (mesh.hasUvs()) out.uvs.insert(out.uvs.end(), mesh.uvs.begin() + std::ptrdiff_t(t) * 3,- mesh.uvs.begin() + std::ptrdiff_t(t) * 3 + 3);+ if (mesh.hasUvs()) {+ const auto uv = mesh.uvs.begin() + std::ptrdiff_t(t) * 3;+ if (flip) out.uvs.insert(out.uvs.end(), {uv[0], uv[2], uv[1]});+ else out.uvs.insert(out.uvs.end(), uv, uv + 3);+ }}out.positions.reserve(kept.size());for (uint32_t v : kept) out.positions.push_back(mesh.positions[v]);@@ -501,6 +530,21 @@ void registerFaceGroupCommands(CommandRegistry& reg) {return {true, "Deleted " + std::to_string(removed) + " triangles, " +std::to_string(doc.mesh.triangleCount()) + " left"};}});++ reg.add({"delete_masked",+ "Permanently delete the masked part of the mesh (undoable): triangles whose corners' average mask is "+ "above 0.5.",+ {},+ [](Document& doc, const Args&) -> CommandResult {+ size_t masked = 0;+ std::vector<uint8_t> keep = trianglesIn(doc.mesh, TriangleSet::Unmasked);+ for (uint8_t k : keep) masked += !k;+ if (masked == 0) return {false, "Nothing is masked"};+ if (masked == doc.mesh.triangleCount()) return {false, "Everything is masked"};+ doc.replaceMeshUndoable(extractTriangles(doc.mesh, keep), "Delete Masked");+ return {true, "Deleted " + std::to_string(masked) + " triangles, " ++ std::to_string(doc.mesh.triangleCount()) + " left"};+ }});}} // namespace sfdiff --git a/src/core/FaceGroups.h b/src/core/FaceGroups.hindex d4cfaa02..b0bb56db 100644--- a/src/core/FaceGroups.h+++ b/src/core/FaceGroups.h@@ -67,9 +67,27 @@ bool facegroupIsolated(const Mesh& mesh, uint32_t group);Mesh deleteHiddenTriangles(const Mesh& mesh);// Copy of the triangles with keep[t] != 0, compacted the same way (hidden flags are kept).Mesh extractTriangles(const Mesh& mesh, const std::vector<uint8_t>& keep);+// The general form, for welds and repairs (core/MeshCheck.h): kept triangle t gets the corner ids corners[t]+// (null: mesh.triangles[t]), each id i standing for vertex source[i] of `mesh` (null: vertex i), whose position and+// attributes it copies; ids are compacted in order of first use, so one vertex can become several (source repeats)+// and several one (corners share an id). flip[t] != 0 (null: none) reverses t's winding, its UVs with it.+struct TriangleRebuild {+ const std::vector<glm::uvec3>* corners = nullptr;+ const std::vector<uint32_t>* source = nullptr;+ const std::vector<uint8_t>* flip = nullptr;+};+Mesh rebuildTriangles(const Mesh& mesh, const std::vector<uint8_t>& keep, const TriangleRebuild& how);++// The triangles Split / Delete by selection take (part_split_hidden / _masked / _unmasked, delete_masked).+// A triangle is masked when the average mask of its three corners is above kMaskedThreshold (so a corner-only+// or soft-edge mask doesn't take its neighbours); unmasked is every other triangle. Hidden and visible alike.+enum class TriangleSet : uint8_t { Hidden, Masked, Unmasked };+inline constexpr float kMaskedThreshold = 0.5f;+// in[t] = 1 for the triangles in `set`; `count` (optional) receives how many.+std::vector<uint8_t> trianglesIn(const Mesh& mesh, TriangleSet set, size_t* count = nullptr);// Adds the face group and visibility commands (face group_*, hide_face group,-// isolate_face group, show_all, invert_visibility, hide_rect, hide_lasso, delete_hidden).+// isolate_face group, show_all, invert_visibility, hide_rect, hide_lasso, delete_hidden, delete_masked).void registerFaceGroupCommands(CommandRegistry& registry);} // namespace sfdiff --git a/src/core/MeshCheck.cpp b/src/core/MeshCheck.cppnew file mode 100644index 00000000..0fe650c6--- /dev/null+++ b/src/core/MeshCheck.cpp@@ -0,0 +1,525 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/MeshCheck.h"++#include "core/CloseHoles.h"+#include "core/Commands.h"+#include "core/FaceGroups.h"+#include "core/Parallel.h"++#include <algorithm>+#include <cmath>+#include <mutex>+#include <numeric>+#include <sstream>++namespace sf {++namespace {++constexpr uint32_t kNone = ~0u;++bool degenerate(const glm::uvec3& t) { return t.x == t.y || t.y == t.z || t.x == t.z; }++// Does triangle t run a -> b (rather than b -> a)? (t has both.)+bool runs(const glm::uvec3& t, uint32_t a, uint32_t b) {+ return (t.x == a && t.y == b) || (t.y == a && t.z == b) || (t.z == a && t.x == b);+}++bool has(const glm::uvec3& t, uint32_t v) { return t.x == v || t.y == v || t.z == v; }++// The non-degenerate triangles around `a` that also use `b`, ascending, into `out`.+void edgeTriangles(const Mesh& mesh, uint32_t a, uint32_t b, std::vector<uint32_t>& out) {+ out.clear();+ for (uint32_t t : mesh.vertexTriangles(a))+ if (has(mesh.triangles[t], b) && !degenerate(mesh.triangles[t])) out.push_back(t);+ std::sort(out.begin(), out.end());+}++// Zero area: three distinct points (all but) in one line, the triangle's height under a millionth of its longest edge.+bool zeroArea(const Mesh& mesh, const glm::uvec3& t) {+ const glm::vec3 a = mesh.positions[t.x], b = mesh.positions[t.y], c = mesh.positions[t.z];+ const float longest = std::max({glm::dot(b - a, b - a), glm::dot(c - b, c - b), glm::dot(a - c, a - c)});+ const float cross = glm::length(glm::cross(b - a, c - a));+ return cross <= 1e-6f * longest;+}++// The triangle earlier than t on the same three points, either winding.+bool duplicateOfEarlier(const Mesh& mesh, uint32_t t) {+ const glm::uvec3 a = mesh.triangles[t];+ for (uint32_t u : mesh.vertexTriangles(a.x)) {+ if (u >= t) continue;+ const glm::uvec3 b = mesh.triangles[u];+ if (has(b, a.y) && has(b, a.z) && !degenerate(b)) return true;+ }+ return false;+}++struct UnionFind {+ std::vector<uint32_t> parent;+ explicit UnionFind(size_t n) : parent(n) { std::iota(parent.begin(), parent.end(), 0u); }+ uint32_t find(uint32_t v) {+ while (parent[v] != v) v = parent[v] = parent[parent[v]];+ return v;+ }+ void unite(uint32_t a, uint32_t b) { // the lower index is the root+ a = find(a), b = find(b);+ if (a != b) parent[std::max(a, b)] = std::min(a, b);+ }+};++// Which triangles to flip so each piece is wound one way (its majority), and closed pieces face outward.+std::vector<uint8_t> flipsNeeded(const Mesh& mesh, size_t& count) {+ const size_t nt = mesh.triangleCount();+ std::vector<uint8_t> flip(nt, 0), seen(nt, 0);+ std::vector<uint32_t> piece, around;+ const glm::vec3 origin = mesh.bounds().valid() ? mesh.bounds().center() : glm::vec3(0.0f);+ count = 0;+ for (uint32_t seed = 0; seed < nt; ++seed) {+ if (seen[seed] || degenerate(mesh.triangles[seed]) || duplicateOfEarlier(mesh, seed)) continue;+ piece.assign(1, seed);+ seen[seed] = 1;+ bool closed = true;+ for (size_t i = 0; i < piece.size(); ++i) {+ const uint32_t t = piece[i];+ const glm::uvec3 tri = mesh.triangles[t];+ for (int k = 0; k < 3; ++k) {+ const uint32_t a = tri[k], b = tri[(k + 1) % 3];+ edgeTriangles(mesh, a, b, around);+ if (around.size() != 2) { // an open or non-manifold edge: no neighbour to agree with+ closed = false;+ continue;+ }+ const uint32_t u = around[0] == t ? around[1] : around[0];+ if (seen[u]) continue;+ seen[u] = 1;+ // Consistent neighbours run the shared edge the other way: the same way means one of them is flipped.+ const bool sameWay = runs(mesh.triangles[u], a, b);+ flip[u] = uint8_t(flip[t] ^ (sameWay ? 1 : 0));+ piece.push_back(u);+ }+ }+ size_t ones = 0;+ for (uint32_t t : piece) ones += flip[t];+ bool invert = ones * 2 > piece.size();+ if (closed) { // a closed piece wound inside out (negative volume) is turned the right way out as a whole+ double volume = 0.0;+ for (uint32_t t : piece) {+ const glm::uvec3 tri = mesh.triangles[t];+ const glm::dvec3 a(mesh.positions[tri.x] - origin), b(mesh.positions[tri.y] - origin),+ c(mesh.positions[tri.z] - origin);+ const double v = glm::dot(a, glm::cross(b, c));+ volume += (flip[t] != 0) != invert ? -v : v;+ }+ if (volume < 0.0) invert = !invert;+ }+ for (uint32_t t : piece) {+ if (invert) flip[t] ^= 1;+ count += flip[t];+ }+ }+ return flip;+}++// The first two triangles of a non-manifold edge stay joined across it: the first and the first one after it wound+// the other way (a consistent pair), else the second.+std::pair<uint32_t, uint32_t> keptPair(const Mesh& mesh, uint32_t a, uint32_t b, const std::vector<uint32_t>& around) {+ const bool first = runs(mesh.triangles[around[0]], a, b);+ for (size_t i = 1; i < around.size(); ++i)+ if (runs(mesh.triangles[around[i]], a, b) != first) return {around[0], around[i]};+ return {around[0], around[1]};+}++Mesh withoutTriangles(const Mesh& mesh, const std::vector<uint8_t>& drop) {+ std::vector<uint8_t> keep(drop.size());+ for (size_t t = 0; t < drop.size(); ++t) keep[t] = !drop[t];+ return extractTriangles(mesh, keep);+}++// Every triangle's corners through `target`; those that collapse are dropped.+Mesh remapped(const Mesh& mesh, const std::vector<uint32_t>& target) {+ std::vector<glm::uvec3> corners(mesh.triangles);+ std::vector<uint8_t> keep(corners.size());+ for (size_t t = 0; t < corners.size(); ++t) {+ for (int k = 0; k < 3; ++k) corners[t][k] = target[corners[t][k]];+ keep[t] = !degenerate(corners[t]);+ }+ TriangleRebuild how;+ how.corners = &corners;+ return rebuildTriangles(mesh, keep, how);+}++uint64_t mix(uint64_t x) { // splitmix64's finaliser+ x ^= x >> 30;+ x *= 0xbf58476d1ce4e5b9ull;+ x ^= x >> 27;+ x *= 0x94d049bb133111ebull;+ return x ^ (x >> 31);+}++} // namespace++std::vector<uint32_t> weldTargets(const Mesh& mesh, float distance, size_t* merged) {+ const size_t nv = mesh.vertexCount();+ std::vector<uint32_t> target(nv);+ std::iota(target.begin(), target.end(), 0u);+ size_t n = 0;+ const AABB box = mesh.bounds();+ if (nv > 1 && box.valid()) {+ // A grid of cells at least twice `distance` wide holding the kept points: a point's matches are in its cell+ // and, along each axis, at most the one neighbour on the side it is near (8 cells at most). Kept points are+ // over `distance` apart, so a cell holds only a few of them, whatever the distance.+ const float d = std::max(0.0f, std::isfinite(distance) ? distance : 0.0f);+ const float cell = std::max({2.0f * d, glm::length(box.extent()) * 1e-6f, 1e-30f});+ constexpr int kBits = 21, kMax = (1 << kBits) - 1;+ auto coord = [&](float v, float lo) { return std::clamp(int((v - lo) / cell), 0, kMax); };+ auto key = [](int x, int y, int z) { return (uint64_t(x) << (2 * kBits)) | (uint64_t(y) << kBits) | uint64_t(z); };+ size_t cap = 16;+ while (cap < nv * 2) cap <<= 1;+ std::vector<uint64_t> keys(cap, ~0ull);+ std::vector<uint32_t> head(cap, kNone), next(nv, kNone);+ auto slot = [&](uint64_t k) {+ size_t i = mix(k) & (cap - 1);+ while (keys[i] != ~0ull && keys[i] != k) i = (i + 1) & (cap - 1);+ return i;+ };+ const float d2 = d * d;+ for (uint32_t v = 0; v < nv; ++v) {+ const glm::vec3 p = mesh.positions[v];+ if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue; // stays, never matched+ const int cx = coord(p.x, box.min.x), cy = coord(p.y, box.min.y), cz = coord(p.z, box.min.z);+ // The neighbour cell each axis needs: -1 / +1 when p is within d of that face, else none (0).+ auto side = [&](float v, float lo, int c) {+ const float local = v - lo - float(c) * cell;+ return local <= d ? -1 : local >= cell - d ? 1 : 0;+ };+ const int sx = side(p.x, box.min.x, cx), sy = side(p.y, box.min.y, cy), sz = side(p.z, box.min.z, cz);+ uint32_t best = kNone;+ float bestD = d2;+ for (int dx = std::min(0, sx); dx <= std::max(0, sx); ++dx)+ for (int dy = std::min(0, sy); dy <= std::max(0, sy); ++dy)+ for (int dz = std::min(0, sz); dz <= std::max(0, sz); ++dz) {+ const int x = cx + dx, y = cy + dy, z = cz + dz;+ if (x < 0 || y < 0 || z < 0 || x > kMax || y > kMax || z > kMax) continue;+ const size_t i = slot(key(x, y, z));+ for (uint32_t u = keys[i] == ~0ull ? kNone : head[i]; u != kNone; u = next[u]) {+ const glm::vec3 e = mesh.positions[u] - p;+ const float dd = glm::dot(e, e);+ if (dd < bestD || (dd == bestD && (best == kNone || u < best))) {+ best = u;+ bestD = dd;+ }+ }+ }+ if (best != kNone) {+ target[v] = best;+ ++n;+ continue;+ }+ const uint64_t k = key(cx, cy, cz);+ const size_t i = slot(k);+ keys[i] = k;+ next[v] = head[i];+ head[i] = v;+ }+ }+ if (merged) *merged = n;+ return target;+}++Mesh weldByDistance(const Mesh& mesh, float distance, size_t* merged) {+ size_t n = 0;+ const std::vector<uint32_t> target = weldTargets(mesh, distance, &n);+ if (merged) *merged = n;+ return n ? remapped(mesh, target) : mesh;+}++const char* meshIssueName(MeshIssue issue) {+ switch (issue) {+ case MeshIssue::NonManifold: return "non_manifold";+ case MeshIssue::Holes: return "holes";+ case MeshIssue::Duplicate: return "duplicate";+ case MeshIssue::Degenerate: return "degenerate";+ case MeshIssue::ZeroArea: return "zero_area";+ case MeshIssue::Flipped: return "flipped";+ case MeshIssue::Isolated: return "isolated";+ default: return "";+ }+}++bool parseMeshIssue(const std::string& name, MeshIssue& out) {+ for (int i = 0; i < kMeshIssueCount; ++i)+ if (name == meshIssueName(MeshIssue(i))) {+ out = MeshIssue(i);+ return true;+ }+ return false;+}++size_t MeshReport::total() const {+ size_t n = 0;+ for (size_t c : count) n += c;+ return n;+}++std::string MeshReport::summary() const {+ static const char* const what[kMeshIssueCount][2] = {+ {"non-manifold edge", "non-manifold edges"}, {"hole", "holes"},+ {"duplicate triangle", "duplicate triangles"}, {"degenerate triangle", "degenerate triangles"},+ {"zero-area triangle", "zero-area triangles"}, {"flipped triangle", "flipped triangles"},+ {"isolated point", "isolated points"}};+ std::string s;+ for (int i = 0; i < kMeshIssueCount; ++i) {+ if (!count[i]) continue;+ if (!s.empty()) s += ", ";+ s += std::to_string(count[i]) + " " + what[i][count[i] == 1 ? 0 : 1];+ }+ return s.empty() ? "No problems found" : s;+}++MeshReport checkMesh(const Mesh& mesh) {+ MeshReport r;+ auto& c = r.count;+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();+ // The per-triangle and per-point counts in parallel chunks, each with its own tally.+ std::mutex lock;+ parallelFor(nt, [&](size_t begin, size_t end) {+ size_t degen = 0, dup = 0, zero = 0;+ for (size_t t = begin; t < end; ++t) {+ const glm::uvec3 tri = mesh.triangles[t];+ if (degenerate(tri)) ++degen;+ else if (duplicateOfEarlier(mesh, uint32_t(t))) ++dup;+ else if (zeroArea(mesh, tri)) ++zero;+ }+ const std::lock_guard<std::mutex> hold(lock);+ c[int(MeshIssue::Degenerate)] += degen;+ c[int(MeshIssue::Duplicate)] += dup;+ c[int(MeshIssue::ZeroArea)] += zero;+ });+ // Edges: non-manifold ones counted, open ones (one triangle) gathered to count the loops they form.+ std::vector<std::pair<uint32_t, uint32_t>> open;+ parallelFor(nv, [&](size_t begin, size_t end) {+ size_t isolated = 0, nonManifold = 0;+ std::vector<uint32_t> around;+ std::vector<std::pair<uint32_t, uint32_t>> edges;+ for (size_t a = begin; a < end; ++a) {+ if (mesh.vertexTriangles(uint32_t(a)).size() == 0) {+ ++isolated;+ continue;+ }+ for (uint32_t b : mesh.neighbors(uint32_t(a))) {+ if (b <= a) continue;+ edgeTriangles(mesh, uint32_t(a), b, around);+ if (around.size() >= 3) ++nonManifold;+ else if (around.size() == 1) edges.push_back({uint32_t(a), b});+ }+ }+ const std::lock_guard<std::mutex> hold(lock);+ c[int(MeshIssue::Isolated)] += isolated;+ c[int(MeshIssue::NonManifold)] += nonManifold;+ open.insert(open.end(), edges.begin(), edges.end());+ });+ // Holes: the connected sets of open edges (two loops touching at one point count as one).+ if (!open.empty()) {+ std::vector<uint32_t> points;+ points.reserve(open.size() * 2);+ for (const auto& [a, b] : open) points.insert(points.end(), {a, b});+ std::sort(points.begin(), points.end());+ points.erase(std::unique(points.begin(), points.end()), points.end());+ auto index = [&](uint32_t v) { return uint32_t(std::lower_bound(points.begin(), points.end(), v) - points.begin()); };+ UnionFind loops(points.size());+ for (const auto& [a, b] : open) loops.unite(index(a), index(b));+ size_t n = 0;+ for (uint32_t i = 0; i < points.size(); ++i) n += loops.find(i) == i;+ c[int(MeshIssue::Holes)] = n;+ }+ flipsNeeded(mesh, c[int(MeshIssue::Flipped)]);+ return r;+}++bool fixMesh(const Mesh& mesh, MeshIssue issue, Mesh& out, size_t& fixed) {+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();+ fixed = 0;+ switch (issue) {+ case MeshIssue::Degenerate:+ case MeshIssue::Duplicate: {+ std::vector<uint8_t> drop(nt, 0);+ for (uint32_t t = 0; t < nt; ++t) {+ const bool d = degenerate(mesh.triangles[t]);+ drop[t] = issue == MeshIssue::Degenerate ? d : !d && duplicateOfEarlier(mesh, t);+ fixed += drop[t];+ }+ if (!fixed) return false;+ out = withoutTriangles(mesh, drop);+ return true;+ }+ case MeshIssue::ZeroArea: {+ UnionFind points(nv);+ for (uint32_t t = 0; t < nt; ++t) {+ const glm::uvec3 tri = mesh.triangles[t];+ if (degenerate(tri) || duplicateOfEarlier(mesh, t) || !zeroArea(mesh, tri)) continue;+ int shortest = 0;+ float best = INFINITY;+ for (int k = 0; k < 3; ++k) {+ const glm::vec3 e = mesh.positions[tri[(k + 1) % 3]] - mesh.positions[tri[k]];+ if (glm::dot(e, e) < best) best = glm::dot(e, e), shortest = k;+ }+ points.unite(tri[shortest], tri[(shortest + 1) % 3]);+ ++fixed;+ }+ if (!fixed) return false;+ std::vector<uint32_t> target(nv);+ for (uint32_t v = 0; v < nv; ++v) target[v] = points.find(v);+ out = remapped(mesh, target);+ return true;+ }+ case MeshIssue::NonManifold: {+ // Around each point of a non-manifold edge, its triangles fall into fans joined across ordinary edges (and+ // across each non-manifold edge only by its kept pair); every fan past the first gets a copy of the point.+ std::vector<uint8_t> onEdge(nv, 0);+ std::vector<uint32_t> around;+ for (uint32_t a = 0; a < nv; ++a)+ for (uint32_t b : mesh.neighbors(a)) {+ if (b <= a) continue;+ edgeTriangles(mesh, a, b, around);+ if (around.size() >= 3) {+ onEdge[a] = onEdge[b] = 1;+ ++fixed;+ }+ }+ if (!fixed) return false;+ std::vector<glm::uvec3> corners(mesh.triangles);+ std::vector<uint32_t> source(nv);+ std::iota(source.begin(), source.end(), 0u);+ std::vector<uint32_t> ring, fanOf;+ for (uint32_t v = 0; v < nv; ++v) {+ if (!onEdge[v]) continue;+ ring.clear();+ for (uint32_t t : mesh.vertexTriangles(v))+ if (!degenerate(mesh.triangles[t])) ring.push_back(t);+ std::sort(ring.begin(), ring.end());+ UnionFind fans(ring.size());+ auto at = [&](uint32_t t) { return uint32_t(std::lower_bound(ring.begin(), ring.end(), t) - ring.begin()); };+ for (uint32_t w : mesh.neighbors(v)) {+ edgeTriangles(mesh, v, w, around);+ if (around.size() == 2) fans.unite(at(around[0]), at(around[1]));+ else if (around.size() >= 3) {+ const auto [p, q] = keptPair(mesh, std::min(v, w), std::max(v, w), around);+ fans.unite(at(p), at(q));+ }+ }+ fanOf.assign(ring.size(), kNone); // fan root -> the id its triangles use for v+ for (size_t i = 0; i < ring.size(); ++i) {+ const uint32_t root = fans.find(uint32_t(i));+ if (root == 0) continue; // the first fan keeps the point+ if (fanOf[root] == kNone) {+ fanOf[root] = uint32_t(source.size());+ source.push_back(v);+ }+ glm::uvec3& c = corners[ring[i]];+ for (int k = 0; k < 3; ++k)+ if (mesh.triangles[ring[i]][k] == v) c[k] = fanOf[root];+ }+ }+ TriangleRebuild how;+ how.corners = &corners;+ how.source = &source;+ out = rebuildTriangles(mesh, std::vector<uint8_t>(nt, 1), how);+ return true;+ }+ case MeshIssue::Flipped: {+ const std::vector<uint8_t> flip = flipsNeeded(mesh, fixed);+ if (!fixed) return false;+ TriangleRebuild how;+ how.flip = &flip;+ out = rebuildTriangles(mesh, std::vector<uint8_t>(nt, 1), how);+ return true;+ }+ case MeshIssue::Isolated: {+ for (uint32_t v = 0; v < nv; ++v) fixed += mesh.vertexTriangles(v).size() == 0;+ if (!fixed) return false;+ out = extractTriangles(mesh, std::vector<uint8_t>(nt, 1));+ return true;+ }+ case MeshIssue::Holes: {+ Mesh m = mesh;+ CloseHolesStats stats;+ std::string error;+ if (!closeHoles(m, CloseHolesOptions{}, stats, error) || stats.filled == 0) return false;+ fixed = stats.filled;+ out = std::move(m);+ return true;+ }+ default: return false;+ }+}++void registerMeshCheckCommands(CommandRegistry& reg) {+ using T = ParamSpec::Type;++ reg.add({"weld_points",+ "Merge by distance: merge the points of the active Part closer than a distance (one undo step). "+ "Triangles that collapse are removed; each merged point takes the kept one's position and attributes.",+ {{"distance", T::Number, "Largest distance between points that merge, in scene units (0 = only "+ "points exactly on top of each other).", true},+ {"preview", T::Bool, "Only count the points that would merge; change nothing.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ const double d = argNumber(a, "distance", 0.0);+ if (!(d >= 0.0) || !std::isfinite(d)) return {false, "distance must be 0 or more"};+ if (doc.mesh.vertexCount() == 0) return {false, "The mesh is empty"};+ size_t n = 0;+ if (argBool(a, "preview", false)) {+ weldTargets(doc.mesh, float(d), &n);+ return {true, std::to_string(n) + " points would merge"};+ }+ Mesh m = weldByDistance(doc.mesh, float(d), &n);+ if (n == 0) return {false, "No points are that close"};+ doc.replaceMeshUndoable(std::move(m), "Merge by Distance");+ return {true, "Merged " + std::to_string(n) + " points, " + std::to_string(doc.mesh.vertexCount()) + " left"};+ }});++ reg.add({"mesh_check",+ "Check the active Part for non-manifold edges, holes, duplicate, degenerate, zero-area and flipped "+ "triangles and isolated points. Changes nothing (mesh_fix repairs).",+ {},+ [](Document& doc, const Args&) -> CommandResult {+ const MeshReport r = checkMesh(doc.mesh);+ std::string s = r.summary() + " (";+ for (int i = 0; i < kMeshIssueCount; ++i)+ s += std::string(i ? " " : "") + meshIssueName(MeshIssue(i)) + "=" + std::to_string(r.count[i]);+ return {true, s + ")"};+ }});++ reg.add({"mesh_fix",+ "Fix one kind of problem mesh_check finds, as one undo step: non_manifold (loosen the extra triangles), "+ "holes (cap them), duplicate / degenerate (delete), zero_area (collapse), flipped (rewind), isolated "+ "(remove). all fixes everything except holes (an open mesh may be open on purpose).",+ {{"issue", T::String, "non_manifold, holes, duplicate, degenerate, zero_area, flipped, isolated or all.", true}},+ [](Document& doc, const Args& a) -> CommandResult {+ const std::string name = argString(a, "issue");+ std::vector<MeshIssue> issues;+ if (name == "all")+ issues = {MeshIssue::Degenerate, MeshIssue::Duplicate, MeshIssue::ZeroArea, MeshIssue::NonManifold,+ MeshIssue::Flipped, MeshIssue::Isolated};+ else if (MeshIssue one; parseMeshIssue(name, one)) issues = {one};+ else return {false, "Unknown issue '" + name + "'"};+ Mesh current;+ const Mesh* m = &doc.mesh;+ std::string done;+ for (MeshIssue issue : issues) {+ Mesh next;+ size_t fixed = 0;+ if (!fixMesh(*m, issue, next, fixed)) continue;+ current = std::move(next);+ m = ¤t;+ MeshReport one;+ one.count[int(issue)] = fixed;+ done += (done.empty() ? "" : ", ") + one.summary();+ }+ if (done.empty()) return {false, "Nothing to fix"};+ doc.replaceMeshUndoable(std::move(current), "Fix Mesh");+ return {true, "Fixed " + done};+ }});+}++} // namespace sfdiff --git a/src/core/MeshCheck.h b/src/core/MeshCheck.hnew file mode 100644index 00000000..b47af28d--- /dev/null+++ b/src/core/MeshCheck.h@@ -0,0 +1,71 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Merge by distance and Check Mesh (Tool > Geometry, @foirgairwolf). Weld merges the points closer than a+// distance; Check Mesh counts what makes a mesh hard to sculpt, remesh, print or export, and each Fix changes+// only what its issue names (nothing is fixed while checking). Everything here works on a copy: the commands+// (weld_points, mesh_check, mesh_fix) replace the active Part's mesh as one undo step.+#pragma once++#include "core/Mesh.h"++#include <cstddef>+#include <cstdint>+#include <string>+#include <vector>++namespace sf {++class CommandRegistry;++// --- Merge by distance ---+// For each vertex, the vertex it merges into (itself when it stays): vertices are taken in order and each one+// within `distance` of a vertex kept before it merges into the nearest such vertex, so the kept points end up at+// least `distance` apart and keep their positions. distance 0 merges exactly coincident points. `merged`+// (optional) receives how many vertices go.+std::vector<uint32_t> weldTargets(const Mesh& mesh, float distance, size_t* merged = nullptr);+// The mesh with those points merged: triangles that collapse (two corners on one point) are dropped and the+// rest keep their attributes (a merged point takes its target's mask, paint and layers).+Mesh weldByDistance(const Mesh& mesh, float distance, size_t* merged = nullptr);++// --- Check Mesh ---+enum class MeshIssue : uint8_t {+ NonManifold, // edges shared by three or more triangles+ Holes, // open boundaries: connected sets of edges with a triangle on one side only+ Duplicate, // triangles on the same three points as an earlier one (either winding)+ Degenerate, // triangles using one point twice+ ZeroArea, // triangles on three points that are (all but) in one line+ Flipped, // triangles wound against their neighbours, or closed pieces that are inside out+ Isolated, // points no triangle uses+ Count+};+inline constexpr int kMeshIssueCount = int(MeshIssue::Count);+// "non_manifold", "holes", "duplicate", "degenerate", "zero_area", "flipped", "isolated" (commands, tests).+const char* meshIssueName(MeshIssue issue);+bool parseMeshIssue(const std::string& name, MeshIssue& out);++struct MeshReport {+ size_t count[kMeshIssueCount] = {}; // per MeshIssue: edges, loops, triangles or points+ size_t total() const;+ // "2 holes, 14 flipped triangles" (or "No problems found").+ std::string summary() const;+};+// Needs the mesh's topology (as every Part has).+MeshReport checkMesh(const Mesh& mesh);++// The mesh with one issue fixed, and how many elements changed in `fixed`:+// - NonManifold: each triangle past the first two on such an edge gets its own copy of the edge's points (the+// fin comes loose; nothing is deleted)+// - Holes: capped as Close Holes does (a patch per loop, in a face group of its own)+// - Duplicate / Degenerate: those triangles are deleted+// - ZeroArea: the shortest edge of each is collapsed (its points merged), which removes it and its neighbour+// - Flipped: the minority winding of each piece is turned to match the rest; a closed piece wound inside out+// is turned the right way out+// - Isolated: the unused points are removed+// Returns false (and leaves `out` alone) when there was nothing to fix.+bool fixMesh(const Mesh& mesh, MeshIssue issue, Mesh& out, size_t& fixed);++// weld_points, mesh_check, mesh_fix.+void registerMeshCheckCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/Parts.cpp b/src/core/Parts.cppindex 0ebe9c27..676c3c1e 100644--- a/src/core/Parts.cpp+++ b/src/core/Parts.cpp@@ -221,6 +221,43 @@ void replaceWithPieces(Document& doc, int index, std::vector<Mesh> pieces) {doc.removePart(index);}+// Split Hidden / Masked / Unmasked: the triangles in `set` leave the active Part for a new Part just below it+// (named "<Part> <suffix>", shown as the source is, in its folder, with its shading). One undo step: the+// source's old mesh and the new Part go back together. Every attribute extractTriangles keeps carries over (UVs,+// face groups, vertex paint, sculpt layers); subdivision levels can't be cut, so the source's are noted dropped+// and undo restores them. The new Part shows everything (Split Hidden) and starts unmasked (Split Masked).+CommandResult splitOffPart(Document& doc, TriangleSet set, const char* label, const char* suffix, const char* what) {+ size_t n = 0;+ std::vector<uint8_t> in = trianglesIn(doc.mesh, set, &n);+ const std::string source = doc.activePartInfo().name;+ if (n == 0) return {false, "Nothing in " + source + " is " + what};+ if (n == doc.mesh.triangleCount()) return {false, "Everything in " + source + " is " + what + ": nothing would stay"};+ Mesh piece = extractTriangles(doc.mesh, in);+ for (uint8_t& k : in) k = !k;+ Mesh rest = extractTriangles(doc.mesh, in);+ in = {};+ if (set == TriangleSet::Hidden) piece.hidden.clear();+ if (set == TriangleSet::Masked) piece.mask.clear();+ const Part& from = doc.activePartInfo();+ const bool visible = from.visible;+ const uint32_t folder = from.folder;+ const Shading shading = from.shading;+ const int at = doc.addPart(std::move(piece), doc.uniquePartName(source + " " + suffix), false, doc.activePart + 1);+ Part& added = doc.parts[size_t(at)];+ added.visible = visible;+ added.folder = folder;+ added.shading = shading;+ const uint32_t id = added.id;+ const std::string name = added.name;+ doc.replaceMeshUndoable(std::move(rest), label);+ if (UndoRecord* r = doc.undo.lastUndo()) {+ r->part = std::make_shared<PartStep>();+ r->part->id = id;+ r->part->at = at;+ }+ return {true, "Split " + countText(n) + " into " + name + ", " + countText(doc.mesh.triangleCount()) + " stay in " + source};+}+// Reads the mesh in a model file for insert_mesh (#34): OBJ, PLY or GLB / glTF through the importers, every// object in it as one mesh. Nothing but the file itself is read.bool loadInsertMesh(const std::string& path, Mesh& out, std::string& error) {@@ -906,6 +943,27 @@ void registerPartCommands(CommandRegistry& reg) {replaceWithPieces(doc, doc.activePart, std::move(pieces));return {true, "Split into " + std::to_string(n) + " Parts"};}});++ reg.add({"part_split_hidden", "Move the hidden triangles of the active Part into a new Part below it (one undo step).", {},+ [](Document& doc, const Args&) -> CommandResult {+ return splitOffPart(doc, TriangleSet::Hidden, "Split Hidden", "hidden", "hidden");+ }});++ reg.add({"part_split_masked",+ "Move the masked triangles of the active Part (corners' average mask above 0.5) into a new, unmasked "+ "Part below it (one undo step).",+ {},+ [](Document& doc, const Args&) -> CommandResult {+ return splitOffPart(doc, TriangleSet::Masked, "Split Masked", "masked", "masked");+ }});++ reg.add({"part_split_unmasked",+ "Move the unmasked triangles of the active Part (corners' average mask 0.5 or less) into a new Part "+ "below it; the masked ones stay (one undo step).",+ {},+ [](Document& doc, const Args&) -> CommandResult {+ return splitOffPart(doc, TriangleSet::Unmasked, "Split Unmasked", "unmasked", "unmasked");+ }});}} // namespace sfdiff --git a/src/core/Parts.h b/src/core/Parts.hindex 488726cd..76a262f3 100644--- a/src/core/Parts.h+++ b/src/core/Parts.h@@ -70,7 +70,8 @@ bool resolveInsertSetPath(const std::string& path, std::string& file, std::strin// part_list, part_select, part_append, part_duplicate, part_delete,// part_rename, part_visibility, part_solo, part_show_all, part_move,-// part_merge_down, part_merge_visible, part_split_groups, part_split_parts.+// part_merge_down, part_merge_visible, part_split_groups, part_split_parts, part_split_hidden,+// part_split_masked, part_split_unmasked.void registerPartCommands(CommandRegistry& registry);} // namespace sfdiff --git a/tests/data/check_mesh_cube.obj b/tests/data/check_mesh_cube.objnew file mode 100644index 00000000..5bca66cc--- /dev/null+++ b/tests/data/check_mesh_cube.obj@@ -0,0 +1,39 @@+# Unwelded cube for tests/ui/mesh_check.sfui: every face has its own points (nudged 1e-5 apart per face),+# triangle 3 is flipped and triangle 1 is repeated at the end. SPDX-License-Identifier: GPL-3.0-or-later+v 1.000010 -1.000000 -1.000000+v 1.000010 1.000000 -1.000000+v 1.000010 1.000000 1.000000+v 1.000010 -1.000000 1.000000+v -0.999980 -1.000000 -1.000000+v -0.999980 1.000000 -1.000000+v -0.999980 1.000000 1.000000+v -0.999980 -1.000000 1.000000+v -0.999970 1.000000 -1.000000+v 1.000030 1.000000 -1.000000+v 1.000030 1.000000 1.000000+v -0.999970 1.000000 1.000000+v -0.999960 -1.000000 -1.000000+v 1.000040 -1.000000 -1.000000+v 1.000040 -1.000000 1.000000+v -0.999960 -1.000000 1.000000+v -0.999950 -1.000000 1.000000+v 1.000050 -1.000000 1.000000+v 1.000050 1.000000 1.000000+v -0.999950 1.000000 1.000000+v -0.999940 -1.000000 -1.000000+v 1.000060 -1.000000 -1.000000+v 1.000060 1.000000 -1.000000+v -0.999940 1.000000 -1.000000+f 1 2 3+f 1 3 4+f 5 7 6+f 5 7 8+f 9 11 10+f 9 12 11+f 13 14 15+f 13 15 16+f 17 18 19+f 17 19 20+f 21 23 22+f 21 24 23+f 1 3 4diff --git a/tests/test_mesh_check.cpp b/tests/test_mesh_check.cppnew file mode 100644index 00000000..26bec545--- /dev/null+++ b/tests/test_mesh_check.cpp@@ -0,0 +1,187 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Merge by distance and Check Mesh / Fix (core/MeshCheck.h; @foirgairwolf).+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/FaceGroups.h"+#include "core/MeshCheck.h"+#include "core/Primitives.h"++using namespace sf;++namespace {++size_t issue(const Mesh& m, MeshIssue i) { return checkMesh(m).count[int(i)]; }++// The mesh's triangles with every corner its own point (as an unwelded import), positions unchanged.+Mesh unwelded(const Mesh& src) {+ Mesh m;+ for (const auto& t : src.triangles) {+ const uint32_t base = uint32_t(m.positions.size());+ for (int k = 0; k < 3; ++k) m.positions.push_back(src.positions[t[k]]);+ m.triangles.push_back({base, base + 1, base + 2});+ }+ m.rebuildTopology();+ m.recomputeAllNormals();+ return m;+}++Mesh fixed(const Mesh& m, MeshIssue i, size_t* n = nullptr) {+ Mesh out;+ size_t count = 0;+ CHECK(fixMesh(m, i, out, count));+ if (n) *n = count;+ return out;+}++} // namespace++TEST(mesh_check_clean_sphere) {+ const Mesh sphere = makeIcosphere(3);+ const MeshReport r = checkMesh(sphere);+ CHECK(r.total() == 0);+ CHECK(r.summary() == "No problems found");+ Mesh out;+ size_t n = 0;+ for (int i = 0; i < kMeshIssueCount; ++i) CHECK(!fixMesh(sphere, MeshIssue(i), out, n)); // nothing to fix+}++TEST(weld_points_by_distance) {+ const Mesh sphere = makeIcosphere(2);+ const Mesh loose = unwelded(sphere);+ CHECK(loose.vertexCount() == sphere.triangleCount() * 3);+ size_t merged = 0;+ Mesh welded = weldByDistance(loose, 0.0f, &merged);+ CHECK(welded.vertexCount() == sphere.vertexCount());+ CHECK(merged == loose.vertexCount() - sphere.vertexCount());+ CHECK(welded.triangleCount() == sphere.triangleCount());+ CHECK(checkMesh(welded).total() == 0);+ // The count only (preview) matches.+ size_t n = 0;+ weldTargets(loose, 0.0f, &n);+ CHECK(n == merged);+ // Points slightly apart merge only within the distance.+ Mesh nudged = loose;+ for (size_t v = 0; v < nudged.vertexCount(); v += 2) nudged.positions[v] += glm::vec3(1e-4f, 0, 0);+ weldTargets(nudged, 0.0f, &n);+ CHECK(n < merged);+ weldTargets(nudged, 2e-4f, &n);+ CHECK(n == merged);+ // A distance as big as the mesh collapses it to nothing that stays a triangle.+ welded = weldByDistance(sphere, 10.0f, &merged);+ CHECK(merged == sphere.vertexCount() - 1 && welded.triangleCount() == 0);+}++TEST(mesh_check_holes_and_isolated) {+ Mesh plane = makePlane(4);+ CHECK(issue(plane, MeshIssue::Holes) == 1);+ CHECK(issue(plane, MeshIssue::Flipped) == 0); // an open piece: no inside to be out+ plane.positions.push_back(glm::vec3(5, 5, 5));+ plane.rebuildTopology();+ CHECK(issue(plane, MeshIssue::Isolated) == 1);+ size_t n = 0;+ Mesh m = fixed(plane, MeshIssue::Isolated, &n);+ CHECK(n == 1 && m.vertexCount() == plane.vertexCount() - 1 && issue(m, MeshIssue::Isolated) == 0);+ m = fixed(m, MeshIssue::Holes, &n);+ CHECK(n == 1 && issue(m, MeshIssue::Holes) == 0);+}++TEST(mesh_check_duplicate_degenerate_zero_area) {+ Mesh m = makeIcosphere(2);+ const size_t nt = m.triangleCount();+ m.triangles.push_back(m.triangles[0]); // duplicate+ m.triangles.push_back({m.triangles[1].x, m.triangles[1].z, m.triangles[1].y}); // duplicate, other winding+ m.triangles.push_back({m.triangles[2].x, m.triangles[2].x, m.triangles[2].y}); // degenerate+ m.rebuildTopology();+ MeshReport r = checkMesh(m);+ CHECK(r.count[int(MeshIssue::Duplicate)] == 2);+ CHECK(r.count[int(MeshIssue::Degenerate)] == 1);+ CHECK(r.count[int(MeshIssue::NonManifold)] > 0); // the duplicates put a third triangle on their edges+ size_t n = 0;+ m = fixed(m, MeshIssue::Degenerate, &n);+ CHECK(n == 1 && m.triangleCount() == nt + 2);+ m = fixed(m, MeshIssue::Duplicate, &n);+ CHECK(n == 2 && m.triangleCount() == nt);+ CHECK(checkMesh(m).total() == 0);++ // Zero area: a sliver B M A (M on the middle of A B) between two triangles above it and one below.+ Mesh sliver;+ sliver.positions = {{0, 0, 0}, {2, 0, 0}, {1, 0, 0}, {1, 1, 0}, {1, -1, 0}}; // A B M C E+ sliver.triangles = {{0, 2, 3}, {2, 1, 3}, {1, 2, 0}, {0, 4, 1}};+ sliver.rebuildTopology();+ CHECK(issue(sliver, MeshIssue::ZeroArea) == 1 && issue(sliver, MeshIssue::Flipped) == 0);+ m = fixed(sliver, MeshIssue::ZeroArea, &n);+ CHECK(n == 1 && m.triangleCount() == 2); // B M collapsed: the sliver and M B C go+ CHECK(checkMesh(m).count[int(MeshIssue::ZeroArea)] == 0 && issue(m, MeshIssue::NonManifold) == 0);+}++TEST(mesh_check_flipped) {+ Mesh m = makeIcosphere(2);+ for (uint32_t t : {3u, 10u, 11u}) std::swap(m.triangles[t].y, m.triangles[t].z);+ m.rebuildTopology();+ size_t n = 0;+ CHECK(issue(m, MeshIssue::Flipped) == 3);+ m = fixed(m, MeshIssue::Flipped, &n);+ CHECK(n == 3 && checkMesh(m).total() == 0);+ // Inside out as a whole: every triangle flips.+ for (auto& t : m.triangles) std::swap(t.y, t.z);+ m.rebuildTopology();+ CHECK(issue(m, MeshIssue::Flipped) == m.triangleCount());+ m = fixed(m, MeshIssue::Flipped, &n);+ CHECK(checkMesh(m).total() == 0);+ // UVs turn with their triangle.+ Mesh uv = makeIcosphere(1);+ uv.uvs.resize(uv.triangleCount() * 3);+ for (size_t c = 0; c < uv.uvs.size(); ++c) uv.uvs[c] = glm::vec2(float(c), 0.0f);+ std::swap(uv.triangles[0].y, uv.triangles[0].z);+ uv.rebuildTopology();+ m = fixed(uv, MeshIssue::Flipped, &n);+ CHECK(n == 1 && m.uvs[1].x == 2.0f && m.uvs[2].x == 1.0f);+}++TEST(mesh_check_non_manifold) {+ // A fin: one extra triangle on an edge of a closed sphere.+ Mesh m = makeIcosphere(2);+ const glm::uvec3 t = m.triangles[0];+ m.positions.push_back(m.positions[t.x] * 1.5f);+ m.triangles.push_back({t.x, t.y, uint32_t(m.positions.size() - 1)});+ m.rebuildTopology();+ CHECK(issue(m, MeshIssue::NonManifold) == 1);+ size_t n = 0;+ const Mesh out = fixed(m, MeshIssue::NonManifold, &n);+ CHECK(n == 1 && issue(out, MeshIssue::NonManifold) == 0);+ CHECK(out.triangleCount() == m.triangleCount()); // nothing deleted: the fin comes loose+ CHECK(out.vertexCount() == m.vertexCount() + 2); // its own copies of the edge's two points+ CHECK(issue(out, MeshIssue::Holes) == 1); // the loose fin is an open piece+}++TEST(mesh_check_commands_undo) {+ Document doc;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 2.0}}).ok);+ const size_t nv = doc.mesh.vertexCount(), nt = doc.mesh.triangleCount();+ CHECK(reg.execute(doc, "mesh_check").message.find("No problems found") == 0);+ CHECK(!reg.execute(doc, "mesh_fix", {{"issue", std::string("all")}}).ok);+ CHECK(!reg.execute(doc, "mesh_fix", {{"issue", std::string("bogus")}}).ok);+ doc.replaceMeshUndoable(unwelded(doc.mesh), "Unweld");+ CHECK(reg.execute(doc, "weld_points", {{"distance", 0.0}, {"preview", true}}).ok);+ CHECK(doc.mesh.vertexCount() == nt * 3); // the preview changes nothing+ CHECK(reg.execute(doc, "weld_points", {{"distance", 0.0}}).ok);+ CHECK(doc.mesh.vertexCount() == nv);+ CHECK(reg.execute(doc, "undo").ok && doc.mesh.vertexCount() == nt * 3);+ CHECK(!reg.execute(doc, "weld_points", {{"distance", -1.0}}).ok);+ // Fix all: one undo step for every fix, holes left open.+ CHECK(reg.execute(doc, "redo").ok);+ Mesh broken = doc.mesh;+ broken.triangles.push_back(broken.triangles[0]);+ std::swap(broken.triangles[5].y, broken.triangles[5].z);+ broken.positions.push_back(glm::vec3(3, 3, 3));+ broken.rebuildTopology();+ doc.replaceMeshUndoable(std::move(broken), "Break");+ CHECK(reg.execute(doc, "mesh_fix", {{"issue", std::string("all")}}).ok);+ CHECK(checkMesh(doc.mesh).total() == 0);+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(checkMesh(doc.mesh).total() > 0);+}diff --git a/tests/test_parts.cpp b/tests/test_parts.cppindex ff183ec6..11be9236 100644--- a/tests/test_parts.cpp+++ b/tests/test_parts.cpp@@ -243,3 +243,66 @@ TEST(part_folders) {// A new scene has no folders.CHECK(reg.execute(doc, "new_sphere").ok && doc.partFolders.empty());}++TEST(part_split_by_selection) {+ // Split Hidden / Masked / Unmasked (@foirgairwolf): the triangles leave for a new Part below, one undo step.+ Document doc;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);+ const size_t total = doc.mesh.triangleCount();+ CHECK(!reg.execute(doc, "part_split_masked").ok); // nothing masked+ CHECK(!reg.execute(doc, "part_split_unmasked").ok); // everything unmasked: nothing would stay+ CHECK(!reg.execute(doc, "part_split_hidden").ok);+ doc.mesh.mask.assign(doc.mesh.vertexCount(), 0.0f);+ for (size_t v = 0; v < doc.mesh.vertexCount(); ++v) doc.mesh.mask[v] = doc.mesh.positions[v].x > 0.0f ? 1.0f : 0.0f;+ doc.mesh.colors.assign(doc.mesh.vertexCount(), glm::vec3(0.2f, 0.4f, 0.6f));+ size_t masked = 0;+ trianglesIn(doc.mesh, TriangleSet::Masked, &masked);+ CHECK(masked > 0 && masked < total);+ CHECK(reg.execute(doc, "part_split_masked").ok);+ CHECK(doc.partCount() == 2 && doc.activePart == 0);+ CHECK(doc.mesh.triangleCount() == total - masked);+ CHECK(doc.partMesh(1).triangleCount() == masked && !doc.partMesh(1).hasMask()); // the new Part starts unmasked+ CHECK(doc.partMesh(1).hasColors() && doc.partMesh(1).colors[0] == glm::vec3(0.2f, 0.4f, 0.6f));+ CHECK(doc.parts[1].name == doc.parts[0].name + " masked");+ // One undo brings the source back whole and takes the new Part away; redo does both again.+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(doc.partCount() == 1 && doc.mesh.triangleCount() == total);+ CHECK(reg.execute(doc, "redo").ok);+ CHECK(doc.partCount() == 2 && doc.mesh.triangleCount() == total - masked && doc.partMesh(1).triangleCount() == masked);+ CHECK(reg.execute(doc, "undo").ok);++ // Unmasked: the masked side stays.+ CHECK(reg.execute(doc, "part_split_unmasked").ok);+ CHECK(doc.mesh.triangleCount() == masked && doc.partMesh(1).triangleCount() == total - masked);+ CHECK(reg.execute(doc, "undo").ok);++ // Hidden: the new Part shows them.+ doc.mesh.hidden.assign(total, uint8_t(0));+ for (size_t t = 0; t < total / 4; ++t) doc.mesh.hidden[t] = 1;+ CHECK(reg.execute(doc, "part_split_hidden").ok);+ CHECK(doc.partMesh(1).triangleCount() == total / 4 && !doc.partMesh(1).hasHidden());+ CHECK(doc.mesh.triangleCount() == total - total / 4 && !doc.mesh.hasHidden());+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(doc.partCount() == 1 && doc.mesh.triangleCount() == total);++ // Delete Masked: the mirror of Delete Hidden.+ CHECK(reg.execute(doc, "delete_masked").ok);+ CHECK(doc.mesh.triangleCount() == total - masked);+ CHECK(reg.execute(doc, "undo").ok && doc.mesh.triangleCount() == total);+ doc.mesh.mask.assign(doc.mesh.vertexCount(), 1.0f);+ CHECK(!reg.execute(doc, "delete_masked").ok); // everything masked+ CHECK(!reg.execute(doc, "part_split_masked").ok);+}++TEST(part_split_mask_threshold) {+ // A triangle is masked when its corners' average mask is above 0.5 (kMaskedThreshold), not at it.+ Mesh m;+ m.positions = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {1, 1, 0}};+ m.triangles = {{0, 1, 2}, {1, 3, 2}};+ m.mask = {0.5f, 0.5f, 0.5f, 1.0f};+ size_t n = 0;+ const auto in = trianglesIn(m, TriangleSet::Masked, &n);+ CHECK(n == 1 && in[0] == 0 && in[1] == 1);+ CHECK(trianglesIn(m, TriangleSet::Unmasked)[0] == 1);+}diff --git a/tests/ui/mesh_check.sfui b/tests/ui/mesh_check.sfuinew file mode 100644index 00000000..9aeb604b--- /dev/null+++ b/tests/ui/mesh_check.sfui@@ -0,0 +1,30 @@+# Merge by Distance and Check Mesh in Tool > Geometry (@foirgairwolf), on a cube whose faces don't share their+# points (each face nudged 1e-5 apart, so the importer keeps them), with one flipped and one repeated triangle.+run open path=$SCRIPT_DIR/../data/check_mesh_cube.obj+expect_value vertices == 24+click "Geometry##tool.geometry"+# Six loose faces: six holes. Checking changes nothing.+click "Check##mesh_check"+expect_text Duplicate triangles+expect_value vertices == 24+# The default distance (a ten-thousandth of the size) catches every nudged copy: 16 of the 24 points merge.+expect_text 16 points will merge+shot weld-preview+click "Merge##weld_points"+expect_value vertices == 8+expect_status Merged 16 points+expect_text The mesh changed: check again+click "Check##mesh_check"+expect_text Flipped triangles+expect_text Non-manifold edges+shot check-rows+click "Fix all##mesh_fix"+expect_status Fixed+expect_text No problems found+expect_value triangles == 12+shot fixed+# One undo brings every problem back; one more brings back the loose faces.+key ctrl+z+expect_value triangles == 13+key ctrl+z+expect_value vertices == 24diff --git a/tests/ui/parts_split_selection.sfui b/tests/ui/parts_split_selection.sfuinew file mode 100644index 00000000..20ae3932--- /dev/null+++ b/tests/ui/parts_split_selection.sfui@@ -0,0 +1,56 @@+# Split hidden / masked / unmasked and Delete masked (@foirgairwolf), and the per-Part shading mark in the list.+run new_sphere subdivisions=4 ; part_rename to=Body+remember triangles all+# Nothing masked yet: the command refuses.+run_fails part_split_masked+expect_value parts == 1++# Mask the right half, split it off: a new Part below, unmasked; one Ctrl+Z puts it back.+run mask_rect x0=0 y0=-1 x1=1 y1=1+click "Parts/Masked##part_split"+expect_value parts == 2+expect_value active_part == 0+expect_status into Body masked+expect "Parts/Body masked"+expect_value triangles < $all+shot split-masked+key ctrl+z+expect_value parts == 1+expect_value triangles == $all++# Unmasked: the masked side stays in Body.+click "Parts/Unmasked##part_split"+expect_value parts == 2+expect "Parts/Body unmasked"+key ctrl+z+expect_value parts == 1++# Hidden: hide the left half, split it off.+run mask_clear ; hide_rect x0=0 y0=-1 x1=1 y1=1+expect_value hidden > 0+click "Parts/Hidden##part_split"+expect_value parts == 2+expect_value hidden == 0+expect "Parts/Body hidden"+key ctrl+z+expect_value parts == 1+expect_value hidden > 0+run show_all++# The shading mark in the Parts list: Scene -> Smooth -> Flat -> Scene.+expect_value part_shading == 0+click "Parts/##shade Body"+expect_value part_shading == 1+click "Parts/##shade Body"+expect_value part_shading == 2+shot shading-flat+click "Parts/##shade Body"+expect_value part_shading == 0++# Delete masked in Tool > Visibility, undoable.+run mask_rect x0=0 y0=-1 x1=1 y1=1+click "Visibility"+click "Delete masked"+expect_value triangles < $all+key ctrl+z+expect_value triangles == $all