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
Close Holes, Cut Clip, X-Ray, light controls, view resolution, Save Render presets; Library close on small screens (#103, #102, #80, #91)
islandmedb3d2b772a6da
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 450f707e..9f40c880 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -71,6 +71,7 @@ add_library(sculptforge_core STATICsrc/core/EnginePresets.cppsrc/core/Masking.cppsrc/core/Cut.cpp+ src/core/CloseHoles.cppsrc/core/BrushAlpha.cppsrc/core/Stroke.cppsrc/core/Precision.cpp@@ -328,6 +329,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/AssetLibrary.cppsrc/app/PanelMasking.cppsrc/app/PanelCut.cpp+ src/app/PanelView.cppsrc/app/PanelPolygroups.cppsrc/app/PanelSelectionSets.cppsrc/app/Selection.cppdiff --git a/changes/fix-0.10.10-small-b.md b/changes/fix-0.10.10-small-b.mdnew file mode 100644index 00000000..171ce0fc--- /dev/null+++ b/changes/fix-0.10.10-small-b.md@@ -0,0 +1,54 @@+---+whats_new: **Close Holes**: **Tool > Geometry > Close Holes** caps every open boundary of a Part with a patch that+ follows the curve of the surface around it.+whats_new: **Clip**: **Tool > Cut > Clip** presses everything on one side of a line, or outside a lasso or rectangle,+ flat onto the shape. Nothing is removed. Use it for hard-surface planes and clean silhouettes.+whats_new: **X-Ray**: the **X-Ray** button next to **Solo** shows the active Part through the others. It is also in+ **View**.+whats_new: **Light**: **Render > Materials > Light** turns the light around the model with a small pad, and sets its+ intensity and ambient light.+whats_new: **View resolution**: **View** or **Preferences > Performance** draws the 3D view at 75% or 50% for slow+ GPUs.+whats_new: **Save Render** sizes (up to 4096 px), shapes (1:1, 16:9, 9:16, 4:3) and JPG.+highlight: Close Holes, Clip and X-Ray+added: **Close Holes** (Tool > Geometry, `close_holes`, #103): caps every open boundary of the active Part (a hole, an+ open bottom, the rim of an extracted shell) with new triangles sized like the ones around it. The patch is faired+ into the curvature around the hole, so a sphere closes round, not flat. The rest of the Part is not changed, and the+ patches get a face group of their own. `max_edges` closes only the small holes. Thanks to the reporter of #103.+added: **Clip** mode for Cut (Tool > Cut, `cut mode=clip`, #102): a line or open polyline presses its shaded side+ flat onto itself, and a lasso, rectangle or closed polyline presses everything outside it onto its outline. Points+ keep their depth and nothing is removed. The cut goes through the whole Part, follows symmetry, and the mask holds+ points back. Thanks to the reporter of #102.+added: **X-Ray** (`xray`, #80, #91): a button next to Solo in Tool > Parts, and a View checkbox. The other Parts turn+ see-through and only their nearest surface shows, so the active Part shows through them. When only the active Part is+ shown, it is see-through itself.+added: **Light controls** (Render > Materials > Light, `light`, #80): drag on the pad to turn the light of the Lit+ Sphere and the studio shading. Intensity and Ambient sliders sit beside it, and Reset goes back to the material's own+ light. The light is saved in the project.+added: **View resolution** (View and Preferences > Performance, `view_resolution`, #80): 100%, 75% or 50%. The 3D+ view is drawn smaller and scaled up, which helps slow or integrated GPUs. Save Render stays at full resolution.+added: **Save Render** sizes, shapes and JPG (Render > Materials, `save_render`, #80): twice the view (as before) or+ 1080, 1920, 2048 or 4096 pixels on the longer side. Shapes: the view's, 1:1, 16:9, 9:16 or 4:3 (a narrower shape+ widens the field of view, so the picture still shows what the view shows). Output is PNG or JPG.+fixed: The Library's close button works on small screens at a large UI scale (#80). When the tabs don't fit beside it,+ they fold into a drop-down, and the Sculpt Timeline no longer covers the Library's header (720p at 150%, ZBrush+ layout).+testers:+ - Windows at 150% scaling on a 1366x768 or 1280x720 screen: press comma to open the Library, then click its X. It+ closes in both layouts (Preferences > Interface > Layout).+ - Tool > Parts with two Parts: click X-Ray. The other Part turns see-through and the active one shows through it.+ Solo plus X-Ray shows the lone Part see-through. Click X-Ray again to make it solid.+ - Render > Materials > Light: drag on the ball. The model's light follows the dot. Try Intensity, Ambient and Reset,+ with a Lit Sphere and with Studio.+ - View > View resolution 50% on a laptop GPU: orbiting a big mesh should feel faster and look a little softer.+ 100% puts it back.+ - Render > Materials: pick 9:16 and JPG, then click Save Render. Library > Image has a tall JPG showing what the view+ shows.+ - Tool > Cut > Clip: Ctrl+Shift+drag a Cut Line across a sphere. One side goes flat and nothing is removed. Try it+ with a Cut Rectangle and with symmetry X on.+ - Hide part of a sphere (Ctrl+Shift+drag), then Visibility > Delete hidden, then Tool > Geometry > Close Holes. The+ holes close smoothly, and Ctrl+Z brings them back.+---+#102 Clip is a Cut mode (Ctrl+Shift picks Cut Line / Lasso / Rectangle / Polyline as before, Tool > Cut > Clip). The+tests are test_close_holes.cpp, the clip test in test_cut.cpp, tests/ui/view_controls.sfui, and the 150% part of+library_small_screen.sfui.diff --git a/docs/guide/cut.md b/docs/guide/cut.mdindex 746f80e5..cd0fd458 100644--- a/docs/guide/cut.md+++ b/docs/guide/cut.md@@ -21,13 +21,14 @@ or **Select Lasso** again to hide parts of the model.## Pick a mode-**Tool > Cut** has three modes:+**Tool > Cut** has four modes:| Mode | What it does || --- | --- || **Away** | Removes everything the shape covers, through the whole Part, and closes the cut with a flat cap. A line slices the Part in two and keeps one side; a lasso or rectangle drawn inside the outline cuts a hole right through. || **In** | Cuts a flat-bottomed pocket where the shape covers the Part. **Depth** sets how deep, measured from the nearest point under the shape. || **Add** | Adds the shape, extruded towards you by **Depth** and joined to the Part (a boolean union): panels, ridges, buttons, sockets. |+| **Clip** | Removes nothing. A line presses its shaded side flat onto itself. A lasso, rectangle or closed polyline presses everything outside it onto its outline. Points keep their depth, so you get flat planes and clean silhouettes through the whole Part. The mask holds points back. |**Depth** is a share of the Part's size (0.10 = a tenth of its largest side), so it means the same on a small orlarge model.diff --git a/docs/guide/first-sculpt.md b/docs/guide/first-sculpt.mdindex 9f53fe0d..d2fa0664 100644--- a/docs/guide/first-sculpt.md+++ b/docs/guide/first-sculpt.md@@ -170,7 +170,9 @@ are there. Every step can be undone with <kbd>Ctrl</kbd>+<kbd>Z</kbd>, so experi2. Open **Render > Materials** and click **PBR** under **Viewport Shading**: studio lighting with soft reflections.3. Turn the view to a three-quarter angle, a little from above, and press <kbd>F</kbd>.4. Click **Save Render** at the bottom of **Render > Materials**. The status bar names the picture (twice the- size of the view); find it under **Library > Image**.+ size of the view); find it under **Library > Image**. **Size** and the shape buttons (1:1, 16:9, 9:16, 4:3)+ below it make a bigger or differently shaped picture, as a PNG or a JPG. **Light**, above it, turns the light+ around the model.5. Press <kbd>Ctrl</kbd>+<kbd>S</kbd> to save the project.diff --git a/docs/guide/geometry.md b/docs/guide/geometry.mdindex 60df6ae2..e49e5fbd 100644--- a/docs/guide/geometry.md+++ b/docs/guide/geometry.md@@ -109,6 +109,15 @@ vertex paint density and symmetry. **Project All** (**Tool > Parts > Project**)the new topology after you divide it. Both have their own chapter: [Quad retopology and detailprojection](retopology.md).+## Close Holes++**Tool > Geometry > Close Holes** caps every open boundary of the active Part, such as a hole, an open bottom or the+rim of an extracted shell. The new patch's triangles are sized like the ones around the hole, and the patch follows+the curve of the surface around it, so a hole in a sphere closes round, not flat. The rest of the Part is not changed.+The patches get a [face group](face-groups.md) of their own, so you can mask or hide them in one click. Close Holes+makes an open scan or an extracted part watertight without a remesh. <kbd>Ctrl</kbd>+<kbd>Z</kbd> brings the holes+back.+## Decimate**Tool > Geometry > Decimate** reduces the triangle count while keeping the shape, using quadric edge collapse (the@@ -201,6 +210,7 @@ each of them. Before a big change on a heavy sculpt:| `remesh` | `resolution` 32-512 voxels across the longest side (default 200); `keep_texture` (default true) || `decimate` | `ratio` 0.01-1 of the triangles to keep (default 0.5), or `triangles` for an exact target || `qremesh` | `target` quads (default 5000), `adaptive`, `keep_groups`, `detect_edges`, `use_polypaint`, `symmetry`, `keep_original`, `keep_texture`; see [Quad retopology](retopology.md#scripting) |+| `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 || `export_lods` | `path` (base name), `levels` 1-8 including LOD0 (default 4), `ratio` 0.1-0.9 (default 0.5) |diff --git a/docs/guide/parts.md b/docs/guide/parts.mdindex 41b9c3e1..1167b366 100644--- a/docs/guide/parts.md+++ b/docs/guide/parts.md@@ -84,6 +84,9 @@ You can also add files as Parts from elsewhere:- The eye on each row shows or hides that Part.- **Solo** shows only the active Part. Click it again to bring the others back. The **Solo** button on the rightshelf does the same.+- **X-Ray**, next to **Solo**, shows the active Part through the others: the other Parts turn see-through and only+ their nearest surface shows. When only the active Part is shown, it is see-through itself. Click **X-Ray** again+ to make them solid. **View > X-Ray** does the same.- **Unhide all** shows every Part.Hidden Parts aren't drawn, can't be selected with <kbd>Alt</kbd>+click, and are left out of exports.diff --git a/docs/guide/performance.md b/docs/guide/performance.mdindex e457097b..1bcb1e1f 100644--- a/docs/guide/performance.md+++ b/docs/guide/performance.md@@ -37,6 +37,7 @@ Open **Preferences** and click **Performance**.| Control | What it does ||---|---|| **Antialiasing** (Off, 2x, 4x, 8x) | How many samples per pixel the 3D view uses to smooth edges. 4x is the default. More samples look smoother and cost more on huge meshes. If the graphics card can't make room for them, the view quietly uses fewer and the panel says so |+| **View resolution** (100%, 75%, 50%) | Draws the 3D view at a share of the window's resolution and scales it up: 75% draws about half the pixels and 50% a quarter. Try it on slow or integrated graphics and big screens. **Save Render** always renders at full resolution. Also in **View** || **Fast Navigation** | While you rotate, pan or zoom a scene bigger than the hardware profile's motion proxy threshold (see below), draw it without antialiasing and draw big meshes as a lighter version with about a fifth of their triangles, so the view keeps up. The full mesh, smooth again, is back as soon as the view stops. On by default || **Predictive Strokes** | The brush is worked out on its own thread while the view keeps drawing at full speed. The dabs it hasn't finished show at once as a preview on the surface, and the brush cursor and the stroke's head are drawn where the pen is about to be, so on a heavy mesh the surface moves under the pen straight away and lifting the pen never waits. The finished sculpt is exactly the same as with it off. On by default (painting, masking, dynamic topology, Move, Tendril and the drag strokes work as before) || **Draft Strokes** | With Predictive Strokes: while you sculpt, the brush only moves the surface, the moved part is shaded from its facets, and the smooth shading, the cavities and the rest are worked out once when you lift the pen. Lighter on laptops and on battery. Inflate and the plane brushes use the surface's direction from the stroke's start, so the result can differ slightly from a full stroke. Off by default |diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 15e33bf8..0cf05e0c 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -62,8 +62,8 @@ documentation** opens links to it).**Show** in **Render > Gaussian Splats** while you sculpt.- On laptops with two GPUs, make sure SculptForge runs on the dedicated one (in the GPU maker's control panelor the operating system's graphics settings).-- **Edit > Preferences > Performance**: lower **Antialiasing** (or turn it off), keep **Fast Navigation** on, and look- at **Last stroke** to see whether brushes or the graphics card take the time. Step down a+- **Edit > Preferences > Performance**: lower **Antialiasing** (or turn it off), try **View resolution** 75% or 50%,+ keep **Fast Navigation** on, and look at **Last stroke** to see whether brushes or the graphics card take the time. Step down a[subdivision level](subdivision-levels.md) for big changes. See [Performance and big meshes](performance.md).- A Part missing from the view with "Not enough GPU memory" in the status bar didn't fit on the graphicscard: hide other Parts or step down a level.diff --git a/src/app/App.cpp b/src/app/App.cppindex d8fe2ad4..f60a3698 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -197,6 +197,7 @@ bool App::init(const AppOptions& options) {ai::setAiEnabled(ai::aiFeaturesAllowed(headless || !options.demo.empty() || aiSettings_.enabled));ai::registerAiCommands(commands_, [this] { return aiSettings_; });registerPaintUiCommands();+ registerViewUiCommands(); // light, xray, view_resolution, save_render (PanelView.cpp)std::snprintf(falKey_, sizeof falKey_, "%s", aiSettings_.falKey.c_str());std::snprintf(falModel_, sizeof falModel_, "%s", aiSettings_.falModel.c_str());std::snprintf(meshyKey_, sizeof meshyKey_, "%s", aiSettings_.meshyKey.c_str());@@ -976,6 +977,7 @@ int App::run() {const int samples = viewSamples();renderSettings_.motionProxy = perf_.proxyNow; // big meshes draw their lighter proxy while the view movesrenderSettings_.materialTint = materialTintFor(doc_.paintColor); // (Color > Colour tints the material)+ renderSettings_.resolutionScale = float(uiPrefs_.viewResolution) / 100.0f; // (#80; only the window's view)perf_.samplesUsed = renderer_.drawView(camera_, fbW, fbH, renderSettings_, canvasViewport(fbW, fbH), samples);if (snapshotEnv && *snapshotEnv && (sm.moving || sm.releasing)) {// Three points of the stroke, and the end (the frame the last dab reached the screen).@@ -998,6 +1000,7 @@ int App::run() {}}renderSettings_.motionProxy = false; // (other renders, e.g. project thumbnails, draw in full)+ renderSettings_.resolutionScale = 1.0f;mark();ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());hardwareProfileFrameEnd();diff --git a/src/app/App.h b/src/app/App.hindex c8018048..b1e31f08 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -593,7 +593,7 @@ private:void drawCutOverlay();void drawCutSection();bool maskFrontFacesOnly_ = false; // Mask Lasso / Rectangle: only vertices facing the viewer (#91.3)- int cutMode_ = 0; // 0 Away, 1 In, 2 Add (core/Cut.h)+ int cutMode_ = 0; // 0 Away, 1 In, 2 Add, 3 Clip (core/Cut.h)float cutDepth_ = 0.1f; // In / Add: fraction of the Part's sizestd::vector<ImVec2> cutPolyline_; // window pixels of the Polyline being placed// Screen selections (Selection.cpp): the rectangle or lasso dragged for@@ -1439,7 +1439,23 @@ private:// The LightBox / picker shortcuts (, B M S) until the action registry dispatches keys.bool lightBoxKey(SDL_Keycode key, SDL_Keymod mod);void quickSave(); // file.quicksave: a timestamped project in <library>/QuickSave- void saveRender(); // render.save_image: the view as a PNG in <library>/Images+ // Save Render (render.save_image, save_render): the view without the interface, by default as a PNG in+ // <library>/Images at twice the view's size. `size` is the longer side (0 = twice the view, at most 4096),+ // `aspect` width / height (0 = the view's); a different shape shows at least what the view shows.+ struct RenderRequest {+ int size = 0;+ float aspect = 0.0f;+ bool jpg = false;+ std::string path; // "" = a new file in <library>/Images+ };+ bool saveRender(const RenderRequest& request, std::string& message);+ void runSaveRender(); // with Material's size, shape and format (PanelView.cpp)+ int renderAspect_ = 0, renderSize_ = 0; // Material > Save Render: indices into PanelView.cpp's lists+ bool renderJpg_ = false;+ // View controls (PanelView.cpp): X-Ray, the view's resolution, the light, Save Render's options.+ void registerViewUiCommands();+ void drawLightControls();+ void drawSaveRenderControls();LibraryRoots library_;FolderScanner libraryScanner_;// ---- end LightBox (B) ----diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 02c7c1bd..2a9291f2 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -109,6 +109,7 @@ Json toJson(const UiPrefs& p) {j.set("spaceMouse", toJson(p.spaceMouse));j.set("antialiasing", double(p.antialiasing));j.set("fastNavigation", p.fastNavigation);+ j.set("viewResolution", double(p.viewResolution));j.set("multithreading", p.multithreading);j.set("predictiveStrokes", p.predictiveStrokes);j.set("draftStrokes", p.draftStrokes);@@ -183,6 +184,10 @@ void fromJson(const Json& j, UiPrefs& p) {const int aa = int(j["antialiasing"].asNumber(p.antialiasing));p.antialiasing = aa >= 8 ? 8 : aa >= 4 ? 4 : aa >= 2 ? 2 : 1;p.fastNavigation = j["fastNavigation"].asBool(p.fastNavigation);+ {+ const int r = int(j["viewResolution"].asNumber(p.viewResolution));+ p.viewResolution = r <= 50 ? 50 : r <= 75 ? 75 : 100;+ }p.multithreading = j["multithreading"].asBool(p.multithreading);p.predictiveStrokes = j["predictiveStrokes"].asBool(p.predictiveStrokes);p.draftStrokes = j["draftStrokes"].asBool(p.draftStrokes);@@ -353,6 +358,11 @@ void App::initActions() {add("edit.redo", "Redo", "Edit", "Ctrl+Shift+Z / Ctrl+Y", [this] { runCommand("redo"); }, ICON_LC_REDO_2, "redo", nullptr,[this] { return doc_.undo.canRedo(); });add("geometry.subdivide", "Subdivide", "Tool > Geometry", nullptr, [this] { runCommand("subdivide"); }, nullptr, "subdivide");+ add("geometry.close_holes", "Close Holes", "Tool > Geometry", nullptr, [this] { runCommand("close_holes"); },+ ICON_LC_CIRCLE_DOT, "close_holes", nullptr, nullptr,+ "Cap every open boundary of the active Part (a hole, an open bottom, the rim of an extracted shell) with a "+ "new patch sized like the polygons around it, so remeshing and sculpting see a closed surface. The rest of "+ "the Part stays as it is; the patches get a face group of their own (#103).");// Subdivision levels (ZBrush Tool > Geometry; core/Multires.h).add("geometry.divide", "Divide", "Tool > Geometry", "Ctrl+D", [this] { runCommand("subdiv_divide", {{"smooth", smt_}}); },ICON_LC_GRID_2X2, "subdiv_divide", nullptr, nullptr,diff --git a/src/app/Config.h b/src/app/Config.hindex 67911f62..b3f2d1cb 100644--- a/src/app/Config.h+++ b/src/app/Config.h@@ -91,6 +91,7 @@ struct UiPrefs {// Preferences > Performance (PanelPerformance.cpp).int antialiasing = 4; // samples per pixel in the 3D view: 1 (off), 2, 4 or 8bool fastNavigation = true; // big scenes draw without antialiasing while the view moves+ int viewResolution = 100; // the 3D view's resolution, % of the window's (#80): 100, 75 or 50bool multithreading = true; // brushes, normals and BVH updates on every core (off: one thread)// Sculpt strokes solved on their own thread with a GPU preview of the dabs still to come, the cursor and the// stroke's head predicted a frame ahead (app/AsyncStroke.cpp). Off: the dabs are placed in the frame loop.diff --git a/src/app/LightBox.cpp b/src/app/LightBox.cppindex 140fe712..36d6a2ee 100644--- a/src/app/LightBox.cpp+++ b/src/app/LightBox.cpp@@ -601,8 +601,30 @@ void LightBox::drawHeader(App& app, float width) {}ImGui::SameLine(0, 14 * scale);- // Tabs: text buttons, the active one underlined in accent.- for (int i = 0; i < int(LibraryTab::Count); ++i) {+ // Tabs: text buttons, the active one underlined in accent. When they don't fit beside the close button (a small+ // screen at a big UI scale, #80), one drop-down lists them instead, so they never run under it.+ float tabsW = 2.0f * (ImGui::GetFrameHeight() + 2.0f) + 10.0f * scale; // (Back / Forward)+ for (int i = 0; i < int(LibraryTab::Count); ++i)+ tabsW += ImGui::CalcTextSize(tr(libraryTabName(LibraryTab(i)))).x + 2.0f * style.FramePadding.x;+ const float roomForTabs = origin.x + width - ImGui::GetCursorScreenPos().x - ImGui::GetFrameHeight() - 16.0f * scale;+ if (tabsW > roomForTabs) {+ float widest = 0.0f;+ for (int i = 0; i < int(LibraryTab::Count); ++i)+ widest = std::max(widest, ImGui::CalcTextSize(tr(libraryTabName(LibraryTab(i)))).x);+ ImGui::SetNextItemWidth(widest + ImGui::GetFrameHeight() + 2.0f * style.FramePadding.x);+ if (ImGui::BeginCombo("##lbtab", tr(libraryTabName(place_.tab)))) {+ for (int i = 0; i < int(LibraryTab::Count); ++i) {+ const auto tab = LibraryTab(i);+ if (ImGui::Selectable(tr(libraryTabName(tab)), place_.tab == tab) && place_.tab != tab)+ navigate(app, {tab, ""});+ }+ ImGui::EndCombo();+ }+ ui::HelpText("Library tabs", nullptr, "What the Library shows: projects, models, brushes, alphas, materials, "+ "images, splats, snapshots, recent files and packs.", "Library");+ ImGui::SameLine(0, 10 * scale);+ }+ for (int i = 0; i < int(LibraryTab::Count) && tabsW <= roomForTabs; ++i) {const auto tab = LibraryTab(i);const bool on = place_.tab == tab;ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32(0, 0, 0, 0));@@ -630,8 +652,8 @@ void LightBox::drawHeader(App& app, float width) {};ui::HelpText(libraryTabName(tab), nullptr, tips[i], "Library");ImGui::SameLine(0, 0);+ if (i == int(LibraryTab::Count) - 1) ImGui::SameLine(0, 10 * scale);}- ImGui::SameLine(0, 10 * scale);// History.ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32(0, 0, 0, 0));@@ -1115,9 +1137,10 @@ void App::initLightBox() {"Your project file is not changed. Find them in the Library's Snapshots tab.",[this] { quickSave(); });add("render.save_image", "Save Render", ICON_LC_CAMERA, "Material", "",- "Render the view (without the interface) at twice its size to a PNG in your library: Library > Image "- "lists it, and the status bar names the file.",- [this] { saveRender(); });+ "Render the view (without the interface) to an image in your library: Library > Image lists it, and the "+ "status bar names the file. Material sets its size (twice the view by default), shape (the view's, 1:1, "+ "16:9, 9:16, 4:3) and format (PNG or JPG).",+ [this] { runSaveRender(); });// ZBrush opens the LightBox at startup on the Project tab (never in tests, renders or recordings).if (uiPrefs_.lightboxAtStartup && interactive() && options_.uiTest.empty() && options_.openPath.empty() &&@@ -1176,53 +1199,70 @@ void App::quickSave() {lastCommandOk_ = true;}-void App::saveRender() {- if (library_.user.empty()) {- status_ = "Save Render needs a library folder (Preferences > Library)";- return;- }- const std::string folder = library_.user + "/Images";+bool App::saveRender(const RenderRequest& request, std::string& message) {+ std::string path = request.path;+ const char* ext = request.jpg ? ".jpg" : ".png";std::error_code ec;- fs::create_directories(fsPath(folder), ec);- const std::time_t t = std::time(nullptr);- std::tm tm{};+ if (path.empty()) {+ if (library_.user.empty()) {+ message = "Save Render needs a library folder (Preferences > Library)";+ return false;+ }+ const std::string folder = library_.user + "/Images";+ fs::create_directories(fsPath(folder), ec);+ const std::time_t t = std::time(nullptr);+ std::tm tm{};#if defined(_WIN32)- localtime_s(&tm, &t);+ localtime_s(&tm, &t);#else- localtime_r(&t, &tm);+ localtime_r(&t, &tm);#endif- char buf[64];- std::strftime(buf, sizeof buf, "Render %Y-%m-%d %H-%M-%S", &tm);- std::string path = folder + "/" + buf + ".png";- for (int serial = 1; fs::exists(fsPath(path), ec); ++serial)- path = folder + "/" + buf + " (" + std::to_string(serial) + ").png";- // The canvas's shape at twice its size (at most 4096 px wide): what you see, without the interface.+ char buf[64];+ std::strftime(buf, sizeof buf, "Render %Y-%m-%d %H-%M-%S", &tm);+ path = folder + "/" + buf + ext;+ for (int serial = 1; fs::exists(fsPath(path), ec); ++serial)+ path = folder + "/" + buf + " (" + std::to_string(serial) + ")" + ext;+ }+ // The canvas's shape (or the one asked for), at twice the canvas's size (at most 4096 px) unless a size is+ // given: what you see, without the interface. A narrower shape than the view's widens the field of view so+ // the picture still shows everything the view does.const CanvasRect c = canvasRect();- const float aspect = c.h > 1.0f ? c.w / c.h : 1.0f;+ const float viewAspect = c.h > 1.0f ? c.w / c.h : 1.0f;+ const float aspect = request.aspect > 0.0f ? request.aspect : viewAspect;+ const int longSide = request.size > 0 ? request.size : std::clamp(int(std::max(c.w, c.h) * 2.0f), 512, 4096);Image img;- img.width = std::clamp(int(c.w * 2.0f), 512, 4096);- img.height = std::max(1, int(float(img.width) / aspect));+ if (aspect >= 1.0f) {+ img.width = longSide;+ img.height = std::max(1, int(std::lround(float(longSide) / aspect)));+ } else {+ img.height = longSide;+ img.width = std::max(1, int(std::lround(float(longSide) * aspect)));+ }Camera cam = camera_;cam.aspect = aspect;+ if (aspect < viewAspect)+ cam.fovY = 2.0f * std::atan(std::tan(camera_.fovY * 0.5f) * viewAspect / aspect);RenderSettings settings = renderSettings_;settings.dimInactive = false; // every Part at full brightnesssettings.showMask = false;+ settings.resolutionScale = 1.0f;constexpr GLenum kFramebufferBinding = 0x8CA6, kViewport = 0x0BA2;GLint fbo = 0, viewport[4] = {};gl::GetIntegerv(kFramebufferBinding, &fbo);gl::GetIntegerv(kViewport, viewport);std::string err;- const bool ok = renderer_.renderToImage(cam, img.width, img.height, settings, img.rgba, err) && img.savePng(path, err);+ bool ok = renderer_.renderToImage(cam, img.width, img.height, settings, img.rgba, err);gl::BindFramebuffer(GL_FRAMEBUFFER, GLuint(fbo));gl::Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);+ if (ok) ok = request.jpg ? img.saveJpg(path, 92, err) : img.savePng(path, err);if (!ok) {- status_ = "Save Render failed: " + err;- lastCommandOk_ = false;- return;+ message = "Save Render failed: " + err;+ return false;}libraryScanner_.invalidate();- status_ = "Saved " + utf8(fsPath(path).filename()) + " (Library > Image)";- lastCommandOk_ = true;+ message = "Saved " + utf8(fsPath(path).filename()) + " (" + std::to_string(img.width) + " x " ++ std::to_string(img.height) + (request.path.empty() ? ", Library > Image)" : ")");+ return true;}} // namespace sfdiff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex f5049708..c5cd379f 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -662,6 +662,9 @@ void App::drawPalette_Render() {ui::HelpAction(*this, "view.mask");ImGui::Checkbox(tr("Show Face Groups##render"), &renderSettings_.showPolygroups);ui::HelpAction(*this, "view.polygroups");+ bool xray = renderSettings_.xray;+ if (ui::Checkbox("X-Ray##render", &xray)) runCommand("xray", {{"on", xray}});+ ui::HelpAction(*this, "view.xray");ImGui::BeginDisabled(doc_.splats.empty());ImGui::Checkbox(tr("Show Splats"), &renderSettings_.showSplats);ImGui::EndDisabled();@@ -670,6 +673,8 @@ void App::drawPalette_Render() {if (ui::Checkbox("Lock camera##view.lock_camera", &lockCamera)) uiPrefs_.airStrokes = lockCamera;ui::HelpAction(*this, "input.toggle_air_strokes");drawBackgroundControls("render");+ ImGui::TextDisabled("%s", tr("View resolution"));+ ui::Segmented(*this, {"perf.res_100", "perf.res_75", "perf.res_50"});actionRow(*this, {"view.frame", "view.fullscreen"});actionRow(*this, {"ui.lightbox", "ui.console"}); // (the SculptForge layout's View menu: they left the shelf)}@@ -755,7 +760,7 @@ void App::drawPalette_Tool() {tray::Section section;Demo::pushScope("Geometry");drawGeometrySection();- actionRow(*this, {"geometry.subdivide"});+ actionRow(*this, {"geometry.subdivide", "geometry.close_holes"});const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;if (ImGui::Button(tr("Decimate"), ImVec2(half, 0))) {Args args{{"ratio", double(decimateRatio_)}};diff --git a/src/app/PanelCut.cpp b/src/app/PanelCut.cppindex 011fc63a..54cba2a8 100644--- a/src/app/PanelCut.cpp+++ b/src/app/PanelCut.cpp@@ -3,7 +3,7 @@//// Cut (#101, #91; core/Cut.h): the Cut shapes sit in the Ctrl+Shift brush picker next to Select Rectangle and// Select Lasso. Ctrl+Shift+drag a line, lasso or rectangle (Alt turns a line round); Cut Polyline places points-// with Ctrl+Shift+click. Tool > Cut picks the mode (Away, In, Add) and the depth. Each cut is one "cut" command+// with Ctrl+Shift+click. Tool > Cut picks the mode (Away, In, Add, Clip) and the depth. Each cut is one "cut" command// with the shape in normalised device coordinates and the current view, mirrored by the symmetry.#include "app/App.h"#include "app/I18n.h"@@ -18,7 +18,7 @@ namespace {constexpr float kCloseRadiusPx = 9.0f; // a Polyline click this close to its first point closes it-const char* modeName(int mode) { return mode == 1 ? "in" : mode == 2 ? "add" : "away"; }+const char* modeName(int mode) { return mode == 1 ? "in" : mode == 2 ? "add" : mode == 3 ? "clip" : "away"; }// Which side of a -> b a line (or the first segment of an open polyline) cuts: the left in NDC (y up), which is the// left on the screen too; `flip` takes the right.@@ -113,9 +113,12 @@ void App::drawCutOverlay() {const bool dragging = drag_ == Drag::Select && selectMoved_ && !selectPath_.empty() && isCutShape(selectShape_);if (!dragging && cutPolyline_.empty()) return;const bool alt = (inputMods() & SDL_KMOD_ALT) != 0;- // Orange: what the cut takes away (Away, In) or adds (Add).- const ImU32 line = cutMode_ == 2 ? IM_COL32(120, 220, 255, 235) : IM_COL32(255, 150, 70, 235);- const ImU32 fill = cutMode_ == 2 ? IM_COL32(120, 220, 255, 45) : IM_COL32(255, 150, 70, 45);+ // Orange: what the cut takes away (Away, In); blue: what it adds (Add); green: what Clip presses flat (the+ // shaded side of a line), or for a closed shape the outline it presses the outside onto.+ const bool clip = cutMode_ == 3;+ const ImU32 line = cutMode_ == 2 ? IM_COL32(120, 220, 255, 235) : clip ? IM_COL32(140, 230, 120, 235) : IM_COL32(255, 150, 70, 235);+ const ImU32 fill = cutMode_ == 2 ? IM_COL32(120, 220, 255, 45) : clip ? IM_COL32(140, 230, 120, 40) : IM_COL32(255, 150, 70, 45);+ const ImU32 closedFill = clip ? IM_COL32(0, 0, 0, 0) : fill; // (Clip keeps a closed shape's inside as it is)ImDrawList* dl = ImGui::GetForegroundDrawList();const CanvasRect c = canvasRect();dl->PushClipRect(ImVec2(c.x, c.y), ImVec2(c.x + c.w, c.y + c.h), true);@@ -145,7 +148,7 @@ void App::drawCutOverlay() {std::hypot(mouse.x - cutPolyline_.front().x, mouse.y - cutPolyline_.front().y) < kCloseRadiusPx * uiScale_;if (closing) {path.back() = cutPolyline_.front();- dl->AddConcavePolyFilled(path.data(), int(path.size()), fill);+ dl->AddConcavePolyFilled(path.data(), int(path.size()), closedFill);dl->AddPolyline(path.data(), int(path.size()), line, ImDrawFlags_Closed, 2.0f);} else {openPath(path, alt);@@ -157,12 +160,12 @@ void App::drawCutOverlay() {} else if (selectShape_ == SelectShape::CutRect) {const ImVec2 a = selectPath_.front();const ImVec2 p0(std::fmin(a.x, mouse.x), std::fmin(a.y, mouse.y)), p1(std::fmax(a.x, mouse.x), std::fmax(a.y, mouse.y));- dl->AddRectFilled(p0, p1, fill);+ dl->AddRectFilled(p0, p1, closedFill);dl->AddRect(p0, p1, line, 0.0f, 0, 2.0f);} else {std::vector<ImVec2> path = selectPath_;path.push_back(mouse);- dl->AddConcavePolyFilled(path.data(), int(path.size()), fill);+ dl->AddConcavePolyFilled(path.data(), int(path.size()), closedFill);dl->AddPolyline(path.data(), int(path.size()), line, ImDrawFlags_Closed, 2.0f);}dl->PopClipRect();@@ -172,8 +175,8 @@ void App::drawCutSection() {ImGui::TextDisabled("%s", tr("Ctrl+Shift+drag a Cut shape"));ui::Segmented(*this, {"cut.line", "cut.lasso"}); // two rows: the names fit a narrow trayui::Segmented(*this, {"cut.rect", "cut.polyline"});- ui::Segmented(*this, {"cut.away", "cut.in", "cut.add"});- if (cutMode_ != 0) {+ ui::Segmented(*this, {"cut.away", "cut.in", "cut.add", "cut.clip"});+ if (cutMode_ == 1 || cutMode_ == 2) {ImGui::SetNextItemWidth(-1);ui::SliderInside("##cutdepth", &cutDepth_, 0.01f, 1.0f, tr("Depth %.2f"));ui::HelpText("Depth", nullptr, tr("How deep Cut In goes, or how far Cut Add stands out, as a share of the Part's size."),diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cppindex e7d46e95..22c8fbc5 100644--- a/src/app/PanelPerformance.cpp+++ b/src/app/PanelPerformance.cpp@@ -158,6 +158,12 @@ void App::drawPerformanceSection() {ui::HelpText("Antialiasing", nullptr,"Samples per pixel in the 3D view: more smooths edges, fewer is faster on huge meshes.", kPath);ui::Segmented(*this, {"perf.aa_1", "perf.aa_2", "perf.aa_4", "perf.aa_8"});+ ImGui::TextUnformatted(tr("View resolution"));+ ui::HelpText("View resolution", nullptr,+ "Draw the 3D view at a share of the window's resolution and scale it up: 75% draws about half the "+ "pixels, 50% a quarter. For slow or integrated GPUs and big screens; Save Render stays sharp (#80).",+ kPath);+ ui::Segmented(*this, {"perf.res_100", "perf.res_75", "perf.res_50"});bool fast = uiPrefs_.fastNavigation;if (ImGui::Checkbox(tr("Fast Navigation"), &fast)) actions_.find("perf.fast_navigation")->run();ui::HelpAction(*this, "perf.fast_navigation");diff --git a/src/app/PanelPolypaint.cpp b/src/app/PanelPolypaint.cppindex b0be4fb8..468c0aa8 100644--- a/src/app/PanelPolypaint.cpp+++ b/src/app/PanelPolypaint.cpp@@ -456,8 +456,9 @@ void App::drawPalette_Material() {ui::HelpText("Base colour", nullptr, "Colour of the Studio material (the clay colour).", "Material");drawShadingControls();drawViewportShadingControls();+ drawLightControls(); // PanelView.cppImGui::Spacing();- ui::ActionButton(*this, "render.save_image", ImVec2(-1, 0), ui::Look::IconLabel);+ drawSaveRenderControls();}// Material > Viewport Shading: Lit Sphere or PBR, and the PBR view's environment. Every change runsdiff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex 1f08d019..baf6ebe3 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -295,6 +295,14 @@ void App::storeProjectSettings() {render.set("backface_culling", renderSettings_.backfaceCulling);render.set("background", std::string(renderSettings_.gradientBackground ? "gradient" : "flat"));render.set("background_color", vec3Json(renderSettings_.backgroundColor));+ {+ Json light = Json::object(); // the Lit Sphere / studio light (#80)+ light.set("yaw", double(renderSettings_.lightYaw));+ light.set("pitch", double(renderSettings_.lightPitch));+ light.set("intensity", double(renderSettings_.lightIntensity));+ light.set("ambient", double(renderSettings_.lightAmbient));+ render.set("light", light);+ }render.set("matcap", renderSettings_.matcap < 0 ? std::string() : std::string(matcapName(renderSettings_.matcap)));// Viewport shading (Material > Viewport Shading): Lit Sphere or PBR with its environment.{@@ -416,6 +424,19 @@ void App::applyProjectSettings() {v.pbrMetallic = num("metallic", defaults.pbrMetallic, 0.0f, 1.0f);v.pbrCavity = num("cavity", defaults.pbrCavity, 0.0f, 1.0f);}+ // The light (#80); projects from before it: the material's own.+ {+ RenderSettings& v = renderSettings_;+ const RenderSettings defaults;+ const Json& light = r["light"];+ auto num = [&](const char* key, float def, float lo, float hi) {+ return light.isObject() && light[key].isNumber() ? std::clamp(float(light[key].asNumber()), lo, hi) : def;+ };+ v.lightYaw = num("yaw", defaults.lightYaw, -180.0f, 180.0f);+ v.lightPitch = num("pitch", defaults.lightPitch, -90.0f, 90.0f);+ v.lightIntensity = num("intensity", defaults.lightIntensity, 0.0f, 3.0f);+ v.lightAmbient = num("ambient", defaults.lightAmbient, 0.0f, 1.0f);+ }// The background (#21); projects from before it: the preferred one.renderSettings_.gradientBackground =r["background"].isString() ? r["background"].asString() != "flat" : uiPrefs_.gradientBackground;diff --git a/src/app/PanelSubTools.cpp b/src/app/PanelSubTools.cppindex b52559da..97a339b8 100644--- a/src/app/PanelSubTools.cpp+++ b/src/app/PanelSubTools.cpp@@ -435,7 +435,6 @@ void App::drawSubToolsContents() {confirm("Delete Part?", "Delete \"" + activeName + "\"? This can't be undone.", "Delete", "subtool_delete");ImGui::EndDisabled();- const float half2 = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) * 0.5f;const float arrowW = ImGui::GetFrameHeight();ImGui::BeginDisabled(active <= 0);if (ImGui::ArrowButton("##up", ImGuiDir_Up)) runCommand("subtool_move", {{"direction", std::string("up")}});@@ -449,17 +448,27 @@ void App::drawSubToolsContents() {if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_DelayNormal))ImGui::SetTooltip("%s", tr("Move down the list"));ImGui::SameLine();+ // Solo and X-Ray side by side (#80), then Unhide all.+ const float rest = ImGui::GetContentRegionAvail().x - 2.0f * (arrowW + style.ItemSpacing.x) - 2.0f * style.ItemSpacing.x;+ const float soloW = std::floor(rest * 0.3f), xrayW = std::floor(rest * 0.32f);const bool solo = count > 1 && visibleCount == 1 && doc_.activeSubtoolInfo().visible;ImGui::BeginDisabled(count < 2);if (solo) ImGui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);- if (ImGui::Button(tr("Solo"), ImVec2(half2 - 2.0f * (arrowW + style.ItemSpacing.x), 0))) runCommand("subtool_solo");+ if (ImGui::Button(tr("Solo"), ImVec2(soloW, 0))) runCommand("subtool_solo");if (solo) ImGui::PopStyleColor();ImGui::EndDisabled();if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))ImGui::SetTooltip(solo ? "Show the other Parts again" : "Show only the active Part");ImGui::SameLine();+ const bool xray = renderSettings_.xray;+ if (xray) ImGui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);+ if (ImGui::Button(tr("X-Ray"), ImVec2(xrayW, 0))) runCommand("xray");+ if (xray) ImGui::PopStyleColor();+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))+ ImGui::SetTooltip("%s", xray ? tr("Draw the other Parts solid again") : tr("See through the other Parts to the active one"));+ ImGui::SameLine();ImGui::BeginDisabled(visibleCount == count);- if (ImGui::Button(tr("Unhide all"), ImVec2(half2, 0))) runCommand("subtool_show_all");+ if (ImGui::Button(tr("Unhide all"), ImVec2(-1, 0))) runCommand("subtool_show_all");ImGui::EndDisabled();const float half = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) * 0.5f;diff --git a/src/app/PanelTimeline.cpp b/src/app/PanelTimeline.cppindex 92b709ce..451d296a 100644--- a/src/app/PanelTimeline.cpp+++ b/src/app/PanelTimeline.cpp@@ -376,9 +376,16 @@ void App::drawTimelineUi() {// The strip: along the bottom of the canvas, or its top (Preferences > Interface > Timeline position, #63:// away from the brush shelf). At the top it sits below the top shelf (the canvas starts there) and what else// the canvas shows at its top (the axis gizmo, the update banner) moves down below it (timelineTopInset_).- const CanvasRect c = canvasRect();+ CanvasRect c = canvasRect();const float sc = uiScale_;const bool top = uiPrefs_.timelineTop;+ // The open Library takes the canvas's top (or bottom) edge: the strip moves off it, so it never covers the+ // Library's tabs and close button (#80, a 720p screen at 150%).+ if (lightbox_.open()) {+ const float lib = std::min(LightBox::height(layout_.lightboxRows, sc), c.h);+ if (!layout_.lightboxBottom) c.y += lib;+ c.h -= lib;+ }timelineTopInset_ = 0.0f;timelineStripY_ = -1.0f;if (c.w < 200 || c.h < 150 || hideUi_) return;@@ -398,7 +405,7 @@ void App::drawTimelineUi() {}ui::HelpText("Sculpt Timeline", nullptr, "Open the history strip.", "Edit");timelineStripY_ = ImGui::GetWindowPos().y;- if (top) timelineTopInset_ = ImGui::GetWindowPos().y + ImGui::GetWindowSize().y - c.y;+ if (top) timelineTopInset_ = ImGui::GetWindowPos().y + ImGui::GetWindowSize().y - canvasRect().y;}ImGui::End();return;@@ -410,7 +417,7 @@ void App::drawTimelineUi() {const float stripY = top ? c.y + margin : c.y + c.h - margin - height;ImGui::SetNextWindowPos(ImVec2(c.x + margin, stripY), ImGuiCond_Always);timelineStripY_ = stripY;- if (top) timelineTopInset_ = margin + height;+ if (top) timelineTopInset_ = stripY + height - canvasRect().y;ImGui::SetNextWindowSize(ImVec2(c.w - 2 * margin, height), ImGuiCond_Always);ImGui::SetNextWindowBgAlpha(0.88f);ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8 * sc, 5 * sc));diff --git a/src/app/PanelView.cpp b/src/app/PanelView.cppnew file mode 100644index 00000000..816cd658--- /dev/null+++ b/src/app/PanelView.cpp@@ -0,0 +1,261 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// View controls (#80, #91): X-Ray (the other Parts see-through, next to Solo), the 3D view's resolution scale+// (Preferences > Performance, Render), the light (Material > Light: a direction pad, intensity and ambient) and+// Save Render's size, shape and format. Each change runs a command (light, xray, view_resolution, save_render),+// so scripts and the console see the same thing.+#include "app/App.h"+#include "app/I18n.h"+#include "app/Ui.h"++#include <IconsLucide.h>++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <iterator>++namespace sf {++namespace {++constexpr const char* kLightPath = "Material > Light";++struct RenderAspect {+ const char* id; // the save_render argument and the action's suffix+ const char* label;+ float ratio; // width / height; 0 = the view's own+};+constexpr RenderAspect kAspects[] = {+ {"view", "View", 0.0f}, {"1:1", "1:1", 1.0f}, {"16:9", "16:9", 16.0f / 9.0f}, {"9:16", "9:16", 9.0f / 16.0f}, {"4:3", "4:3", 4.0f / 3.0f}};+constexpr int kAspectCount = int(sizeof kAspects / sizeof kAspects[0]);+// The longer side in pixels; 0 = twice the view's size (at most 4096), as Save Render always did.+constexpr int kRenderSizes[] = {0, 1080, 1920, 2048, 4096};++std::string aspectActionId(int i) {+ std::string id = kAspects[i].id;+ std::replace(id.begin(), id.end(), ':', 'x');+ return "render.aspect_" + id;+}++} // namespace++void App::registerViewUiCommands() {+ using T = ParamSpec::Type;+ commands_.add({"light",+ "The light of the Lit Sphere and studio shading (#80): turn it from where the material has it, set its "+ "intensity, and lift the shadows with ambient light. Only changes what the view (and Save Render) "+ "shows; saved in the project. (The PBR view has its own environment rotation and exposure.)",+ {{"yaw", T::Number, "Degrees about the view's up axis, + to the right (-180 to 180; default 0).", false},+ {"pitch", T::Number, "Degrees up (+) or down (-) (-90 to 90; default 0).", false},+ {"intensity", T::Number, "Brightness, 0 to 3 (default 1).", false},+ {"ambient", T::Number, "Ambient light that lifts the shadows, 0 to 1 (default 0).", false},+ {"reset", T::Bool, "Back to the material's own light first.", false}},+ [this](Document&, const Args& a) -> CommandResult {+ RenderSettings& v = renderSettings_;+ if (argBool(a, "reset", false)) {+ const RenderSettings defaults;+ v.lightYaw = defaults.lightYaw;+ v.lightPitch = defaults.lightPitch;+ v.lightIntensity = defaults.lightIntensity;+ v.lightAmbient = defaults.lightAmbient;+ }+ double yaw = std::fmod(argNumber(a, "yaw", v.lightYaw), 360.0);+ if (yaw > 180.0) yaw -= 360.0;+ if (yaw < -180.0) yaw += 360.0;+ v.lightYaw = float(yaw);+ v.lightPitch = std::clamp(float(argNumber(a, "pitch", v.lightPitch)), -90.0f, 90.0f);+ v.lightIntensity = std::clamp(float(argNumber(a, "intensity", v.lightIntensity)), 0.0f, 3.0f);+ v.lightAmbient = std::clamp(float(argNumber(a, "ambient", v.lightAmbient)), 0.0f, 1.0f);+ char buf[160];+ std::snprintf(buf, sizeof buf, "Light: %.0f deg right, %.0f deg up, intensity %.2f, ambient %.2f",+ double(v.lightYaw), double(v.lightPitch), double(v.lightIntensity), double(v.lightAmbient));+ return {true, buf};+ }});+ commands_.add({"xray",+ "X-Ray (#80, #91): draw the other visible Parts see-through so the active Part shows through them "+ "(with only the active Part shown, it is see-through itself). Only changes the view.",+ {{"on", T::Bool, "On or off (default: toggle).", false},+ {"opacity", T::Number, "How solid the see-through Parts look, 0.05 to 1 (default 0.3).", false}},+ [this](Document&, const Args& a) -> CommandResult {+ RenderSettings& v = renderSettings_;+ v.xray = argBool(a, "on", a.contains("opacity") ? v.xray : !v.xray);+ v.xrayOpacity = std::clamp(float(argNumber(a, "opacity", v.xrayOpacity)), 0.05f, 1.0f);+ return {true, v.xray ? "X-Ray on" : "X-Ray off"};+ }});+ commands_.add({"view_resolution",+ "The 3D view's resolution as a share of the window's (#80): 100 (full), 75 or 50. Lower draws a "+ "quarter to half the pixels and scales the picture up: faster on slow or integrated GPUs. Saved "+ "with the preferences. Save Render always renders at full resolution.",+ {{"percent", T::Number, "100, 75 or 50.", true}},+ [this](Document&, const Args& a) -> CommandResult {+ const int p = int(std::lround(argNumber(a, "percent", 100.0)));+ if (p != 100 && p != 75 && p != 50) return {false, "View resolution is 100, 75 or 50 (percent)"};+ uiPrefs_.viewResolution = p;+ return {true, "View resolution " + std::to_string(p) + "%"};+ }});+ commands_.add({"save_render",+ "Save Render: render the view without the interface to an image in your library (Library > Image), "+ "or to `path`. Choose the size and the shape: the shape's picture shows at least what the view shows.",+ {{"size", T::Number, "The longer side in pixels, 256 to 8192 (default: twice the view, at most 4096).", false},+ {"aspect", T::String, "view (default), 1:1, 16:9, 9:16 or 4:3, or a width / height ratio such as 2.35.", false},+ {"format", T::String, "png (default) or jpg.", false},+ {"path", T::String, "Where to write it (default: a new file in <library>/Images).", false}},+ [this](Document&, const Args& a) -> CommandResult {+ RenderRequest r;+ r.size = int(std::lround(argNumber(a, "size", 0.0)));+ if (r.size != 0 && (r.size < 256 || r.size > 8192)) return {false, "Save Render: size is 256 to 8192 pixels"};+ const std::string aspect = argString(a, "aspect", "view");+ bool known = false;+ for (const RenderAspect& k : kAspects)+ if (aspect == k.id) {+ r.aspect = k.ratio;+ known = true;+ }+ if (!known) {+ char* end = nullptr;+ const double ratio = std::strtod(aspect.c_str(), &end);+ if (end == aspect.c_str() || *end || !(ratio >= 0.1 && ratio <= 10.0))+ return {false, "Save Render: aspect is view, 1:1, 16:9, 9:16, 4:3 or a ratio (0.1 to 10)"};+ r.aspect = float(ratio);+ }+ const std::string format = argString(a, "format", "png");+ if (format != "png" && format != "jpg" && format != "jpeg") return {false, "Save Render: format is png or jpg"};+ r.jpg = format != "png";+ r.path = argString(a, "path");+ std::string message;+ const bool ok = saveRender(r, message);+ return {ok, message};+ }});++ auto add = [this](std::string id, std::string label, const char* icon, std::string description, std::string palette,+ std::function<void()> run, std::function<bool()> checked) {+ actions_.add({std::move(id), std::move(label), icon, std::move(description), std::move(palette), "", "",+ std::move(run), std::move(checked), nullptr});+ };+ add("view.xray", "X-Ray", ICON_LC_SCAN, "See through the other Parts to the active one (again: solid). With only the "+ "active Part shown, it is see-through itself (#80, #91).", "Tool > Parts",+ [this] { runCommand("xray"); }, [this] { return renderSettings_.xray; });+ for (int p : {100, 75, 50})+ add("perf.res_" + std::to_string(p), std::to_string(p) + "%", nullptr,+ p == 100 ? "Draw the 3D view at the window's full resolution."+ : "Draw the 3D view at " + std::to_string(p) + "% of the window's resolution and scale it up: " ++ (p == 75 ? "about half the pixels" : "a quarter of the pixels") ++ ", faster on slow GPUs, a little softer. Save Render stays at full resolution.",+ "Preferences > Performance", [this, p] { runCommand("view_resolution", {{"percent", double(p)}}); },+ [this, p] { return uiPrefs_.viewResolution == p; });+ for (int i = 0; i < kAspectCount; ++i)+ add(aspectActionId(i), kAspects[i].label, nullptr,+ i == 0 ? std::string("Save Render keeps the view's own shape.")+ : std::string("Save Render makes a ") + kAspects[i].label + " picture.",+ "Material", [this, i] { renderAspect_ = i; }, [this, i] { return renderAspect_ == i; });+ add("render.format_png", "PNG", nullptr, "Save Render writes a PNG (lossless).", "Material", [this] { renderJpg_ = false; },+ [this] { return !renderJpg_; });+ add("render.format_jpg", "JPG", nullptr, "Save Render writes a JPG (smaller files, for sharing).", "Material",+ [this] { renderJpg_ = true; }, [this] { return renderJpg_; });+}++void App::runSaveRender() {+ Args a{{"aspect", std::string(kAspects[std::clamp(renderAspect_, 0, kAspectCount - 1)].id)},+ {"format", std::string(renderJpg_ ? "jpg" : "png")}};+ const int size = kRenderSizes[std::clamp(renderSize_, 0, int(std::size(kRenderSizes)) - 1)];+ if (size) a["size"] = double(size);+ runCommand("save_render", a);+}++// Material: Save Render with its size, shape and format.+void App::drawSaveRenderControls() {+ ui::ActionButton(*this, "render.save_image", ImVec2(-1, 0), ui::Look::IconLabel);+ const int count = int(std::size(kRenderSizes));+ renderSize_ = std::clamp(renderSize_, 0, count - 1);+ auto sizeLabel = [](int s) { return s == 0 ? std::string("View x2") : std::to_string(s) + " px"; };+ ImGui::SetNextItemWidth(-1);+ if (ImGui::BeginCombo("##rendersize", (std::string(tr("Size")) + ": " + sizeLabel(kRenderSizes[renderSize_])).c_str())) {+ for (int i = 0; i < count; ++i)+ if (ImGui::Selectable(sizeLabel(kRenderSizes[i]).c_str(), i == renderSize_)) renderSize_ = i;+ ImGui::EndCombo();+ }+ ui::HelpText("Size", nullptr,+ "Save Render's longer side: twice the view (at most 4096 pixels), or 1080, 1920, 2048 or 4096 pixels.",+ "Material");+ ui::Segmented(*this, {"render.aspect_view", "render.aspect_1x1", "render.aspect_16x9"});+ ui::Segmented(*this, {"render.aspect_9x16", "render.aspect_4x3", "render.format_png", "render.format_jpg"});+}++// Material > Light: a pad to drag the light around the model, its intensity and ambient light.+void App::drawLightControls() {+ RenderSettings& v = renderSettings_;+ ImGui::Spacing();+ ImGui::TextDisabled("%s", tr("Light"));+ ImGui::BeginDisabled(v.pbr());+ const float s = uiScale_;+ const float side = std::floor(std::min(ImGui::GetFrameHeightWithSpacing() * 3.0f - ImGui::GetStyle().ItemSpacing.y,+ ImGui::GetContentRegionAvail().x * 0.4f));+ const ImVec2 p0 = ImGui::GetCursorScreenPos();+ ImGui::InvisibleButton("##lightpad", ImVec2(side, side));+ const bool held = ImGui::IsItemActive() && !v.pbr();+ const ImVec2 c(p0.x + side * 0.5f, p0.y + side * 0.5f);+ const float r = side * 0.5f - 2.0f * s;+ if (held) {+ const ImVec2 m = ImGui::GetIO().MousePos;+ float x = (m.x - c.x) / r, y = (c.y - m.y) / r;+ const float len = std::sqrt(x * x + y * y);+ if (len > 1.0f) {+ x /= len;+ y /= len;+ }+ const float z = std::sqrt(std::max(0.0f, 1.0f - x * x - y * y));+ v.lightYaw = glm::degrees(std::atan2(x, z));+ v.lightPitch = glm::degrees(std::asin(std::clamp(y, -1.0f, 1.0f)));+ }+ if (ImGui::IsItemDeactivated() && !v.pbr())+ runCommand("light", {{"yaw", double(v.lightYaw)}, {"pitch", double(v.lightPitch)}});+ if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))+ runCommand("light", {{"yaw", 0.0}, {"pitch", 0.0}});+ ui::HelpText("Light direction", nullptr,+ "Drag on the ball to move the light around the model (the dot is the light); double-click puts it "+ "back where the material has it. Lit Sphere and studio shading.",+ kLightPath);+ // The pad: a ball lit from the light's direction (a few soft discs towards the light), and the light's dot.+ {+ const glm::mat3 rot = lightRotation(v.lightYaw, v.lightPitch);+ const glm::vec3 dir = rot * glm::vec3(0.0f, 0.0f, 1.0f);+ const ImVec2 dot(c.x + dir.x * r, c.y - dir.y * r);+ ImDrawList* dl = ImGui::GetWindowDrawList();+ dl->AddCircleFilled(c, r, IM_COL32(38, 38, 42, 255), 48);+ constexpr int kSteps = 10;+ for (int i = 1; i <= kSteps; ++i) {+ const float t = float(i) / float(kSteps);+ const float lift = dir.z < 0.0f ? 0.4f : 1.0f; // a light behind the model leaves it mostly dark+ const ImVec2 ci(c.x + (dot.x - c.x) * t * 0.7f, c.y + (dot.y - c.y) * t * 0.7f);+ const int g = int(44.0f + (205.0f - 44.0f) * t * t * lift);+ dl->AddCircleFilled(ci, r * (1.0f - 0.9f * t), IM_COL32(g, g, g + 4, 255), 40);+ }+ dl->AddCircle(c, r, IM_COL32(90, 90, 96, 255), 48, 1.0f * s);+ const ImU32 sun = held || ImGui::IsItemHovered() ? ui::color::accentHover : ui::color::accent;+ dl->AddCircleFilled(dot, 4.0f * s, sun, 16);+ dl->AddCircle(dot, 4.0f * s, IM_COL32(20, 20, 20, 255), 16, 1.0f * s);+ }+ ImGui::SameLine();+ ImGui::BeginGroup();+ auto slider = [&](const char* id, const char* key, float* value, float lo, float hi, const char* fmt, const char* title,+ const char* help) {+ ImGui::SetNextItemWidth(-1);+ ui::SliderInside(id, value, lo, hi, fmt);+ if (ImGui::IsItemDeactivatedAfterEdit()) runCommand("light", {{key, double(*value)}});+ ui::HelpText(title, nullptr, help, kLightPath);+ };+ slider("##lightintensity", "intensity", &v.lightIntensity, 0.0f, 2.0f, tr("Intensity %.2f"), "Intensity",+ "How bright the light is: 1 is the material as made.");+ slider("##lightambient", "ambient", &v.lightAmbient, 0.0f, 1.0f, tr("Ambient %.2f"), "Ambient",+ "Even light from everywhere that lifts the shadows, so the dark side still reads.");+ if (ImGui::Button(tr("Reset##light"), ImVec2(-1, 0))) runCommand("light", {{"reset", true}});+ ui::HelpText("Reset", nullptr, "The material's own light again: direction, intensity and no ambient.", kLightPath);+ ImGui::EndGroup();+ ImGui::EndDisabled();+ if (v.pbr()) ImGui::TextDisabled("%s", tr("PBR: Viewport Shading's rotation and exposure"));+}++} // namespace sfdiff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex beae5ff9..4015bc55 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -442,11 +442,13 @@ void App::registerShellActions() {// Cut (PanelCut.cpp, core/Cut.h): the same Ctrl+Shift drag, cutting instead of hiding.shape("cut.line", "Cut Line", "Tool > Cut", &hideShape_, SelectShape::CutLine,"Ctrl+Shift+drag a line: the shaded side is cut (Alt: the other side). Away removes it through the whole "- "Part and closes the cut flat; In steps it down by Depth; Add raises it.");+ "Part and closes the cut flat; In steps it down by Depth; Add raises it; Clip presses it flat onto the line.");shape("cut.lasso", "Cut Lasso", "Tool > Cut", &hideShape_, SelectShape::CutLasso,- "Ctrl+Shift+drag a lasso: Away cuts a hole through the Part, In a pocket Depth deep, Add raises the shape.");+ "Ctrl+Shift+drag a lasso: Away cuts a hole through the Part, In a pocket Depth deep, Add raises the shape, "+ "Clip presses what lies outside it onto its outline.");shape("cut.rect", "Cut Rectangle", "Tool > Cut", &hideShape_, SelectShape::CutRect,- "Ctrl+Shift+drag a rectangle: Away cuts a hole through the Part, In a pocket Depth deep, Add a block.");+ "Ctrl+Shift+drag a rectangle: Away cuts a hole through the Part, In a pocket Depth deep, Add a block, Clip "+ "presses what lies outside it onto its edges.");shape("cut.polyline", "Cut Polyline", "Tool > Cut", &hideShape_, SelectShape::CutPolyline,"Ctrl+Shift+click points: click the first point to cut the polygon, double-click or Enter to cut along an ""open bent line (Alt: the other side), Esc to drop it.");@@ -457,6 +459,10 @@ void App::registerShellActions() {cutMode("cut.away", "Away", 0, "Remove what the shape covers, through the whole Part, and close the cut with a flat cap.");cutMode("cut.in", "In", 1, "Cut a flat-bottomed pocket Depth deep where the shape covers the Part.");cutMode("cut.add", "Add", 2, "Add the shape, extruded Depth out of the surface, joined to the Part.");+ cutMode("cut.clip", "Clip", 3,+ "Remove nothing: press the shaded side of a line, or everything outside a lasso or rectangle, flat onto "+ "the shape's outline, through the whole Part (#102). Hard-surface planes and clean silhouettes; the mask "+ "holds parts back.");flag("draw.pressure_strength", "Pressure > Strength", nullptr, "Draw > Tablet", "", &pressureStrength_,"Pen pressure scales the brush strength.");flag("draw.pressure_size", "Pressure > Size", nullptr, "Draw > Tablet", "", &pressureSize_,diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 586e1b6f..e87858e7 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -135,6 +135,9 @@// antialiasing (Preferences > Performance: 1, 2, 4, 8), view_samples (what the interactive// view draws with now: 1 while Fast Navigation moves a big scene), multithreading (1 on),// last_stroke_dabs (dabs of the last finished stroke)+// xray (1 on), view_resolution (percent), light_yaw / light_pitch (degrees),+// light_intensity, light_ambient, render_aspect (Save Render's shape: 0 view, 1 1:1, 2 16:9,+// 3 9:16, 4 4:3)// dynamic (1 while dynamic topology is on), dynamic_detail (its Detail, 0-100)// last_stroke_dabs (dabs of the last finished stroke), stroke_type (0 Dots, 1 DragRect,// 2 DragDot, 3 Spray, 4 LazyMouse), vdms (VDM brush maps), vdm_files (.sfvdm in the library)@@ -820,6 +823,13 @@ double Demo::query(const std::string& name, bool& known) const {if (name == "stroking") return app_.drag_ == App::Drag::Stroke ? 1.0 : 0.0;if (name == "tablet_mouse_mode") return app_.uiPrefs_.tablet.mouseMode ? 1.0 : 0.0;if (name == "backface_culling") return app_.renderSettings_.backfaceCulling ? 1.0 : 0.0;+ if (name == "xray") return app_.renderSettings_.xray ? 1.0 : 0.0;+ if (name == "view_resolution") return double(app_.uiPrefs_.viewResolution);+ if (name == "light_yaw") return double(app_.renderSettings_.lightYaw);+ if (name == "light_pitch") return double(app_.renderSettings_.lightPitch);+ if (name == "light_intensity") return double(app_.renderSettings_.lightIntensity);+ if (name == "light_ambient") return double(app_.renderSettings_.lightAmbient);+ if (name == "render_aspect") return double(app_.renderAspect_);if (name == "draw_ms") return app_.benchmarkDrawMs(30); // the 3D view drawn 30 times: ms per frameif (name == "drawn_triangles") { // the 3D view drawn once more now: the triangles it drewapp_.benchmarkDrawMs(0);diff --git a/src/core/CloseHoles.cpp b/src/core/CloseHoles.cppnew file mode 100644index 00000000..0d4df1c2--- /dev/null+++ b/src/core/CloseHoles.cpp@@ -0,0 +1,511 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Close Holes (see CloseHoles.h).+#include "core/CloseHoles.h"++#include "core/Commands.h"+#include "core/Document.h"+#include "core/PaintLayer.h"++#include <algorithm>+#include <array>+#include <cmath>+#include <numeric>+#include <unordered_map>+#include <unordered_set>++namespace sf {++namespace {++using dvec2 = glm::dvec2;+using dvec3 = glm::dvec3;++uint64_t directed(uint32_t a, uint32_t b) { return (uint64_t(a) << 32) | b; }+uint64_t undirected(uint32_t a, uint32_t b) { return a < b ? directed(a, b) : directed(b, a); }++constexpr size_t kBestEarLimit = 300; // loops up to this many edges pick the best ear each step (O(n^3))++// One hole's patch, in local indices: 0..n-1 are the loop's vertices (fixed), the rest are new. `ring[i]` holds+// the positions of loop vertex i's neighbours on the Part (fixed), for fairing the patch into the surface around.+struct Patch {+ std::vector<dvec3> p;+ std::vector<std::array<uint32_t, 3>> tris;+ size_t fixed = 0;+ std::vector<std::vector<dvec3>> ring;+};++// Ear clipping in the plane of the loop, wound like `normal`. False when some step finds no ear (the loop folds+// over itself in that plane).+bool earClip(Patch& patch, const dvec3& normal) {+ const size_t n = patch.fixed;+ dvec3 u = std::abs(normal.x) < 0.9 ? glm::cross(normal, dvec3(1, 0, 0)) : glm::cross(normal, dvec3(0, 1, 0));+ u = glm::normalize(u);+ const dvec3 w = glm::cross(normal, u);+ std::vector<dvec2> q(n);+ for (size_t i = 0; i < n; ++i) q[i] = dvec2(glm::dot(patch.p[i], u), glm::dot(patch.p[i], w));+ auto orient = [&](uint32_t a, uint32_t b, uint32_t c) {+ const dvec2 e = q[b] - q[a], f = q[c] - q[a];+ return e.x * f.y - e.y * f.x;+ };+ std::vector<uint32_t> poly(n);+ std::iota(poly.begin(), poly.end(), 0u);+ std::vector<std::array<uint32_t, 3>> out;+ const bool best = n <= kBestEarLimit;+ while (poly.size() > 3) {+ const size_t m = poly.size();+ double bestScore = -1.0;+ size_t bestAt = m;+ for (size_t i = 0; i < m; ++i) {+ const uint32_t a = poly[(i + m - 1) % m], b = poly[i], c = poly[(i + 1) % m];+ const double area = orient(a, b, c);+ if (area <= 1e-14 * (glm::dot(q[c] - q[a], q[c] - q[a]) + 1e-30)) continue; // reflex or flat+ bool empty = true;+ for (size_t j = 0; j < m && empty; ++j) {+ const uint32_t v = poly[j];+ if (v == a || v == b || v == c) continue;+ if (q[v] == q[a] || q[v] == q[b] || q[v] == q[c]) continue; // a pinch: the same point twice+ empty = !(orient(a, b, v) >= 0.0 && orient(b, c, v) >= 0.0 && orient(c, a, v) >= 0.0);+ }+ if (!empty) continue;+ // Score: the triangle's smallest angle (well-shaped ears first).+ const dvec3 A = patch.p[a], B = patch.p[b], C = patch.p[c];+ const double la = glm::length(B - C), lb = glm::length(C - A), lc = glm::length(A - B);+ const double area3 = glm::length(glm::cross(B - A, C - A));+ const double score = area3 / std::max({la * lb, lb * lc, lc * la, 1e-30});+ if (score > bestScore) {+ bestScore = score;+ bestAt = i;+ }+ if (!best) break;+ }+ if (bestAt == m) return false;+ out.push_back({poly[(bestAt + m - 1) % m], poly[bestAt], poly[(bestAt + 1) % m]});+ poly.erase(poly.begin() + std::ptrdiff_t(bestAt));+ }+ out.push_back({poly[0], poly[1], poly[2]});+ patch.tris = std::move(out);+ return true;+}++// A fan around the loop's centre (a new vertex).+void fan(Patch& patch) {+ const size_t n = patch.fixed;+ dvec3 c(0.0);+ for (size_t i = 0; i < n; ++i) c += patch.p[i];+ patch.p.push_back(c / double(n));+ const uint32_t centre = uint32_t(patch.p.size() - 1);+ patch.tris.clear();+ for (uint32_t i = 0; i < n; ++i) patch.tris.push_back({i, uint32_t((i + 1) % n), centre});+}++using EdgeMap = std::unordered_map<uint64_t, std::array<int64_t, 2>>; // edge -> the (up to) two triangles on it++EdgeMap edgeMap(const Patch& patch) {+ EdgeMap e;+ e.reserve(patch.tris.size() * 2);+ for (size_t t = 0; t < patch.tris.size(); ++t)+ for (int k = 0; k < 3; ++k) {+ auto [it, fresh] = e.try_emplace(undirected(patch.tris[t][k], patch.tris[t][(k + 1) % 3]), std::array<int64_t, 2>{-1, -1});+ (it->second[0] < 0 ? it->second[0] : it->second[1]) = int64_t(t);+ }+ return e;+}++int cornerOf(const std::array<uint32_t, 3>& t, uint32_t v) { return t[0] == v ? 0 : t[1] == v ? 1 : t[2] == v ? 2 : -1; }++// Splits every inside edge longer than `limit` at its middle (one edge per triangle per pass). Returns the splits.+size_t splitPass(Patch& patch, double limit) {+ const EdgeMap edges = edgeMap(patch);+ std::vector<std::pair<double, uint64_t>> longEdges;+ for (const auto& [key, tris] : edges) {+ if (tris[1] < 0) continue; // the loop: never split (it is shared with the Part)+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key);+ const double len = glm::length(patch.p[a] - patch.p[b]);+ if (len > limit) longEdges.push_back({len, key});+ }+ std::sort(longEdges.begin(), longEdges.end(), std::greater<>());+ std::vector<uint8_t> touched(patch.tris.size(), 0);+ size_t splits = 0;+ for (const auto& [len, key] : longEdges) {+ const auto& tris = edges.at(key);+ if (touched[size_t(tris[0])] || touched[size_t(tris[1])]) continue;+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key);+ patch.p.push_back((patch.p[a] + patch.p[b]) * 0.5);+ const uint32_t m = uint32_t(patch.p.size() - 1);+ for (int64_t ti : tris) {+ std::array<uint32_t, 3> t = patch.tris[size_t(ti)];+ // Rotate so the split edge is t[0] -> t[1].+ int k = 0;+ while (!((t[k] == a && t[(k + 1) % 3] == b) || (t[k] == b && t[(k + 1) % 3] == a))) ++k;+ const uint32_t x = t[k], y = t[(k + 1) % 3], z = t[(k + 2) % 3];+ patch.tris[size_t(ti)] = {x, m, z};+ patch.tris.push_back({m, y, z});+ touched[size_t(ti)] = 1;+ touched.push_back(1);+ }+ ++splits;+ }+ return splits;+}++// Flips inside edges whose two opposite angles add up to more than pi (towards a Delaunay triangulation), unless+// the flip would fold the patch or duplicate an edge.+void flipPass(Patch& patch) {+ EdgeMap edges = edgeMap(patch);+ std::vector<uint64_t> keys;+ keys.reserve(edges.size());+ for (const auto& [key, tris] : edges)+ if (tris[1] >= 0) keys.push_back(key);+ std::sort(keys.begin(), keys.end());+ auto angle = [&](uint32_t at, uint32_t x, uint32_t y) {+ const dvec3 e = glm::normalize(patch.p[x] - patch.p[at]), f = glm::normalize(patch.p[y] - patch.p[at]);+ return std::acos(std::clamp(glm::dot(e, f), -1.0, 1.0));+ };+ for (uint64_t key : keys) {+ auto it = edges.find(key);+ if (it == edges.end() || it->second[1] < 0) continue;+ const uint32_t a0 = uint32_t(key >> 32), b0 = uint32_t(key);+ const size_t t1 = size_t(it->second[0]), t2 = size_t(it->second[1]);+ std::array<uint32_t, 3> T1 = patch.tris[t1], T2 = patch.tris[t2];+ // Name them so T1 = (a, b, c) and T2 = (b, a, d).+ int k = cornerOf(T1, a0);+ uint32_t a = a0, b = b0;+ if (T1[(k + 1) % 3] != b0) std::swap(a, b);+ k = cornerOf(T1, a);+ if (T1[(k + 1) % 3] != b) continue; // inconsistent winding: leave it+ const uint32_t c = T1[(k + 2) % 3];+ const int k2 = cornerOf(T2, b);+ if (k2 < 0 || T2[(k2 + 1) % 3] != a) continue;+ const uint32_t d = T2[(k2 + 2) % 3];+ if (c == d || edges.count(undirected(c, d))) continue;+ if (angle(c, a, b) + angle(d, b, a) <= 3.14159265358979 + 1e-9) continue;+ const dvec3 nOld = glm::cross(patch.p[b] - patch.p[a], patch.p[c] - patch.p[a]) ++ glm::cross(patch.p[a] - patch.p[b], patch.p[d] - patch.p[b]);+ const dvec3 n1 = glm::cross(patch.p[d] - patch.p[a], patch.p[c] - patch.p[a]);+ const dvec3 n2 = glm::cross(patch.p[b] - patch.p[d], patch.p[c] - patch.p[d]);+ if (glm::dot(n1, nOld) <= 0.0 || glm::dot(n2, nOld) <= 0.0) continue;+ patch.tris[t1] = {a, d, c};+ patch.tris[t2] = {d, b, c};+ // Keep the map current for the edges this flip touched.+ edges.erase(key);+ edges[undirected(c, d)] = {int64_t(t1), int64_t(t2)};+ auto retarget = [&](uint32_t x, uint32_t y, size_t from, size_t to) {+ auto e = edges.find(undirected(x, y));+ if (e == edges.end()) return;+ for (int64_t& t : e->second)+ if (t == int64_t(from)) t = int64_t(to);+ };+ retarget(a, d, t2, t1); // (a, d) moved from T2 to T1+ retarget(b, c, t1, t2); // (b, c) moved from T1 to T2+ }+}++// Fairs the new vertices so the patch continues the curvature around it: they minimise the squared umbrella+// Laplacian summed over the new vertices and the loop's (whose neighbours include the Part's ring around the+// hole, held fixed). A least-squares problem, solved by conjugate gradients on its normal equations per axis.+void fair(Patch& patch, int maxIterations) {+ const size_t nv = patch.p.size(), n = patch.fixed, m = nv - n;+ if (m == 0) return;+ std::vector<std::vector<uint32_t>> nbr(nv);+ for (const auto& t : patch.tris)+ for (int k = 0; k < 3; ++k) {+ nbr[t[k]].push_back(t[(k + 1) % 3]);+ nbr[t[(k + 1) % 3]].push_back(t[k]);+ }+ for (auto& r : nbr) {+ std::sort(r.begin(), r.end());+ r.erase(std::unique(r.begin(), r.end()), r.end());+ }+ // Row u of the Laplacian: deg * p_u - sum of neighbours. A loop vertex's neighbours: the Part's ring plus the+ // patch's new vertices and the diagonals the patch added between loop vertices (the loop's own edges are on+ // the Part's side already).+ struct Row {+ double deg = 0.0;+ std::vector<uint32_t> unknown; // neighbours among the new vertices (index - n)+ dvec3 known{0.0}; // deg * p_u (if fixed) less the fixed neighbours+ int self = -1; // the row's own unknown, or -1 for a loop vertex+ };+ std::vector<Row> rows(nv);+ for (size_t u = 0; u < nv; ++u) {+ Row& r = rows[u];+ if (u < n) {+ const std::vector<dvec3>& ring = patch.ring[u];+ r.deg = double(ring.size());+ r.known = dvec3(0.0);+ for (const dvec3& q : ring) r.known -= q;+ for (uint32_t w : nbr[u]) {+ if (w >= n) {+ r.unknown.push_back(uint32_t(w - n));+ r.deg += 1.0;+ } else {+ bool onPart = false; // the loop's edges (and any edge the Part has) are in the ring+ for (const dvec3& q : ring) onPart = onPart || q == patch.p[w];+ if (!onPart) {+ r.known -= patch.p[w];+ r.deg += 1.0;+ }+ }+ }+ r.known += r.deg * patch.p[u];+ } else {+ r.self = int(u - n);+ r.deg = double(nbr[u].size());+ for (uint32_t w : nbr[u]) {+ if (w >= n) r.unknown.push_back(uint32_t(w - n));+ else r.known -= patch.p[w];+ }+ }+ }+ // B x + known: the rows' Laplacians for the unknowns x.+ auto applyB = [&](const std::vector<double>& x, std::vector<double>& out) {+ out.assign(nv, 0.0);+ for (size_t u = 0; u < nv; ++u) {+ const Row& r = rows[u];+ double v = r.self >= 0 ? r.deg * x[size_t(r.self)] : 0.0;+ for (uint32_t w : r.unknown) v -= x[w];+ out[u] = v;+ }+ };+ auto applyBt = [&](const std::vector<double>& y, std::vector<double>& out) {+ out.assign(m, 0.0);+ for (size_t u = 0; u < nv; ++u) {+ const Row& r = rows[u];+ if (r.self >= 0) out[size_t(r.self)] += r.deg * y[u];+ for (uint32_t w : r.unknown) out[w] -= y[u];+ }+ };+ for (int axis = 0; axis < 3; ++axis) {+ std::vector<double> x(m), c(nv), tmp, b, r, d, q, Bd;+ for (size_t i = 0; i < m; ++i) x[i] = patch.p[n + i][axis];+ for (size_t u = 0; u < nv; ++u) c[u] = -rows[u].known[axis];+ applyBt(c, b); // normal equations: Bt B x = Bt c+ applyB(x, tmp);+ applyBt(tmp, r);+ for (size_t i = 0; i < m; ++i) r[i] = b[i] - r[i];+ d = r;+ double rr = 0.0, bb = 0.0;+ for (size_t i = 0; i < m; ++i) rr += r[i] * r[i], bb += b[i] * b[i];+ const double tol = 1e-24 * std::max(bb, 1e-30);+ for (int it = 0; it < maxIterations && rr > tol; ++it) {+ applyB(d, Bd);+ double dAd = 0.0;+ for (double v : Bd) dAd += v * v;+ if (dAd <= 0.0) break;+ const double alpha = rr / dAd;+ applyBt(Bd, q);+ double rrNew = 0.0;+ for (size_t i = 0; i < m; ++i) {+ x[i] += alpha * d[i];+ r[i] -= alpha * q[i];+ rrNew += r[i] * r[i];+ }+ const double beta = rrNew / rr;+ rr = rrNew;+ for (size_t i = 0; i < m; ++i) d[i] = r[i] + beta * d[i];+ }+ for (size_t i = 0; i < m; ++i) patch.p[n + i][axis] = x[i];+ }+}++// Triangulates one loop (wound for the patch) and refines it to `target` edge length.+void buildPatch(Patch& patch, bool refine) {+ const size_t n = patch.fixed;+ if (n == 3) {+ patch.tris = {{0, 1, 2}};+ return;+ }+ dvec3 normal(0.0); // Newell's normal of the loop+ for (size_t i = 0; i < n; ++i) normal += glm::cross(patch.p[i], patch.p[(i + 1) % n]);+ const bool planar = glm::length(normal) > 1e-20;+ if (!planar || !earClip(patch, glm::normalize(normal))) fan(patch);+ if (!refine) return;+ double target = 0.0;+ for (size_t i = 0; i < n; ++i) target += glm::length(patch.p[i] - patch.p[(i + 1) % n]);+ target /= double(n);+ if (target <= 0.0) return;+ for (int pass = 0; pass < 14; ++pass) {+ const size_t splits = splitPass(patch, target * 1.33);+ flipPass(patch);+ fair(patch, 60); // coarse to fine: each level starts from the last one's surface, so the last fairing is short+ if (splits == 0 || patch.tris.size() > 4'000'000) break;+ }+ flipPass(patch);+ fair(patch, 400); // into the curvature around the hole+ flipPass(patch);+}++} // namespace++std::vector<std::vector<uint32_t>> boundaryLoops(const Mesh& mesh) {+ std::unordered_map<uint64_t, uint32_t> count;+ count.reserve(mesh.triangleCount() * 3);+ for (const glm::uvec3& t : mesh.triangles)+ for (int k = 0; k < 3; ++k) count[directed(t[k], t[(k + 1) % 3])] += 1;+ std::unordered_map<uint32_t, std::vector<uint32_t>> out; // a -> b for every open edge a -> b+ for (const auto& [key, c] : count) {+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key);+ if (c == 1 && a != b && !count.count(directed(b, a))) out[a].push_back(b);+ }+ for (auto& [a, list] : out) std::sort(list.begin(), list.end()); // (the same loops on every run)+ std::vector<uint32_t> starts;+ for (const auto& [a, list] : out) starts.push_back(a);+ std::sort(starts.begin(), starts.end());+ std::vector<std::vector<uint32_t>> loops;+ for (uint32_t start : starts) {+ while (!out[start].empty()) {+ std::vector<uint32_t> loop{start};+ uint32_t cur = out[start].front();+ out[start].erase(out[start].begin());+ bool closed = false;+ while (true) {+ if (cur == start) {+ closed = true;+ break;+ }+ loop.push_back(cur);+ auto it = out.find(cur);+ if (it == out.end() || it->second.empty()) break; // an open chain (non-manifold edges cut it)+ const uint32_t next = it->second.front();+ it->second.erase(it->second.begin());+ cur = next;+ }+ if (closed && loop.size() >= 3) loops.push_back(std::move(loop));+ }+ }+ return loops;+}++bool closeHoles(Mesh& mesh, const CloseHolesOptions& options, CloseHolesStats& stats, std::string& error) {+ stats = {};+ if (mesh.triangleCount() == 0) {+ error = "Close Holes: the Part is empty";+ return false;+ }+ const std::vector<std::vector<uint32_t>> loops = boundaryLoops(mesh);+ stats.holes = loops.size();+ if (loops.empty()) return true;+ const size_t nv0 = mesh.vertexCount(), nt0 = mesh.triangleCount();+ std::vector<glm::vec3> newPositions;+ std::vector<glm::uvec3> newTris;+ std::vector<uint32_t> newSource; // per new vertex: a loop vertex whose attributes it takes+ std::vector<glm::vec3> loopColor; // per new vertex: its loop's mean colour+ // The Part's neighbours of every loop vertex (fairing reads the ring around each hole).+ std::unordered_map<uint32_t, std::vector<uint32_t>> partRing;+ if (options.refine) {+ for (const std::vector<uint32_t>& loop : loops)+ for (uint32_t v : loop) partRing[v];+ for (const glm::uvec3& t : mesh.triangles)+ for (int k = 0; k < 3; ++k)+ if (auto it = partRing.find(t[k]); it != partRing.end()) {+ it->second.push_back(t[(k + 1) % 3]);+ it->second.push_back(t[(k + 2) % 3]);+ }+ for (auto& [v, r] : partRing) {+ std::sort(r.begin(), r.end());+ r.erase(std::unique(r.begin(), r.end()), r.end());+ }+ }+ for (const std::vector<uint32_t>& loop : loops) {+ if (options.maxEdges && loop.size() > options.maxEdges) {+ ++stats.skipped;+ continue;+ }+ // The patch runs the other way round: its triangles hold the open edges b -> a.+ Patch patch;+ patch.fixed = loop.size();+ std::vector<uint32_t> global(loop.rbegin(), loop.rend());+ for (uint32_t v : global) patch.p.push_back(dvec3(mesh.positions[v]));+ if (options.refine)+ for (uint32_t v : global) {+ patch.ring.emplace_back();+ for (uint32_t w : partRing[v]) patch.ring.back().push_back(dvec3(mesh.positions[w]));+ }+ buildPatch(patch, options.refine);+ glm::vec3 color(1.0f);+ if (mesh.hasColors()) {+ glm::dvec3 s(0.0);+ for (uint32_t v : global) s += glm::dvec3(mesh.colors[v]);+ color = glm::vec3(s / double(global.size()));+ }+ for (size_t i = patch.fixed; i < patch.p.size(); ++i) {+ global.push_back(uint32_t(nv0 + newPositions.size()));+ newPositions.push_back(glm::vec3(patch.p[i]));+ newSource.push_back(global.front());+ loopColor.push_back(color);+ }+ for (const auto& t : patch.tris) newTris.push_back(glm::uvec3(global[t[0]], global[t[1]], global[t[2]]));+ ++stats.filled;+ }+ if (newTris.empty()) return true;+ stats.triangles = newTris.size();++ const size_t nv = nv0 + newPositions.size(), nt = nt0 + newTris.size();+ std::vector<uint32_t> kept(nv);+ std::iota(kept.begin(), kept.begin() + std::ptrdiff_t(nv0), 0u);+ std::copy(newSource.begin(), newSource.end(), kept.begin() + std::ptrdiff_t(nv0));+ const Mesh before = mesh.paintLayers.empty() ? Mesh() : mesh; // (copyPaintLayers reads the old layers)++ mesh.positions.insert(mesh.positions.end(), newPositions.begin(), newPositions.end());+ if (!mesh.layers.empty()) {+ mesh.base.insert(mesh.base.end(), newPositions.begin(), newPositions.end());+ for (SculptLayer& l : mesh.layers) l.delta.resize(nv, glm::vec3(0.0f));+ }+ if (mesh.hasMask()) mesh.mask.resize(nv, 0.0f);+ if (mesh.hasColors()) mesh.colors.insert(mesh.colors.end(), loopColor.begin(), loopColor.end());+ if (!before.paintLayers.empty()) copyPaintLayers(before, mesh, kept);+ mesh.triangles.insert(mesh.triangles.end(), newTris.begin(), newTris.end());+ if (options.newGroup || mesh.hasPolygroups()) {+ uint32_t group = 0;+ for (uint32_t g : mesh.polygroups) group = std::max(group, g);+ const bool had = mesh.hasPolygroups();+ mesh.polygroups.resize(nt0, 0u);+ mesh.polygroups.resize(nt, options.newGroup ? (had ? group + 1 : 1u) : 0u);+ }+ if (mesh.hasHidden()) mesh.hidden.resize(nt, 0);+ if (mesh.hasUvs()) mesh.uvs.resize(nt * 3, glm::vec2(0.0f));+ if (mesh.hasUvFlags()) mesh.uvFlags.resize(nt * 3, 0);+ if (mesh.hasQuads()) mesh.quadPartners.resize(nt, Mesh::kNoQuad);+ mesh.rebuildTopology();+ mesh.recomputeAllNormals();+ mesh.sanitizeAttributes();+ return true;+}++void registerCloseHolesCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ registry.add(+ {"close_holes",+ "Close Holes: cap every open boundary of the active Part (a hole, an open bottom, the edge of an extracted "+ "shell) with a new patch of triangles sized like the edges around it, curved to continue the surface around the hole. The "+ "rest of the Part is not changed. The patches get a new face group.",+ {{"max_edges", T::Number, "Only holes with at most this many boundary edges (default 0: every hole).", false},+ {"refine", T::Bool, "Split and curve the patches to the density and shape around them (default true; false: as few "+ "triangles as possible).", false},+ {"new_group", T::Bool, "Give the patches a new face group (default true).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (doc.mesh.triangleCount() == 0) return {false, "The Part is empty"};+ if (!doc.mesh.zspheres.empty()) return {false, "Close Holes: make Forge Spheres into a mesh first"};+ if (doc.mesh.micro) return {false, "Close Holes: apply or remove the micro level first"};+ CloseHolesOptions o;+ o.maxEdges = size_t(std::max(0.0, argNumber(a, "max_edges", 0.0)));+ o.refine = argBool(a, "refine", true);+ o.newGroup = argBool(a, "new_group", true);+ Mesh m = doc.mesh;+ CloseHolesStats s;+ std::string error;+ if (!closeHoles(m, o, s, error)) return {false, error};+ if (s.holes == 0) return {true, "Close Holes: the Part has no holes"};+ if (s.filled == 0)+ return {true, "Close Holes: " + std::to_string(s.holes) + " hole" + (s.holes == 1 ? "" : "s") ++ ", none small enough to close (max_edges)"};+ doc.replaceMeshUndoable(std::move(m), "Close Holes");+ std::string msg = "Close Holes: closed " + std::to_string(s.filled) + " hole" + (s.filled == 1 ? "" : "s") ++ " (+" + std::to_string(s.triangles) + " triangles)";+ if (s.skipped) msg += ", left " + std::to_string(s.skipped) + " bigger one" + (s.skipped == 1 ? "" : "s");+ return {true, msg};+ }});+}++} // namespace sfdiff --git a/src/core/CloseHoles.h b/src/core/CloseHoles.hnew file mode 100644index 00000000..ea1296e6--- /dev/null+++ b/src/core/CloseHoles.h@@ -0,0 +1,45 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Close Holes (#103): caps the open boundaries of a Part with new polygon patches, so an extracted shell, a cut+// scan or an imported open mesh becomes closed without remeshing. Each boundary loop is triangulated (the best+// ear first, in the loop's best-fit plane; a fan around its centre when the loop folds over itself in that+// plane), then the patch is refined towards the boundary's edge length (long edges split, edges flipped to+// better-shaped triangles) and its inside vertices faired so the patch continues the curvature around it (a+// sphere's hole closes round, not flat). The rest of the Part is not touched: its vertices, triangles and+// attributes keep their order and values. Patches get a face group of their own.+#pragma once++#include "core/Mesh.h"++#include <cstddef>+#include <string>++namespace sf {++class CommandRegistry;++struct CloseHolesOptions {+ size_t maxEdges = 0; // only holes with at most this many boundary edges (0 = every hole)+ bool refine = true; // split and fair the patch to the density and shape around it (off: the plain triangulation)+ bool newGroup = true; // the patches get a new face group+};++struct CloseHolesStats {+ size_t holes = 0; // boundary loops found+ size_t filled = 0; // loops capped+ size_t skipped = 0; // loops over maxEdges, or through a vertex shared by two loops in a way that can't be capped+ size_t triangles = 0; // triangles added+};++// The boundary loops of `mesh`: each a closed list of vertices v0 v1 ... with the mesh's edges vi -> vi+1 open+// (no triangle on their other side). Edges used by more than two triangles are left out.+std::vector<std::vector<uint32_t>> boundaryLoops(const Mesh& mesh);++// Caps the holes of `mesh` in place. Returns false with `error` when the mesh can't be changed (empty).+bool closeHoles(Mesh& mesh, const CloseHolesOptions& options, CloseHolesStats& stats, std::string& error);++// Registers "close_holes".+void registerCloseHolesCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex e776bde5..603f6f00 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -18,6 +18,7 @@#include "core/HardwareProfile.h"#include "core/ImageTo3D.h"#include "core/Masking.h"+#include "core/CloseHoles.h"#include "core/Cut.h"#include "core/Multires.h"#include "core/Micro.h"@@ -807,6 +808,7 @@ CommandRegistry::CommandRegistry() {registerMaskingCommands(*this);registerCutCommands(*this); // cut (core/Cut.h)+ registerCloseHolesCommands(*this); // close_holes (core/CloseHoles.h)registerPolygroupCommands(*this);registerSelectionSetCommands(*this); // selection_set_* (core/SelectionSets.h)registerSubToolCommands(*this);diff --git a/src/core/Cut.cpp b/src/core/Cut.cppindex e92ab05b..da41ff56 100644--- a/src/core/Cut.cpp+++ b/src/core/Cut.cpp@@ -50,6 +50,7 @@ const char* cutModeName(CutMode m) {case CutMode::Away: return "away";case CutMode::In: return "in";case CutMode::Add: return "add";+ case CutMode::Clip: return "clip";}return "away";}@@ -68,7 +69,7 @@ bool parseCutShape(const std::string& name, CutShape& out) {}bool parseCutMode(const std::string& name, CutMode& out) {- for (CutMode m : {CutMode::Away, CutMode::In, CutMode::Add})+ for (CutMode m : {CutMode::Away, CutMode::In, CutMode::Add, CutMode::Clip})if (name == cutModeName(m)) {out = m;return true;@@ -940,6 +941,57 @@ bool cutRegion(CutShape shape, const std::vector<glm::vec2>& points, bool flip,return true;}+size_t clipMesh(Mesh& mesh, const glm::mat4& viewProj, const std::vector<glm::dvec2>& region,+ const std::vector<glm::dvec2>& outline, bool open) {+ const glm::dmat4 vp(viewProj), inv = glm::inverse(vp);+ const size_t segments = open ? outline.size() - 1 : outline.size();+ if (outline.size() < 2 || region.size() < 3) return 0;+ auto inside = [&](dvec2 q) { // even-odd+ bool in = false;+ for (size_t i = 0, j = region.size() - 1; i < region.size(); j = i++) {+ const dvec2 a = region[i], b = region[j];+ if ((a.y > q.y) != (b.y > q.y) && q.x < (b.x - a.x) * (q.y - a.y) / (b.y - a.y) + a.x) in = !in;+ }+ return in;+ };+ auto nearest = [&](dvec2 q) {+ dvec2 best = outline[0];+ double bestD = 1e300;+ for (size_t i = 0; i < segments; ++i) {+ const dvec2 a = outline[i], b = outline[(i + 1) % outline.size()], ab = b - a;+ const double len2 = glm::dot(ab, ab);+ const double t = len2 > 0.0 ? std::clamp(glm::dot(q - a, ab) / len2, 0.0, 1.0) : 0.0;+ const dvec2 p = a + ab * t;+ const double d = glm::dot(q - p, q - p);+ if (d < bestD) {+ bestD = d;+ best = p;+ }+ }+ return best;+ };+ const bool layers = !mesh.layers.empty();+ std::vector<uint32_t> moved;+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {+ const float weight = 1.0f - mesh.maskAt(v);+ if (weight <= 0.0f || (mesh.hasHidden() && mesh.vertexHidden(v))) continue;+ const glm::dvec4 c = vp * glm::dvec4(dvec3(mesh.positions[v]), 1.0);+ if (c.w <= 1e-12) continue; // behind the camera+ const dvec3 ndc = dvec3(c) / c.w;+ if (inside(dvec2(ndc)) != open) continue;+ const dvec2 to = nearest(dvec2(ndc));+ glm::dvec4 w = inv * glm::dvec4(to, ndc.z, 1.0);+ const glm::vec3 target = glm::vec3(dvec3(w) / w.w);+ const glm::vec3 d = (target - mesh.positions[v]) * weight;+ if (glm::dot(d, d) <= 0.0f) continue;+ mesh.positions[v] += d;+ if (layers) mesh.base[v] += d;+ moved.push_back(v);+ }+ if (!moved.empty()) mesh.recomputeAllNormals();+ return moved.size();+}+bool cutMesh(const Mesh& mesh, const glm::mat4& viewProj, const std::vector<glm::dvec2>& region, CutMode mode,float depth, Mesh& out, std::string& error) {if (mesh.triangleCount() == 0) {@@ -1243,13 +1295,14 @@ void registerCutCommands(CommandRegistry& registry) {{"cut","Cut the active Part with a shape drawn on the screen (Line, Lasso, Rectangle or Polyline), extruded along ""the view. Modes: away (remove what the shape covers, through the whole Part, and close it with a flat cap), "- "in (cut a flat-bottomed pocket `depth` deep), add (add the shape extruded `depth` out of the surface). The "- "result stays watertight. Coordinates are normalised (-1..1, y up) in the given view; without a view the "+ "in (cut a flat-bottomed pocket `depth` deep), add (add the shape extruded `depth` out of the surface), clip "+ "(remove nothing: press what lies on the shaded side of a line, or outside a closed shape, flat onto the "+ "shape's outline, like a clip brush). The result stays watertight. Coordinates are normalised (-1..1, y up) in the given view; without a view the ""shape is drawn on the Part seen from the front (+Z).",{{"shape", T::String, "line, lasso, rect or polyline. Default lasso.", false},{"points", T::String, "The shape's points \"x0 y0 x1 y1 ...\": two for a line (or a rect's corners), three or ""more for a lasso, two or more for a polyline.", true},- {"mode", T::String, "away, in or add. Default away.", false},+ {"mode", T::String, "away, in, add or clip. Default away.", false},{"depth", T::Number, "In and add: how deep or tall, as a fraction of the Part's size (0.001-4). Default 0.1.", false},{"flip", T::Bool, "Line and open polyline: cut the right side instead of the left. Default false.", false},{"closed", T::Bool, "Polyline: a closed polygon (cuts its inside) instead of a bent line. Default false.", false},@@ -1262,7 +1315,7 @@ void registerCutCommands(CommandRegistry& registry) {CutShape shape = CutShape::Lasso;CutMode mode = CutMode::Away;if (!parseCutShape(argString(a, "shape", "lasso"), shape)) return {false, "Cut: shape is line, lasso, rect or polyline"};- if (!parseCutMode(argString(a, "mode", "away"), mode)) return {false, "Cut: mode is away, in or add"};+ if (!parseCutMode(argString(a, "mode", "away"), mode)) return {false, "Cut: mode is away, in, add or clip"};std::vector<glm::vec2> points;{const std::string text = argString(a, "points");@@ -1285,6 +1338,34 @@ void registerCutCommands(CommandRegistry& registry) {std::vector<glm::dvec2> region;if (!cutRegion(shape, points, argBool(a, "flip", false), argBool(a, "closed", false), region, error))return {false, error};+ if (mode == CutMode::Clip) {+ // The outline the vertices are pressed onto: a line or open polyline runs on far past its ends.+ const bool open = shape == CutShape::Line || (shape == CutShape::Polyline && !argBool(a, "closed", false));+ std::vector<glm::dvec2> outline;+ for (const glm::vec2& p : points)+ if (outline.empty() || glm::length(glm::dvec2(p) - outline.back()) > 1e-6) outline.push_back(glm::dvec2(p));+ if (shape == CutShape::Line && outline.size() > 2) outline = {outline.front(), outline.back()};+ if (shape == CutShape::Rect && outline.size() == 2) {+ const glm::dvec2 p = outline[0], q = outline[1];+ outline = {p, {q.x, p.y}, q, {p.x, q.y}};+ }+ if (open) {+ const glm::dvec2 d0 = glm::normalize(outline[1] - outline[0]);+ const glm::dvec2 d1 = glm::normalize(outline.back() - outline[outline.size() - 2]);+ outline.front() -= d0 * 1000.0;+ outline.back() += d1 * 1000.0;+ }+ Mesh m = doc.mesh;+ size_t moved = 0;+ for (const SymCopy& copy : copies) {+ glm::mat4 inv(glm::transpose(copy.m));+ inv[3] = glm::vec4(copy.pivot - glm::transpose(copy.m) * copy.pivot, 1.0f);+ moved += clipMesh(m, vp * inv, region, outline, open);+ }+ if (moved == 0) return {true, "Clip: the shape misses the Part"};+ doc.replaceMeshUndoable(std::move(m), "Clip");+ return {true, "Clip: " + std::to_string(moved) + " vertices pressed flat"};+ }const float depth = float(argNumber(a, "depth", 0.1));// A mirror image of the shape that lands on the shape itself (a rectangle across the mirror plane) would// cut the same prism twice: skip it.diff --git a/src/core/Cut.h b/src/core/Cut.hindex 1dab44a9..3cf36050 100644--- a/src/core/Cut.h+++ b/src/core/Cut.h@@ -6,7 +6,10 @@// Modes, each an exact boolean between the Part and the shape extruded along the view:// Away - removes everything the shape covers, through the whole Part, and closes the cut with a flat cap;// In - boolean difference with the shape pushed `depth` into the surface (a flat-bottomed pocket);-// Add - boolean union with the shape extruded `depth` out of the surface (anchored halfway into the Part).+// Add - boolean union with the shape extruded `depth` out of the surface (anchored halfway into the Part);+// Clip - nothing is removed (#102): the vertices on the shaded side of a Line or open Polyline, or outside a+// Lasso, Rectangle or closed Polyline, are pressed flat onto the shape's outline extruded along the view,+// keeping their depth (hard-surface planes, clean silhouettes). The mask holds vertices back.// The result is watertight when the Part is (open Parts are trimmed without a cap; Add needs a closed one).// The boolean runs in normalised device coordinates, where the extrusion is a straight prism: intersection// points are shared by the Part's triangles and the prism's faces, so no cracks; the Part's surface is kept@@ -26,9 +29,9 @@ namespace sf {class CommandRegistry;enum class CutShape : uint8_t { Line, Lasso, Rect, Polyline };-enum class CutMode : uint8_t { Away, In, Add };+enum class CutMode : uint8_t { Away, In, Add, Clip };const char* cutShapeName(CutShape s); // "line", "lasso", "rect", "polyline"-const char* cutModeName(CutMode m); // "away", "in", "add"+const char* cutModeName(CutMode m); // "away", "in", "add", "clip"bool parseCutShape(const std::string& name, CutShape& out);bool parseCutMode(const std::string& name, CutMode& out);@@ -45,6 +48,12 @@ bool cutRegion(CutShape shape, const std::vector<glm::vec2>& points, bool flip,bool cutMesh(const Mesh& mesh, const glm::mat4& viewProj, const std::vector<glm::dvec2>& region, CutMode mode,float depth, Mesh& out, std::string& error);+// Clip: moves the vertices of `mesh` that `region` (from cutRegion) covers (`open`: a Line or open Polyline) or+// leaves out (a closed shape) onto `outline` (NDC; open: a polyline, closed: a polygon), along the screen at their+// own depth in the view of `viewProj`. Masked vertices move less, hidden ones not at all. Returns how many moved.+size_t clipMesh(Mesh& mesh, const glm::mat4& viewProj, const std::vector<glm::dvec2>& region,+ const std::vector<glm::dvec2>& outline, bool open);+// Every edge of `mesh` is shared by exactly two triangles, wound opposite ways (a closed, manifold surface).bool isWatertight(const Mesh& mesh);diff --git a/src/core/Image.cpp b/src/core/Image.cppindex 1b57bdab..fe395e8d 100644--- a/src/core/Image.cpp+++ b/src/core/Image.cpp@@ -82,6 +82,31 @@ bool Image::savePng(const std::string& path, std::string& error) const {return true;}+bool Image::saveJpg(const std::string& path, int quality, std::string& error) const {+ if (empty()) {+ error = "Empty image";+ return false;+ }+ std::vector<uint8_t> rgb(size_t(width) * size_t(height) * 3);+ for (size_t i = 0, n = size_t(width) * size_t(height); i < n; ++i)+ for (int c = 0; c < 3; ++c) rgb[i * 3 + size_t(c)] = uint8_t(unsigned(rgba[i * 4 + size_t(c)]) * rgba[i * 4 + 3] / 255u);+ std::vector<uint8_t> jpg;+ auto write = [](void* ctx, void* data, int size) {+ auto* o = static_cast<std::vector<uint8_t>*>(ctx);+ o->insert(o->end(), static_cast<uint8_t*>(data), static_cast<uint8_t*>(data) + size);+ };+ if (!stbi_write_jpg_to_func(write, &jpg, width, height, 3, rgb.data(), std::clamp(quality, 1, 100))) {+ error = "JPEG encoding failed";+ return false;+ }+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);+ if (!f.write(reinterpret_cast<const char*>(jpg.data()), std::streamsize(jpg.size()))) {+ error = "Cannot write " + path;+ return false;+ }+ return true;+}+Image Image::downscaled(int maxSide) const {if (empty() || std::max(width, height) <= maxSide) return *this;const float f = float(std::max(width, height)) / float(maxSide);diff --git a/src/core/Image.h b/src/core/Image.hindex cc8b28d9..fba7ece5 100644--- a/src/core/Image.h+++ b/src/core/Image.h@@ -24,6 +24,8 @@ struct Image {static bool decode(const unsigned char* bytes, size_t size, Image& out, std::string& error);bool savePng(const std::string& path, std::string& error) const;bool encodePng(std::vector<uint8_t>& out) const;+ // JPEG (no alpha: transparent pixels go over black) at `quality` 1-100.+ bool saveJpg(const std::string& path, int quality, std::string& error) const;// Box-filtered copy whose longer side is at most `maxSide` (unchanged if already smaller).Image downscaled(int maxSide) const;// Crops to the opaque subject plus `margin` (fraction of its size) and centresdiff --git a/src/render/GL.h b/src/render/GL.hindex 67218d11..53817b53 100644--- a/src/render/GL.h+++ b/src/render/GL.h@@ -98,6 +98,8 @@ constexpr GLbitfield GL_MAP_WRITE_BIT = 0x0002;constexpr GLbitfield GL_MAP_INVALIDATE_BUFFER_BIT = 0x0008;constexpr GLenum GL_UNSIGNED_SHORT = 0x1403;constexpr GLenum GL_CULL_FACE = 0x0B44;+constexpr GLenum GL_FRONT = 0x0404;+constexpr GLenum GL_BACK = 0x0405;constexpr GLenum GL_R16UI = 0x8234;constexpr GLenum GL_RED_INTEGER = 0x8D94;constexpr GLenum GL_R16I = 0x8233;@@ -113,6 +115,7 @@ constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;X(void, Scissor, GLint, GLint, GLsizei, GLsizei) \X(void, Enable, GLenum) \X(void, Disable, GLenum) \+ X(void, CullFace, GLenum) \X(void, DepthFunc, GLenum) \X(void, DepthMask, GLboolean) \X(void, ColorMask, GLboolean, GLboolean, GLboolean, GLboolean) \diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex e9277272..2a4ed610 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -369,12 +369,15 @@ uniform int uMatcap; // 1: shade with the matcap texture instead of theuniform sampler2D uMatcapTex; // sRGB-encoded lit sphere (core/Matcap.h)uniform vec2 uMatcapCavity; // crease darkening, ridge lift (sf::matcapCavity)uniform int uDim; // 1: an inactive SubTool, shown a little darker and greyer+uniform mat3 uLightRot; // turns the light (Lit Sphere and studio) in view space (RenderSettings::lightYaw / Pitch)+uniform vec2 uLightLevels; // light intensity, ambient+uniform float uAlpha; // X-Ray: the see-through Parts' opacity (1 = opaque)uniform int uTwoSided; // 1: back faces shade with the normal turned towards the viewer; 0: the motion proxy,// whose folds face backwards on the outside of the surfaceout vec4 fragColor;vec4 finish(vec3 c) {if (uDim == 1) c = mix(c, vec3(dot(c, vec3(0.2126, 0.7152, 0.0722))), 0.25) * 0.72;- return vec4(pow(c, vec3(1.0 / 2.2)), 1.0);+ return vec4(pow(c, vec3(1.0 / 2.2)), uAlpha);}// Keep in sync with sf::polygroupColor.vec3 groupColor(uint id) {@@ -539,8 +542,9 @@ void main() {// View-aligned basis so the material stays put towards the edges of a perspective view.vec3 bx = normalize(vec3(v.z, 0.0, -v.x));vec3 by = cross(v, bx);- vec2 uv = vec2(dot(bx, n), dot(by, n)) * 0.495 + 0.5;- vec3 mc = pow(texture(uMatcapTex, uv).rgb, vec3(2.2));+ vec3 ln = transpose(uLightRot) * n; // the normal turned against the light: the material's light turns+ vec2 uv = vec2(dot(bx, ln), dot(by, ln)) * 0.495 + 0.5;+ vec3 mc = pow(texture(uMatcapTex, uv).rgb, vec3(2.2)) * uLightLevels.x + uLightLevels.y * 0.6;// Starts above the curvature of a smooth sphere's own facets, so only real creases darken and a broad// stroke doesn't pool into a smear.float mcrease = smoothstep(0.03, 0.18, curvature);@@ -550,8 +554,8 @@ void main() {fragColor = finish(c);return;}- vec3 key = normalize(vec3(0.45, 0.65, 0.6));- vec3 fill = normalize(vec3(-0.7, -0.1, 0.4));+ vec3 key = uLightRot * normalize(vec3(0.45, 0.65, 0.6));+ vec3 fill = uLightRot * normalize(vec3(-0.7, -0.1, 0.4));float diff = max((dot(n, key) + 0.25) / 1.25, 0.0);float fillL = max(dot(n, fill), 0.0) * 0.25;float hemi = 0.5 + 0.5 * n.y;@@ -567,6 +571,7 @@ void main() {c *= mix(vec3(1.0), vec3(0.72, 0.55, 0.5), crease * 0.7); // warm, deeper colour in the cracksc += albedo * ridge * 0.3 * diff; // ridges catch the key lightc += vec3(spec) * (1.0 - crease) + rim * vec3(0.8, 0.85, 1.0);+ c = c * uLightLevels.x + albedo * uLightLevels.y * 0.6;if (uShowMask == 1) c *= 1.0 - 0.75 * clamp(V_MASK, 0.0, 1.0);fragColor = finish(c);}@@ -886,6 +891,9 @@ const Renderer::MeshProgram* Renderer::meshProgram(int features) {p.matcap = at("uMatcap");p.matcapCavity = at("uMatcapCavity");p.dim = at("uDim");+ p.lightRot = at("uLightRot");+ p.lightLevels = at("uLightLevels");+ p.alpha = at("uAlpha");p.primBase = at("uPrimBase");p.hasPaint = at("uHasPaint");p.normalFlipY = at("uNormalFlipY");@@ -2574,6 +2582,48 @@ int Renderer::drawView(const Camera& camera, int width, int height, const Rendergl::GetIntegerv(GL_MAX_SAMPLES, &maxSamples);samples = std::clamp(samples, 1, std::max(1, int(maxSamples)));if (directView_) samples = 1;+ // Resolution scale (#80): the view drawn into a smaller target and scaled up into the window.+ const float scale = std::clamp(settings.resolutionScale, 0.25f, 1.0f);+ if (scale < 0.999f && !directView_ && !scaleFailed_) {+ const int sw = std::max(1, int(std::lround(width * scale))), sh = std::max(1, int(std::lround(height * scale)));+ const bool inset = viewport.w > 0 && viewport.h > 0;+ Viewport small = viewport;+ if (inset) {+ small.x = int(std::lround(viewport.x * scale));+ small.y = int(std::lround(viewport.y * scale));+ small.w = std::max(1, int(std::lround(viewport.w * scale)));+ small.h = std::max(1, int(std::lround(viewport.h * scale)));+ }+ int s = samples;+ while (s > 1 && !viewTarget(sw, sh, s)) s /= 2;+ if (s > 1 || viewTarget(sw, sh, 1)) {+ gl::BindFramebuffer(GL_FRAMEBUFFER, viewFbo_);+ draw(camera, sw, sh, settings, small);+ for (int i = 0; i < 16 && gl::GetError() != GL_NO_ERROR; ++i) {+ }+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, viewFbo_);+ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, viewResolveFbo_);+ gl::BlitFramebuffer(0, 0, sw, sh, 0, 0, sw, sh, GL_COLOR_BUFFER_BIT, GL_NEAREST);+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);+ gl::Disable(GL_SCISSOR_TEST);+ gl::Viewport(0, 0, width, height);+ if (inset) { // the window around the view, as draw() leaves it+ gl::ClearColor(viewport.surround.x, viewport.surround.y, viewport.surround.z, 1.0f);+ gl::Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);+ }+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, viewResolveFbo_);+ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);+ if (inset)+ gl::BlitFramebuffer(small.x, small.y, small.x + small.w, small.y + small.h, viewport.x, viewport.y,+ viewport.x + viewport.w, viewport.y + viewport.h, GL_COLOR_BUFFER_BIT, GL_LINEAR);+ else gl::BlitFramebuffer(0, 0, sw, sh, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);+ const GLenum blitError = gl::GetError();+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);+ if (blitError == GL_NO_ERROR) return s;+ scaleFailed_ = true; // (don't try every frame)+ SDL_Log("Scaled view copy to the window failed (GL error 0x%04x); drawing at full resolution", unsigned(blitError));+ }+ }while (samples > 1 && !viewTarget(width, height, samples)) samples /= 2;if (samples <= 1) {gl::BindFramebuffer(GL_FRAMEBUFFER, 0);@@ -2755,8 +2805,52 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, congl::ActiveTexture(GL_TEXTURE0);gl::Enable(GL_POLYGON_OFFSET_FILL);gl::PolygonOffset(1.0f, 1.0f);+ // X-Ray (#80, #91): the other Parts are see-through, or the active one when it is the only one shown.+ const bool xray = settings.xray && !thumbnailPass_;+ bool others = false;for (const DrawItem& item : drawList_)- if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0) drawSlot(*s, item.active, item.flat, settings);+ if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0 && !item.active) others = true;+ auto seeThrough = [&](const DrawItem& item) { return xray && (others ? !item.active : true); };+ drawAlpha_ = 1.0f;+ for (const DrawItem& item : drawList_)+ if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0 && !seeThrough(item))+ drawSlot(*s, item.active, item.flat, settings);+ if (xray) {+ gl::Enable(GL_BLEND);+ gl::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);+ const float opacity = std::clamp(settings.xrayOpacity, 0.05f, 1.0f);+ if (others) {+ // Only each see-through Part's nearest surface: its depth first, then its colour where that depth is+ // (no inside folds or back faces piling up), over the opaque active Part.+ gl::ColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);+ for (const DrawItem& item : drawList_)+ if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0 && seeThrough(item))+ drawSlot(*s, item.active, item.flat, settings);+ gl::ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);+ gl::DepthMask(GL_FALSE);+ drawAlpha_ = opacity;+ for (const DrawItem& item : drawList_)+ if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0 && seeThrough(item))+ drawSlot(*s, item.active, item.flat, settings);+ } else {+ // The lone active Part: its back faces first, then its front faces over them, so its far side and+ // insides show through in order (exact for a convex Part, close for the rest).+ gl::DepthMask(GL_FALSE);+ keepBackfaces_ = true;+ drawAlpha_ = opacity;+ for (GLenum cull : {GL_FRONT, GL_BACK}) {+ xrayCull_ = cull;+ for (const DrawItem& item : drawList_)+ if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0)+ drawSlot(*s, item.active, item.flat, settings);+ }+ xrayCull_ = 0;+ keepBackfaces_ = false;+ }+ drawAlpha_ = 1.0f;+ gl::DepthMask(GL_TRUE);+ gl::Disable(GL_BLEND);+ }proxyUsed_ = settings.motionProxy;gl::Disable(GL_POLYGON_OFFSET_FILL);for (GLenum unit : {kTexture7, kTexture6, GL_TEXTURE3, GL_TEXTURE1}) {@@ -2835,7 +2929,7 @@ void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy) {}return;}- v.backfaces = !v.ortho && s.closed && s.volume > 0.0 && !s.anyHidden && s.box.valid() &&+ v.backfaces = !keepBackfaces_ && !v.ortho && s.closed && s.volume > 0.0 && !s.anyHidden && s.box.valid() &&(e.x < s.box.min.x || e.y < s.box.min.y || e.z < s.box.min.z || e.x > s.box.max.x || e.y > s.box.max.y ||e.z > s.box.max.z);auto reachesNear = [&](const ClusterBounds& b) {@@ -2941,6 +3035,7 @@ void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const Rendergl::Uniform1i(p->showMask, active && settings.showMask ? 1 : 0);gl::Uniform1i(p->groups, active && settings.showPolygroups ? 2 : 0);gl::Uniform1i(p->dim, !active && settings.dimInactive ? 1 : 0);+ setLightUniforms(*p, settings);gl::Uniform1i(p->twoSided, 1);// Moving (Fast Navigation): a coarser target and half the budget, so orbiting stays smooth.const bool moving = settings.motionProxy;@@ -2952,6 +3047,23 @@ void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const RenderlastDrawn_ += s.microDrawn;}+glm::mat3 lightRotation(float yawDegrees, float pitchDegrees) {+ const float y = glm::radians(yawDegrees), p = glm::radians(pitchDegrees);+ // Yaw about the view's up axis (+: the light moves right), then pitch about its side axis (+: up).+ const glm::mat3 yaw(glm::vec3(std::cos(y), 0.0f, -std::sin(y)), glm::vec3(0.0f, 1.0f, 0.0f),+ glm::vec3(std::sin(y), 0.0f, std::cos(y)));+ const glm::mat3 pitch(glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, std::cos(p), -std::sin(p)),+ glm::vec3(0.0f, std::sin(p), std::cos(p)));+ return yaw * pitch;+}++void Renderer::setLightUniforms(const MeshProgram& p, const RenderSettings& settings) const {+ const glm::mat3 r = lightRotation(settings.lightYaw, settings.lightPitch);+ gl::UniformMatrix3fv(p.lightRot, 1, GL_FALSE, glm::value_ptr(r));+ gl::Uniform2f(p.lightLevels, std::max(settings.lightIntensity, 0.0f), std::max(settings.lightAmbient, 0.0f));+ gl::Uniform1f(p.alpha, drawAlpha_);+}+void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {if (s.micro) {drawMicro(s, active, flat, settings);@@ -3016,6 +3128,7 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSgl::Uniform1i(p->showMask, active && settings.showMask && s.hasMask ? 1 : 0);gl::Uniform1i(p->groups, groups);gl::Uniform1i(p->dim, !active && settings.dimInactive ? 1 : 0);+ setLightUniforms(*p, settings);gl::Uniform1i(p->twoSided, 1);gl::Uniform1i(p->checker, checker ? 1 : 0);gl::Uniform1f(p->checkerScale, checker ? s.overlay->checkerScale : 8.0f);@@ -3030,7 +3143,8 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSconst bool perTriangle = features & (kPrim | kTextured | kNormalMap); // (not kFlat: no per-triangle data)cull(s, frameCull_, settings.motionProxy && !perTriangle && !(active && settings.wireframe));// The back faces left in clusters along the silhouette: the GPU skips them too when they can't show.- if (cullBackfaces_) gl::Enable(GL_CULL_FACE);+ if (cullBackfaces_ || xrayCull_) gl::Enable(GL_CULL_FACE);+ if (xrayCull_) gl::CullFace(xrayCull_);// The predictive preview (render/Ghost.h): the clusters a ghost dab reaches draw with the GHOST program, the// rest as usual (most of the mesh, which then doesn't pay for the preview).// A draft stroke (Sculptor::draftStrokes) left the normals of the clusters it moved as they were: those draw@@ -3083,6 +3197,7 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSdrawClusters(s, proxyClusters_, GL_TRIANGLES, Part::Proxy, -1);}gl::Disable(GL_CULL_FACE);+ if (xrayCull_) gl::CullFace(GL_BACK);}// ---------------------------------------------------------------------------diff --git a/src/render/Renderer.h b/src/render/Renderer.hindex ee4be4f2..e69ec29f 100644--- a/src/render/Renderer.h+++ b/src/render/Renderer.h@@ -69,9 +69,24 @@ struct RenderSettings {float backgroundBlur = 0.4f; // 0 = sharp .. 1 = the roughest levelfloat pbrRoughness = 0.45f, pbrMetallic = 0.0f;float pbrCavity = 0.5f; // how much the sculpt's creases darken under PBR (0 = physically plain)+ // Lit Sphere and studio lighting (#80): the light turned from where the material has it, in degrees about the+ // view's up axis (yaw, + to the right) and its side axis (pitch, + up), its intensity (a multiplier) and an+ // ambient term that lifts the shadows (a share of the colour). The defaults leave the material as it is.+ float lightYaw = 0.0f, lightPitch = 0.0f;+ float lightIntensity = 1.0f, lightAmbient = 0.0f;+ // X-Ray (#80, #91): the other visible Parts are drawn see-through (only their nearest surface, at+ // xrayOpacity), so the active Part shows through them; with no other Part shown, the active one is see-through.+ bool xray = false;+ float xrayOpacity = 0.3f;+ // The 3D view's resolution as a share of the window's (#80): lower draws fewer pixels on slow GPUs and scales+ // the picture up (Renderer::drawView). 1 = full resolution.+ float resolutionScale = 1.0f;bool pbr() const { return shading == Shading::Pbr; }};+// RenderSettings::lightYaw / lightPitch as a rotation of view-space directions (the shader's uLightRot).+glm::mat3 lightRotation(float yawDegrees, float pitchDegrees);+// A baked tangent-space normal map to preview on a mesh (core/Bake.h): RGB8 rows bottom-up, with the// MikkTSpace tangent + sign of every triangle corner it was baked against. `serial` changes with the data.struct NormalMapView {@@ -386,6 +401,11 @@ private:// level), the BRDF table (RG16F) and the SH9, built when the environment first shows or changes.bool ensureEnvironment(int index);void setPbrUniforms(const MeshProgram& p, const RenderSettings& settings, bool textured, const MeshSlot& s);+ void setLightUniforms(const MeshProgram& p, const RenderSettings& settings) const;+ float drawAlpha_ = 1.0f; // the opacity the next meshes draw with (X-Ray's see-through Parts)+ bool scaleFailed_ = false; // the scaled view couldn't reach the window: full resolution from then on+ bool keepBackfaces_ = false;+ GLenum xrayCull_ = 0; // X-Ray's lone Part: the faces this pass culls (GL_FRONT, then GL_BACK) // X-Ray's lone see-through Part: draw its back faces too (cull)GLuint envTexture_ = 0, brdfTexture_ = 0, envBgProgram_ = 0;struct EnvJob;std::shared_ptr<EnvJob> envJob_;@@ -420,7 +440,8 @@ private:GLuint id = 0;GLint view = -1, proj = -1, gridOrigin = -1, gridStep = -1, viewport = -1, projScale = -1, baseColor = -1, paint = -1,showMask = -1, groups = -1, matcap = -1, matcapCavity = -1, dim = -1, primBase = -1, hasPaint = -1,- normalFlipY = -1, twoSided = -1, checker = -1, checkerScale = -1, tintShift = -1;+ normalFlipY = -1, twoSided = -1, checker = -1, checkerScale = -1, tintShift = -1, lightRot = -1,+ lightLevels = -1, alpha = -1;GLint hasOrm = -1, hasEmissive = -1, hasMatNormal = -1, envLevels = -1, exposure = -1, toneMap = -1, material = -1,pbrCavity = -1, viewToEnv = -1, sh = -1;GLint ghostGroups = -1, ghostRange = -1, ghostEdge = -1, ghostA = -1, ghostB = -1, ghostC = -1, ghostBound = -1, ghostKind = -1, ghostFocal = -1;diff --git a/tests/test_close_holes.cpp b/tests/test_close_holes.cppnew file mode 100644index 00000000..65c3158e--- /dev/null+++ b/tests/test_close_holes.cpp@@ -0,0 +1,164 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Close Holes (#103): holes in a sphere, an open hemisphere, a plane, the size filter, attributes and undo.+#include "TestHarness.h"++#include "core/CloseHoles.h"+#include "core/Commands.h"+#include "core/Cut.h"+#include "core/Primitives.h"++#include <chrono>+#include <cmath>+#include <cstdio>++using namespace sf;++namespace {++const CommandRegistry& registry() {+ static CommandRegistry r;+ return r;+}++double volume(const Mesh& m) {+ double v = 0.0;+ for (const glm::uvec3& t : m.triangles)+ v += glm::dot(glm::dvec3(m.positions[t.x]), glm::cross(glm::dvec3(m.positions[t.y]), glm::dvec3(m.positions[t.z])));+ return v / 6.0;+}++// Removes the triangles whose centre `drop` picks (their vertices stay, unused).+template <class F>+Mesh withHoles(Mesh m, F drop) {+ std::vector<glm::uvec3> kept;+ for (const glm::uvec3& t : m.triangles)+ if (!drop((m.positions[t.x] + m.positions[t.y] + m.positions[t.z]) / 3.0f)) kept.push_back(t);+ m.triangles = kept;+ m.rebuildTopology();+ m.recomputeAllNormals();+ return m;+}++double meanEdge(const Mesh& m, size_t fromTriangle) {+ double sum = 0.0;+ size_t n = 0;+ for (size_t t = fromTriangle; t < m.triangleCount(); ++t)+ for (int k = 0; k < 3; ++k) {+ sum += glm::length(m.positions[m.triangles[t][k]] - m.positions[m.triangles[t][(k + 1) % 3]]);+ ++n;+ }+ return n ? sum / double(n) : 0.0;+}++} // namespace++TEST(close_holes_two_holes_in_a_sphere) {+ const Mesh sphere = makeIcosphere(4);+ const double v0 = volume(sphere);+ Mesh open = withHoles(sphere, [](glm::vec3 c) { return c.z > 0.85f || c.x < -0.9f; });+ CHECK(!isWatertight(open));+ CHECK(boundaryLoops(open).size() == 2);+ const size_t t0 = open.triangleCount();+ Document d = makeDoc(open);+ const CommandResult r = registry().execute(d, "close_holes");+ CHECK(r.ok);+ CHECK(r.message.find("closed 2 holes") != std::string::npos);+ CHECK(isWatertight(d.mesh));+ CHECK(boundaryLoops(d.mesh).empty());+ // The rest of the Part is untouched, and the caps continue the sphere's curvature (round, not flat).+ for (size_t t = 0; t < t0; ++t) CHECK(d.mesh.triangles[t] == open.triangles[t]);+ for (size_t v = 0; v < open.vertexCount(); ++v) CHECK(d.mesh.positions[v] == open.positions[v]);+ const double v1 = volume(d.mesh);+ CHECK(std::abs(v1 - v0) < 0.005 * v0);+ float worst = 0.0f;+ for (size_t v = open.vertexCount(); v < d.mesh.vertexCount(); ++v) worst = std::max(worst, std::abs(glm::length(d.mesh.positions[v]) - 1.0f));+ CHECK(worst < 0.03f); // (within 3% of the radius over a hole 60 degrees across)+ // The patches are as dense as the sphere around them.+ const double around = meanEdge(open, 0), patch = meanEdge(d.mesh, t0);+ CHECK(patch > 0.6 * around && patch < 1.5 * around);+ // Each patch is its own new face group.+ CHECK(d.mesh.hasPolygroups());+ CHECK(d.mesh.polygroupAt(0) == 0 && d.mesh.polygroupAt(uint32_t(d.mesh.triangleCount() - 1)) == 1);+ // Undo brings the holes back; a second Close Holes finds none.+ CHECK(registry().execute(d, "undo").ok);+ CHECK(d.mesh.triangleCount() == t0);+ CHECK(registry().execute(d, "redo").ok);+ const CommandResult again = registry().execute(d, "close_holes");+ CHECK(again.ok && again.message.find("no holes") != std::string::npos);+}++TEST(close_holes_open_hemisphere_and_plane) {+ // The open bottom of a hemisphere: one big loop, capped watertight and rounded on (towards the full sphere).+ Mesh half = withHoles(makeIcosphere(4), [](glm::vec3 c) { return c.y < 0.0f; });+ CHECK(boundaryLoops(half).size() == 1);+ CloseHolesStats s;+ std::string error;+ Mesh m = half;+ CHECK(closeHoles(m, {}, s, error));+ CHECK(s.holes == 1 && s.filled == 1 && s.triangles > 50);+ CHECK(isWatertight(m));+ float lowest = 0.0f;+ for (size_t v = half.vertexCount(); v < m.vertexCount(); ++v) {+ CHECK(m.positions[v].y < 0.05f && m.positions[v].y > -1.1f);+ lowest = std::min(lowest, m.positions[v].y);+ }+ CHECK(lowest < -0.3f);+ // Without refining: only the loop's own vertices (an ear-clipped polygon, n - 2 triangles).+ m = half;+ CloseHolesOptions plain;+ plain.refine = false;+ CHECK(closeHoles(m, plain, s, error));+ CHECK(m.vertexCount() == half.vertexCount());+ CHECK(s.triangles == boundaryLoops(half)[0].size() - 2);+ CHECK(isWatertight(m));+ // A plane: its rim is the hole, capped on the back.+ Mesh plane = makePlane(8);+ m = plane;+ CHECK(closeHoles(m, {}, s, error));+ CHECK(s.filled == 1 && isWatertight(m));+}++TEST(close_holes_size_filter_and_attributes) {+ Mesh open = withHoles(makeIcosphere(4), [](glm::vec3 c) { return c.z > 0.97f || c.y < -0.3f; });+ const std::vector<std::vector<uint32_t>> loops = boundaryLoops(open);+ CHECK(loops.size() == 2);+ const size_t small = std::min(loops[0].size(), loops[1].size());+ open.ensureMask(0.5f);+ open.ensureColors(glm::vec3(0.2f, 0.4f, 0.6f));+ open.ensurePolygroups(7);+ open.uvs.assign(open.triangleCount() * 3, glm::vec2(0.25f));+ Document d = makeDoc(open);+ const CommandResult r = registry().execute(d, "close_holes", {{"max_edges", double(small)}});+ CHECK(r.ok);+ CHECK(r.message.find("closed 1 hole") != std::string::npos && r.message.find("left 1 bigger one") != std::string::npos);+ CHECK(boundaryLoops(d.mesh).size() == 1);+ const Mesh& m = d.mesh;+ CHECK(m.mask.size() == m.vertexCount() && m.colors.size() == m.vertexCount());+ CHECK(m.polygroups.size() == m.triangleCount() && m.uvs.size() == m.triangleCount() * 3);+ CHECK(m.polygroupAt(uint32_t(m.triangleCount() - 1)) == 8);+ CHECK(m.mask.back() == 0.0f);+ CHECK(glm::length(m.colors.back() - glm::vec3(0.2f, 0.4f, 0.6f)) < 1e-4f);+ // Forge Spheres and empty Parts are refused.+ Document empty = makeDoc(Mesh());+ CHECK(!registry().execute(empty, "close_holes").ok);+}++TEST(close_holes_big_hole_is_quick) {+ // A dense hemisphere's open bottom (a loop of hundreds of edges: the fan path) closes round in well under a second.+ Mesh half = withHoles(makeIcosphere(6), [](glm::vec3 c) { return c.y < 0.0f; });+ const size_t loop = boundaryLoops(half)[0].size();+ CHECK(loop > 300);+ CloseHolesStats s;+ std::string error;+ const auto start = std::chrono::steady_clock::now();+ CHECK(closeHoles(half, {}, s, error));+ const double seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();+ std::printf(" close holes: %zu-edge loop, %zu triangles in %.0f ms\n", loop, s.triangles, seconds * 1000.0);+ CHECK(seconds < sf::test::timeLimit(1.5));+ CHECK(isWatertight(half));+ float lowest = 0.0f;+ for (const glm::vec3& p : half.positions) lowest = std::min(lowest, p.y);+ CHECK(lowest < -0.5f);+}diff --git a/tests/test_cut.cpp b/tests/test_cut.cppindex 2369087f..3dd14125 100644--- a/tests/test_cut.cpp+++ b/tests/test_cut.cpp@@ -296,3 +296,42 @@ TEST(mask_lasso_front_faces_only) {for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) back += d.mesh.normals[v].z < -0.5f && d.mesh.mask[v] > 0.5f;CHECK(back > 0);}++TEST(cut_clip_presses_flat_without_removing) {+ // #102: a line clips the shaded side flat onto the line; nothing is removed, the depth (z) is kept.+ const Mesh sphere = makeIcosphere(4);+ Document d = makeDoc(sphere);+ CommandResult r = cut(d, "line", "0.5 -2 0.5 2", "clip", {{"flip", true}}); // the right side (x > 0.5)+ CHECK(r.ok);+ CHECK(r.message.find("Clip:") == 0);+ CHECK(d.mesh.vertexCount() == sphere.vertexCount() && d.mesh.triangles == sphere.triangles);+ float maxX = -1.0f;+ for (size_t v = 0; v < sphere.vertexCount(); ++v) {+ maxX = std::max(maxX, d.mesh.positions[v].x);+ CHECK(std::abs(d.mesh.positions[v].z - sphere.positions[v].z) < 1e-4f);+ if (sphere.positions[v].x < 0.49f) CHECK(d.mesh.positions[v] == sphere.positions[v]);+ }+ CHECK(maxX < 0.5f + 1e-3f && maxX > 0.5f - 1e-3f);+ CHECK(isWatertight(d.mesh));+ CHECK(registry().execute(d, "undo").ok);+ CHECK(d.mesh.positions == sphere.positions);++ // A rectangle presses everything outside it onto its outline.+ r = cut(d, "rect", "-0.4 -0.3 0.4 0.3", "clip");+ CHECK(r.ok);+ for (const glm::vec3& p : d.mesh.positions) CHECK(std::abs(p.x) < 0.401f && std::abs(p.y) < 0.301f);+ CHECK(registry().execute(d, "undo").ok);++ // The mask holds vertices back; a fully masked Part doesn't move.+ d.mesh.ensureMask(1.0f);+ r = cut(d, "rect", "-0.4 -0.3 0.4 0.3", "clip");+ CHECK(r.ok && r.message.find("misses") != std::string::npos);+ CHECK(d.mesh.positions == sphere.positions);++ // Symmetry X: a line on the right clips the left too.+ Document s = makeDoc(sphere);+ CHECK(cut(s, "line", "0.5 -2 0.5 2", "clip", {{"flip", true}, {"symmetry", std::string("x")}}).ok);+ float minX = 1.0f;+ for (const glm::vec3& p : s.mesh.positions) minX = std::min(minX, p.x);+ CHECK(minX > -0.501f);+}diff --git a/tests/ui/library_small_screen.sfui b/tests/ui/library_small_screen.sfuiindex 2b469d5c..d27da155 100644--- a/tests/ui/library_small_screen.sfui+++ b/tests/ui/library_small_screen.sfui@@ -20,3 +20,23 @@ wait 0.2hover_window 0.79 0.4wait_idle 30shot right-shelf-outline++# At 150% (a 720p laptop at Windows' 150% scaling, #80): the tabs fold into a drop-down instead of running under the+# close button, and the Sculpt Timeline moves off the Library instead of covering its header, in both layouts.+ui_scale 150+wait 0.3+key ,+expect_value lightbox_open == 1+wait_idle 30+shot library-150+click "Library/##lbclose"+expect_value lightbox_open == 0+run ui_look layout=zbrush+ui_scale 150+wait 0.3+key ,+expect_value lightbox_open == 1+wait_idle 30+shot library-zbrush-150+click "Library/##lbclose"+expect_value lightbox_open == 0diff --git a/tests/ui/view_controls.sfui b/tests/ui/view_controls.sfuinew file mode 100644index 00000000..8b896e5b--- /dev/null+++ b/tests/ui/view_controls.sfui@@ -0,0 +1,116 @@+# View controls (#80, #91, #102, #103): X-Ray next to Solo, the view's resolution, the light, Save Render's size+# and shape, Cut's Clip mode and Tool > Geometry > Close Holes.+run new_sphere subdivisions=4+run subtool_append type=cube name=Box+run subtool_select index=0+camera -30 -10+key f+wait_idle 30++# X-Ray: the Parts panel's button beside Solo; the Box turns see-through, the sphere shows through it.+expect_value xray == 0+click "X-Ray"+expect_value xray == 1+wait 0.2+shot xray-parts-panel+run subtool_select index=1+wait 0.2+shot xray-box-active+run subtool_select index=0+# The lone Part is see-through itself.+run subtool_solo+wait 0.2+shot xray-solo+run subtool_solo+click "X-Ray"+expect_value xray == 0++# View resolution: View > Display > 50% draws a quarter of the pixels; back to 100%.+click "View##menu.view"+click "50%##perf.res_50"+expect_value view_resolution == 50+wait 0.2+shot view-resolution-50+click "100%##perf.res_100"+expect_value view_resolution == 100+key escape++# The light: Render > Materials > Light. Turned to the left and lower, brighter, with ambient; Reset puts it back.+click "Render##menu.render"+click "Materials##section.material"+run light yaw=-60 pitch=-20 intensity=1.3 ambient=0.25+expect_value light_yaw == -60+expect_value light_ambient > 0.24+wait 0.2+shot light-panel+key escape+wait 0.2+shot light-turned+run set_material name=studio+wait 0.2+shot light-turned-studio+click "Render##menu.render"+click "Materials##section.material"+click "Reset##light"+expect_value light_yaw == 0+expect_value light_intensity == 1++# Save Render: 9:16 and JPG from the Material palette, then a script render at 1080 square.+click "9:16##render.aspect_9x16"+click "JPG##render.format_jpg"+expect_value render_aspect == 3+click "Material/Save Render##render.save_image"+expect_status Saved Render+expect_status Library > Image+run save_render size=1080 aspect=1:1+expect_status 1080 x 1080+shot save-render-panel+click "View##render.aspect_view"+click "PNG##render.format_png"+key escape++# Clip (#102): Tool > Cut > Clip, a line across the sphere presses its right side flat; nothing is removed. (X turns+# the symmetry off for it, and on again after.)+run subtool_delete index=1+camera 0 0+key f+remember triangles full+key x+click "Cut"+click "Clip##cut.clip"+click "Cut Line##cut.line"+expect_value hide_shape == 3+hold ctrl+shift+drag_path 0.58 0.25 0.58 0.75 keep+wait 0.1+shot clip-line-dragging+release+hold none+wait 0.2+expect_value triangles == $full+expect_value can_undo == 1+expect_status Clip:+camera -40 -10+wait 0.2+shot clip-line-done+key ctrl+z+key x+click "Away##cut.away"++# Close Holes (#103): a hole through the sphere (hide a square of it, delete the hidden part), closed again from+# Tool > Geometry.+camera 0 0+run hide_rect x0=-0.25 y0=-0.25 x1=0.25 y1=0.25 inside=true+run delete_hidden+remember triangles open+camera -35 -15+wait 0.2+shot close-holes-before+click "Tool/Geometry"+click "Close Holes##geometry.close_holes"+expect_status Close Holes: closed 2 holes+expect_value triangles > $open+wait 0.2+shot close-holes-after+key ctrl+z+expect_value triangles == $open