Skip to content

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.

Community requests for 0.10.6: pointer-only Forge Spheres (#8), Maya sideways zoom (#32), moving along the normal, Polish / Relax / Smooth / Balloon, Smooth remesh, Connected only and View falloff

islandmedc74270388ae7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5a9c7210..c4eed47d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,36 @@ All notable changes to SculptForge are listed here. The format follows
kept as small `.sfmaterial` text files, laid on a Part in one undoable step from **Tool > Paint Layers >
Material Recipe**. Save your own from a Part's Fill layers (`material_recipe name=worn_metal`,
`material_recipe action=save path=mine.sfmaterial`).
+- Forge Spheres with the pointer only (#8): **Drag places child** (or <kbd>Ctrl</kbd>+drag) moves a new sphere away
+ from its parent in one Draw drag; the sphere last clicked or added is selected (outlined in orange) for **Delete
+ Selected**, **Insert Between** and **Set as Root**, and a right click on a sphere opens a menu with the same.
+ Set as Root keeps the armature's shape and links (`zsphere_set_root index=3`).
+- Maya input style (#32): <kbd>Alt</kbd>+right drag zooms with a sideways drag (right zooms in), as Maya's own
+ dolly; **Preferences > Input > Zoom drag** switches it back to up and down, and **Invert zoom** turns zoom drags
+ around in every style.
+- Along the normal (from the discussions): Move, Tendril, Elastic Tendril and KelvinGrab started with the invert
+ key held (<kbd>Alt</kbd>; <kbd>Ctrl</kbd> in the Blender and Maya styles) move the surface along the average
+ normal under the brush instead of the view plane. These brushes had no use for the key; **Preferences > Input >
+ Along the normal** makes it Always or Never.
+- Whole-Part deformations (from the discussions): **Tool > Deformation > Polish** (bilateral normal filtering:
+ noise goes, planes and edges stay), **Relax** (even spacing along the surface), **Smooth** (Laplacian, or Taubin
+ with Smooth keeps volume) and **Balloon** (fills the form out; negative lets the air out), each with an amount,
+ mask-aware, open borders and hidden faces kept, one undo step, and as commands (`deform_polish`, `deform_relax`,
+ `deform_smooth`, `deform_balloon`). 10.5M vertices at amount 50: Smooth 0.5 s, Balloon 0.7 s, Relax 0.9 s,
+ Polish 2 s (Apple M1 Pro).
+- Dynamic topology's **Smooth remesh** (from the discussions): how much Shift-smoothing remeshes while Dynamic is
+ on, from **Smooth only** (the topology stays) to **Simplify** (the default, as before); a preference, saved with
+ the project, `dyntopo smooth_remesh=0`.
+- Brush falloff options (from the discussions): **Connected only** keeps a dab to the surface joined to the point
+ under the cursor, **View falloff** measures the falloff on screen (a cylinder through the model along the view),
+ as Blender's proportional editing. For every sculpt brush, recipes, VDM stamps, masking and vertex paint; saved
+ with the preferences, the project and custom brushes. A dab moving 470k of 10.5M vertices: 9.6 ms, 16 ms with
+ Connected only.
+
+### Fixed
+- Maya input style (#32): <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+drag erases the mask instead of starting
+ the <kbd>Ctrl</kbd>+<kbd>Shift</kbd> visibility selection.
+
## [0.10.5] - 2026-11-01
### Added
- **Radial symmetry** (#63): **R** in Transform > Symmetry and on the top shelf repeats strokes around the X, Y or Z
diff --git a/CMakeLists.txt b/CMakeLists.txt
index eddf160a..62eda424 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -50,6 +50,7 @@ add_library(sculptforge_core STATIC
src/core/SubTools.cpp
src/core/ExtractMirror.cpp
src/core/MeshTransform.cpp
+ src/core/Deform.cpp
src/core/TransformCommands.cpp
src/core/Decimate.cpp
src/core/Script.cpp
diff --git a/docs/guide/dynamic-topology.md b/docs/guide/dynamic-topology.md
index 06f030f7..f38b47ea 100644
--- a/docs/guide/dynamic-topology.md
+++ b/docs/guide/dynamic-topology.md
@@ -36,6 +36,19 @@ Under the brush, edges longer than the target are split, edges much shorter are
triangles are evened out. Outside the brush nothing changes, so you can have big triangles on the back of a head
and fine ones around the eyes.
+## Smooth remesh
+
+Smoothing (<kbd>Shift</kbd>) with Dynamic on also simplifies by default: it remeshes toward triangles twice the
+size, so the smoothed area gets coarser, as in Sculptris Pro. **Smooth remesh** under **Draw > Dynamic topology**
+sets how much (from the discussions):
+
+- **Smooth only** (0): Shift only smooths; the triangles stay as they are.
+- **Light** (50): it remeshes toward triangles one and a half times the size.
+- **Simplify** (100, the default): as before.
+
+It is a preference (Store Config keeps it) and is saved with the project; from a script,
+`dyntopo smooth_remesh=0`.
+
## What it keeps and what it doesn't
- **Symmetry.** With X (or Y, Z) symmetry on, both sides are remeshed together and get mirrored triangles, not
diff --git a/docs/guide/forge-spheres.md b/docs/guide/forge-spheres.md
index 70611002..8e76b0a8 100644
--- a/docs/guide/forge-spheres.md
+++ b/docs/guide/forge-spheres.md
@@ -39,6 +39,22 @@ you added, moved or scaled.
> **Tip:** build the structure first with few spheres (one per joint), set the proportions with Move and Scale,
> and add joints on links only where a limb needs to bend or swell.
+## Pointer only
+
+Everything also works with the pointer alone, without a key held (#8):
+
+- **Drag places child**: with it on, a Draw drag on a sphere makes a new sphere half its size and moves it away
+ from its parent as you drag, so one drag places the next joint of a limb. With it off, hold <kbd>Ctrl</kbd> while
+ you drag for the same.
+- **The selected sphere**: the sphere you last clicked or added is outlined in orange. **Delete Selected** deletes
+ it and everything growing from it, **Insert Between** adds a joint halfway to the sphere it grows from, and **Set
+ as Root** makes it the root: the armature keeps its shape and links and grows from there, so the skin doesn't
+ change.
+- **Right click** a sphere (a click, not a drag: a right drag still turns the view) for a menu with **Delete
+ Sphere**, **Insert Between** and **Set as Root**.
+
+Each is one undo step, and Symmetry mirrors Delete and Insert. From a script: `zsphere_set_root index=3`.
+
## Preview the skin
**Preview** (<kbd>A</kbd>) shows the skin over the spheres instead of the spheres themselves, so you can judge the
diff --git a/docs/guide/sculpting.md b/docs/guide/sculpting.md
index 8231a0f9..c4e72936 100644
--- a/docs/guide/sculpting.md
+++ b/docs/guide/sculpting.md
@@ -193,16 +193,40 @@ These toggles sit on the top shelf and in the **Draw** palette:
The **Brush** palette has the same Front and invert settings as the checkboxes **Front faces only** and
**Invert (Alt)**.
+### Falloff options
+
+Two more checkboxes in the **Brush** palette change what a brush reaches, as Blender's proportional editing
+does (from the discussions). Both work with every sculpt brush, recipes, VDM stamps, masking and vertex paint, and
+are saved with the preferences and the project (custom brushes can turn them on for themselves in the Brush Lab):
+
+| Option | What it does |
+|---|---|
+| **Connected only** | The brush only moves the surface joined to the point under the cursor, within the brush size. Inflate a finger and the next finger stays as it is; Move one leg and the other doesn't follow, however close they are. |
+| **View falloff** | The falloff is measured on screen, across the view: everything inside the brush circle is reached, through the model and out the back, as a cylinder along the view. Add **Connected only** to keep it to the piece under the cursor. |
+
+Kelvinlet brushes keep their own elastic falloff, and the Gizmo's falloff eases in from the mask's edge rather
+than from a brush centre, so these options don't apply to them. On a 10-million-vertex Part a dab that moves half
+a million vertices takes about 10 ms, and about 16 ms with Connected only.
+
## Modifier keys while sculpting
| Hold | Effect |
|---|---|
-| <kbd>Alt</kbd> | Inverts the brush for this stroke (see the table of brushes). |
+| <kbd>Alt</kbd> | Inverts the brush for this stroke (see the table of brushes). For Move, Tendril, Elastic Tendril and KelvinGrab, which have nothing to invert, it moves the surface along the normal instead (below). |
| <kbd>Shift</kbd> (before the stroke) | Smooths with the Smooth brush, whatever brush is active, at Smooth's own Intensity. With the Paint brush active, <kbd>Shift</kbd> still smooths the shape. |
| <kbd>Shift</kbd> (after the stroke started) | Draws a straight line from where you pressed <kbd>Shift</kbd>, snapped to 45 degree steps on screen. Let go of <kbd>Shift</kbd> to carry on freehand. |
| <kbd>Ctrl</kbd> | Paints a mask instead of sculpting; <kbd>Ctrl</kbd>+<kbd>Alt</kbd> erases it. A <kbd>Ctrl</kbd>+click without dragging blurs the mask (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+click sharpens it). See [Masking](masking.md). |
| <kbd>Ctrl</kbd>+<kbd>Shift</kbd> | Visibility gestures: isolate, hide and show face groups. See [Face Groups and visibility](face-groups.md). |
+### Along the normal
+
+Move, Tendril, Elastic Tendril and KelvinGrab normally move the surface across the screen. Hold <kbd>Alt</kbd> as
+you start the stroke (<kbd>Ctrl</kbd> in the Blender and Maya styles, where that key inverts) and the surface moves
+along the average normal under the brush where you pressed instead (from the discussions): drag out and it pulls
+straight out of the surface, drag back and it pushes straight in, however the view is turned. When the normal
+points right at you, drag up to pull it out. **Preferences > Input > Along the normal** can make it **Always**
+(no key needed, handy with a pen) or **Never**.
+
## The Quick Menu
Press <kbd>Space</kbd> for ZBrush's QuickMenu under the cursor: the Brush, Stroke, Alpha and Material tiles,
@@ -243,6 +267,23 @@ Both keys are free in every input style. Make your own in **Preferences > Input
**Store Config** (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd>) keeps your menus.
+## Whole-Part deformations
+
+**Tool > Deformation** has four operations that work on the whole active Part at once, each with its amount
+beside it (from the discussions). The mask holds what it covers (partly masked areas move partly), hidden faces and
+open borders stay where they are, and each is one undo step:
+
+| Operation | What it does |
+|---|---|
+| **Polish** | Flattens fine noise and small bumps while flat areas and sharp edges stay sharp: a scan's grain, or the ripples a voxel remesh leaves on a hard-surface piece. |
+| **Relax** | Evens out the spacing of the vertices along the surface without changing its shape, for areas a big Move or Tendril stretched. |
+| **Smooth** | Smooths everything; with **Smooth keeps volume** it doesn't shrink the form. |
+| **Balloon** | Fills the form out toward a rounder volume, like blowing into it (ZBrush users: Inflate Balloon). A negative amount lets the air out. |
+
+They are commands too: `deform_polish amount=60`, `deform_relax`, `deform_smooth amount=30 keep_volume=true`,
+`deform_balloon amount=-20` (add `masked=false` to ignore the mask). On a 10-million-vertex Part at amount 50,
+Smooth takes about 0.5 s, Balloon 0.7 s, Relax 0.9 s and Polish 2 s (Apple M1 Pro).
+
## Strokes
The stroke type decides how cursor movement becomes brush dabs. Choose it from the **Stroke** tile on the left
diff --git a/docs/guide/shortcuts.md b/docs/guide/shortcuts.md
index 5527e9a2..55e3d1b9 100644
--- a/docs/guide/shortcuts.md
+++ b/docs/guide/shortcuts.md
@@ -279,6 +279,25 @@ Everything else, from the <kbd>B</kbd> brush letters and <kbd>S</kbd> / <kbd>U</
<kbd>Ctrl</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd> gestures, is the same in both styles. The **Maya** style keeps
these ZBrush-style keys and changes only the view controls (<kbd>Alt</kbd>+left, middle and right drags).
+## Maya keys
+
+With **Preferences > Input > Style** on **Maya** (#32), the view works as in Maya, on the model or beside it, as
+long as <kbd>Alt</kbd> is the only key held:
+
+| To | Maya style |
+|---|---|
+| Rotate | <kbd>Alt</kbd>+left-drag |
+| Pan | <kbd>Alt</kbd>+middle-drag |
+| Zoom | <kbd>Alt</kbd>+right-drag **sideways**: right zooms in, left zooms out, as Maya's own dolly |
+| Invert the brush (subtract) | Hold <kbd>Ctrl</kbd> while sculpting |
+| Paint a mask / erase it | <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+drag / <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+drag |
+| Smooth | Hold <kbd>Shift</kbd> while sculpting |
+| Visibility gestures | <kbd>Ctrl</kbd>+<kbd>Shift</kbd>, as in the other styles |
+
+Maya's default dolly follows a sideways drag, so that is the default here too. **Preferences > Input > Zoom
+drag** switches it to **Up and down** (drag up to zoom in) if you set Maya up that way. **Invert zoom**, in every
+style, turns zoom drags around (the mouse wheel stays as it is).
+
## Blender keys
With **Preferences > Input > Style** on **Blender** (also at the top of the Controls window, <kbd>F1</kbd>), the
diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.md
index 7e4c8b04..b09aa128 100644
--- a/docs/guide/whats-new.md
+++ b/docs/guide/whats-new.md
@@ -22,6 +22,26 @@ chapter opens by itself the first time you start a new version; you can always f
- **More maps from Tool > Bake**: curvature, thickness, position and ID; bake a Part's top subdivision level (or
micro level) onto its lowest level without a second Part; UDIM tiles bake as one set of files per tile. See
[Baking](baking.md).
+- **Forge Spheres with the pointer alone** (#8): **Drag places child** (or <kbd>Ctrl</kbd> while you drag) moves a
+ new sphere away from its parent in one drag; **Delete Selected**, **Insert Between** and **Set as Root** work on
+ the sphere you last clicked, and a right click on a sphere opens a menu with the same. See
+ [Forge Spheres](forge-spheres.md#pointer-only).
+- **Maya zoom** (#32): in the Maya input style <kbd>Alt</kbd>+right drag zooms sideways, as Maya's own dolly (right
+ zooms in), and **Invert zoom** turns any zoom drag around; <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd> erases
+ the mask. See [Maya keys](shortcuts.md#maya-keys).
+- **Move along the normal** (from the discussions): Move, Tendril, Elastic Tendril and KelvinGrab started with
+ <kbd>Alt</kbd> held pull the surface straight out of itself (or push it straight in) instead of across the screen.
+ See [Sculpting](sculpting.md#along-the-normal).
+- **Polish, Relax, Smooth and Balloon** (from the discussions): **Tool > Deformation** works on the whole Part by an
+ amount: Polish flattens fine noise and keeps edges, Relax evens out the spacing, Smooth can keep the volume, and
+ Balloon fills the form out. The mask holds what it covers; one undo step each. See
+ [Sculpting](sculpting.md#whole-part-deformations).
+- **Smooth without remeshing** (from the discussions): **Smooth remesh** in **Draw > Dynamic topology** sets how
+ much Shift-smoothing changes the topology, down to **Smooth only**. See
+ [Dynamic topology](dynamic-topology.md#smooth-remesh).
+- **Connected only and View falloff** (from the discussions): brush options that keep a stroke to the piece under
+ the cursor (the other leg, the next finger stay put) or reach through the model along the view, as Blender's
+ proportional editing. See [Sculpting](sculpting.md#falloff-options).
## Version 0.10.5
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 7af9bb5b..b656e291 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -1180,6 +1180,11 @@ void App::onMouseDown(float x, float y, Uint8 button) {
rightClick_.x = x;
rightClick_.y = y;
rightClick_.dx = rightClick_.dy = 0.0f;
+ zsMenu_.armed = false;
+ // A right click on a Forge Sphere opens its menu (#8): Delete, Insert Between, Set as Root.
+ if (button == SDL_BUTTON_RIGHT && zsphereActive() && !doc_.mesh.zspherePreview &&
+ !(SDL_GetModState() & (SDL_KMOD_SHIFT | SDL_KMOD_CTRL | SDL_KMOD_ALT | SDL_KMOD_GUI)))
+ zsphereRightDown(x, y);
if (spaceHeld_) { // Preferences > Input > Hold Space and drag to move the camera (#43)
switch (spaceCameraMove(button, ctrlDown(SDL_GetModState()))) {
case SpaceCameraMove::Orbit: drag_ = Drag::Orbit; break;
@@ -1336,8 +1341,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
case Drag::Orbit: orbitBy(dx, dy); break;
case Drag::Roll: rollBy(x, y, dx, dy); break;
case Drag::Pan: camera_.pan(dx, dy, canvasHeight()); break;
- // ZBrush: dragging up (forward) zooms out, every zoom drag; the SculptForge and Blender styles zoom in.
- case Drag::Zoom: camera_.zoom((zbrushStyle() ? dy : -dy) * 0.05f); break;
+ case Drag::Zoom: camera_.zoom(zoomDragAmount(dx, dy)); break;
case Drag::MaskCanvas: maskCanvasMove(x, y); break;
case Drag::SubToolClick: subtoolClickMove(x, y); break;
case Drag::Select: selectionMove(x, y); break;
@@ -1352,6 +1356,15 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
}
}
+// How far a zoom drag zooms in (negative: out). ZBrush: dragging up (forward) zooms out; the SculptForge and
+// Blender styles zoom in. Maya (#32): a drag to the right zooms in, as Maya's own dolly (Preferences > Input >
+// Zoom drag can make it vertical). Invert zoom turns either around.
+float App::zoomDragAmount(float dx, float dy) const {
+ float a = mayaStyle() && uiPrefs_.mayaZoomHorizontal ? dx : zbrushStyle() ? dy : -dy;
+ if (uiPrefs_.invertZoom) a = -a;
+ return a * 0.05f;
+}
+
void App::orbitBy(float dx, float dy) {
if (autoOrtho_) { // an axis view turned: back to perspective (Blender's Auto Perspective)
camera_.ortho = false;
@@ -1387,6 +1400,7 @@ void App::rollBy(float x, float y, float dx, float dy) {
void App::onMouseUp() {
rollPending_ = false;
rightClick_.pending = false;
+ zsMenu_.armed = false;
orbitStarted_ = false;
panFromAlt_ = false;
if (drag_ == Drag::Select) selectionMouseUp();
@@ -1462,9 +1476,45 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
// Strokes
// ---------------------------------------------------------------------------
+bool App::alongNormalBrush(BrushType t) const {
+ return t == BrushType::Move || t == BrushType::SnakeHook || t == BrushType::KelvinSnake || t == BrushType::KelvinGrab;
+}
+
+// Along the normal (from the discussions): with the invert key held as the stroke begins (Preferences > Input >
+// Along the normal), the grab slides along the average normal under the brush rather than across the view. These
+// brushes don't use the invert key otherwise (Alt flips only Elastic Tendril's click-without-moving bump).
+void App::beginAlongNormal(const RayHit& hit, float radius) {
+ strokeAlongNormal_ = false;
+ if (!alongNormalBrush(strokeBrush_) || uiPrefs_.alongNormal == 2) return;
+ const bool key = (inputMods() & SDL_KMOD_ALT) != 0 || (erasing() && eraserAction() == PenAction::Invert);
+ if (uiPrefs_.alongNormal == 0 && !key) return;
+ glm::vec3 n = brushAreaNormal(doc_.mesh, doc_.bvh, hit.position, std::max(radius, 1e-6f), focalShift_);
+ if (glm::length(n) < 0.5f) n = hit.normal;
+ if (glm::length(n) < 0.5f) return;
+ if (glm::dot(n, camera_.forward()) > 0.0f && glm::dot(hit.normal, camera_.forward()) < 0.0f) n = -n; // (outward, to the viewer)
+ strokeAlongNormal_ = true;
+ alongNormalDir_ = glm::normalize(n);
+ alongNormalAnchor_ = hit.position;
+ alongNormalStartY_ = lastY_;
+ strokeInvert_ = invertToggle_; // (the key chose the direction, it doesn't invert the stroke)
+ status_ = std::string(brushLabel(strokeBrush_)) + ": along the normal";
+}
+
+// The point on the normal line the cursor asks for: nearest the cursor's ray, or, when the normal points at the
+// viewer (the cursor can't say how far along it), by how far the cursor went up since the press.
+glm::vec3 App::alongNormalTarget(float x, float y) const {
+ glm::vec3 origin, dir;
+ canvasRay(x, y, origin, dir);
+ float s = 0.0f;
+ if (!lineRayClosest(alongNormalAnchor_, alongNormalDir_, origin, dir, s))
+ s = (alongNormalStartY_ - y) * camera_.worldPerPixel(alongNormalAnchor_, canvasHeight());
+ return alongNormalAnchor_ + alongNormalDir_ * s;
+}
+
void App::beginStroke(float x, float y, const RayHit& hit) {
refreshSymmetryPivot(); // (local symmetry: the active Part's centre as the stroke starts)
strokeBrush_ = activeBrush();
+ strokeAlongNormal_ = false;
straight_ = {};
straight_.shiftAtStart = (inputMods() & SDL_KMOD_SHIFT) != 0;
strokeAltSmooth_ = false;
@@ -1521,17 +1571,22 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
p.radius = radiusPx_ * pressure * camera_.worldPerPixel(hit.position, canvasHeight());
p.strength = strength_;
p.focal = focalShift_;
+ p.connectedOnly = uiPrefs_.connectedOnly;
+ p.viewFalloff = uiPrefs_.viewFalloff;
doc_.sculptor.beginGrab(doc_.mesh, doc_.bvh, p, symmetry_);
grabPlanePoint_ = grabLast_ = hit.position;
+ beginAlongNormal(hit, p.radius);
return;
}
if (kelvinStrokeBrush()) { // KelvinGrab / Twist / Scale (PanelKelvinlet.cpp)
kelvinBegin(hit);
+ if (strokeBrush_ == BrushType::KelvinGrab) beginAlongNormal(hit, kelvinRadius_);
return;
}
lazyMouse_.reset(glm::vec2(x, y));
if ((strokeBrush_ == BrushType::SnakeHook || strokeBrush_ == BrushType::KelvinSnake) && !recipe && strokeSculpt_) {
grabPlanePoint_ = grabLast_ = hit.position; // the pulled tip (see snakeHookTo)
+ beginAlongNormal(hit, radiusPx_ * camera_.worldPerPixel(hit.position, canvasHeight()));
return;
}
if (strokeType_ == StrokeType::DragRect) {
@@ -1565,6 +1620,12 @@ void App::strokeTo(float x, float y) {
firstDab(maskClickX_, maskClickY_);
}
const BrushRecipe* recipe = strokeRecipe();
+ if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_ && strokeAlongNormal_) {
+ const glm::vec3 p = alongNormalTarget(x, y);
+ doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
+ grabLast_ = p;
+ return;
+ }
if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_) {
glm::vec3 origin, dir;
canvasRay(x, y, origin, dir);
@@ -1726,6 +1787,8 @@ void App::dabAt(float x, float y, float pressure) {
p.pressure = st.pressureStrength ? pressure : 1.0f;
p.invert = st.invert;
p.frontFacesOnly = st.frontFacesOnly;
+ p.connectedOnly = st.connectedOnly;
+ p.viewFalloff = st.viewFalloff;
p.focal = st.focal;
if (!dabView_) lastDabScreen_ = glm::vec2(x, y); // (the solver's: when its batch is committed)
if (st.mask) {
@@ -2065,6 +2128,7 @@ void App::drawUi() {
drawQRemeshGuides(); // QRemesh Guides curves (PanelRetopo.cpp)
drawUvEditorOverlay(); // UV seams on the model, the Seam tool's cursor (PanelUvEditor.cpp)
drawZSphereOverlay(); // the sphere under the cursor (PanelZSpheres.cpp)
+ drawZSphereMenu(); // a right click on a sphere
drawFaceOverlay(); // facial landmarks (PanelFace.cpp)
drawSplatTrainOverlay(); // splat training progress (PanelSplatTrain.cpp)
drawSculptableOverlay(); // Make sculptable: crop box, face landmarks (PanelSculptable.cpp)
@@ -2348,7 +2412,11 @@ void App::drawRecipeEditor(BrushRecipe& recipe) {
case RecipeParam::Kind::Float:
ImGui::SliderFloat(p.label, recipe.field(p.key), p.min, p.max, "%.2f");
break;
- case RecipeParam::Kind::Bool: ImGui::Checkbox(p.label, &recipe.frontFacesOnly); break;
+ case RecipeParam::Kind::Bool:
+ ImGui::Checkbox(p.label, &recipe.frontFacesOnly);
+ ImGui::Checkbox("Connected only##recipe", &recipe.connectedOnly); // (falloff options, not recipeParams)
+ ImGui::Checkbox("View falloff##recipe", &recipe.viewFalloff);
+ break;
case RecipeParam::Kind::Enum: {
int idx = recipe.enumIndex(p.key);
if (ImGui::Combo(p.label, &idx, p.options.data(), int(p.options.size()))) recipe.setEnumIndex(p.key, idx);
diff --git a/src/app/App.h b/src/app/App.h
index 846ef205..16da87dd 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -284,6 +284,7 @@ private:
float sprayScatter = 1.0f;
bool smoothKeepVolume = false; // Smooth keeps the volume (smoothKeepVolume_, or the alternate smooth)
bool pressureSize = false, pressureStrength = true, invert = false, frontFacesOnly = false;
+ bool connectedOnly = false, viewFalloff = false; // the falloff options (Brush palette)
bool mask = false, paint = false, sculpt = true, visible = true;
BrushType brush = BrushType::Standard;
StrokeType strokeType = StrokeType::Dots;
@@ -343,6 +344,16 @@ private:
BrushType strokeBrush_ = BrushType::Standard;
bool strokeInvert_ = false;
glm::vec3 grabPlanePoint_{0.0f}, grabLast_{0.0f};
+ // Along the normal (from the discussions): Move, Tendril, Elastic Tendril and KelvinGrab strokes that began with
+ // the invert key held (Preferences > Input > Along the normal) slide along the average normal under the brush
+ // at the press instead of the view plane. alongNormalTarget: where the cursor puts the grabbed point.
+ bool strokeAlongNormal_ = false;
+ glm::vec3 alongNormalDir_{0.0f, 0.0f, 1.0f};
+ glm::vec3 alongNormalAnchor_{0.0f};
+ float alongNormalStartY_ = 0.0f;
+ bool alongNormalBrush(BrushType t) const;
+ void beginAlongNormal(const RayHit& hit, float radius);
+ glm::vec3 alongNormalTarget(float x, float y) const;
std::string status_;
bool lastCommandOk_ = true; // result of the last runCommand (UI tests check it)
@@ -918,6 +929,25 @@ private:
int zsphereAt(float x, float y, bool* link = nullptr) const; // sphere (or link's child) under the cursor, or -1
float worldPerPixel(const glm::vec3& at) const; // world size of one canvas pixel at `at`'s depth
ZSphereMode zsphereMode_ = ZSphereMode::Draw;
+ bool zspherePlaceChild_ = false; // Draw: the drag moves the new sphere away from its parent (Ctrl does it too)
+ int zsphereSelected_ = -1; // the sphere last clicked or added (Delete Selected, the menu); -1 none
+ // The right-click menu on a sphere: armed by a right press on one, opened if it was a click.
+ struct ZSphereMenu {
+ bool armed = false, open = false;
+ int sphere = -1;
+ bool link = false;
+ float x = 0.0f, y = 0.0f;
+ } zsMenu_;
+ bool zsphereRightDown(float x, float y); // a right press on a sphere arms the menu
+ float deformAmount_[4] = {50.0f, 50.0f, 50.0f, 50.0f}; // Tool > Deformation: Polish, Relax, Smooth, Balloon
+ bool deformKeepVolume_ = false;
+ float zoomDragAmount(float dx, float dy) const; // Drag::Zoom's step (App.cpp)
+ void drawZSphereMenu();
+ bool zsMenuShown_ = false; // the menu was drawn this frame (UI tests)
+ // Delete, Insert (a joint on the link to its parent) or Set as root on sphere `i`, symmetric, one undo step.
+ enum class ZSphereEdit { Delete, Insert, SetRoot };
+ void zsphereEdit(ZSphereEdit edit, int i);
+ int zsphereSelection() const; // zsphereSelected_ when it is still a sphere, else -1
int zsphereResolution_ = 128; // Make Mesh resolution
struct ZSphereDrag {
ZSphereMode op = ZSphereMode::Draw; // what this drag does (a Draw click on a link then moves the new joint)
@@ -927,6 +957,8 @@ private:
glm::vec3 grab{0.0f}; // Move: the centre's offset from the grab plane's hit
float x = 0.0f, y = 0.0f; // where the press was
bool changed = false;
+ bool place = false; // Draw: the new sphere follows the cursor (Drag places child, Ctrl)
+ int added = -1; // Draw: the new sphere's index
const char* label = "";
} zsDrag_;
const BrushRecipe* strokeRecipe() const; // recipe the current stroke sculpts with (none for Smooth / paint only)
diff --git a/src/app/AsyncStroke.cpp b/src/app/AsyncStroke.cpp
index 27bbeaf8..f661563d 100644
--- a/src/app/AsyncStroke.cpp
+++ b/src/app/AsyncStroke.cpp
@@ -318,6 +318,8 @@ App::DabSettings App::dabSettings() const {
st.pressureStrength = pressureStrength_;
st.invert = strokeInvert_;
st.frontFacesOnly = frontFacesOnly_;
+ st.connectedOnly = uiPrefs_.connectedOnly;
+ st.viewFalloff = uiPrefs_.viewFalloff;
st.mask = strokeMask_;
st.paint = strokePaint_;
st.sculpt = strokeSculpt_;
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 4b85bce2..555753bb 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -54,6 +54,12 @@ Json toJson(const UiPrefs& p) {
j.set("emulateNumpad", p.emulateNumpad);
j.set("rightClickQuickMenu", p.rightClickQuickMenu);
j.set("spaceCamera", p.spaceCamera);
+ j.set("mayaZoomHorizontal", p.mayaZoomHorizontal);
+ j.set("invertZoom", p.invertZoom);
+ j.set("alongNormal", std::string(p.alongNormal == 1 ? "always" : p.alongNormal == 2 ? "never" : "invert_key"));
+ j.set("connectedOnly", p.connectedOnly);
+ j.set("viewFalloff", p.viewFalloff);
+ j.set("dyntopoSmoothRemesh", double(p.dyntopoSmoothRemesh));
j.set("airStrokes", p.airStrokes);
j.set("cursorFollowsSurface", p.cursorFollowsSurface);
j.set("timelinePosition", std::string(p.timelineTop ? "top" : "bottom"));
@@ -97,6 +103,15 @@ void fromJson(const Json& j, UiPrefs& p) {
p.emulateNumpad = j["emulateNumpad"].asBool(p.emulateNumpad);
p.rightClickQuickMenu = j["rightClickQuickMenu"].asBool(p.rightClickQuickMenu);
p.spaceCamera = j["spaceCamera"].asBool(p.spaceCamera);
+ p.mayaZoomHorizontal = j["mayaZoomHorizontal"].asBool(p.mayaZoomHorizontal);
+ p.invertZoom = j["invertZoom"].asBool(p.invertZoom);
+ if (j["alongNormal"].isString()) {
+ const std::string a = j["alongNormal"].asString();
+ p.alongNormal = a == "always" ? 1 : a == "never" ? 2 : 0;
+ }
+ p.connectedOnly = j["connectedOnly"].asBool(p.connectedOnly);
+ p.viewFalloff = j["viewFalloff"].asBool(p.viewFalloff);
+ p.dyntopoSmoothRemesh = std::clamp(float(j["dyntopoSmoothRemesh"].asNumber(p.dyntopoSmoothRemesh)), 0.0f, 1.0f);
p.airStrokes = j["airStrokes"].asBool(p.airStrokes);
p.cursorFollowsSurface = j["cursorFollowsSurface"].asBool(p.cursorFollowsSurface);
if (j["timelinePosition"].isString()) p.timelineTop = j["timelinePosition"].asString() != "bottom";
@@ -360,6 +375,30 @@ void App::initActions() {
add(kMirrorIds[k], kNames[k], "Tool > Deformation", nullptr, [this, k] { mirrorAxes_[k] = !mirrorAxes_[k]; }, nullptr,
nullptr, [this, k] { return mirrorAxes_[k]; }, nullptr, "An axis Mirror flips along (several: one after the other).");
}
+ // Whole-mesh deformations (core/Deform.h, PanelExtract.cpp), each by its amount slider.
+ {
+ static const char* const kIds[4] = {"deformation.polish", "deformation.relax", "deformation.smooth", "deformation.balloon"};
+ static const char* const kLabels[4] = {"Polish", "Relax", "Smooth", "Balloon"};
+ static const char* const kCommands[4] = {"deform_polish", "deform_relax", "deform_smooth", "deform_balloon"};
+ static const char* const kHelp[4] = {
+ "Polish the whole Part by the amount beside it: fine noise and small bumps flatten out while flat areas and "
+ "sharp edges stay. The mask holds what it covers; one undo step.",
+ "Relax the whole Part: the vertices even out their spacing along the surface without changing its shape "
+ "(stretched areas after big moves). The mask holds what it covers; one undo step.",
+ "Smooth the whole Part by the amount beside it (Smooth keeps volume: without shrinking it). The mask "
+ "holds what it covers; one undo step.",
+ "Fill the whole Part out toward a rounder volume, like a balloon (ZBrush's Inflate Balloon); a negative "
+ "amount lets the air out. The mask holds what it covers; one undo step."};
+ for (int k = 0; k < 4; ++k)
+ add(kIds[k], kLabels[k], "Tool > Deformation", nullptr,
+ [this, k] {
+ Args a{{"amount", double(deformAmount_[k])}};
+ if (k == 2) a["keep_volume"] = deformKeepVolume_;
+ runCommand(kCommands[k], a);
+ },
+ nullptr, kCommands[k], nullptr, [this, k] { return doc_.mesh.vertexCount() > 0 && deformAmount_[k] != 0.0f; },
+ kHelp[k]);
+ }
add("file.new_sphere", "New Sphere", "File", "Ctrl+N", [this] { confirmDiscard([this] { runCommand("new_sphere"); }); },
ICON_LC_FILE_PLUS, "new_sphere");
add("file.new_plane", "New Plane", "File", nullptr, [this] { confirmDiscard([this] { runCommand("new_plane"); }); }, nullptr,
@@ -685,6 +724,7 @@ bool App::readUiConfig(const std::string& path, std::string& err) {
applyPerformancePrefs();
applyInputStyle();
doc_.sculptor.dyntopo.constantDetail = uiPrefs_.dyntopoConstantDetail;
+ doc_.sculptor.dyntopo.smoothRemesh = uiPrefs_.dyntopoSmoothRemesh;
renderSettings_.flatShading = uiPrefs_.flatShading;
renderSettings_.gradientBackground = uiPrefs_.gradientBackground;
renderSettings_.backgroundColor = uiPrefs_.backgroundColor;
diff --git a/src/app/Config.h b/src/app/Config.h
index 8441ce2e..701f6244 100644
--- a/src/app/Config.h
+++ b/src/app/Config.h
@@ -39,6 +39,18 @@ struct UiPrefs {
bool emulateNumpad = false; // Blender style: the 1-9 and 0 keys above the letters act as the numpad (laptops)
bool rightClickQuickMenu = true; // a right click on the canvas (no drag) opens the QuickMenu, as in ZBrush (#22)
bool spaceCamera = false; // hold Space and drag to move the camera (#43; off: Space opens the QuickMenu)
+ // Zoom drags (#32): the Maya style zooms with a sideways drag (right = in), as Maya's own dolly; false makes it
+ // vertical as the other styles. invertZoom turns every zoom drag around.
+ bool mayaZoomHorizontal = true;
+ bool invertZoom = false;
+ // Along the normal (from the discussions): 0 = with the invert key (Alt; Ctrl in the Blender and Maya styles),
+ // 1 = always, 2 = never. For Move, Tendril, Elastic Tendril and KelvinGrab.
+ int alongNormal = 0;
+ // Brush falloff options (from the discussions): Connected only, View falloff (App::connectedOnly_ / viewFalloff_).
+ bool connectedOnly = false;
+ bool viewFalloff = false;
+ // Dynamic topology: how much Smooth remeshes, 0-1 (DyntopoSettings::smoothRemesh; 1 as before).
+ float dyntopoSmoothRemesh = 1.0f;
bool airStrokes = false; // start strokes off the model (#62): a left-drag on the background sculpts once it
// reaches the surface instead of turning the view (off: it turns the view, ZBrush)
bool showAxes = true; // Draw > Camera > Axes: the X / Y / Z gizmo in the canvas corner (#31)
diff --git a/src/app/Input.cpp b/src/app/Input.cpp
index 3929ea0e..a18f7a7e 100644
--- a/src/app/Input.cpp
+++ b/src/app/Input.cpp
@@ -443,6 +443,34 @@ void App::drawInputSection() {
if (ui::Checkbox("Hold Space and drag to move the camera##input.space_camera", &spaceCamera))
uiPrefs_.spaceCamera = spaceCamera;
ui::HelpAction(*this, "input.space_camera");
+ if (mayaStyle()) {
+ int zoom = uiPrefs_.mayaZoomHorizontal ? 0 : 1;
+ ImGui::TextDisabled("%s", tr("Zoom drag"));
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ const std::string zooms = std::string(tr("Sideways (Maya)")) + '\0' + tr("Up and down") + '\0';
+ if (ImGui::Combo("##input.maya_zoom", &zoom, zooms.c_str())) uiPrefs_.mayaZoomHorizontal = zoom == 0;
+ ui::HelpText("Zoom drag", nullptr,
+ "Alt+right drag zooms. Sideways (the default, as Maya's own dolly): drag right to zoom in, left to "
+ "zoom out. Up and down: drag up to zoom in, as the SculptForge style.",
+ "Preferences > Input");
+ }
+ ui::Checkbox("Invert zoom##input.invert_zoom", &uiPrefs_.invertZoom);
+ ui::HelpText("Invert zoom", nullptr, "Turn zoom drags around (the mouse wheel stays as it is).", "Preferences > Input");
+ {
+ ImGui::TextDisabled("%s", tr("Along the normal"));
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ const char* key = blenderStyle() || mayaStyle() ? "With Ctrl" : "With Alt";
+ const std::string modes = std::string(tr(key)) + '\0' + tr("Always") + '\0' + tr("Never") + '\0';
+ ImGui::Combo("##input.along_normal", &uiPrefs_.alongNormal, modes.c_str());
+ ui::HelpText("Along the normal", nullptr,
+ "Move, Tendril, Elastic Tendril and KelvinGrab: with the invert key held as the stroke begins "
+ "(Alt; Ctrl in the Blender and Maya styles), the surface moves along the average normal under the "
+ "brush instead of across the screen, so it pulls straight out of the surface or pushes straight "
+ "in. Always: every stroke of those brushes does; Never: the key does nothing for them.",
+ "Preferences > Input");
+ }
bool airStrokes = uiPrefs_.airStrokes;
if (ui::Checkbox("Start strokes off the model##input.air_strokes", &airStrokes)) uiPrefs_.airStrokes = airStrokes;
ui::HelpAction(*this, "input.air_strokes");
@@ -536,9 +564,14 @@ void App::openQuickMenu() {
}
void App::rightClickRelease() {
- if (!rightClick_.pending) return;
+ const bool click = rightClick_.pending;
rightClick_.pending = false;
- if (!uiPrefs_.rightClickQuickMenu) return;
+ if (zsMenu_.armed) { // on a Forge Sphere: its menu instead (PanelZSpheres.cpp)
+ zsMenu_.armed = false;
+ zsMenu_.open = click;
+ return;
+ }
+ if (!click || !uiPrefs_.rightClickQuickMenu) return;
// Opened as a tap of Space would: it stays until a click elsewhere or Esc.
quickMenu_.open = true;
quickMenu_.at = ImVec2(rightClick_.x, rightClick_.y);
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 9ad74609..01f66491 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -232,6 +232,11 @@ void App::drawPalette_Brush() {
ImGui::SameLine();
ImGui::Checkbox(tr("Invert (Alt)"), &invertToggle_);
ui::HelpText("Invert", "Alt", "Brushes subtract instead of add (ZBrush Zsub). Holding Alt flips it for one stroke.", "Brush");
+ ui::Checkbox("Connected only##draw.connected_only", &uiPrefs_.connectedOnly);
+ ui::HelpAction(*this, "draw.connected_only");
+ ImGui::SameLine();
+ ui::Checkbox("View falloff##draw.view_falloff", &uiPrefs_.viewFalloff);
+ ui::HelpAction(*this, "draw.view_falloff");
ImGui::Checkbox(tr("Smooth keeps volume##smooth_keep_volume"), &smoothKeepVolume_);
ui::HelpText("Smooth keeps volume", nullptr,
"The Smooth brush (and Shift) removes bumps without shrinking the form, instead of the plain smooth "
@@ -295,6 +300,32 @@ void App::drawPalette_Draw() {
"Off (the default): the triangle size follows the brush size on screen, as in Dynamic Topology. On: one "
"size for the whole mesh, set by Detail. A preference (Store Config keeps it).",
"Draw > Dynamic topology");
+ {
+ float remesh = doc_.sculptor.dyntopo.smoothRemesh * 100.0f;
+ ImGui::SetNextItemWidth(-1);
+ const char* shown = remesh <= 0.5f ? "Smooth remesh: none (smooth only)" : "Smooth remesh %.0f";
+ if (ui::SliderInside("##dyntopo_smooth_remesh", &remesh, 0.0f, 100.0f, shown)) {
+ doc_.sculptor.dyntopo.smoothRemesh = std::clamp(remesh / 100.0f, 0.0f, 1.0f);
+ uiPrefs_.dyntopoSmoothRemesh = doc_.sculptor.dyntopo.smoothRemesh;
+ }
+ ui::HelpText("Smooth remesh", nullptr,
+ "How much Smooth (Shift) changes the topology while Dynamic is on. 100 (the default): it also "
+ "simplifies, merging triangles toward twice the size. Lower: it remeshes less. 0: Smooth only "
+ "smooths and the triangles stay as they are. A preference (Store Config keeps it).",
+ "Draw > Dynamic topology");
+ const float third = (ImGui::GetContentRegionAvail().x - 2.0f * ImGui::GetStyle().ItemSpacing.x) / 3.0f;
+ const struct {
+ const char* label;
+ float value;
+ } presets[] = {{"Smooth only##sr0", 0.0f}, {"Light##sr50", 0.5f}, {"Simplify##sr100", 1.0f}};
+ for (int k = 0; k < 3; ++k) {
+ if (k) ImGui::SameLine();
+ if (ImGui::Button(presets[k].label, ImVec2(k == 2 ? -1.0f : third, 0))) {
+ doc_.sculptor.dyntopo.smoothRemesh = presets[k].value;
+ uiPrefs_.dyntopoSmoothRemesh = presets[k].value;
+ }
+ }
+ }
if (doc_.sculptor.dyntopo.enabled && !dyntopoBlocker(doc_.mesh).empty())
hint(*this, "This Part has subdivision levels, so strokes don't remesh it: delete the lower (or higher) levels "
"first.");
diff --git a/src/app/PanelBrushes.cpp b/src/app/PanelBrushes.cpp
index 3cc57544..c7010957 100644
--- a/src/app/PanelBrushes.cpp
+++ b/src/app/PanelBrushes.cpp
@@ -78,7 +78,8 @@ void App::snakeHookTo(float x, float y) {
const glm::vec3 n = camera_.forward();
const float denom = glm::dot(dir, n);
if (std::abs(denom) < 1e-6f) return;
- const glm::vec3 target = origin + dir * (glm::dot(grabLast_ - origin, n) / denom);
+ // Along the normal (App::beginAlongNormal): the tip slides out along the normal at the press.
+ const glm::vec3 target = strokeAlongNormal_ ? alongNormalTarget(x, y) : origin + dir * (glm::dot(grabLast_ - origin, n) / denom);
const float pressure = strokePressure();
DabParams p;
@@ -88,6 +89,8 @@ void App::snakeHookTo(float x, float y) {
p.pressure = pressureStrength_ ? pressure : 1.0f;
p.invert = strokeInvert_;
p.focal = focalShift_;
+ p.connectedOnly = uiPrefs_.connectedOnly;
+ p.viewFalloff = uiPrefs_.viewFalloff;
p.alpha = &doc_.brushAlpha;
p.alphaUp = screenUpVector(0.0f);
// Small steps keep the tip under the cursor and the pulled surface even.
@@ -119,6 +122,8 @@ void App::dragRectTo(float x, float y) {
p.pressure = pressureStrength_ ? pressure : 1.0f;
p.invert = strokeInvert_;
p.frontFacesOnly = frontFacesOnly_;
+ p.connectedOnly = uiPrefs_.connectedOnly;
+ p.viewFalloff = uiPrefs_.viewFalloff;
p.focal = focalShift_;
p.alpha = &doc_.brushAlpha;
p.alphaUp = glm::normalize(q * glm::vec3(drag.x, -drag.y, 0.0f)); // the alpha's top follows the drag
diff --git a/src/app/PanelExtract.cpp b/src/app/PanelExtract.cpp
index a187f6ac..bbd644a5 100644
--- a/src/app/PanelExtract.cpp
+++ b/src/app/PanelExtract.cpp
@@ -82,6 +82,28 @@ void App::drawDeformationContents() {
ui::HelpAction(*this, "deformation.mirror");
ImGui::SameLine();
ui::Segmented(*this, {"deformation.mirror_x", "deformation.mirror_y", "deformation.mirror_z"}, -1.0f);
+ // Whole-mesh deformations (core/Deform.h, from the discussions): a button and its amount on one row.
+ const float button = ImGui::CalcTextSize("Balloon").x + 2.0f * style.FramePadding.x + ImGui::GetFrameHeight();
+ const struct {
+ const char* action;
+ float* amount;
+ float lo;
+ const char* slider;
+ } rows[] = {{"deformation.polish", &deformAmount_[0], 0.0f, "##deform_polish_amount"},
+ {"deformation.relax", &deformAmount_[1], 0.0f, "##deform_relax_amount"},
+ {"deformation.smooth", &deformAmount_[2], 0.0f, "##deform_smooth_amount"},
+ {"deformation.balloon", &deformAmount_[3], -100.0f, "##deform_balloon_amount"}};
+ for (const auto& r : rows) {
+ ui::ActionButton(*this, r.action, ImVec2(button, 0));
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ ui::SliderInside(r.slider, r.amount, r.lo, 100.0f, "%.0f");
+ }
+ ui::Checkbox("Smooth keeps volume##deformation.smooth_volume", &deformKeepVolume_);
+ ui::HelpText("Smooth keeps volume", nullptr,
+ "Deformation > Smooth smooths without shrinking the form (Taubin smoothing) instead of the plain "
+ "smooth, which also shrinks it.",
+ "Tool > Deformation");
}
} // namespace sf
diff --git a/src/app/PanelKelvinlet.cpp b/src/app/PanelKelvinlet.cpp
index dc8524e3..3fab2ad8 100644
--- a/src/app/PanelKelvinlet.cpp
+++ b/src/app/PanelKelvinlet.cpp
@@ -66,13 +66,15 @@ void App::kelvinTo(float x, float y) {
const float pressure = pressureStrength_ ? strokePressure() : 1.0f;
kelvinAmount_ = std::min(1.0f, 2.0f * strength_) * pressure;
if (strokeBrush_ == BrushType::KelvinGrab) {
- // The grabbed point follows the cursor in the plane through it facing the camera (as Move).
+ // The grabbed point follows the cursor in the plane through it facing the camera (as Move), or along the
+ // normal (App::beginAlongNormal).
glm::vec3 origin, dir;
canvasRay(x, y, origin, dir);
const glm::vec3 n = camera_.forward();
const float denom = glm::dot(dir, n);
- if (std::abs(denom) < 1e-6f) return;
- kelvinTarget_ = origin + dir * (glm::dot(grabPlanePoint_ - origin, n) / denom);
+ if (strokeAlongNormal_) kelvinTarget_ = alongNormalTarget(x, y);
+ else if (std::abs(denom) < 1e-6f) return;
+ else kelvinTarget_ = origin + dir * (glm::dot(grabPlanePoint_ - origin, n) / denom);
} else {
// Twist / Scale: the drag's sideways distance in brush radii (Alt reverses).
const float dx = (x - kelvinLastX_) / std::max(radiusPx_, 1.0f) * kelvinAmount_ * (strokeInvert_ ? -1.0f : 1.0f);
diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cpp
index 2c8ca6bc..9a824f3b 100644
--- a/src/app/PanelProject.cpp
+++ b/src/app/PanelProject.cpp
@@ -304,11 +304,14 @@ void App::storeProjectSettings() {
brush.set("focal_shift", double(focalShift_));
brush.set("invert", invertToggle_);
brush.set("front_faces_only", frontFacesOnly_);
+ brush.set("connected_only", uiPrefs_.connectedOnly);
+ brush.set("view_falloff", uiPrefs_.viewFalloff);
brush.set("pressure_strength", pressureStrength_);
brush.set("pressure_size", pressureSize_);
brush.set("paint_color", vec3Json(doc_.paintColor));
brush.set("dynamic", doc_.sculptor.dyntopo.enabled); // dynamic topology (core/Dyntopo.h)
brush.set("dynamic_detail", double(doc_.sculptor.dyntopo.detail));
+ brush.set("dynamic_smooth_remesh", double(doc_.sculptor.dyntopo.smoothRemesh));
brush.set("vdm", doc_.brushVdm ? doc_.brushVdm->name : std::string()); // by name: the map stays in the library
s.set("brush", std::move(brush));
@@ -425,12 +428,16 @@ void App::applyProjectSettings() {
readBool(b, "invert", invertToggle_);
readBool(b, "smooth_keep_volume", smoothKeepVolume_);
readBool(b, "front_faces_only", frontFacesOnly_);
+ readBool(b, "connected_only", uiPrefs_.connectedOnly);
+ readBool(b, "view_falloff", uiPrefs_.viewFalloff);
readBool(b, "pressure_strength", pressureStrength_);
readVec3(b["paint_color"], doc_.paintColor);
readBool(b, "pressure_size", pressureSize_);
readBool(b, "dynamic", doc_.sculptor.dyntopo.enabled);
readFloat(b, "dynamic_detail", doc_.sculptor.dyntopo.detail);
doc_.sculptor.dyntopo.detail = std::clamp(doc_.sculptor.dyntopo.detail, 0.0f, 1.0f);
+ readFloat(b, "dynamic_smooth_remesh", doc_.sculptor.dyntopo.smoothRemesh);
+ doc_.sculptor.dyntopo.smoothRemesh = std::clamp(doc_.sculptor.dyntopo.smoothRemesh, 0.0f, 1.0f);
if (const int vdm = b["vdm"].isString() ? findVdm(doc_, b["vdm"].asString()) : -1; vdm >= 0)
doc_.brushVdm = doc_.vdms[size_t(vdm)];
}
diff --git a/src/app/PanelVdm.cpp b/src/app/PanelVdm.cpp
index 127047eb..a1f9c42d 100644
--- a/src/app/PanelVdm.cpp
+++ b/src/app/PanelVdm.cpp
@@ -143,6 +143,8 @@ void App::dragDotTo(float x, float y) {
p.pressure = pressureStrength_ ? pressure : 1.0f;
p.invert = strokeInvert_;
p.frontFacesOnly = frontFacesOnly_;
+ p.connectedOnly = uiPrefs_.connectedOnly;
+ p.viewFalloff = uiPrefs_.viewFalloff;
p.focal = focalShift_;
p.alpha = &doc_.brushAlpha;
p.alphaUp = screenUpVector(0.0f);
diff --git a/src/app/PanelZSpheres.cpp b/src/app/PanelZSpheres.cpp
index 189572fb..98e87b9b 100644
--- a/src/app/PanelZSpheres.cpp
+++ b/src/app/PanelZSpheres.cpp
@@ -8,9 +8,13 @@
// Move - drag a sphere to move it across the screen
// Scale - drag a sphere up/right to grow it, down/left to shrink it
// Alt+click a sphere deletes it with everything growing from it. Symmetry mirrors every edit.
+// Pointer only (#8): Drag places child makes a Draw drag move the new sphere away from its parent (Ctrl+drag does
+// it once), the last sphere clicked or added is selected (Delete Selected, Insert Between, Set as Root), and a
+// right click on a sphere opens a menu with the same three.
// Dragging the background navigates as usual. Every drag is one undo step (the SubTool's mesh, which carries
// the armature, is replaced once at release); the panel's buttons run the zsphere_* commands.
#include "app/App.h"
+#include "app/Demo.h"
#include "app/Palettes.h"
#include "app/Ui.h"
@@ -25,6 +29,8 @@ namespace {
constexpr const char* kZSpheresPath = "Tool > Forge Spheres";
+bool ctrlDown(SDL_Keymod mod) { return (mod & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0; } // as App.cpp
+
const char* modeName(int m) { return m == 0 ? "Draw" : m == 1 ? "Move" : "Scale"; } // App::ZSphereMode order
// Where the ray o + t*d meets the plane through p with normal n (t clamped to stay in front).
@@ -73,6 +79,22 @@ void App::registerZSphereUiActions() {
"Drag a sphere to move it; the links stretch to follow. Symmetry moves its mirror twin too.");
add("zsphere.scale", "Scale", mode(ZSphereMode::Scale), active, [this] { return zsphereMode_ == ZSphereMode::Scale; },
"Drag a sphere up or right to make it bigger, down or left to make it smaller.");
+ add("zsphere.place_child", "Drag places child", [this] { zspherePlaceChild_ = !zspherePlaceChild_; }, active,
+ [this] { return zspherePlaceChild_; },
+ "Draw: dragging on a sphere moves the new sphere away from it (one drag places a limb joint) instead of "
+ "sizing it. Off, hold Ctrl while you drag for the same.");
+ const auto selected = [this] { return zsphereActive() && zsphereSelection() > 0; };
+ add("zsphere.delete_selected", "Delete Selected", [this] { zsphereEdit(ZSphereEdit::Delete, zsphereSelection()); },
+ selected, nullptr,
+ "Delete the selected sphere (the one you last clicked or added, outlined in orange) and everything growing "
+ "from it. The root stays.");
+ add("zsphere.insert_selected", "Insert Between", [this] { zsphereEdit(ZSphereEdit::Insert, zsphereSelection()); },
+ selected, nullptr, "Add a joint halfway along the link from the selected sphere to the one it grows from.");
+ add("zsphere.set_root", "Set as Root", [this] { zsphereEdit(ZSphereEdit::SetRoot, zsphereSelection()); }, selected,
+ nullptr,
+ "Make the selected sphere the root: the armature keeps its shape and grows from there (the links on the way "
+ "turn around).",
+ "zsphere_set_root");
add("zsphere.preview", "Preview", [this] { runCommand("zsphere_preview"); }, active,
[this] { return doc_.mesh.zspherePreview; },
"Show the skin Make Mesh would build instead of the spheres (ZBrush's Preview). Turn it off to edit the "
@@ -104,10 +126,19 @@ void App::drawZSpheresContents() {
ui::ActionButton(*this, "zsphere.move", ImVec2(third, 0));
ImGui::SameLine();
ui::ActionButton(*this, "zsphere.scale", ImVec2(-1, 0));
+ ui::ActionButton(*this, "zsphere.place_child", ImVec2(full, 0));
+ ui::ActionButton(*this, "zsphere.delete_selected", ImVec2(full, 0));
+ ui::ActionButton(*this, "zsphere.insert_selected", ImVec2(half, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "zsphere.set_root", ImVec2(-1, 0));
ui::ActionButton(*this, "zsphere.preview", ImVec2(half, 0));
ImGui::SameLine();
ImGui::AlignTextToFramePadding();
ImGui::TextDisabled("%zu %s", doc_.mesh.zspheres.size(), doc_.mesh.zspheres.size() == 1 ? "sphere" : "spheres");
+ if (const int sel = zsphereSelection(); sel >= 0) {
+ ImGui::SameLine();
+ ImGui::TextDisabled(sel == 0 ? "(root selected)" : "(sphere %d selected)", sel);
+ }
tray::GroupLabel(*this, "Make Mesh");
ui::ActionButton(*this, "zsphere.make_mesh", ImVec2(half, 0));
ImGui::SameLine();
@@ -158,8 +189,10 @@ bool App::zsphereMouseDown(float x, float y, SDL_Keymod mod) {
zsphereDelete(s, i, symmetry_);
doc_.replaceMeshUndoable(zsphereMesh(s, false), "Forge Sphere delete");
status_ = "Forge Spheres: deleted " + std::to_string(before - s.size()) + " spheres; " + std::to_string(s.size()) + " left";
+ zsphereSelected_ = -1;
return true;
}
+ if (!link) zsphereSelected_ = i;
ZSphereDrag& d = zsDrag_;
d = {};
d.start = doc_.mesh.zspheres;
@@ -178,6 +211,7 @@ bool App::zsphereMouseDown(float x, float y, SDL_Keymod mod) {
doc_.bvh.build(doc_.mesh);
} else if (d.op == ZSphereMode::Draw) {
d.label = "Forge Sphere add";
+ d.place = zspherePlaceChild_ || ctrlDown(mod); // the drag moves the new sphere out instead of sizing it
} else {
d.label = d.op == ZSphereMode::Move ? "Forge Sphere move" : "Forge Sphere scale";
}
@@ -210,9 +244,20 @@ void App::zsphereDragTo(float x, float y) {
if (off < z.radius) // the front of the sphere under the press
n = glm::normalize(closest - glm::normalize(dir) * std::sqrt(z.radius * z.radius - off * off) - z.center);
const glm::vec3 c = z.center + n * z.radius;
+ if (d.place) {
+ // Half the parent's size, starting on its surface and following the cursor in the plane through
+ // that point facing the camera.
+ glm::vec3 o2, dir2;
+ canvasRay(x, y, o2, dir2);
+ const glm::vec3 at = planeHit(o2, dir2, c, glm::normalize(dir));
+ zsphereAdd(s, d.sphere, at, 0.5f * z.radius, symmetry_, &d.added);
+ status_ = "Forge Spheres: new sphere, " + std::to_string(glm::distance(at, z.center) / z.radius).substr(0, 4) +
+ " parent radii out";
+ break;
+ }
const float wpp = worldPerPixel(c);
const float r = moved > 3.0f * uiScale_ && wpp > 0.0f ? std::max(moved * wpp, 0.02f * z.radius) : 0.5f * z.radius;
- zsphereAdd(s, d.sphere, c, r, symmetry_);
+ zsphereAdd(s, d.sphere, c, r, symmetry_, &d.added);
status_ = "Forge Spheres: new sphere, radius " + std::to_string(r).substr(0, 5);
break;
}
@@ -242,10 +287,92 @@ void App::zsphereRelease() {
doc_.mesh = std::move(d.before);
doc_.replaceMeshUndoable(std::move(after), d.label);
status_ = std::string("Forge Spheres: ") + d.label + "; " + std::to_string(doc_.mesh.zspheres.size()) + " spheres";
+ if (d.added >= 0) zsphereSelected_ = d.added; // the new sphere
+ else if (d.op == ZSphereMode::Move) zsphereSelected_ = d.sphere; // (an inserted joint, too)
}
d = {};
}
+int App::zsphereSelection() const {
+ return zsphereActive() && zsphereSelected_ >= 0 && size_t(zsphereSelected_) < doc_.mesh.zspheres.size() ? zsphereSelected_
+ : -1;
+}
+
+void App::zsphereEdit(ZSphereEdit edit, int i) {
+ if (!zsphereActive() || i < 0 || size_t(i) >= doc_.mesh.zspheres.size()) return;
+ if (i == 0) {
+ status_ = edit == ZSphereEdit::SetRoot ? "Forge Spheres: that sphere is the root already"
+ : "Forge Spheres: the root sphere stays (select another sphere)";
+ return;
+ }
+ std::vector<ZSphere> s = doc_.mesh.zspheres;
+ const size_t before = s.size();
+ const char* label = "";
+ int select = -1;
+ switch (edit) {
+ case ZSphereEdit::Delete:
+ zsphereDelete(s, i, symmetry_);
+ label = "Forge Sphere delete";
+ break;
+ case ZSphereEdit::Insert:
+ zsphereInsert(s, i, symmetry_, &select);
+ label = "Forge Sphere insert";
+ break;
+ case ZSphereEdit::SetRoot:
+ zsphereSetRoot(s, i);
+ label = "Forge Sphere set root";
+ select = 0;
+ break;
+ }
+ doc_.replaceMeshUndoable(zsphereMesh(s, doc_.mesh.zspherePreview), label);
+ zsphereSelected_ = select;
+ status_ = edit == ZSphereEdit::Delete ? "Forge Spheres: deleted " + std::to_string(before - s.size()) + " spheres; " +
+ std::to_string(s.size()) + " left"
+ : edit == ZSphereEdit::Insert ? std::string("Forge Spheres: Forge Sphere insert; ") + std::to_string(s.size()) + " spheres"
+ : std::string("Forge Spheres: Forge Sphere set root (the selected sphere is the root now)");
+}
+
+bool App::zsphereRightDown(float x, float y) {
+ zsMenu_ = {};
+ bool link = false;
+ const int i = zsphereAt(x, y, &link);
+ if (i < 0) return false;
+ zsMenu_.armed = true;
+ zsMenu_.sphere = i;
+ zsMenu_.link = link;
+ zsMenu_.x = x;
+ zsMenu_.y = y;
+ rightClick_.pending = true; // a click opens the menu; a drag past the slop still turns the view
+ return true;
+}
+
+void App::drawZSphereMenu() {
+ constexpr const char* kMenu = "Forge Sphere##zsphere_menu";
+ const bool appearing = zsMenu_.open;
+ if (zsMenu_.open) {
+ ImGui::OpenPopup(kMenu);
+ zsMenu_.open = false;
+ }
+ if (appearing) ImGui::SetNextWindowPos(ImVec2(zsMenu_.x, zsMenu_.y));
+ zsMenuShown_ = false;
+ if (!ImGui::BeginPopup(kMenu)) return;
+ zsMenuShown_ = true;
+ const int i = zsMenu_.sphere;
+ if (!zsphereActive() || i < 0 || size_t(i) >= doc_.mesh.zspheres.size()) {
+ ImGui::CloseCurrentPopup();
+ ImGui::EndPopup();
+ return;
+ }
+ Demo::pushScope("Forge Sphere menu");
+ ImGui::TextDisabled(i == 0 ? "Root sphere" : "Sphere %d", i);
+ ImGui::Separator();
+ if (ImGui::MenuItem("Delete Sphere", nullptr, false, i > 0)) zsphereEdit(ZSphereEdit::Delete, i);
+ if (ImGui::MenuItem("Insert Between", nullptr, false, i > 0)) zsphereEdit(ZSphereEdit::Insert, i);
+ if (ImGui::MenuItem("Set as Root", nullptr, false, i > 0)) zsphereEdit(ZSphereEdit::SetRoot, i);
+ Demo::popScope();
+ ImGui::EndPopup();
+}
+
void App::drawZSphereOverlay() {
if (!zsphereActive() || doc_.mesh.zspherePreview || !doc_.activeSubtoolInfo().visible) return;
if (ImGui::GetIO().WantCaptureMouse) return;
@@ -253,13 +380,21 @@ void App::drawZSphereOverlay() {
if (!cr.contains(mouseX_, mouseY_)) return;
const bool dragging = drag_ == Drag::ZSphere;
if (drag_ != Drag::None && !dragging) return;
+ ImDrawList* dl = ImGui::GetBackgroundDrawList();
+ const float s = uiScale_;
+ if (const int sel = zsphereSelection(); sel >= 0 && !dragging) { // the selected sphere, in orange
+ const ZSphere& z = doc_.mesh.zspheres[size_t(sel)];
+ ImVec2 c;
+ const float wpp = worldPerPixel(z.center);
+ dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);
+ if (gizmoProject(z.center, c) && wpp > 0.0f) dl->AddCircle(c, z.radius / wpp + 2.0f * s, IM_COL32(255, 170, 60, 220), 64, 2.0f * s);
+ dl->PopClipRect();
+ }
bool link = false;
const int i = dragging ? zsDrag_.sphere : zsphereAt(mouseX_, mouseY_, &link);
if (i < 0 || size_t(i) >= doc_.mesh.zspheres.size()) return;
const bool alt = !dragging && (inputMods() & SDL_KMOD_ALT);
- ImDrawList* dl = ImGui::GetBackgroundDrawList();
dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);
- const float s = uiScale_;
const ImU32 col = alt ? IM_COL32(255, 90, 80, 230) : IM_COL32(120, 200, 255, 230);
if (link && !dragging) { // Draw: the joint a click would add
const ZSphere& c = doc_.mesh.zspheres[size_t(i)];
diff --git a/src/app/Shell.cpp b/src/app/Shell.cpp
index e0c4a2c6..7e35bf35 100644
--- a/src/app/Shell.cpp
+++ b/src/app/Shell.cpp
@@ -366,6 +366,14 @@ void App::registerShellActions() {
flag("draw.rgb", "Rgb", nullptr, "Draw", "", &paintRgb_, "Sculpt brushes also paint the colour (ZBrush Rgb with Zadd).");
flag("draw.front_faces", "Front", nullptr, "Brush", "", &frontFacesOnly_,
"Front faces only: brushes leave the far side of thin parts alone.");
+ flag("draw.connected_only", "Connected only", nullptr, "Brush", "", &uiPrefs_.connectedOnly,
+ "Brushes only reach the surface joined to the point under the cursor, within the brush size: the other leg, "
+ "the next finger or a lip across a gap stay as they are (Blender's Connected Only). Saved with the "
+ "preferences and the project.");
+ flag("draw.view_falloff", "View falloff", nullptr, "Brush", "", &uiPrefs_.viewFalloff,
+ "The brush falloff is measured on screen: everything inside the brush circle is reached, through the model "
+ "and out the back, as a cylinder along the view (Blender's Projected from View). Turn on Connected only too "
+ "to keep it to one piece.");
add({"draw.dynamic", "Dynamic", nullptr,
"Dynamic topology (ZBrush's Sculptris Pro): brushes add triangles where they need detail and remove them "
"where they don't, so you can pull out horns or fingers without stretching. Detail sets how small the "
diff --git a/src/app/Tablet.cpp b/src/app/Tablet.cpp
index dcbc8de0..4654267e 100644
--- a/src/app/Tablet.cpp
+++ b/src/app/Tablet.cpp
@@ -198,7 +198,9 @@ SDL_Keymod App::inputMods() const {
if (blenderStyle()) mods = blenderMods(mods); // Blender's Ctrl inverts, its Mask brush masks (Input.cpp)
if (mayaStyle()) { // Maya: Ctrl inverts (as ZBrush's Alt), Ctrl+Alt masks (as ZBrush's Ctrl)
const bool ctrl = (mods & SDL_KMOD_CTRL) != 0, alt = (mods & SDL_KMOD_ALT) != 0, shift = (mods & SDL_KMOD_SHIFT) != 0;
- if (ctrl && alt) mods = SDL_Keymod((mods & ~SDL_KMOD_ALT) | SDL_KMOD_LCTRL);
+ // Ctrl+Alt+Shift erases the mask (#32): ZBrush's Ctrl+Alt, not Ctrl+Shift (visibility).
+ if (ctrl && alt && shift) mods = SDL_Keymod((mods & ~SDL_KMOD_SHIFT) | SDL_KMOD_LCTRL | SDL_KMOD_LALT);
+ else if (ctrl && alt) mods = SDL_Keymod((mods & ~SDL_KMOD_ALT) | SDL_KMOD_LCTRL);
else if (ctrl && !shift) mods = SDL_Keymod((mods & ~SDL_KMOD_CTRL) | SDL_KMOD_LALT);
}
for (int b = 1; b <= kPenButtons; ++b) {
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index a8b0d679..55ea46da 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -405,6 +405,23 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "guides_mode") return app_.guidesMode_ ? 1.0 : 0.0;
if (name == "zspheres") return double(m.zspheres.size());
if (name == "zsphere_preview") return m.zspherePreview ? 1.0 : 0.0;
+ if (name == "zsphere_selected") return double(app_.zsphereSelection());
+ if (name == "zsphere_menu") return app_.zsMenuShown_ ? 1.0 : 0.0;
+ if (name == "zsphere_place_child") return app_.zspherePlaceChild_ ? 1.0 : 0.0;
+ if (name.rfind("zsphere_out", 0) == 0) { // zsphere_out2: how far sphere 2 is from its parent, in the parent's radii
+ const size_t i = size_t(std::atoi(name.c_str() + 11));
+ if (i == 0 || i >= m.zspheres.size()) return -1.0;
+ const ZSphere& p = m.zspheres[size_t(m.zspheres[i].parent)];
+ return double(glm::distance(m.zspheres[i].center, p.center) / p.radius);
+ }
+ if (name == "zsphere_root_x") return m.zspheres.empty() ? 0.0 : double(m.zspheres[0].center.x);
+ if (name == "connected_only") return app_.uiPrefs_.connectedOnly ? 1.0 : 0.0;
+ if (name == "view_falloff") return app_.uiPrefs_.viewFalloff ? 1.0 : 0.0;
+ if (name == "smooth_remesh") return std::round(app_.doc_.sculptor.dyntopo.smoothRemesh * 100.0f);
+ if (name == "invert_zoom") return app_.uiPrefs_.invertZoom ? 1.0 : 0.0;
+ if (name == "maya_zoom_horizontal") return app_.uiPrefs_.mayaZoomHorizontal ? 1.0 : 0.0;
+ if (name == "along_normal") return double(app_.uiPrefs_.alongNormal);
+ if (name == "stroke_along_normal") return app_.strokeAlongNormal_ ? 1.0 : 0.0;
if (name.rfind("zsphere_x", 0) == 0 || name.rfind("zsphere_r", 0) == 0) { // zsphere_x2, zsphere_r2: sphere 2's x / radius
const size_t i = size_t(std::atoi(name.c_str() + 9));
if (i >= m.zspheres.size()) return -1.0;
diff --git a/src/core/BVH.cpp b/src/core/BVH.cpp
index 78c58942..d8d1149f 100644
--- a/src/core/BVH.cpp
+++ b/src/core/BVH.cpp
@@ -281,19 +281,19 @@ void BVH::forEachLeafInSphere(const glm::vec3& center, float radius,
}
}
-void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) const {
+template <class Shape>
+void BVH::queryVerticesIn(const Mesh& mesh, const Shape& shape, std::vector<uint32_t>& out) const {
out.clear();
queryLeaves_.clear();
if (nodes_.empty()) return;
if (vertBits_.capacity() < mesh.vertexCount()) vertBits_.resize(mesh.vertexCount());
- const float r2 = radius * radius;
// The units of parallel work: the subtrees the sphere touches, split breadth first until there are enough
// of them (the same ones for any thread count).
constexpr size_t kTasks = 128, kSerialTriangles = 16384;
std::vector<uint32_t>& tasks = queryTasks_;
tasks.clear();
- if (sphereBox(nodes_[0].box, center, r2)) tasks.push_back(0);
+ if (shape.touches(nodes_[0].box)) tasks.push_back(0);
int depth = 0; // of every inner node in `tasks` (median splits: each holds about nt >> depth triangles)
for (bool split = true; split && tasks.size() < kTasks; ++depth) {
split = false;
@@ -306,7 +306,7 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,
}
split = true;
for (uint32_t c : {n.first, n.first + 1})
- if (sphereBox(nodes_[c].box, center, r2)) queryNext_.push_back(c);
+ if (shape.touches(nodes_[c].box)) queryNext_.push_back(c);
}
tasks.swap(queryNext_);
}
@@ -318,13 +318,13 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,
const uint32_t ni = nodeStack.back();
const Node& n = nodes_[ni];
nodeStack.pop_back();
- if (!sphereBox(n.box, center, r2) || (n.count == 0 && n.first == kNoLeaf)) continue;
+ if (!shape.touches(n.box) || (n.count == 0 && n.first == kNoLeaf)) continue;
if (n.count == 0) {
nodeStack.push_back(n.first);
nodeStack.push_back(n.first + 1);
continue;
}
- if (boxInSphere(n.box, center, r2)) { // every corner is inside
+ if (shape.containsBox(n.box)) { // every corner is inside
for (uint32_t i = n.first; i < n.first + n.count; ++i) {
const auto& t = mesh.triangles[triIndices_[i]];
found.insertLocal(t.x);
@@ -343,8 +343,7 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,
any = true;
continue;
}
- const glm::vec3 d = mesh.positions[v] - center;
- if (glm::dot(d, d) <= r2) {
+ if (shape.contains(mesh.positions[v])) {
found.insertLocal(v);
any = true;
}
@@ -374,6 +373,56 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,
vertBits_.take(out);
}
+namespace {
+
+struct SphereShape {
+ glm::vec3 c;
+ float r2;
+ bool touches(const AABB& b) const { return sphereBox(b, c, r2); }
+ bool containsBox(const AABB& b) const { return boxInSphere(b, c, r2); }
+ bool contains(const glm::vec3& p) const { return glm::dot(p - c, p - c) <= r2; }
+};
+
+// An infinite cylinder: the points within sqrt(r2) of the line through c along the unit vector a.
+struct CylinderShape {
+ glm::vec3 c, a;
+ float r, r2;
+ float dist2(const glm::vec3& p) const {
+ const glm::vec3 d = p - c;
+ const glm::vec3 off = d - a * glm::dot(d, a);
+ return glm::dot(off, off);
+ }
+ bool touches(const AABB& b) const { // conservative: the box's bounding sphere against the cylinder
+ const glm::vec3 mid = (b.min + b.max) * 0.5f;
+ const float reach = r + glm::length(b.max - mid);
+ return dist2(mid) <= reach * reach;
+ }
+ bool containsBox(const AABB& b) const {
+ for (int k = 0; k < 8; ++k) {
+ const glm::vec3 p((k & 1) ? b.max.x : b.min.x, (k & 2) ? b.max.y : b.min.y, (k & 4) ? b.max.z : b.min.z);
+ if (dist2(p) > r2) return false;
+ }
+ return true;
+ }
+ bool contains(const glm::vec3& p) const { return dist2(p) <= r2; }
+};
+
+} // namespace
+
+void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) const {
+ queryVerticesIn(mesh, SphereShape{center, radius * radius}, out);
+}
+
+void BVH::queryVerticesCylinder(const Mesh& mesh, const glm::vec3& point, const glm::vec3& axis, float radius,
+ std::vector<uint32_t>& out) const {
+ const float len = glm::length(axis);
+ if (!(len > 1e-12f)) {
+ queryVertices(mesh, point, radius, out);
+ return;
+ }
+ queryVerticesIn(mesh, CylinderShape{point, axis / len, radius, radius * radius}, out);
+}
+
void BVH::refit(const Mesh& mesh, std::span<const uint32_t> movedVerts) {
if (nodes_.empty()) return;
if (leafBits_.capacity() < nodes_.size()) leafBits_.resize(nodes_.size());
diff --git a/src/core/BVH.h b/src/core/BVH.h
index 1ff0c02f..d74922c0 100644
--- a/src/core/BVH.h
+++ b/src/core/BVH.h
@@ -28,6 +28,10 @@ public:
// Appends every vertex within `radius` of `center` to `out` (cleared first), in increasing index order.
// Ignores visibility; brushes use sf::brushVertices, which filters hidden ones.
void queryVertices(const Mesh& mesh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) const;
+ // queryVertices for an infinite cylinder: every vertex within `radius` of the line through `point` along
+ // `axis` (a brush whose falloff is measured on screen reaches through the model along the view).
+ void queryVerticesCylinder(const Mesh& mesh, const glm::vec3& point, const glm::vec3& axis, float radius,
+ std::vector<uint32_t>& out) const;
// Appends every triangle whose bounds touch the sphere (cleared first; hidden ones included).
void queryTriangles(const Mesh& mesh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) const;
// Calls fn(triangles of the leaf) for every leaf whose box touches the sphere (hidden triangles included);
@@ -98,6 +102,8 @@ private:
void refitAncestors(std::span<const uint32_t> leaves); // refitLeaves for many leaves, in parallel
void splitLeaf(const Mesh& mesh, uint32_t leaf);
+ template <class Shape>
+ void queryVerticesIn(const Mesh& mesh, const Shape& shape, std::vector<uint32_t>& out) const;
mutable IndexBits vertBits_; // queryVertices: the vertices found so far
mutable std::vector<uint32_t> queryLeaves_; // the leaves holding them, for refitQueried()
mutable std::vector<uint32_t> queryTasks_, queryNext_;
diff --git a/src/core/BrushRecipe.cpp b/src/core/BrushRecipe.cpp
index cbdb39bf..297189b6 100644
--- a/src/core/BrushRecipe.cpp
+++ b/src/core/BrushRecipe.cpp
@@ -138,6 +138,8 @@ Json BrushRecipe::toJson() const {
Json j = Json::object();
j.set("name", r.name);
j.set("description", r.description);
+ if (connectedOnly) j.set("connectedOnly", true);
+ if (viewFalloff) j.set("viewFalloff", true);
for (const auto& p : recipeParams()) {
switch (p.kind) {
case K::Float: j.set(p.key, std::round(double(*floatField(r, p.key)) * 1000.0) / 1000.0); break;
@@ -156,6 +158,8 @@ void BrushRecipe::applyJson(const Json& j) {
if (!j.isObject()) return;
if (j["name"].isString()) name = j["name"].asString();
if (j["description"].isString()) description = j["description"].asString();
+ if (j["connectedOnly"].isBool()) connectedOnly = j["connectedOnly"].asBool();
+ if (j["viewFalloff"].isBool()) viewFalloff = j["viewFalloff"].asBool();
for (const auto& p : recipeParams()) {
const Json& v = j[p.key];
if (v.isNull()) continue;
diff --git a/src/core/BrushRecipe.h b/src/core/BrushRecipe.h
index ddcfe37d..21b5087d 100644
--- a/src/core/BrushRecipe.h
+++ b/src/core/BrushRecipe.h
@@ -66,6 +66,10 @@ struct BrushRecipe {
// Masking
bool frontFacesOnly = false;
+ // Falloff options (DabParams::connectedOnly / viewFalloff), on with the app's own or on their own. Written to
+ // the recipe's JSON only when on, so other recipes' files stay as they were.
+ bool connectedOnly = false;
+ bool viewFalloff = false;
float cavityMask = 0.0f; // -1..1: >0 only affects cavities, <0 only ridges/peaks
// Library bookkeeping, not part of the recipe: never written by toJson().
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 84b608df..fd5ba176 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -28,6 +28,7 @@
#include "core/Project.h"
#include "core/QRemesh.h"
#include "core/ZSpheres.h"
+#include "core/Deform.h"
#include "core/Sculptable.h"
#include "core/Splats.h"
#include "core/TextureTransfer.h"
@@ -562,6 +563,13 @@ CommandRegistry::CommandRegistry() {
: T::String;
params.push_back({rp.key, type, rp.help, false});
}
+ params.push_back({"connectedOnly", T::Bool,
+ "Only reach the surface joined to the point under the cursor (the other leg, the next finger "
+ "stay). Default false.",
+ false});
+ params.push_back({"viewFalloff", T::Bool,
+ "Measure the falloff on screen: a cylinder through the model along the view. Default false.",
+ false});
add({"brush_create",
"Create (or update, by name) a custom sculpting brush from a recipe and make it the active brush. "
"Omitted parameters use neutral defaults.",
@@ -618,6 +626,7 @@ CommandRegistry::CommandRegistry() {
registerRetopoCommands(*this); // qremesh, project_all (RetopoCommands.cpp)
registerQRemeshGuideCommands(*this); // qremesh_guide, ... (QRemeshGuides.cpp)
registerZSphereCommands(*this); // zsphere_new, ... (ZSpheres.cpp)
+ registerDeformCommands(*this); // deform_polish, deform_relax, deform_smooth, deform_balloon (Deform.cpp)
add({"stroke",
"Apply a brush along a path on the active Part, like dragging the cursor in the viewport (one undo "
diff --git a/src/core/Deform.cpp b/src/core/Deform.cpp
new file mode 100644
index 00000000..3d4b43ef
--- /dev/null
+++ b/src/core/Deform.cpp
@@ -0,0 +1,279 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Deform.h"
+
+#include "core/Commands.h"
+#include "core/Document.h"
+#include "core/ThreadPool.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+const char* deformName(DeformOp op) {
+ switch (op) {
+ case DeformOp::Polish: return "Polish";
+ case DeformOp::Relax: return "Relax";
+ case DeformOp::Smooth: return "Smooth";
+ case DeformOp::Balloon: return "Balloon";
+ }
+ return "Deform";
+}
+
+namespace {
+
+using glm::vec3;
+
+constexpr size_t kGrain = 2048;
+
+// How much each vertex may move: 0 when hidden, on an open border (or a non-manifold one) or unconnected;
+// otherwise 1 - mask (1 with useMask off).
+std::vector<float> freedom(const Mesh& m, bool useMask) {
+ std::vector<float> k(m.vertexCount(), 0.0f);
+ poolFor(k.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const uint32_t v = uint32_t(i);
+ const IndexRing ring = m.neighbors(v);
+ if (ring.empty() || ring.size() != m.vertexTriangles(v).size()) continue; // a border: n neighbours, n-1 faces
+ if (m.hasHidden() && m.vertexHidden(v)) continue;
+ k[i] = useMask ? 1.0f - m.maskAt(v) : 1.0f;
+ }
+ }, kGrain);
+ return k;
+}
+
+// Area-weighted vertex normals of the surface at positions P.
+void normalsOf(const Mesh& m, const std::vector<vec3>& P, std::vector<vec3>& N) {
+ N.resize(P.size());
+ poolFor(P.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ vec3 n(0.0f);
+ for (uint32_t t : m.vertexTriangles(uint32_t(i))) {
+ const glm::uvec3& f = m.triangles[t];
+ n += glm::cross(P[f.y] - P[f.x], P[f.z] - P[f.x]);
+ }
+ const float l = glm::length(n);
+ N[i] = l > 1e-30f ? n / l : vec3(0.0f);
+ }
+ }, kGrain);
+}
+
+vec3 laplacian(const Mesh& m, const std::vector<vec3>& P, uint32_t v) {
+ const IndexRing ring = m.neighbors(v);
+ vec3 avg(0.0f);
+ for (uint32_t n : ring) avg += P[n];
+ return avg / float(ring.size()) - P[v];
+}
+
+// One Jacobi step: Q[v] = P[v] + k[v] * step(v) for the vertices that may move.
+template <class F>
+void step(const std::vector<float>& k, std::vector<vec3>& P, std::vector<vec3>& Q, F&& delta) {
+ Q.resize(P.size());
+ poolFor(P.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) Q[i] = k[i] > 0.0f ? P[i] + delta(uint32_t(i)) * k[i] : P[i];
+ }, kGrain);
+ P.swap(Q);
+}
+
+// The amount as passes: `most` passes at 100, each a fraction of a full one so the total is proportional.
+void passes(float amount, int most, int& count, float& each) {
+ const float t = std::clamp(std::abs(amount), 0.0f, 100.0f) / 100.0f * float(most);
+ count = int(std::ceil(t - 1e-4f));
+ each = count > 0 ? t / float(count) : 0.0f;
+}
+
+} // namespace
+
+std::vector<vec3> deformPositions(const Mesh& m, DeformOp op, const DeformOptions& o) {
+ std::vector<vec3> P = m.positions, Q, N;
+ if (m.vertexCount() == 0 || m.triangleCount() == 0) return P;
+ const std::vector<float> k = freedom(m, o.useMask);
+ int count = 0;
+ float each = 0.0f;
+ switch (op) {
+ case DeformOp::Smooth: {
+ passes(o.amount, 20, count, each);
+ const float lambda = 0.5f * each;
+ // Taubin: mu from lambda and the pass-band frequency 0.1 (1/lambda + 1/mu = 0.1), a little stronger back.
+ const float mu = 1.0f / (0.1f - 1.0f / std::max(lambda, 1e-3f));
+ for (int i = 0; i < count; ++i) {
+ step(k, P, Q, [&](uint32_t v) { return laplacian(m, P, v) * lambda; });
+ if (o.keepVolume) step(k, P, Q, [&](uint32_t v) { return laplacian(m, P, v) * mu; });
+ }
+ break;
+ }
+ case DeformOp::Relax: {
+ passes(o.amount, 20, count, each);
+ const float lambda = 0.5f * each;
+ for (int i = 0; i < count; ++i) {
+ normalsOf(m, P, N);
+ step(k, P, Q, [&](uint32_t v) {
+ const vec3 l = laplacian(m, P, v);
+ return (l - N[v] * glm::dot(N[v], l)) * lambda; // along the surface only
+ });
+ }
+ break;
+ }
+ case DeformOp::Polish: {
+ // Bilateral normal filtering (Zheng et al. 2011): each face's normal becomes a weighted average of the
+ // normals of the faces around it, weighted down by distance and, steeply, by how different they are, so
+ // the small tilts of noise average out while the faces across an edge or corner don't count. Then the
+ // vertices move to fit the filtered normals (Sun et al. 2007), which keeps edges where they are.
+ passes(o.amount, 6, count, each);
+ const size_t nt = m.triangleCount();
+ std::vector<vec3> fn(nt), fc(nt), filtered(nt);
+ std::vector<float> fa(nt);
+ auto faces = [&] {
+ poolFor(nt, [&](size_t b, size_t e) {
+ for (size_t t = b; t < e; ++t) {
+ const glm::uvec3& f = m.triangles[t];
+ const vec3 c = glm::cross(P[f.y] - P[f.x], P[f.z] - P[f.x]);
+ const float l = glm::length(c);
+ fa[t] = 0.5f * l;
+ fn[t] = l > 1e-30f ? c / l : vec3(0.0f);
+ fc[t] = (P[f.x] + P[f.y] + P[f.z]) / 3.0f;
+ }
+ }, kGrain);
+ };
+ constexpr float kSigmaNormal = 0.35f; // |n_f - n_g| of a 20 degree tilt; a 90 degree edge is 1.41
+ for (int i = 0; i < count; ++i) {
+ faces();
+ poolFor(nt, [&](size_t b, size_t e) {
+ for (size_t t = b; t < e; ++t) {
+ const glm::uvec3& f = m.triangles[t];
+ // The faces sharing a corner with t (some twice, which only weighs them a little more).
+ float spacing = 0.0f;
+ for (int c = 0; c < 3; ++c) spacing += glm::distance(P[f[c]], fc[t]);
+ spacing = std::max(spacing / 3.0f * 2.0f, 1e-20f);
+ vec3 sum(0.0f);
+ for (int c = 0; c < 3; ++c)
+ for (uint32_t g : m.vertexTriangles(f[c])) {
+ const vec3 dn = fn[g] - fn[t];
+ const vec3 dc = fc[g] - fc[t];
+ const float w = fa[g] * std::exp(-glm::dot(dc, dc) / (2.0f * spacing * spacing)) *
+ std::exp(-glm::dot(dn, dn) / (2.0f * kSigmaNormal * kSigmaNormal));
+ sum += fn[g] * w;
+ }
+ const float l = glm::length(sum);
+ filtered[t] = l > 1e-30f ? sum / l : fn[t];
+ }
+ }, kGrain);
+ for (int fit = 0; fit < 3; ++fit) {
+ if (fit > 0) faces();
+ step(k, P, Q, [&](uint32_t v) {
+ vec3 d(0.0f);
+ const IndexRing tris = m.vertexTriangles(v);
+ for (uint32_t t : tris) d += filtered[t] * glm::dot(filtered[t], fc[t] - P[v]);
+ return d * (each / float(tris.size()));
+ });
+ }
+ }
+ break;
+ }
+ case DeformOp::Balloon: {
+ passes(o.amount, 10, count, each);
+ const float diagonal = glm::length(m.bounds().extent());
+ const float push = (o.amount < 0.0f ? -1.0f : 1.0f) * 0.01f * diagonal * each;
+ for (int i = 0; i < count; ++i) {
+ normalsOf(m, P, N);
+ // Out along the normal, then the skin pulls taut (a Laplacian step): flat sides bulge, corners round.
+ step(k, P, Q, [&](uint32_t v) { return N[v] * push; });
+ step(k, P, Q, [&](uint32_t v) { return laplacian(m, P, v) * (0.5f * each); });
+ }
+ break;
+ }
+ }
+ return P;
+}
+
+size_t deformActivePart(Document& doc, DeformOp op, const DeformOptions& o, std::string& error) {
+ Mesh& mesh = doc.mesh;
+ const std::string name = deformName(op);
+ if (doc.sculptor.strokeActive()) {
+ error = name + ": finish the stroke first";
+ return 0;
+ }
+ if (mesh.vertexCount() == 0 || mesh.triangleCount() == 0) {
+ error = name + ": the active Part is empty";
+ return 0;
+ }
+ if (!mesh.zspheres.empty()) {
+ error = name + ": the active Part is a Forge Sphere Part (Make Mesh first)";
+ return 0;
+ }
+ if (mesh.micro) {
+ error = name + ": the active Part has a micro level (Bake Micro or Delete Micro first)";
+ return 0;
+ }
+ doc.syncBvh();
+ const std::vector<vec3> P = deformPositions(mesh, op, o);
+ std::vector<uint32_t> verts;
+ std::vector<vec3> d;
+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {
+ const vec3 dv = P[v] - mesh.positions[v];
+ if (dv != vec3(0.0f) && std::isfinite(dv.x + dv.y + dv.z)) {
+ verts.push_back(v);
+ d.push_back(dv);
+ }
+ }
+ if (verts.empty()) {
+ error = name + ": nothing moved" + (o.useMask && mesh.hasMask() ? " (is everything masked?)" : "");
+ return 0;
+ }
+ if (!doc.sculptor.beginStroke(mesh, name, doc.activeLayer)) {
+ error = name + ": the active layer's weight is 0";
+ return 0;
+ }
+ doc.sculptor.moveVertices(mesh, doc.bvh, verts, d);
+ UndoRecord r = doc.sculptor.endStroke();
+ if (!r.empty()) doc.undo.push(std::move(r));
+ return verts.size();
+}
+
+void registerDeformCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+ struct Spec {
+ const char* name;
+ DeformOp op;
+ const char* what;
+ };
+ static const Spec kSpecs[] = {
+ {"deform_polish", DeformOp::Polish,
+ "Polish the active Part: flatten fine noise and small bumps while keeping flat areas and sharp edges."},
+ {"deform_relax", DeformOp::Relax,
+ "Relax the active Part: even out the spacing of its vertices along the surface without changing its shape."},
+ {"deform_smooth", DeformOp::Smooth,
+ "Smooth the whole active Part (Laplacian; keep_volume=true for Taubin smoothing, which doesn't shrink it)."},
+ {"deform_balloon", DeformOp::Balloon,
+ "Balloon (ZBrush users: Inflate Balloon): fill the active Part out toward a rounder volume; a negative "
+ "amount lets the air out."},
+ };
+ for (const Spec& sp : kSpecs) {
+ std::vector<ParamSpec> params = {
+ {"amount", T::Number,
+ sp.op == DeformOp::Balloon ? "How much, -100 to 100 (default 50)." : "How much, 0 to 100 (default 50).",
+ false},
+ {"masked", T::Bool, "Masked parts stay (default true; false ignores the mask).", false}};
+ if (sp.op == DeformOp::Smooth) params.push_back({"keep_volume", T::Bool, "Taubin smoothing (default false).", false});
+ const DeformOp op = sp.op;
+ reg.add({sp.name,
+ std::string(sp.what) + " Mask-aware (partly masked vertices move partly), hidden faces and open "
+ "borders stay; one undo step.",
+ params, [op](Document& doc, const Args& a) -> CommandResult {
+ DeformOptions o;
+ const double lo = op == DeformOp::Balloon ? -100.0 : 0.0;
+ o.amount = float(std::clamp(argNumber(a, "amount", 50.0), lo, 100.0));
+ o.useMask = argBool(a, "masked", true);
+ o.keepVolume = argBool(a, "keep_volume", false);
+ if (o.amount == 0.0f) return {true, std::string(deformName(op)) + ": amount 0, nothing to do"};
+ std::string err;
+ const size_t moved = deformActivePart(doc, op, o, err);
+ if (moved == 0) return {false, err};
+ return {true, std::string(deformName(op)) + " " + std::to_string(int(std::lround(o.amount))) + ": moved " +
+ std::to_string(moved) + " vertices"};
+ }});
+ }
+}
+
+} // namespace sf
diff --git a/src/core/Deform.h b/src/core/Deform.h
new file mode 100644
index 00000000..8d25c6f0
--- /dev/null
+++ b/src/core/Deform.h
@@ -0,0 +1,48 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Whole-mesh deformations (Tool > Deformation, from the discussions): Polish, Relax, Smooth and Balloon, each over
+// the whole active Part with an amount, the mask holding masked parts in place (partly masked ones move partly),
+// hidden faces and open borders kept, and one undo step. They write through the Sculptor, so a sculpt layer that
+// is being recorded takes the change as a stroke would.
+// Polish - flattens fine noise while keeping planes and sharp edges: each vertex moves along its normal by a
+// bilateral average of its neighbours' heights (Fleishman, Drori and Cohen-Or 2003, one ring), so
+// small bumps average out and big steps (edges) barely count.
+// Relax - evens out the spacing of the vertices along the surface without changing its shape: the Laplacian
+// step with its normal part removed.
+// Smooth - Laplacian smoothing; with keepVolume, Taubin's lambda | mu steps, which don't shrink the form.
+// Balloon - pushes the surface out along its normals with a little smoothing each step, so the form fills out
+// toward a rounder volume (a negative amount lets the air out).
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class CommandRegistry;
+struct Document;
+
+enum class DeformOp { Polish, Relax, Smooth, Balloon };
+const char* deformName(DeformOp op); // "Polish", "Relax", "Smooth", "Balloon"
+
+struct DeformOptions {
+ float amount = 50.0f; // 0-100 (Balloon -100..100)
+ bool keepVolume = false; // Smooth: Taubin smoothing
+ bool useMask = true; // false: the mask is ignored (hidden faces are still kept)
+};
+
+// The positions `mesh` gets from `op` (the mesh is left alone); every vertex, in order. Deterministic (the same
+// result for any thread count).
+std::vector<glm::vec3> deformPositions(const Mesh& mesh, DeformOp op, const DeformOptions& options);
+
+// Runs `op` on the active Part of `doc` as one undo step. Returns how many vertices moved (0 with `error` set when
+// nothing could: an empty Part, everything masked, a micro level, a stroke in progress).
+size_t deformActivePart(Document& doc, DeformOp op, const DeformOptions& options, std::string& error);
+
+// deform_polish, deform_relax, deform_smooth, deform_balloon.
+void registerDeformCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/Dyntopo.h b/src/core/Dyntopo.h
index da677eea..030782d3 100644
--- a/src/core/Dyntopo.h
+++ b/src/core/Dyntopo.h
@@ -27,6 +27,7 @@
#include <glm/glm.hpp>
+#include <algorithm>
#include <cstdint>
#include <memory>
#include <span>
@@ -42,8 +43,17 @@ struct DyntopoSettings {
// true: one detail size for the whole mesh, relative to its size.
bool constantDetail = false;
float detail = 0.5f; // 0 (coarse) .. 1 (fine)
+ // How much Smooth (Shift) remeshes while dynamic topology is on (from the discussions): 0 = smooth only, the
+ // topology stays; 1 (the default, as before) = it remeshes toward twice the edge length, so smoothing also
+ // simplifies. In between it remeshes toward 1 + smoothRemesh times the edge length.
+ float smoothRemesh = 1.0f;
};
+// The edge-length scale Smooth remeshes with (0 = it doesn't remesh): 1 + smoothRemesh, as above.
+inline float dyntopoSmoothScale(const DyntopoSettings& s) {
+ return s.smoothRemesh <= 0.005f ? 0.0f : 1.0f + std::min(s.smoothRemesh, 1.0f);
+}
+
// The edge length dabs of world radius `radius` remesh towards, on a mesh whose bounding box diagonal is `diagonal`.
float dyntopoEdgeLength(const DyntopoSettings& s, float radius, float diagonal);
diff --git a/src/core/DyntopoCommands.cpp b/src/core/DyntopoCommands.cpp
index 581c2f32..d0375b3d 100644
--- a/src/core/DyntopoCommands.cpp
+++ b/src/core/DyntopoCommands.cpp
@@ -11,7 +11,11 @@ namespace sf {
std::string dyntopoSummary(const DyntopoSettings& s) {
const int detail = int(std::lround(std::clamp(s.detail, 0.0f, 1.0f) * 100.0f));
return std::string("Dynamic topology ") + (s.enabled ? "on" : "off") + ": Detail " + std::to_string(detail) +
- (s.constantDetail ? " (one size for the whole mesh)" : " (follows the brush size)");
+ (s.constantDetail ? " (one size for the whole mesh)" : " (follows the brush size)") +
+ (s.smoothRemesh <= 0.005f ? "; Smooth leaves the topology alone"
+ : s.smoothRemesh >= 0.995f
+ ? ""
+ : "; Smooth remeshes " + std::to_string(int(std::lround(s.smoothRemesh * 100.0f))) + "%");
}
void registerDyntopoCommands(CommandRegistry& registry) {
@@ -26,6 +30,10 @@ void registerDyntopoCommands(CommandRegistry& registry) {
{"constant", T::Bool,
"false (default) = the triangle size follows the brush size on screen (zoom in or shrink the brush "
"for finer detail); true = one size for the whole mesh, set by Detail.",
+ false},
+ {"smooth_remesh", T::Number,
+ "0-100: how much Smooth (Shift) remeshes while on. 0 = smooth only, the topology stays; 100 "
+ "(default) = it simplifies toward larger triangles as it smooths.",
false}},
[](Document& doc, const Args& a) -> CommandResult {
DyntopoSettings& s = doc.sculptor.dyntopo;
@@ -36,6 +44,8 @@ void registerDyntopoCommands(CommandRegistry& registry) {
}
if (a.count("detail")) s.detail = float(std::clamp(argNumber(a, "detail", 50.0), 0.0, 100.0) / 100.0);
s.constantDetail = argBool(a, "constant", s.constantDetail);
+ if (a.count("smooth_remesh"))
+ s.smoothRemesh = float(std::clamp(argNumber(a, "smooth_remesh", 100.0), 0.0, 100.0) / 100.0);
s.enabled = enable;
return {true, dyntopoSummary(s)};
}});
diff --git a/src/core/Masking.cpp b/src/core/Masking.cpp
index 1a042e8c..04048b72 100644
--- a/src/core/Masking.cpp
+++ b/src/core/Masking.cpp
@@ -336,7 +336,7 @@ void Sculptor::dabMask(Mesh& mesh, const BVH& bvh, const DabParams& p, Symmetry
std::vector<float>& mask = mesh.ensureMask();
for (const SymCopy& mirror : copies(sym)) {
const glm::vec3 center = mirror.point(p.center), viewDir = mirror.dir(p.viewDir);
- brushVertices(mesh, bvh, center, p.radius, verts_);
+ brushRegion(mesh, bvh, center, viewDir, p.radius, p.connectedOnly, p.viewFalloff, verts_, connected_);
// New values in parallel; recording and writing them in order.
weights_.resize(verts_.size());
poolFor(verts_.size(), [&](size_t b, size_t e) {
@@ -344,7 +344,7 @@ void Sculptor::dabMask(Mesh& mesh, const BVH& bvh, const DabParams& p, Symmetry
const uint32_t v = verts_[i];
weights_[i] = -1.0f; // unchanged
if (p.frontFacesOnly && glm::dot(mesh.normals[v], viewDir) > 0.0f) continue;
- const float a = s * brushFalloff(glm::distance(mesh.positions[v], center), p.radius, p.focal);
+ const float a = s * brushFalloff(brushDistance(mesh.positions[v], center, viewDir, p.viewFalloff), p.radius, p.focal);
if (a <= 0.0f) continue;
const float m = p.invert ? mask[v] * (1.0f - a) : mask[v] + (1.0f - mask[v]) * a;
if (m != mask[v]) weights_[i] = m;
diff --git a/src/core/Polypaint.cpp b/src/core/Polypaint.cpp
index 3f8f267f..6fd63df8 100644
--- a/src/core/Polypaint.cpp
+++ b/src/core/Polypaint.cpp
@@ -125,10 +125,12 @@ size_t paintDab(Sculptor& sculptor, Mesh& mesh, const BVH& bvh, const DabParams&
size_t changed = 0;
for (const SymCopy& m : Sculptor::copies(sym)) {
const glm::vec3 center = m.point(p.center), viewDir = m.dir(p.viewDir);
- brushVertices(mesh, bvh, center, p.radius, verts);
+ static thread_local ConnectedScratch connected;
+ brushRegion(mesh, bvh, center, viewDir, p.radius, p.connectedOnly, p.viewFalloff, verts, connected);
for (uint32_t v : verts) {
if (p.frontFacesOnly && v < mesh.normals.size() && glm::dot(mesh.normals[v], viewDir) > 0.0f) continue;
- const float w = brushFalloff(glm::distance(mesh.positions[v], center), p.radius, p.focal) * s * vertexInfluence(mesh, v);
+ const float w = brushFalloff(brushDistance(mesh.positions[v], center, viewDir, p.viewFalloff), p.radius, p.focal) * s *
+ vertexInfluence(mesh, v);
if (w <= 0.0f) continue;
sculptor.recordColor(mesh, v);
paintVertex(mesh, v, color, w, p.invert); // Alt paints Base back to white, erases a layer
diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cpp
index d6d3cb04..7354f0ad 100644
--- a/src/core/Sculpt.cpp
+++ b/src/core/Sculpt.cpp
@@ -9,6 +9,7 @@
#include <algorithm>
#include <cctype>
#include <cmath>
+#include <limits>
#include <unordered_map>
namespace sf {
@@ -89,6 +90,72 @@ void brushVertices(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, fl
if (mesh.hasHidden()) std::erase_if(out, [&](uint32_t v) { return mesh.vertexHidden(v); });
}
+glm::vec3 brushAreaNormal(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, float radius, float focal) {
+ std::vector<uint32_t> verts;
+ brushVertices(mesh, bvh, center, radius, verts);
+ glm::vec3 n(0.0f);
+ for (uint32_t v : verts)
+ if (v < mesh.normals.size()) n += mesh.normals[v] * brushFalloff(glm::distance(mesh.positions[v], center), radius, focal);
+ const float l = glm::length(n);
+ return l > 1e-20f ? n / l : glm::vec3(0.0f);
+}
+
+bool lineRayClosest(const glm::vec3& point, const glm::vec3& dir, const glm::vec3& origin, const glm::vec3& rayDir,
+ float& s, float minSine) {
+ const float rl = glm::length(rayDir);
+ if (!(rl > 1e-20f)) return false;
+ const glm::vec3 r = rayDir / rl;
+ const float b = glm::dot(dir, r);
+ const float denom = 1.0f - b * b; // sin^2 of the angle between them
+ if (!(denom > minSine * minSine)) return false;
+ const glm::vec3 w = point - origin;
+ s = (b * glm::dot(r, w) - glm::dot(dir, w)) / denom;
+ return std::isfinite(s);
+}
+
+void keepConnected(const Mesh& mesh, const glm::vec3& seed, std::vector<uint32_t>& verts, ConnectedScratch& sc) {
+ if (verts.empty()) return;
+ const size_t n = mesh.vertexCount();
+ if (sc.stamp.size() < n) sc.stamp.resize(n, 0);
+ if (sc.epoch >= 0xfffffff0u) { // wrapped: start the stamps again
+ std::fill(sc.stamp.begin(), sc.stamp.end(), 0u);
+ sc.epoch = 0;
+ }
+ const uint32_t inside = ++sc.epoch, reached = ++sc.epoch;
+ uint32_t start = verts[0];
+ float best = std::numeric_limits<float>::max();
+ for (uint32_t v : verts) {
+ sc.stamp[v] = inside;
+ const glm::vec3 d = mesh.positions[v] - seed;
+ const float d2 = glm::dot(d, d);
+ if (d2 < best) best = d2, start = v;
+ }
+ // Breadth first through the edges between vertices in the region.
+ std::vector<uint32_t>& q = sc.queue;
+ q.clear();
+ q.push_back(start);
+ sc.stamp[start] = reached;
+ for (size_t head = 0; head < q.size(); ++head)
+ for (uint32_t w : mesh.neighbors(q[head]))
+ if (sc.stamp[w] == inside) {
+ sc.stamp[w] = reached;
+ q.push_back(w);
+ }
+ if (q.size() == verts.size()) return; // all of it is one piece
+ std::erase_if(verts, [&](uint32_t v) { return sc.stamp[v] != reached; });
+}
+
+void brushRegion(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, const glm::vec3& viewDir, float radius,
+ bool connectedOnly, bool viewFalloff, std::vector<uint32_t>& out, ConnectedScratch& scratch) {
+ if (viewFalloff) {
+ bvh.queryVerticesCylinder(mesh, center, viewDir, radius, out);
+ if (mesh.hasHidden()) std::erase_if(out, [&](uint32_t v) { return mesh.vertexHidden(v); });
+ } else {
+ brushVertices(mesh, bvh, center, radius, out);
+ }
+ if (connectedOnly) keepConnected(mesh, center, out, scratch);
+}
+
namespace {
glm::vec3 projectOnPlane(const glm::vec3& v, const glm::vec3& n) { return v - n * glm::dot(v, n); }
@@ -513,7 +580,15 @@ void Sculptor::displace(Mesh& mesh, uint32_t v, const glm::vec3& d) {
// displace() for many vertices (each listed once), in parallel: the influences and which vertices the stroke
// moves for the first time, then their undo entries (in list order, at offsets counted per block) and the moves.
-void Sculptor::displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::span<const glm::vec3> d) {
+void Sculptor::moveVertices(Mesh& mesh, BVH& bvh, std::span<const uint32_t> verts, std::span<const glm::vec3> d) {
+ if (!active_ || verts.empty()) return;
+ displaceAll(mesh, verts, d, false);
+ mesh.updateNormals(verts);
+ if (verts.size() * 4 > mesh.vertexCount()) bvh.refitAll(mesh);
+ else bvh.refit(mesh, verts);
+}
+
+void Sculptor::displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::span<const glm::vec3> d, bool influence) {
const size_t n = verts.size();
if (dynTopo_.active()) // the remesher's record keeps them (see touch); their bits then keep them out of ours
for (uint32_t v : verts)
@@ -525,7 +600,7 @@ void Sculptor::displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::spa
poolFor(n, [&](size_t b, size_t e) {
uint32_t count = 0;
for (size_t i = b; i < e; ++i) {
- const float k = vertexInfluence(mesh, verts[i]);
+ const float k = influence ? vertexInfluence(mesh, verts[i]) : 1.0f;
influence_[i] = k;
firstTouch_[i] = k > 0.0f && markBit(touched_, verts[i]);
count += firstTouch_[i];
@@ -613,7 +688,9 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Sym
if (type != BrushType::Move && type != BrushType::Morph) { // (Morph needs the vertices the target has)
const bool useAlpha = p.alpha && !p.alpha->empty(); // (the reach dabSingle gives the brush)
const float reach = useAlpha ? kAlphaReach : type == BrushType::ClayBuildup ? 1.3f : 1.0f;
- remeshDab(mesh, bvh, p, sym, type == BrushType::Smooth ? 2.0f : 1.0f, reach);
+ const float scale = type == BrushType::Smooth ? dyntopoSmoothScale(dyntopo) : 1.0f;
+ if (scale > 0.0f) remeshDab(mesh, bvh, p, sym, scale, reach);
+ else lastRemesh_ = false; // (Smooth only: no repair pass either)
}
dabVerts_.clear();
dabLeaves_.clear();
@@ -632,7 +709,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
// Alphas and the square ClayBuildup tip reach into the corners of their square.
const bool useAlpha = p.alpha && !p.alpha->empty();
const float reach = useAlpha ? kAlphaReach : type == BrushType::ClayBuildup ? 1.3f : 1.0f;
- brushVertices(mesh, bvh, p.center, p.radius * reach, verts_);
+ brushRegion(mesh, bvh, p.center, p.viewDir, p.radius * reach, p.connectedOnly, p.viewFalloff, verts_, connected_);
if (verts_.empty()) return;
auto& pos = mesh.positions;
@@ -646,7 +723,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
// Weighted area normal and centre of the brush region.
const AreaSums sums = areaSums(verts_.size(), [&](size_t i, AreaSums& acc) {
const uint32_t v = verts_[i];
- float w = brushFalloff(glm::distance(pos[v], p.center), p.radius, p.focal);
+ float w = brushFalloff(brushDistance(p, pos[v]), p.radius, p.focal);
acc.normal += nrm[v] * w;
acc.center += pos[v] * w;
acc.weight += w;
@@ -688,7 +765,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
const glm::vec3& x = pos[v];
const glm::vec3 o = x - p.center;
const float f = useAlpha ? p.alpha->stamp(glm::dot(o, right) / r, glm::dot(o, up) / r, p.focal)
- : brushFalloff(glm::length(o), r, p.focal);
+ : brushFalloff(brushDistance(p, x), r, p.focal);
glm::vec3 d(0.0f);
switch (type) {
@@ -920,6 +997,8 @@ void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const
DabParams base = p;
base.pressure = std::pow(std::clamp(p.pressure, 0.0f, 1.0f), recipe.pressureCurve);
base.frontFacesOnly = p.frontFacesOnly || recipe.frontFacesOnly;
+ base.connectedOnly = p.connectedOnly || recipe.connectedOnly;
+ base.viewFalloff = p.viewFalloff || recipe.viewFalloff;
dabVerts_.clear();
dabLeaves_.clear();
for (const SymCopy& m : copies(sym)) {
@@ -933,7 +1012,7 @@ void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const
void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p) {
auto clock = std::chrono::steady_clock::now();
- brushVertices(mesh, bvh, p.center, p.radius, verts_);
+ brushRegion(mesh, bvh, p.center, p.viewDir, p.radius, p.connectedOnly, p.viewFalloff, verts_, connected_);
if (verts_.empty()) return;
const auto& pos = mesh.positions;
const auto& nrm = mesh.normals;
@@ -963,7 +1042,7 @@ void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const
const float patternFreq = 1.0f / std::max(rad * r.patternScale, 1e-6f);
const AreaSums sums = areaSums(verts_.size(), [&](size_t i, AreaSums& acc) {
const uint32_t v = verts_[i];
- float t = std::clamp((1.0f - glm::distance(pos[v], p.center) / rad) / edge, 0.0f, 1.0f);
+ float t = std::clamp((1.0f - brushDistance(p, pos[v]) / rad) / edge, 0.0f, 1.0f);
if (p.focal != 0.0f) t = std::pow(t, std::exp2(2.0f * std::clamp(p.focal, -1.0f, 1.0f))); // (brushFalloff's)
float w = std::pow(t * t * (3.0f - 2.0f * t), exponent);
acc.normal += nrm[v] * w;
@@ -1078,10 +1157,10 @@ void Sculptor::beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym)
return;
}
for (const SymCopy& m : copies(sym)) {
- glm::vec3 c = m.point(p.center);
- brushVertices(mesh, bvh, c, p.radius, verts_);
+ const glm::vec3 c = m.point(p.center), view = m.dir(p.viewDir);
+ brushRegion(mesh, bvh, c, view, p.radius, p.connectedOnly, p.viewFalloff, verts_, connected_);
for (uint32_t v : verts_) {
- float w = brushFalloff(glm::distance(mesh.positions[v], c), p.radius, p.focal) *
+ float w = brushFalloff(brushDistance(mesh.positions[v], c, view, p.viewFalloff), p.radius, p.focal) *
std::clamp(p.strength * 2.0f, 0.0f, 1.0f);
if (w <= 0.0f) continue;
grabVerts_.push_back(v);
diff --git a/src/core/Sculpt.h b/src/core/Sculpt.h
index b65a074f..1203f417 100644
--- a/src/core/Sculpt.h
+++ b/src/core/Sculpt.h
@@ -72,6 +72,11 @@ struct DabParams {
// Smooth: keep the volume (#40). A Taubin step, one shrink then one inflate, removes bumps as the plain
// (Laplacian) smooth does without shrinking the form. Not on micro levels (they smooth plainly).
bool keepVolume = false;
+ // Falloff options (#55, Blender's proportional editing): `connectedOnly` keeps the dab to the surface joined
+ // to the point under the cursor (the other leg, the next finger stay put); `viewFalloff` measures the falloff
+ // on screen, so the brush reaches through the model along the view as a cylinder.
+ bool connectedOnly = false;
+ bool viewFalloff = false;
};
// Local symmetry's centre for a Part: the middle of its bounding box (in parallel).
@@ -98,6 +103,37 @@ inline float vertexInfluence(const Mesh& mesh, uint32_t v) {
}
// Vertices within `radius` of `center` that a brush may touch (fully hidden ones excluded).
void brushVertices(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, float radius, std::vector<uint32_t>& out);
+// Distance from the dab centre for the falloff: in space, or (viewFalloff) across the view only.
+inline float brushDistance(const glm::vec3& x, const glm::vec3& center, const glm::vec3& viewDir, bool viewFalloff) {
+ const glm::vec3 o = x - center;
+ if (!viewFalloff) return glm::length(o);
+ const float l2 = glm::dot(viewDir, viewDir);
+ return l2 > 1e-24f ? glm::length(o - viewDir * (glm::dot(o, viewDir) / l2)) : glm::length(o);
+}
+inline float brushDistance(const struct DabParams& p, const glm::vec3& x) {
+ return brushDistance(x, p.center, p.viewDir, p.viewFalloff);
+}
+// Scratch for keepConnected (a stamp per vertex, so nothing is cleared between dabs).
+struct ConnectedScratch {
+ std::vector<uint32_t> stamp, queue;
+ uint32_t epoch = 0;
+};
+// Connected only: keeps the vertices of `verts` (in increasing order) that the vertex of `verts` nearest `seed`
+// reaches through edges between vertices of `verts`; the order stays.
+void keepConnected(const Mesh& mesh, const glm::vec3& seed, std::vector<uint32_t>& verts, ConnectedScratch& scratch);
+// The vertices a dab may touch with the falloff options: brushVertices, or the cylinder along `viewDir`
+// (viewFalloff), then keepConnected from `center` (connectedOnly).
+void brushRegion(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, const glm::vec3& viewDir, float radius,
+ bool connectedOnly, bool viewFalloff, std::vector<uint32_t>& out, ConnectedScratch& scratch);
+// Along the normal (from the discussions: Move, Tendril, Elastic Tendril and Elastic Grab with Alt): the
+// falloff-weighted average normal of the visible surface within `radius` of `center`, unit length (zero when
+// there is no surface there).
+glm::vec3 brushAreaNormal(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, float radius, float focal = 0.0f);
+// The parameter s of the point point + s * dir (dir unit length) nearest the ray origin + t * rayDir: where a
+// cursor ray says a grab sliding along the line should be. False when the line is within `minSine` (the sine of
+// the angle between them) of parallel to the ray, so the cursor can't say where along it.
+bool lineRayClosest(const glm::vec3& point, const glm::vec3& dir, const glm::vec3& origin, const glm::vec3& rayDir,
+ float& s, float minSine = 0.25f);
// Smoothstep brush falloff: 1 at the centre, 0 at `radius`. `focal` is ZBrush's Focal Shift (-1..1): below 0
// the full-strength centre widens (a harder, broader tip), above 0 it narrows to a softer point; 0 is the plain
// smoothstep, unchanged.
@@ -149,6 +185,10 @@ public:
UndoRecord endStroke();
bool strokeActive() const { return active_; }
+ // Whole-mesh operations (core/Deform.h) inside a stroke: moves `verts` (each once, increasing) by `d` as given
+ // (the caller weighed in the mask), recorded for undo and written to the stroke's layer; then their normals
+ // and the BVH.
+ void moveVertices(Mesh& mesh, BVH& bvh, std::span<const uint32_t> verts, std::span<const glm::vec3> d);
SculptTimings timings;
// The brush's frame on the surface at the last dab's first (unmirrored) pass: the dab centre, the area normal
@@ -254,7 +294,7 @@ private:
void touch(Mesh& mesh, uint32_t v);
// The one place brushes move vertices: scales `d` by vertexInfluence().
void displace(Mesh& mesh, uint32_t v, const glm::vec3& d);
- void displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::span<const glm::vec3> d);
+ void displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::span<const glm::vec3> d, bool influence = true);
// Dynamic topology: remeshes before a dab, and keeps the stroke's per-vertex state in step with it.
void remeshDab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym, float scale, float reach);
@@ -284,6 +324,7 @@ private:
void clearRecorded();
std::vector<uint32_t> verts_, dabVerts_; // one mirror's vertices; every mirror's (for the normals)
+ ConnectedScratch connected_; // Connected only (DabParams::connectedOnly)
std::vector<uint32_t> dabLeaves_; // the BVH leaves every mirror's query listed (the normals' set)
std::vector<float> curvature_; // strokeCurvature
bool curvatureFilled_ = false; // every entry current (a draft stroke packs them as they are)
diff --git a/src/core/Vdm.cpp b/src/core/Vdm.cpp
index 8a6d995f..5ff2ab4f 100644
--- a/src/core/Vdm.cpp
+++ b/src/core/Vdm.cpp
@@ -648,7 +648,7 @@ void Sculptor::dabVdmSingle(Mesh& mesh, BVH& bvh, const DabParams& p, float hand
auto clock = std::chrono::steady_clock::now();
const VectorDisplacement* vdm = p.vdm && !p.vdm->empty() ? p.vdm : builtinVdms().front().get();
// The stamp is the brush's square, so the corners reach out to radius x sqrt(2).
- brushVertices(mesh, bvh, p.center, p.radius * 1.4143f, verts_);
+ brushRegion(mesh, bvh, p.center, p.viewDir, p.radius * 1.4143f, p.connectedOnly, p.viewFalloff, verts_, connected_);
if (verts_.empty()) return;
const auto& pos = mesh.positions;
const auto& nrm = mesh.normals;
diff --git a/src/core/ZSpheres.cpp b/src/core/ZSpheres.cpp
index 99d8dc9a..2fe33183 100644
--- a/src/core/ZSpheres.cpp
+++ b/src/core/ZSpheres.cpp
@@ -326,6 +326,25 @@ bool zsphereInsert(std::vector<ZSphere>& s, int child, Symmetry sym, int* added)
return true;
}
+bool zsphereSetRoot(std::vector<ZSphere>& s, int i) {
+ if (!validIndex(s, i) || i == 0) return false;
+ // Turn the path from i up to the root around.
+ int at = i, below = -1;
+ while (at >= 0) {
+ const int up = s[size_t(at)].parent;
+ s[size_t(at)].parent = below;
+ below = at;
+ at = up;
+ }
+ // Swap indices 0 and i.
+ std::swap(s[0], s[size_t(i)]);
+ for (ZSphere& z : s) {
+ if (z.parent == 0) z.parent = i;
+ else if (z.parent == i) z.parent = 0;
+ }
+ return true;
+}
+
Json zspheresToJson(const std::vector<ZSphere>& s) {
Json out = Json::array();
for (const ZSphere& z : s) {
@@ -458,6 +477,20 @@ void registerZSphereCommands(CommandRegistry& reg) {
return {false, "index must be from 1 to " + std::to_string(s.size() - 1)};
return applyEdit(doc, std::move(s), "Forge Sphere insert", "Inserted sphere " + std::to_string(added));
}});
+ reg.add({"zsphere_set_root",
+ "Make sphere `index` of the active Forge Sphere Part the root (index 0): the armature keeps its shape and "
+ "links, and grows from there. The old root takes the sphere's index.",
+ {{"index", T::Number, "Sphere index (1 or more).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ auto s = doc.mesh.zspheres;
+ if (s.empty()) return {false, kNotZSphere};
+ const int i = int(argNumber(a, "index", -1));
+ if (!zsphereSetRoot(s, i))
+ return {false, i == 0 ? "Sphere 0 is the root already"
+ : "index must be from 1 to " + std::to_string(s.size() - 1)};
+ return applyEdit(doc, std::move(s), "Forge Sphere set root",
+ "Sphere " + std::to_string(i) + " is the root now (index 0)");
+ }});
reg.add({"zsphere_preview",
"Show the skin over the active Forge Sphere Part's spheres instead of the spheres (ZBrush's Preview, A).",
{{"on", T::Bool, "Default: toggle.", false}},
diff --git a/src/core/ZSpheres.h b/src/core/ZSpheres.h
index f6c7ef91..68bdaafe 100644
--- a/src/core/ZSpheres.h
+++ b/src/core/ZSpheres.h
@@ -55,6 +55,9 @@ bool zsphereSet(std::vector<ZSphere>& spheres, int i, const glm::vec3& center, f
bool zsphereDelete(std::vector<ZSphere>& spheres, int i, Symmetry sym);
// Inserts a sphere halfway along the link from `child` to its parent; `added` gets its index.
bool zsphereInsert(std::vector<ZSphere>& spheres, int child, Symmetry sym, int* added = nullptr);
+// Makes sphere `i` the root: the links on its way to the old root turn around, and it moves to index 0 (the old
+// root takes its index). The spheres and links stay where they are, so the skin is the same. False for the root.
+bool zsphereSetRoot(std::vector<ZSphere>& spheres, int i);
// "x,y,z,radius,parent" per sphere, as a flat array; FromJson drops an armature that doesn't form a tree.
Json zspheresToJson(const std::vector<ZSphere>& spheres);
diff --git a/tests/test_community_0106.cpp b/tests/test_community_0106.cpp
new file mode 100644
index 00000000..938f2d0a
--- /dev/null
+++ b/tests/test_community_0106.cpp
@@ -0,0 +1,473 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Community requests for 0.10.6: the Connected only and View falloff brush options (#55 in the discussions), the
+// whole-mesh deformations (core/Deform.h), moving along the normal (lineRayClosest, brushAreaNormal) and Forge
+// Spheres' Set as root (#8).
+#include "TestHarness.h"
+
+#include "core/BrushRecipe.h"
+#include "core/Commands.h"
+#include "core/Deform.h"
+#include "core/Primitives.h"
+#include "core/Sculpt.h"
+#include "core/ZSpheres.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+#include <random>
+
+using namespace sf;
+using glm::vec3;
+
+namespace {
+
+// Two meshes as one (separate pieces), with topology and normals.
+Mesh merged(const Mesh& a, const Mesh& b, const vec3& offsetB) {
+ Mesh m = a;
+ const uint32_t base = uint32_t(a.vertexCount());
+ for (const vec3& p : b.positions) m.positions.push_back(p + offsetB);
+ for (const glm::uvec3& t : b.triangles) m.triangles.push_back(t + glm::uvec3(base));
+ m.quadPartners.clear();
+ m.normals.clear();
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ return m;
+}
+
+float stddevOver(const std::vector<float>& v, float& mean) {
+ mean = 0.0f;
+ for (float x : v) mean += x;
+ mean /= float(v.size());
+ float var = 0.0f;
+ for (float x : v) var += (x - mean) * (x - mean);
+ return std::sqrt(var / float(v.size()));
+}
+
+// Distances from the centroid: their spread over their mean (0 for a sphere).
+float roundness(const std::vector<vec3>& P) {
+ vec3 c(0.0f);
+ for (const vec3& p : P) c += p;
+ c /= float(P.size());
+ std::vector<float> d;
+ for (const vec3& p : P) d.push_back(glm::length(p - c));
+ float mean = 0.0f;
+ const float sd = stddevOver(d, mean);
+ return sd / mean;
+}
+
+// The volume a closed mesh at positions P encloses.
+float volume(const Mesh& m, const std::vector<vec3>& P) {
+ double v = 0.0;
+ for (const glm::uvec3& t : m.triangles) v += double(glm::dot(P[t.x], glm::cross(P[t.y], P[t.z])));
+ return float(v / 6.0);
+}
+
+// An icosphere with every vertex pushed in or out a little (deterministic).
+Mesh noisySphere(int subdivisions, float noise) {
+ Mesh m = makeIcosphere(subdivisions, 1.0f);
+ std::mt19937 rng(7);
+ std::uniform_real_distribution<float> u(-noise, noise);
+ for (vec3& p : m.positions) p *= 1.0f + u(rng);
+ m.recomputeAllNormals();
+ return m;
+}
+
+std::vector<float> edgeLengths(const Mesh& m, const std::vector<vec3>& P) {
+ std::vector<float> out;
+ for (const glm::uvec3& t : m.triangles)
+ for (int k = 0; k < 3; ++k) out.push_back(glm::distance(P[t[k]], P[t[(k + 1) % 3]]));
+ return out;
+}
+
+} // namespace
+
+// --- Connected only and View falloff ---------------------------------------------------------------------
+
+TEST(falloff_keep_connected_flood_fill) {
+ // Two spheres 0.1 apart: a region reaching into both keeps only the piece the seed is on.
+ const Mesh m = merged(makeIcosphere(3, 0.5f), makeIcosphere(3, 0.5f), vec3(1.1f, 0, 0));
+ BVH bvh;
+ bvh.build(m);
+ const uint32_t firstB = uint32_t(makeIcosphere(3, 0.5f).vertexCount());
+ std::vector<uint32_t> verts;
+ ConnectedScratch scratch;
+ brushRegion(m, bvh, vec3(0.5f, 0, 0), vec3(0, 0, -1), 0.4f, false, false, verts, scratch);
+ const bool both = std::any_of(verts.begin(), verts.end(), [&](uint32_t v) { return v < firstB; }) &&
+ std::any_of(verts.begin(), verts.end(), [&](uint32_t v) { return v >= firstB; });
+ CHECK(both);
+ const size_t all = verts.size();
+ brushRegion(m, bvh, vec3(0.5f, 0, 0), vec3(0, 0, -1), 0.4f, true, false, verts, scratch);
+ CHECK(!verts.empty() && verts.size() < all);
+ CHECK(std::all_of(verts.begin(), verts.end(), [&](uint32_t v) { return v < firstB; }));
+ CHECK(std::is_sorted(verts.begin(), verts.end()));
+ // From the other side: the other piece.
+ brushRegion(m, bvh, vec3(0.6f, 0, 0), vec3(0, 0, -1), 0.4f, true, false, verts, scratch);
+ CHECK(!verts.empty() && std::all_of(verts.begin(), verts.end(), [&](uint32_t v) { return v >= firstB; }));
+ // One piece only: nothing dropped.
+ const Mesh one = makeIcosphere(4, 1.0f);
+ BVH ob;
+ ob.build(one);
+ std::vector<uint32_t> plain;
+ brushRegion(one, ob, vec3(0, 0, 1), vec3(0, 0, -1), 0.5f, false, false, plain, scratch);
+ brushRegion(one, ob, vec3(0, 0, 1), vec3(0, 0, -1), 0.5f, true, false, verts, scratch);
+ CHECK(verts == plain);
+}
+
+TEST(falloff_connected_brush_leaves_the_other_piece) {
+ // Two fingers side by side: inflating one with a brush that reaches the other leaves the other one alone.
+ const Mesh start = merged(makeIcosphere(3, 0.5f), makeIcosphere(3, 0.5f), vec3(1.1f, 0, 0));
+ const uint32_t firstB = uint32_t(makeIcosphere(3, 0.5f).vertexCount());
+ auto run = [&](bool connected) {
+ Document e = makeDoc(start);
+ DabParams p;
+ p.center = vec3(0.5f, 0, 0);
+ p.viewDir = vec3(0, 0, -1);
+ p.radius = 0.4f;
+ p.strength = 1.0f;
+ p.connectedOnly = connected;
+ CHECK(e.sculptor.beginStroke(e.mesh, "Inflate"));
+ e.sculptor.dab(e.mesh, e.bvh, BrushType::Inflate, p, Symmetry{false, false, false});
+ e.undo.push(e.sculptor.endStroke());
+ float movedB = 0.0f, movedA = 0.0f;
+ for (uint32_t v = 0; v < e.mesh.vertexCount(); ++v) {
+ const float l = glm::distance(e.mesh.positions[v], start.positions[v]);
+ (v < firstB ? movedA : movedB) += l;
+ }
+ return std::make_pair(movedA, movedB);
+ };
+ const auto [a0, b0] = run(false);
+ const auto [a1, b1] = run(true);
+ CHECK(a0 > 0.0f && b0 > 0.0f); // the plain brush moves both
+ CHECK(a1 > 0.0f && b1 == 0.0f);
+ // The Move brush too.
+ Document e = makeDoc(start);
+ DabParams p;
+ p.center = vec3(0.5f, 0, 0);
+ p.viewDir = vec3(0, 0, -1);
+ p.radius = 0.4f;
+ p.strength = 1.0f;
+ p.connectedOnly = true;
+ CHECK(e.sculptor.beginStroke(e.mesh, "Move"));
+ e.sculptor.beginGrab(e.mesh, e.bvh, p, Symmetry{false, false, false});
+ e.sculptor.grab(e.mesh, e.bvh, vec3(0, 0.2f, 0));
+ e.undo.push(e.sculptor.endStroke());
+ bool aMoved = false, bMoved = false;
+ for (uint32_t v = 0; v < e.mesh.vertexCount(); ++v)
+ (v < firstB ? aMoved : bMoved) |= e.mesh.positions[v] != start.positions[v];
+ CHECK(aMoved && !bMoved);
+}
+
+TEST(falloff_view_cylinder) {
+ // Two planes one unit apart, seen from above: the view falloff reaches the lower one, the sphere doesn't.
+ const Mesh m = merged(makePlane(32, 2.0f), makePlane(32, 2.0f), vec3(0, -1, 0));
+ BVH bvh;
+ bvh.build(m);
+ const uint32_t firstB = uint32_t(makePlane(32, 2.0f).vertexCount());
+ std::vector<uint32_t> sphere, cylinder;
+ ConnectedScratch scratch;
+ brushRegion(m, bvh, vec3(0, 0, 0), vec3(0, -1, 0), 0.3f, false, false, sphere, scratch);
+ brushRegion(m, bvh, vec3(0, 0, 0), vec3(0, -1, 0), 0.3f, false, true, cylinder, scratch);
+ CHECK(std::none_of(sphere.begin(), sphere.end(), [&](uint32_t v) { return v >= firstB; }));
+ CHECK(std::any_of(cylinder.begin(), cylinder.end(), [&](uint32_t v) { return v >= firstB; }));
+ // Every vertex within 0.3 of the vertical line, and only those (a brute-force check of the BVH query).
+ std::vector<uint32_t> brute;
+ for (uint32_t v = 0; v < m.vertexCount(); ++v)
+ if (std::hypot(m.positions[v].x, m.positions[v].z) <= 0.3f) brute.push_back(v);
+ CHECK(cylinder == brute);
+ // With Connected only, the lower plane is a separate piece again.
+ std::vector<uint32_t> both;
+ brushRegion(m, bvh, vec3(0, 0, 0), vec3(0, -1, 0), 0.3f, true, true, both, scratch);
+ CHECK(!both.empty() && std::none_of(both.begin(), both.end(), [&](uint32_t v) { return v >= firstB; }));
+ // The distance: across the view only.
+ CHECK(std::abs(brushDistance(vec3(0.1f, -5.0f, 0.0f), vec3(0.0f), vec3(0, -1, 0), true) - 0.1f) < 1e-6f);
+ CHECK(std::abs(brushDistance(vec3(0.1f, -5.0f, 0.0f), vec3(0.0f), vec3(0, -1, 0), false) - std::hypot(0.1f, 5.0f)) < 1e-5f);
+ // A tilted view: brute force again.
+ const vec3 view = glm::normalize(vec3(0.3f, -1.0f, 0.2f));
+ bvh.queryVerticesCylinder(m, vec3(0.1f, 0.0f, 0.1f), view, 0.25f, cylinder);
+ brute.clear();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v)
+ if (brushDistance(m.positions[v], vec3(0.1f, 0.0f, 0.1f), view, true) <= 0.25f) brute.push_back(v);
+ CHECK(cylinder == brute);
+}
+
+TEST(falloff_options_in_recipes) {
+ BrushRecipe r;
+ CHECK(r.toJson()["connectedOnly"].isNull()); // other recipes' files stay as they were
+ r.connectedOnly = true;
+ r.viewFalloff = true;
+ const BrushRecipe back = BrushRecipe::fromJson(r.toJson());
+ CHECK(back.connectedOnly && back.viewFalloff);
+}
+
+// --- Along the normal ------------------------------------------------------------------------------------
+
+TEST(along_normal_line_ray) {
+ float s = 0.0f;
+ // The line up the z axis; a ray across at height 5 meets it at s = 5.
+ CHECK(lineRayClosest(vec3(0.0f), vec3(0, 0, 1), vec3(3, 0, 5), vec3(-1, 0, 0), s));
+ CHECK(std::abs(s - 5.0f) < 1e-5f);
+ // A skew ray: the nearest point of the line.
+ CHECK(lineRayClosest(vec3(1, 2, 3), vec3(0, 1, 0), vec3(0, 0, 0), glm::normalize(vec3(1, 1, 3)), s));
+ const vec3 q = vec3(1, 2, 3) + vec3(0, 1, 0) * s;
+ const vec3 r = glm::normalize(vec3(1, 1, 3));
+ const vec3 onRay = r * glm::dot(q, r);
+ CHECK(std::abs(glm::dot(q - onRay, vec3(0, 1, 0))) < 1e-4f); // the gap is square to the line
+ // The line pointing at the viewer: no answer.
+ CHECK(!lineRayClosest(vec3(0.0f), vec3(0, 0, 1), vec3(0, 0, 5), vec3(0.01f, 0, -1), s));
+ // The area normal of a plane, and of a sphere's pole.
+ const Mesh plane = makePlane(16, 2.0f);
+ BVH pb;
+ pb.build(plane);
+ CHECK(glm::distance(brushAreaNormal(plane, pb, vec3(0.0f), 0.3f), vec3(0, 1, 0)) < 1e-4f);
+ const Mesh ball = makeIcosphere(4, 1.0f);
+ BVH bb;
+ bb.build(ball);
+ const vec3 n = brushAreaNormal(ball, bb, glm::normalize(vec3(1, 1, 0)), 0.3f);
+ CHECK(glm::distance(n, glm::normalize(vec3(1, 1, 0))) < 0.02f);
+ CHECK(brushAreaNormal(ball, bb, vec3(5.0f), 0.3f) == vec3(0.0f));
+}
+
+TEST(along_normal_move_extrudes) {
+ // A Move stroke whose grab slides along the normal: the region moves straight out of the plane.
+ Document d = makeDoc(makePlane(32, 2.0f));
+ const std::vector<vec3> before = d.mesh.positions;
+ const vec3 n = brushAreaNormal(d.mesh, d.bvh, vec3(0.0f), 0.3f);
+ DabParams p;
+ p.center = vec3(0.0f);
+ p.viewDir = glm::normalize(vec3(0, -0.2f, -1)); // seen nearly edge on
+ p.radius = 0.3f;
+ p.strength = 1.0f;
+ CHECK(d.sculptor.beginStroke(d.mesh, "Move"));
+ d.sculptor.beginGrab(d.mesh, d.bvh, p, Symmetry{false, false, false});
+ // The cursor ray passes 0.5 above the press point: the grab goes 0.5 out along the normal.
+ float s = 0.0f;
+ CHECK(lineRayClosest(vec3(0.0f), n, vec3(0, 0.5f, 4), vec3(0, 0, -1), s));
+ CHECK(std::abs(s - 0.5f) < 1e-4f);
+ d.sculptor.grab(d.mesh, d.bvh, n * s);
+ d.undo.push(d.sculptor.endStroke());
+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {
+ const vec3 m = d.mesh.positions[v] - before[v];
+ CHECK(std::abs(m.x) < 1e-6f && std::abs(m.z) < 1e-6f); // only along the normal
+ }
+}
+
+// --- Whole-mesh deformations -----------------------------------------------------------------------------
+
+TEST(deform_smooth_and_keep_volume) {
+ const Mesh m = noisySphere(4, 0.05f);
+ const float r0 = roundness(m.positions);
+ DeformOptions o;
+ o.amount = 60.0f;
+ const std::vector<vec3> plain = deformPositions(m, DeformOp::Smooth, o);
+ o.keepVolume = true;
+ const std::vector<vec3> taubin = deformPositions(m, DeformOp::Smooth, o);
+ CHECK(roundness(plain) < 0.5f * r0 && roundness(taubin) < 0.5f * r0);
+ const float v0 = volume(m, m.positions);
+ const float lostPlain = v0 - volume(m, plain), lostTaubin = std::abs(v0 - volume(m, taubin));
+ CHECK(lostPlain > 0.0f && lostTaubin < 0.25f * lostPlain);
+ // 0 does nothing, more does more.
+ o.keepVolume = false;
+ o.amount = 0.0f;
+ CHECK(deformPositions(m, DeformOp::Smooth, o) == m.positions);
+ o.amount = 20.0f;
+ CHECK(roundness(deformPositions(m, DeformOp::Smooth, o)) > roundness(plain));
+}
+
+TEST(deform_relax_evens_spacing_keeps_shape) {
+ // A sphere whose vertices slid along it at random, by up to a third of the spacing (the shape is still the
+ // sphere).
+ Mesh m = makeIcosphere(4, 1.0f);
+ std::mt19937 rng(5);
+ std::uniform_real_distribution<float> u(-0.025f, 0.025f);
+ for (vec3& p : m.positions) p = glm::normalize(p + vec3(u(rng), u(rng), u(rng)));
+ m.recomputeAllNormals();
+ float mean = 0.0f;
+ const float cv0 = stddevOver(edgeLengths(m, m.positions), mean) / mean;
+ DeformOptions o;
+ o.amount = 100.0f;
+ const std::vector<vec3> P = deformPositions(m, DeformOp::Relax, o);
+ const float cv1 = stddevOver(edgeLengths(m, P), mean) / mean;
+ std::printf("relax: edge length spread %.4f -> %.4f\n", cv0, cv1);
+ CHECK(cv1 < 0.7f * cv0);
+ float off = 0.0f;
+ for (const vec3& p : P) off = std::max(off, std::abs(glm::length(p) - 1.0f));
+ CHECK(off < 0.02f); // still the sphere
+}
+
+TEST(deform_polish_keeps_planes_and_edges) {
+ // A cube with a little noise on its faces: Polish takes the noise away, the corners and edges stay sharp.
+ Mesh m = makeCube(12, 2.0f);
+ std::mt19937 rng(3);
+ std::uniform_real_distribution<float> u(-0.01f, 0.01f);
+ auto onEdge = [](const vec3& p) {
+ int at = 0;
+ for (int a = 0; a < 3; ++a) at += std::abs(std::abs(p[a]) - 1.0f) < 1e-4f;
+ return at >= 2;
+ };
+ std::vector<vec3> clean = m.positions;
+ for (vec3& p : m.positions)
+ if (!onEdge(p)) p += vec3(u(rng), u(rng), u(rng));
+ m.recomputeAllNormals();
+ // Distance of each vertex from the cube's surface.
+ auto noise = [&](const std::vector<vec3>& P) {
+ double sum = 0.0;
+ size_t n = 0;
+ for (size_t i = 0; i < P.size(); ++i) {
+ if (onEdge(clean[i])) continue;
+ int face = 0;
+ for (int a = 1; a < 3; ++a)
+ if (std::abs(clean[i][a]) > std::abs(clean[i][face])) face = a;
+ const float h = std::abs(P[i][face]) - 1.0f;
+ sum += double(h * h);
+ ++n;
+ }
+ return float(std::sqrt(sum / double(n))); // RMS
+ };
+ DeformOptions o;
+ o.amount = 100.0f;
+ const std::vector<vec3> P = deformPositions(m, DeformOp::Polish, o);
+ std::printf("polish noise %.4f -> %.4f\n", noise(m.positions), noise(P));
+ CHECK(noise(P) < 0.5f * noise(m.positions));
+ // The corners barely move (a plain smooth rounds them off).
+ const std::vector<vec3> S = deformPositions(m, DeformOp::Smooth, o);
+ float polishCorner = 0.0f, smoothCorner = 0.0f;
+ for (size_t i = 0; i < P.size(); ++i)
+ if (std::abs(std::abs(clean[i].x) - 1) < 1e-4f && std::abs(std::abs(clean[i].y) - 1) < 1e-4f &&
+ std::abs(std::abs(clean[i].z) - 1) < 1e-4f) {
+ polishCorner = std::max(polishCorner, glm::distance(P[i], clean[i]));
+ smoothCorner = std::max(smoothCorner, glm::distance(S[i], clean[i]));
+ }
+ std::printf("corner polish %.4f smooth %.4f\n", polishCorner, smoothCorner);
+ CHECK(polishCorner < 0.03f && smoothCorner > 4.0f * polishCorner);
+}
+
+TEST(deform_balloon_rounds_out) {
+ const Mesh cube = makeCube(10, 2.0f);
+ DeformOptions o;
+ o.amount = 100.0f;
+ const std::vector<vec3> P = deformPositions(cube, DeformOp::Balloon, o);
+ CHECK(roundness(P) < 0.6f * roundness(cube.positions));
+ CHECK(volume(cube, P) > volume(cube, cube.positions));
+ o.amount = -100.0f;
+ CHECK(volume(cube, deformPositions(cube, DeformOp::Balloon, o)) < volume(cube, cube.positions));
+}
+
+TEST(deform_mask_border_and_undo) {
+ Document d = makeDoc(noisySphere(4, 0.05f));
+ // Mask the top half: it stays exactly.
+ std::vector<float>& mask = d.mesh.ensureMask();
+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) mask[v] = d.mesh.positions[v].y > 0.0f ? 1.0f : 0.0f;
+ const std::vector<vec3> before = d.mesh.positions;
+ CommandRegistry reg;
+ const CommandResult r = reg.execute(d, "deform_smooth", {{"amount", 80.0}});
+ CHECK(r.ok);
+ bool lowerMoved = false;
+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {
+ if (mask[v] == 1.0f) CHECK(d.mesh.positions[v] == before[v]);
+ else lowerMoved |= d.mesh.positions[v] != before[v];
+ }
+ CHECK(lowerMoved);
+ // One undo step puts it back.
+ const size_t steps = d.undo.undoCount();
+ CHECK(steps == 1);
+ CHECK(d.undo.undo(d.mesh, d.bvh));
+ CHECK(d.mesh.positions == before);
+ // masked=false moves the top too; every command runs.
+ for (const char* name : {"deform_polish", "deform_relax", "deform_smooth", "deform_balloon"})
+ CHECK(reg.execute(d, name, {{"amount", 50.0}, {"masked", false}}).ok);
+ // Everything masked: an error, nothing recorded.
+ std::fill(d.mesh.mask.begin(), d.mesh.mask.end(), 1.0f);
+ const size_t n = d.undo.undoCount();
+ CHECK(!reg.execute(d, "deform_relax").ok);
+ CHECK(d.undo.undoCount() == n);
+ // Open borders stay where they are.
+ Document plane = makeDoc(makePlane(16, 2.0f));
+ std::vector<vec3> flat = plane.mesh.positions;
+ for (size_t i = 0; i < flat.size(); ++i) plane.mesh.positions[i].y = 0.05f * std::sin(7.0f * flat[i].x);
+ plane.mesh.recomputeAllNormals();
+ plane.bvh.build(plane.mesh);
+ const std::vector<vec3> wavy = plane.mesh.positions;
+ CHECK(reg.execute(plane, "deform_smooth", {{"amount", 100.0}}).ok);
+ for (uint32_t v = 0; v < plane.mesh.vertexCount(); ++v)
+ if (std::abs(std::abs(flat[v].x) - 1.0f) < 1e-4f || std::abs(std::abs(flat[v].z) - 1.0f) < 1e-4f)
+ CHECK(plane.mesh.positions[v] == wavy[v]);
+}
+
+TEST(deform_large_mesh_timing) {
+ // SF_DEFORM_BENCH=1: the four deformations and a Connected only dab on a 5M-vertex sphere (skipped otherwise).
+ if (!std::getenv("SF_DEFORM_BENCH")) return;
+ Document d = makeDoc(makeIcosphere(std::atoi(std::getenv("SF_DEFORM_BENCH")) > 1 ? 10 : 9, 1.0f)); // 2.6M or 10.5M vertices
+ std::printf("bench mesh: %zu vertices, %zu triangles\n", d.mesh.vertexCount(), d.mesh.triangleCount());
+ using clock = std::chrono::steady_clock;
+ for (DeformOp op : {DeformOp::Polish, DeformOp::Relax, DeformOp::Smooth, DeformOp::Balloon}) {
+ DeformOptions o;
+ o.amount = 50.0f;
+ const auto t0 = clock::now();
+ std::string err;
+ const size_t moved = deformActivePart(d, op, o, err);
+ const double ms = std::chrono::duration<double, std::milli>(clock::now() - t0).count();
+ std::printf("deform %s 50: %zu vertices in %.0f ms\n", deformName(op), moved, ms);
+ }
+ for (bool connected : {false, true})
+ for (float radius : {0.05f, 0.2f, 0.5f, 1.0f}) {
+ DabParams p;
+ p.center = *std::max_element(d.mesh.positions.begin(), d.mesh.positions.end(),
+ [](const vec3& a, const vec3& b) { return a.z < b.z; }); // the top
+ p.viewDir = vec3(0, 0, -1);
+ p.radius = radius;
+ p.strength = 0.5f;
+ p.connectedOnly = connected;
+ std::vector<uint32_t> verts;
+ brushVertices(d.mesh, d.bvh, p.center, radius, verts);
+ CHECK(d.sculptor.beginStroke(d.mesh, "Standard"));
+ const auto t0 = clock::now();
+ for (int i = 0; i < 10; ++i) { // in and out again, so the surface stays under the centre
+ p.invert = i % 2 == 1;
+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{false, false, false});
+ }
+ const double ms = std::chrono::duration<double, std::milli>(clock::now() - t0).count() / 10.0;
+ d.undo.push(d.sculptor.endStroke());
+ std::printf("dab radius %.2f (%zu vertices)%s: %.2f ms\n", radius, verts.size(), connected ? " connected only" : "", ms);
+ }
+}
+
+// --- Forge Spheres: Set as root --------------------------------------------------------------------------
+
+TEST(zspheres_set_root) {
+ // Root 0, an arm 1 from it, a hand 2 from the arm, a head 3 from the root.
+ std::vector<ZSphere> s{{vec3(0.0f), 0.5f, -1}, {vec3(1, 0, 0), 0.3f, 0}, {vec3(2, 0, 0), 0.2f, 1}, {vec3(0, 1, 0), 0.3f, 0}};
+ const std::vector<ZSphere> before = s;
+ CHECK(!zsphereSetRoot(s, 0) && !zsphereSetRoot(s, 9));
+ CHECK(zsphereSetRoot(s, 2));
+ CHECK(zspheresValidate(s).empty());
+ // The hand is the root now (index 0), the old root took its index (2).
+ CHECK(s[0].center == before[2].center && s[0].parent == -1);
+ CHECK(s[2].center == before[0].center && s[2].parent == 1); // the old root hangs from the arm
+ CHECK(s[1].parent == 0); // the arm from the hand
+ CHECK(s[3].parent == 2); // the head still from the old root
+ // Same spheres, same links (as unordered pairs of centres).
+ auto links = [](const std::vector<ZSphere>& z) {
+ std::vector<std::pair<float, float>> out;
+ for (const ZSphere& a : z)
+ if (a.parent >= 0) {
+ const float p = a.center.x + 10.0f * a.center.y, q = z[size_t(a.parent)].center.x + 10.0f * z[size_t(a.parent)].center.y;
+ out.push_back({std::min(p, q), std::max(p, q)});
+ }
+ std::sort(out.begin(), out.end());
+ return out;
+ };
+ CHECK(links(s) == links(before));
+ // The command, with undo.
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "zsphere_new", {{"radius", 0.5}}).ok);
+ CHECK(reg.execute(doc, "zsphere_add", {{"parent", 0.0}, {"position", std::string("1,0,0")}, {"radius", 0.25}}).ok);
+ CHECK(!reg.execute(doc, "zsphere_set_root", {{"index", 0.0}}).ok);
+ CHECK(reg.execute(doc, "zsphere_set_root", {{"index", 1.0}}).ok);
+ CHECK(doc.mesh.zspheres[0].center.x == 1.0f && doc.mesh.zspheres[1].parent == 0);
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.zspheres[0].center.x == 0.0f);
+}
diff --git a/tests/test_dyntopo.cpp b/tests/test_dyntopo.cpp
index 72f6f59c..fc7b2b0f 100644
--- a/tests/test_dyntopo.cpp
+++ b/tests/test_dyntopo.cpp
@@ -590,6 +590,29 @@ TEST(dyntopo_smooth_simplifies) {
CHECK(d.mesh.triangleCount() < before);
}
+// Smooth remesh (from the discussions): 0 smooths without touching the topology, in between it remeshes less
+// than the default, which simplifies the most.
+TEST(dyntopo_smooth_remesh_setting) {
+ auto run = [](float smoothRemesh) {
+ Document d = sphereDoc(4);
+ d.sculptor.dyntopo.detail = 0.0f;
+ d.sculptor.dyntopo.smoothRemesh = smoothRemesh;
+ const std::vector<glm::vec3> before = d.mesh.positions;
+ CHECK(d.sculptor.beginStroke(d.mesh, "Smooth"));
+ for (int i = 0; i < 10; ++i) dabToward(d, glm::vec3(0.05f * float(i), 0.0f, 3.0f), 0.5f, BrushType::Smooth, Symmetry{});
+ d.undo.push(d.sculptor.endStroke());
+ CHECK(invalid(d.mesh, true).empty());
+ if (smoothRemesh == 0.0f) CHECK(d.mesh.positions.size() == before.size() && d.mesh.positions != before); // smoothed
+ return d.mesh.triangleCount();
+ };
+ const size_t start = makeIcosphere(4, 1.0f).triangleCount();
+ const size_t none = run(0.0f), half = run(0.5f), full = run(1.0f);
+ CHECK(none == start);
+ CHECK(full < start);
+ CHECK(half <= start && half >= full);
+ CHECK(dyntopoSmoothScale(DyntopoSettings{}) == 2.0f); // the default stays as before
+}
+
// Long randomized sessions (set SF_STRESS=1, or another number for other seeds; skipped otherwise, it takes a while): every brush, detail, radius,
// symmetry and invert, with a partial mask, polygroups, hidden triangles, a sculpt layer and polypaint, random
// undo / redo between strokes; the mesh stays valid after every stroke and undoing everything gives the start back.
diff --git a/tests/ui/along_normal.sfui b/tests/ui/along_normal.sfui
new file mode 100644
index 00000000..d440e747
--- /dev/null
+++ b/tests/ui/along_normal.sfui
@@ -0,0 +1,58 @@
+# Along the normal (from the discussions): Move, Tendril and the elastic brushes, started with Alt held, move the
+# surface along the average normal under the brush instead of across the screen. A drag up and to the right on the
+# sphere's right side: plainly it moves up as much as out; with Alt it only moves out. Preferences > Input > Along
+# the normal: Always does it without the key, Never turns it off.
+run new_sphere subdivisions=5
+camera 0 0
+click "Move##brush.move"
+
+# Plain Move: up and out.
+snapshot
+stroke 0.86 0.5 0.98 0.38
+expect_value stroke_along_normal == 0
+remember moved_sum plain
+expect_value moved_out < $plain*0.75
+key ctrl+z
+
+# Alt: straight out along the normal.
+hold alt
+stroke 0.86 0.5 0.98 0.38
+hold none
+expect_value stroke_along_normal == 1
+remember moved_sum along
+expect_value moved_sum > 0
+expect_value moved_out > $along*0.9
+shot move_along_normal
+key ctrl+z
+expect_value moved == 0
+
+# Tendril with Alt pulls straight out too.
+click "Tendril##brush.snakehook"
+hold alt
+stroke 0.86 0.5 0.98 0.38
+hold none
+expect_value stroke_along_normal == 1
+remember moved_sum tendril
+expect_value moved_out > $tendril*0.85
+key ctrl+z
+
+# KelvinGrab with Alt.
+click "KelvinGrab##brush.kelvingrab"
+hold alt
+stroke 0.86 0.5 0.98 0.38
+hold none
+expect_value stroke_along_normal == 1
+expect_value moved > 0
+key ctrl+z
+
+# Preferences: Always (no key), Never (the key does nothing).
+click "Move##brush.move"
+click "Preferences##palette.preferences"
+click "Input##preferences.input"
+expect "##input.along_normal"
+hold ctrl
+hover "##input.along_normal"
+expect_help "average normal"
+hold none
+click "Preferences##palette.preferences"
+expect_value along_normal == 0
diff --git a/tests/ui/brush_falloff_options.sfui b/tests/ui/brush_falloff_options.sfui
new file mode 100644
index 00000000..a717019b
--- /dev/null
+++ b/tests/ui/brush_falloff_options.sfui
@@ -0,0 +1,63 @@
+# Brush falloff options (from the discussions, Blender's proportional editing): Connected only keeps a stroke to
+# the piece under the cursor (a small ball pressed into a big one: only the ball moves), View falloff reaches
+# through the model along the view (the back of the sphere moves too). Both are in the Brush palette and saved
+# with the preferences.
+run new_sphere subdivisions=5
+run insert_primitive type=sphere x=0 y=0 z=1 nx=0 ny=0 nz=1 size=0.5
+camera 0 0
+zoom 0.4
+click "Inflate##brush.inflate"
+click "Brush##palette.brush"
+expect "Connected only##draw.connected_only"
+hold ctrl
+hover "Connected only##draw.connected_only"
+expect_help "other leg"
+hover "View falloff##draw.view_falloff"
+expect_help "through the model"
+hold none
+click "Brush##palette.brush"
+expect_value connected_only == 0
+expect_value view_falloff == 0
+
+# Plain: the stroke on the ball also swells the big sphere around it.
+snapshot
+stroke 0.48 0.5 0.52 0.5
+remember moved plain
+expect_value moved > 0
+key ctrl+z
+expect_value moved == 0
+
+# Connected only: just the ball (642 vertices).
+click "Brush##palette.brush"
+click "Connected only##draw.connected_only"
+click "Brush##palette.brush"
+expect_value connected_only == 1
+stroke 0.48 0.5 0.52 0.5
+expect_value moved > 0
+expect_value moved <= 642
+expect_value moved < $plain
+shot connected
+key ctrl+z
+click "Brush##palette.brush"
+click "Connected only##draw.connected_only"
+click "Brush##palette.brush"
+expect_value connected_only == 0
+
+# View falloff on the plain sphere: the back moves too, so many more vertices.
+run new_sphere subdivisions=4
+camera 0 0
+snapshot
+stroke 0.48 0.5 0.52 0.5
+remember moved front
+key ctrl+z
+click "Brush##palette.brush"
+click "View falloff##draw.view_falloff"
+click "Brush##palette.brush"
+expect_value view_falloff == 1
+stroke 0.48 0.5 0.52 0.5
+expect_value moved > $front*1.6
+key ctrl+z
+click "Brush##palette.brush"
+click "View falloff##draw.view_falloff"
+click "Brush##palette.brush"
+expect_value view_falloff == 0
diff --git a/tests/ui/deformation_ops.sfui b/tests/ui/deformation_ops.sfui
new file mode 100644
index 00000000..1afd749c
--- /dev/null
+++ b/tests/ui/deformation_ops.sfui
@@ -0,0 +1,49 @@
+# Tool > Deformation's whole-Part operations (from the discussions): Polish, Relax, Smooth and Balloon, each with
+# its amount beside it, one undo step each, the mask holding what it covers.
+run new_sphere subdivisions=4
+run deform_balloon amount=-40
+click "Tool##palette.tool"
+click "Deformation##tool.deformation"
+expect "Deformation/Polish"
+expect "##deform_balloon_amount"
+hold ctrl
+hover "Deformation/Polish"
+expect_help "sharp edges stay"
+hover "Deformation/Balloon"
+expect_help "rounder volume"
+hold none
+
+# Balloon fills the Part out; undo takes it back in one step.
+snapshot
+click "Deformation/Balloon"
+expect_status "Balloon 50"
+expect_value moved_out > 0
+shot balloon
+key ctrl+z
+expect_value moved == 0
+
+# Smooth, Polish and Relax each move it, and each is one undo step.
+click "Deformation/Smooth"
+expect_status "Smooth 50"
+expect_value moved > 0
+key ctrl+z
+expect_value moved == 0
+click "Smooth keeps volume##deformation.smooth_volume"
+click "Deformation/Smooth"
+expect_value moved > 0
+key ctrl+z
+click "Deformation/Polish"
+expect_status "Polish 50"
+key ctrl+z
+expect_value moved == 0
+click "Deformation/Relax"
+expect_status "Relax 50"
+expect_value moved > 0
+key ctrl+z
+
+# Masked all over: nothing moves, and the status says why.
+run mask_all
+click "Deformation/Balloon"
+expect_status "everything masked"
+expect_value moved == 0
+run mask_clear
diff --git a/tests/ui/dyntopo_smooth_remesh.sfui b/tests/ui/dyntopo_smooth_remesh.sfui
new file mode 100644
index 00000000..c79316d3
--- /dev/null
+++ b/tests/ui/dyntopo_smooth_remesh.sfui
@@ -0,0 +1,35 @@
+# Dynamic topology's Smooth remesh (from the discussions): how much Shift-smoothing changes the topology while
+# Dynamic is on. Smooth only leaves the triangles as they are; Simplify (the default, as before) merges them.
+run new_sphere subdivisions=4
+run dyntopo enabled=true detail=0
+click "Draw##palette.draw"
+expect "##dyntopo_smooth_remesh"
+expect_value smooth_remesh == 100
+hold ctrl
+hover "##dyntopo_smooth_remesh"
+expect_help "Smooth only"
+hold none
+
+# Smooth only: Shift-smoothing keeps the triangle count.
+click "Smooth only##sr0"
+expect_value smooth_remesh == 0
+click "Draw##palette.draw"
+remember triangles before
+snapshot
+hold shift
+stroke 0.3 0.5 0.7 0.5
+hold none
+expect_value moved > 0
+expect_value triangles == $before
+key ctrl+z
+
+# Simplify (the default): the same stroke merges triangles.
+click "Draw##palette.draw"
+click "Simplify##sr100"
+expect_value smooth_remesh == 100
+click "Draw##palette.draw"
+hold shift
+stroke 0.3 0.5 0.7 0.5
+hold none
+expect_value triangles < $before
+key ctrl+z
diff --git a/tests/ui/forge_spheres_pointer.sfui b/tests/ui/forge_spheres_pointer.sfui
new file mode 100644
index 00000000..7e711d79
--- /dev/null
+++ b/tests/ui/forge_spheres_pointer.sfui
@@ -0,0 +1,88 @@
+# Forge Spheres with the pointer only (#8): Drag places child makes one Draw drag move the new sphere away from its
+# parent (Ctrl+drag does the same with it off), the new sphere is selected, Delete Selected / Insert Between /
+# Set as Root work on it, and a right click on a sphere opens a menu with the same (a right drag still turns the
+# view). Symmetry X is on, so arms come in pairs.
+run zsphere_new radius=1
+run subtool_visibility index=0 visible=false
+wait 0.3
+click "Forge Spheres##tool.zspheres"
+expect "ZSpheres/Drag places child"
+hold ctrl
+hover "ZSpheres/Drag places child"
+expect_help "moves the new sphere away"
+hover "ZSpheres/Delete Selected"
+expect_help "selected sphere"
+hold none
+
+# Off (the default): a Draw drag sizes the new sphere on the parent's surface, about one radius out.
+expect_value zsphere_place_child == 0
+view_drag 0.515 0.518 0.545 0.518
+expect_value zspheres == 3
+expect_value zsphere_out1 < 1.05
+expect_value zsphere_selected == 1
+key ctrl+z
+expect_value zspheres == 1
+
+# On: the same drag pulls the new sphere out, at half the parent's size.
+click "ZSpheres/Drag places child"
+expect_value zsphere_place_child == 1
+view_drag 0.515 0.518 0.600 0.518
+expect_value zspheres == 3
+expect_value zsphere_out1 > 1.4
+expect_value zsphere_r1 == 0.5
+expect_value zsphere_x2 < -1.0
+expect_status "Forge Sphere add"
+expect_value zsphere_selected == 1
+shot placed
+key ctrl+z
+click "ZSpheres/Drag places child"
+expect_value zsphere_place_child == 0
+
+# Ctrl+drag places too, with the toggle off.
+hold ctrl
+view_drag 0.515 0.518 0.600 0.518
+hold none
+expect_value zspheres == 3
+expect_value zsphere_out1 > 1.4
+
+# Insert Between on the selected arm: a joint (and its mirror), selected.
+click "ZSpheres/Insert Between"
+expect_value zspheres == 5
+expect_status "Forge Sphere insert"
+expect_value zsphere_selected == 3
+
+# Delete Selected: the joint and the arm beyond it go (both sides); the root stays.
+click "ZSpheres/Delete Selected"
+expect_value zspheres == 1
+expect_value zsphere_selected == -1
+key ctrl+z
+expect_value zspheres == 5
+
+# A right drag on a sphere still turns the view and opens nothing.
+remember camera_yaw yaw
+button_drag right 0.5 0.518 0.56 0.518
+expect_value zsphere_menu == 0
+expect_value camera_yaw != $yaw
+camera 0 0
+wait 0.1
+
+# A right click on the arm: its menu. Set as Root makes it the root (index 0), one undo step.
+remember zsphere_root_x rootx
+button_drag right 0.585 0.518 0.585 0.518 0.05
+expect_value zsphere_menu == 1
+expect "Forge Sphere menu/Set as Root"
+shot menu
+click "Forge Sphere menu/Set as Root"
+expect_value zsphere_menu == 0
+expect_value zsphere_root_x > 1.0
+expect_value zspheres == 5
+expect_status "set root"
+key ctrl+z
+expect_value zsphere_root_x == $rootx
+
+# The root's own menu can't delete it.
+button_drag right 0.41 0.518 0.41 0.518 0.05
+expect_value zsphere_menu == 1
+click "Forge Sphere menu/Delete Sphere"
+expect_value zspheres == 5
+key escape
diff --git a/tests/ui/maya_keys.sfui b/tests/ui/maya_keys.sfui
index 04d9991a..e0a2dc26 100644
--- a/tests/ui/maya_keys.sfui
+++ b/tests/ui/maya_keys.sfui
@@ -36,12 +36,38 @@ hold alt
button_drag middle 0.4 0.5 0.6 0.5
hold none
expect_value camera_pan != $p0
-# Alt+right zooms.
+# Alt+right zooms with a sideways drag, as Maya's dolly (#32): right zooms in, left out; up and down don't.
+expect_value maya_zoom_horizontal == 1
remember camera_distance d0
hold alt
+button_drag right 0.4 0.5 0.6 0.5
+hold none
+expect_value camera_distance < $d0
+remember camera_distance d1
+hold alt
+button_drag right 0.6 0.5 0.4 0.5
+hold none
+expect_value camera_distance > $d1
+remember camera_distance d2
+hold alt
button_drag right 0.5 0.4 0.5 0.6
hold none
-expect_value camera_distance != $d0
+expect_value camera_distance == $d2
+# Invert zoom turns it around.
+click "Preferences##palette.preferences"
+expect "##input.maya_zoom"
+click "Invert zoom##input.invert_zoom"
+expect_value invert_zoom == 1
+click "Preferences##palette.preferences"
+remember camera_distance d3
+hold alt
+button_drag right 0.4 0.5 0.6 0.5
+hold none
+expect_value camera_distance > $d3
+click "Preferences##palette.preferences"
+click "Invert zoom##input.invert_zoom"
+expect_value invert_zoom == 0
+click "Preferences##palette.preferences"
# Ctrl+Alt+drag on the model masks.
key f
@@ -49,6 +75,14 @@ hold ctrl+alt
stroke 0.3 0.5 0.7 0.5
hold none
expect_value masked > 0
+# Ctrl+Alt+Shift+drag erases the mask (#32; not Ctrl+Shift's visibility selection).
+remember masked m0
+remember hidden h0
+hold ctrl+alt+shift
+stroke 0.3 0.5 0.7 0.5
+hold none
+expect_value masked < $m0
+expect_value hidden == $h0
click "Preferences##palette.preferences"
click "ZBrush-style##input.style_zbrush"