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.

Deformation stack and Size (foirgairwolf on Discord): Move, Turn, Scale, Squash, Bend, Twist, Taper, Shear, Round, Box, Flatten, Sag and Depth on the whole Part along any of X Y Z, with a live preview, Apply, Apply Selected, Reset and Repeat (Tool > Deformation > Stack, deform_stack, deform_<op>); Size shows the Part's X Y Z in scene units, drag or type exact values, Uniform keeps proportions (deform_size). Design doc with slice 2 and the Lattice slice 3 (fenix on Discord)

islandmedb3ce98a6ed29
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 09f7b670..ca5fc522 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -460,6 +460,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelSupportCard.cpp
src/app/PanelIntegrations.cpp
src/app/WhatsNewPopup.cpp
+ src/app/PanelDeform.cpp
src/app/PanelExtract.cpp
src/app/PanelTimeline.cpp
src/app/ProofMode.cpp
diff --git a/changes/feat-deform-panel.md b/changes/feat-deform-panel.md
new file mode 100644
index 00000000..c8399c12
--- /dev/null
+++ b/changes/feat-deform-panel.md
@@ -0,0 +1,26 @@
+---
+whats_new: **Deformation stack** (requested by foirgairwolf on Discord): **Tool > Deformation > Stack** bends, twists, tapers,
+ shears, turns, moves, scales, squashes, rounds, boxes, flattens, sags or puts depth on the whole Part, along any of
+ X, Y and Z, with a live preview. Stack steps up, switch them on and off, repeat one, then **Apply** (one undo step),
+ **Apply Selected** or **Reset**. Every step is a command too: `deform_stack ops="bend 45 y soft; twist 90 y"`.
+whats_new: **Exact size** (requested by foirgairwolf on Discord): **Tool > Deformation > Size** shows the Part's width, height
+ and depth in scene units; drag one or type an exact value to resize it, with **Uniform** keeping its proportions.
+highlight: Deformation stack: bend, twist, taper and more on the whole Part, live
+added: **Deformation stack** (Tool > Deformation > Stack, requested by foirgairwolf on Discord): thirteen whole-Part shape
+ operations in four groups (Transform: Move, Turn, Scale, Squash; Bend & Twist: Bend, Twist, Taper, Shear; Shape:
+ Round, Box, Flatten, Sag, Depth; plus the Surface ones), each along any of X, Y and Z about the Part's centre (or
+ the gizmo's placed pivot), with Direction for Bend and Shear and Soft for an eased profile. The preview is the
+ stack applied as one undo step and follows each change; Apply, Apply Selected, Reset and Repeat. The mask holds
+ what it covers. Commands `deform_move` ... `deform_depth` and `deform_stack` for scripts and the AI.
+added: **Size** (Tool > Deformation, requested by foirgairwolf on Discord): the active Part's X, Y and Z dimensions in scene
+ units, to drag or type exactly; it resizes about its centre (Uniform: in proportion), one undo step. Command
+ `deform_size`.
+testers:
+ - Any OS: New Sphere, Tool > Deformation > Stack > Add step > Bend; drag its amount: the sphere bends live. Add
+ Twist, switch Bend off and on, then Apply: one Ctrl+Z takes the whole stack back.
+ - Any OS: mask the top half (Ctrl+drag), add Taper 60 on Y: the masked half stays put.
+ - Any OS: Tool > Deformation > Size: double-click X, type 4, Enter: the Part is 4 wide and, with Uniform on,
+ keeps its proportions; Ctrl+Z puts it back.
+ - Windows: a 5M+ triangle Part: the preview follows each slider when you let go; Apply stays under a second.
+---
+Slice 1 of the Deform panel (docs/design/deform-panel.md). Slice 2: Noise, Contrast, Inflate, re-symmetrize.
diff --git a/docs/design/deform-panel.md b/docs/design/deform-panel.md
new file mode 100644
index 00000000..033f8044
--- /dev/null
+++ b/docs/design/deform-panel.md
@@ -0,0 +1,68 @@
+# Deform panel: a whole-Part deformation stack
+
+Request: foirgairwolf on Discord (#ideas, 11-06): a full toolbox of whole-Part deformations with an axis per
+operation, a live preview, and a list to repeat, apply and reset. Clean-room: generic geometry verbs, our own
+grouping, labels, order, ranges and UI.
+
+## Operations (core/Deform.h)
+
+Every operation maps a point `q = p - pivot` to `q'`; a vertex takes `p + w (p' - p)` with `w = 1 - mask` (0 on
+hidden vertices; open borders move, unlike the smoothing operations). The pivot is the Part's bounds centre, or
+the gizmo's pivot when it was placed. `ext[a]` = the largest `|q[a]|` over the Part (never 0), so `u = q[a] / ext[a]`
+runs over -1..1 whatever the pivot. **Soft** swaps the linear profile `s(u) = u` for `u (3 - u^2) / 2` (flat at the
+ends): the effect concentrates in the middle and eases out.
+
+| Group | Op | Amount | Math |
+|---|---|---|---|
+| Transform | **Move** | -100..100 (% of `ext`) | `q[a] += t ext[a]` on each chosen axis |
+| | **Turn** | -180..180 deg | rotate about each chosen axis in turn, X then Y then Z |
+| | **Scale** | -100..100 | chosen components times `2^(t)` (100 doubles, -100 halves) |
+| | **Squash** | -100..100 | per chosen axis: `f = 2^(-t)` along it, `1/sqrt(f)` across it (volume kept) |
+| Bend & Twist | **Bend** | -180..180 deg end to end | centreline angle `phi(y) = Phi/2 s(u)`, `p' = C(y) + x N(phi)`, `C = integral of T(phi)` (table of 2049 samples) |
+| | **Twist** | -360..360 deg end to end | rotate the cross-section about the axis by `Phi/2 s(u)` |
+| | **Taper** | -100..100 | cross-section times `max(0, 1 + t s(u))` |
+| | **Shear** | -100..100 (100 = 45 deg) | `q += b t ext[a] s(u)` |
+| Shape | **Round** | -100..100 | chosen components toward the sphere / cylinder of their mean radius |
+| | **Box** | -100..100 | toward the cube / square of their mean max-norm |
+| | **Flatten** | -100..100 (% of the depth) | cut the + side (- side for negative) at a plane moved in by `t`; Soft blends over a band |
+| | **Sag** | -100..100 | along -axis by `t R/2 (r/R)^2`, `r` = distance from the axis line (outer parts droop) |
+| | **Depth** | -90..90 | cross-section times `1 / (1 - t u / 2)` (a perspective) |
+| Surface | Polish, Relax, Smooth, Balloon | as before | unchanged (they keep borders) |
+
+Bend and Shear bend / shift toward a **Direction** (0..360 deg) in the plane across the axis; 0 is +Y for X and Z,
++X for Y. Axis-type operations (Turn, Squash, Bend, Twist, Taper, Shear, Flatten, Sag, Depth) run once per chosen
+axis, X then Y then Z; vector-type ones (Move, Scale, Round, Box) take the chosen components together (Round on
+XZ = a cylinder about Y). Axis set = any of X Y Z (7 combinations).
+
+Slice 2 (0.11.14): Surface group extras (Noise, Contrast, Inflate), re-symmetrize (+ averaged), using the
+topological mirror map.
+
+## Stack and preview
+
+The panel holds a list (op, amount, axes, direction, soft, on). The command `deform_stack ops="bend 40 y soft;
+twist 90 y"` runs the enabled entries in order as **one** undo step; each op also has its own command
+(`deform_bend amount=40 axes=y soft=true`). Preview = the stack really applied (one undo step, label
+"Deform stack"); a change undoes that step (only while `undo.revision()` still matches, as Line Gradient does)
+and applies again. Below 1M vertices this follows the slider while dragging; above, on release. **Apply** keeps
+it (the step stays, the list clears); **Apply selected** keeps only the selected entry; **Reset** undoes the
+preview and clears the list. Anything else that touches the undo stack makes the preview stale: it is then simply
+kept, never undone behind the user's back.
+
+Cost: pointwise ops are one parallel pass (poolFor) over the vertices; the apply goes through the Sculptor
+(layers record it like a stroke). Gate: 10M-vertex Part apply < 1 s on the laptop (heavy.sh bench).
+
+## Slice 3: Lattice (fenix on Discord, #ideas 1568540856477024347)
+
+Clean-room: the Python sketch posted with the request is not opened or used. Classic free-form deformation
+(Sederberg and Parry 1986).
+
+1. **Generate**: a cage of (l+1)(m+1)(n+1) control points on the Part's bounds (padded 1%), resolution per axis
+ (2-8, default 3). Each vertex gets its local (s, t, u) in 0..1 once, at Generate.
+2. **Edit**: the control points are picked and moved with the gizmo (one or a box selection); the preview is the
+ Bernstein sum `p = sum B_i^l(s) B_j^m(t) B_k^n(u) P_ijk` (trilinear for resolution 1), weighted by 1 - mask,
+ recomputed in parallel per change (positions only, through the same undo-replace preview as the stack).
+3. **Apply**: bake into the vertices as one undo step and drop the cage; **Cancel** drops it unchanged.
+ Toolbar buttons (Generate Lattice, Apply Lattice) plus Tool > Deformation > Lattice; commands
+ `lattice_generate res=3,3,3`, `lattice_move_points`, `lattice_apply`, `lattice_cancel`.
+
+The What's New fragment for this slice credits fenix on Discord.
diff --git a/docs/guide/sculpting.md b/docs/guide/sculpting.md
index f65277ea..cb27ef7d 100644
--- a/docs/guide/sculpting.md
+++ b/docs/guide/sculpting.md
@@ -310,6 +310,46 @@ They are commands too: `deform_polish amount=60`, `deform_relax`, `deform_smooth
`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).
+### Size
+
+**Tool > Deformation > Size** shows the active Part's width (**X**), height (**Y**) and depth (**Z**) in scene
+units (requested by foirgairwolf on Discord). Drag one, or double-click it and type an exact value: the Part resizes about its
+centre as one undo step. With **Uniform** on (the default) the other sides follow in proportion; off, only that side
+changes. The mask holds what it covers. Command: `deform_size x=2.5` (any of `x`, `y`, `z`), or `deform_size
+uniform=10` for the largest side.
+
+### Deformation stack
+
+**Tool > Deformation > Stack** shapes the whole Part with a list of steps (requested by foirgairwolf on Discord). **Add step**
+picks one; click a step to set its amount, its axes (**X Y Z**, any mix) and, where it applies, **Direction** and
+**Soft**. With **Preview** on, the Part follows each change (on very heavy Parts, when you let go of the slider).
+
+| Group | Step | What it does along the chosen axis |
+|---|---|---|
+| Transform | **Move** | Moves the Part by a percent of its half-size. |
+| | **Turn** | Turns it by degrees about the axis (several axes: X, then Y, then Z). |
+| | **Scale** | 100 doubles it, -100 halves it, on the chosen axes only. |
+| | **Squash** | Shorter along the axis and wider across it, keeping the volume (negative: taller and thinner). |
+| Bend & Twist | **Bend** | Curves it end to end by degrees toward **Direction** (0 = toward +Y, +X for the Y axis). |
+| | **Twist** | Turns one end against the other by degrees. |
+| | **Taper** | The + end wider and the - end narrower (negative: the other way). |
+| | **Shear** | Leans it toward **Direction**; 100 is 45 degrees. |
+| Shape | **Round** | Toward a sphere; with one axis left out, toward a cylinder about it. |
+| | **Box** | Toward a cube (or a square bar). |
+| | **Flatten** | Cuts the + side flat by a percent of the depth (negative: the - side). |
+| | **Sag** | Parts far from the axis droop down it, like a weight on outstretched arms (negative lifts). |
+| | **Depth** | A perspective: the + end wider, the - end narrower, more toward the ends. |
+| Surface | **Polish**, **Relax**, **Smooth**, **Balloon** | As above. |
+
+**Soft** eases Bend, Twist, Taper and Shear toward the ends (a bend that curves most in the middle) and rounds
+Flatten's cut. Steps work about the Part's centre, or about the gizmo's pivot when you placed it.
+
+The checkbox beside a step switches it off without losing it; **Repeat** adds the selected step again; **Remove**
+takes it out. **Apply** keeps the result (one undo step) and starts a new stack, **Apply Selected** keeps only
+the selected step, and **Reset** takes the preview back off. The mask holds what it covers and hidden faces stay.
+For scripts and the AI: `deform_stack ops="bend 45 y soft; twist 90 y; taper -30 y"`, or one step at a time with
+`deform_bend amount=45 axes=y soft=true direction=90`.
+
## Strokes
The stroke type decides how cursor movement becomes brush dabs. Choose it from the **Stroke** tile on the left
diff --git a/src/app/App.h b/src/app/App.h
index b4c35602..e9557eaa 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -30,6 +30,7 @@
#include "core/Pack.h"
#include "core/Parts.h"
#include "core/Document.h"
+#include "core/Deform.h"
#include "core/DiscordPresence.h"
#include "core/Face.h"
#include "core/GeneratedRemesh.h"
@@ -1797,6 +1798,35 @@ private:
bool extractTBorder_ = false; // TBorder
bool mirrorWeldAxes_[3] = {true, false, false}; // Mirror And Weld's X Y Z
bool mirrorAxes_[3] = {true, false, false}; // Deformation > Mirror's X Y Z
+ // Deformation > Stack (docs/design/deform-panel.md): the steps, the one being edited and the preview, which is
+ // the stack really applied as one undo step (redone after each change while it is still the last step).
+ struct DeformStackUi {
+ std::vector<DeformStep> steps;
+ std::vector<char> on; // per step: runs in the stack
+ int selected = -1;
+ int addOp = int(DeformOp::Bend);
+ bool preview = true;
+ bool previewed = false; // the preview step is in the undo history
+ uint64_t revision = 0; // undo revision right after it
+ uint32_t part = 0; // the Part it was applied to
+ } deformStack_;
+ void drawDeformStack();
+ // Deformation > Size: the active Part's dimensions (scene units), worked out again when the undo history, the
+ // active Part or its vertex count changes; editing one resizes the Part (deform_size).
+ struct DeformSizeUi {
+ uint64_t revision = ~uint64_t(0);
+ uint32_t part = 0;
+ size_t vertices = 0;
+ glm::vec3 size{0.0f}, edit{0.0f};
+ bool uniform = true;
+ } deformSize_;
+ void drawDeformSize();
+ void deformStackRefresh(); // undo the preview if it is still the last step, then preview again
+ bool deformStackUndoPreview(); // undo it if it is the last step; false when there was none (or it is stale)
+ void deformStackRun(const std::vector<DeformStep>& steps); // as one undo step (the preview, or an apply)
+ void deformStackApply(bool selectedOnly);
+ void deformStackReset();
+ void deformStackAdd(DeformOp op);
void pollAlphaFile();
ShellGeometry shell_; // this frame's regions (drawShell)
ImFont* fontSmall_ = nullptr, *fontTiny_ = nullptr, *fontIcons_ = nullptr, *fontBold_ = nullptr;
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 973f378a..93b83c9c 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -543,6 +543,69 @@ void App::initActions() {
nullptr, kCommands[k], nullptr, [this, k] { return doc_.mesh.vertexCount() > 0 && deformAmount_[k] != 0.0f; },
kHelp[k]);
}
+ // Deformation > Stack (PanelDeform.cpp, docs/design/deform-panel.md).
+ {
+ auto sel = [this]() -> DeformStep* {
+ DeformStackUi& ds = deformStack_;
+ return ds.selected >= 0 && ds.selected < int(ds.steps.size()) ? &ds.steps[size_t(ds.selected)] : nullptr;
+ };
+ auto any = [this] { return !deformStack_.steps.empty(); };
+ add("deformation.stack_apply", "Apply", "Tool > Deformation", nullptr, [this] { deformStackApply(false); }, nullptr,
+ nullptr, nullptr, any,
+ "Keep the stack's result on the Part (one undo step) and start a new stack. With Preview on, what you "
+ "see is what stays.");
+ add("deformation.stack_apply_selected", "Apply Selected", "Tool > Deformation", nullptr,
+ [this] { deformStackApply(true); }, nullptr, nullptr, nullptr, [sel] { return sel() != nullptr; },
+ "Keep only the selected step on the Part (one undo step) and take it off the stack; the rest stay to "
+ "edit.");
+ add("deformation.stack_reset", "Reset", "Tool > Deformation", nullptr, [this] { deformStackReset(); }, nullptr,
+ nullptr, nullptr, any, "Take the preview back off the Part and empty the stack.");
+ add("deformation.stack_repeat", "Repeat", "Tool > Deformation", nullptr,
+ [this, sel] {
+ if (DeformStep* st = sel()) {
+ const DeformStep copy = *st;
+ deformStack_.steps.insert(deformStack_.steps.begin() + deformStack_.selected + 1, copy);
+ deformStack_.on.insert(deformStack_.on.begin() + deformStack_.selected + 1, char(1));
+ ++deformStack_.selected;
+ deformStackRefresh();
+ }
+ },
+ nullptr, nullptr, nullptr, [sel] { return sel() != nullptr; },
+ "Add the selected step again right after it (twice the twist, a second bend...).");
+ add("deformation.stack_remove", "Remove", "Tool > Deformation", nullptr,
+ [this, sel] {
+ if (sel()) {
+ deformStack_.steps.erase(deformStack_.steps.begin() + deformStack_.selected);
+ deformStack_.on.erase(deformStack_.on.begin() + deformStack_.selected);
+ deformStack_.selected = std::min(deformStack_.selected, int(deformStack_.steps.size()) - 1);
+ deformStackRefresh();
+ }
+ },
+ nullptr, nullptr, nullptr, [sel] { return sel() != nullptr; }, "Take the selected step off the stack.");
+ static const char* const kAxisIds[3] = {"deformation.stack_x", "deformation.stack_y", "deformation.stack_z"};
+ static const char* const kAxisNames[3] = {"X", "Y", "Z"};
+ for (int k = 0; k < 3; ++k)
+ add(kAxisIds[k], kAxisNames[k], "Tool > Deformation", nullptr,
+ [this, sel, k] {
+ DeformStep* st = sel();
+ if (!st) return;
+ const uint8_t bit = uint8_t(1 << k);
+ if ((st->options.axes & ~bit) == 0) return; // keep at least one axis
+ st->options.axes ^= bit;
+ deformStackRefresh();
+ },
+ nullptr, nullptr,
+ [sel, k] {
+ const DeformStep* st = sel();
+ return st && (st->options.axes & (1 << k));
+ },
+ [sel] {
+ const DeformStep* st = sel();
+ return st && deformUsesAxes(st->op);
+ },
+ "An axis the selected step works along (several: one after the other, or together for Move, Scale, "
+ "Round and Box).");
+ }
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,
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index eafaf004..118d5220 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -787,6 +787,48 @@ constexpr Entry kSimplifiedChinese[] = {
{"Roll", "翻滚"},
{"Tilt", "倾斜"},
{"Spin", "旋转"},
+ // --- Deformation > Stack (PanelDeform.cpp) ---
+ {"Turn", "旋转"},
+ {"Bend", "弯曲"},
+ {"Twist", "扭转"},
+ {"Taper", "渐细"},
+ {"Shear", "斜切"},
+ {"Round", "变圆"},
+ {"Box", "方块"},
+ {"Sag", "下垂"},
+ {"Shape", "形状"},
+ {"Bend & Twist", "弯曲与扭转"},
+ {"Stack", "堆叠"},
+ {"Add step", "添加步骤"},
+ {"No steps yet: Add step", "还没有步骤:添加步骤"},
+ {"Direction", "方向"},
+ {"Keep volume", "保持体积"},
+ {"Repeat", "重复"},
+ {"Apply Selected", "应用所选"},
+ {"Add a deformation to the stack: Transform (Move, Turn, Scale, Squash), Bend & Twist (Bend, Twist, Taper, Shear), Shape (Round, Box, Flatten, Sag, Depth) or Surface (Polish, Relax, Smooth, Balloon). The steps run in order on the whole Part.",
+ "在堆叠中添加一个变形:变换(移动、旋转、缩放、压缩)、弯曲与扭转(弯曲、扭转、渐细、斜切)、形状(变圆、方块、平面化、下垂、深度)或表面(Polish、Relax、平滑、Balloon)。各步骤依次作用于整个部件。"},
+ {"Add the selected step again right after it (twice the twist, a second bend...).",
+ "在所选步骤之后再添加一次(两倍的扭转、第二次弯曲……)。"},
+ {"An axis the selected step works along (several: one after the other, or together for Move, Scale, Round and Box).",
+ "所选步骤作用的轴(多个时依次作用;移动、缩放、变圆与方块则一起作用)。"},
+ {"Ease the step out toward the ends of the Part instead of an even change along it (a bend that curves most in the middle, a cut with a rounded edge).",
+ "让步骤朝部件两端逐渐变小,而不是均匀变化(中间弯得最多的弯曲、边缘圆滑的切面)。"},
+ {"Keep only the selected step on the Part (one undo step) and take it off the stack; the rest stay to edit.",
+ "只把所选步骤保留在部件上(一个撤销步骤)并从堆叠中移除;其余步骤仍可编辑。"},
+ {"Keep the stack's result on the Part (one undo step) and start a new stack. With Preview on, what you see is what stays.",
+ "把堆叠的结果保留在部件上(一个撤销步骤)并开始新的堆叠。开启预览时,所见即所留。"},
+ {"Show the stack on the Part as you edit it. It is applied for real (one undo step), so it saves and exports like any change; Reset takes it back.",
+ "编辑时在部件上显示堆叠的效果。它会真正应用(一个撤销步骤),因此会像其他修改一样被保存和导出;重置可将其撤回。"},
+ {"Take the preview back off the Part and empty the stack.", "把预览从部件上撤回并清空堆叠。"},
+ {"Take the selected step off the stack.", "从堆叠中移除所选步骤。"},
+ {"Which way the step bends or leans, in degrees around its axis: 0 is toward +Y (toward +X for the Y axis).",
+ "步骤弯曲或倾斜的方向,以绕其轴的角度表示:0 朝向 +Y(Y 轴时朝向 +X)。"},
+ {"Uniform",
+ "等比"},
+ {"Resizing one side resizes the others in proportion, keeping the Part's shape.",
+ "调整一边的尺寸时,其他边按比例跟着调整,部件保持原来的形状。"},
+ {"The active Part's width (X), height (Y) and depth (Z) in scene units. Drag, or double-click and type an exact value: the Part resizes about its centre (one undo step). With Uniform, the other sides follow in proportion.",
+ "当前部件的宽度(X)、高度(Y)和深度(Z),以场景单位表示。拖动,或双击输入精确数值:部件会以其中心调整尺寸(一个撤销步骤)。开启等比时,其他边按比例跟着调整。"},
// --- Extract, Project, Deformation ---
{"E Smt", "E Smt"},
{"Parts too", "连同其他部件"},
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index 8a63ea2a..89d3657f 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -940,6 +940,48 @@ constexpr Entry kSpanish[] = {
{"Tilt", "Inclinación"},
{"Spin", "Giro"},
+ // --- Deformation > Stack (PanelDeform.cpp) ---
+ {"Turn", "Girar"},
+ {"Bend", "Doblar"},
+ {"Twist", "Torcer"},
+ {"Taper", "Afilar"},
+ {"Shear", "Inclinar"},
+ {"Round", "Redondear"},
+ {"Box", "Caja"},
+ {"Sag", "Combar"},
+ {"Shape", "Forma"},
+ {"Bend & Twist", "Doblar y torcer"},
+ {"Stack", "Pila"},
+ {"Add step", "Añadir paso"},
+ {"No steps yet: Add step", "Aún no hay pasos: Añadir paso"},
+ {"Direction", "Dirección"},
+ {"Keep volume", "Mantener volumen"},
+ {"Repeat", "Repetir"},
+ {"Apply Selected", "Aplicar selección"},
+ {"Add a deformation to the stack: Transform (Move, Turn, Scale, Squash), Bend & Twist (Bend, Twist, Taper, Shear), Shape (Round, Box, Flatten, Sag, Depth) or Surface (Polish, Relax, Smooth, Balloon). The steps run in order on the whole Part.",
+ "Añade una deformación a la pila: Transformar (Mover, Girar, Escalar, Aplastar), Doblar y torcer (Doblar, Torcer, Afilar, Inclinar), Forma (Redondear, Caja, Aplanar, Combar, Profundidad) o Superficie (Pulir, Relajar, Suavizar, Globo). Los pasos se aplican en orden a toda la pieza."},
+ {"Add the selected step again right after it (twice the twist, a second bend...).",
+ "Añade de nuevo el paso seleccionado justo después (el doble de torsión, un segundo doblez...)."},
+ {"An axis the selected step works along (several: one after the other, or together for Move, Scale, Round and Box).",
+ "Un eje sobre el que actúa el paso seleccionado (varios: uno tras otro, o juntos para Mover, Escalar, Redondear y Caja)."},
+ {"Ease the step out toward the ends of the Part instead of an even change along it (a bend that curves most in the middle, a cut with a rounded edge).",
+ "Suaviza el paso hacia los extremos de la pieza en lugar de un cambio uniforme (un doblez que se curva más en el centro, un corte con el borde redondeado)."},
+ {"Keep only the selected step on the Part (one undo step) and take it off the stack; the rest stay to edit.",
+ "Conserva solo el paso seleccionado en la pieza (un paso de deshacer) y lo quita de la pila; el resto sigue editable."},
+ {"Keep the stack's result on the Part (one undo step) and start a new stack. With Preview on, what you see is what stays.",
+ "Conserva el resultado de la pila en la pieza (un paso de deshacer) y empieza una pila nueva. Con Vista previa activada, se queda lo que ves."},
+ {"Show the stack on the Part as you edit it. It is applied for real (one undo step), so it saves and exports like any change; Reset takes it back.",
+ "Muestra la pila en la pieza mientras la editas. Se aplica de verdad (un paso de deshacer), así que se guarda y exporta como cualquier cambio; Restablecer la deshace."},
+ {"Take the preview back off the Part and empty the stack.", "Quita la vista previa de la pieza y vacía la pila."},
+ {"Take the selected step off the stack.", "Quita el paso seleccionado de la pila."},
+ {"Which way the step bends or leans, in degrees around its axis: 0 is toward +Y (toward +X for the Y axis).",
+ "Hacia dónde se dobla o inclina el paso, en grados alrededor de su eje: 0 es hacia +Y (hacia +X para el eje Y)."},
+ {"Uniform",
+ "Uniforme"},
+ {"Resizing one side resizes the others in proportion, keeping the Part's shape.",
+ "Al cambiar el tamaño de un lado, los demás cambian en proporción y la pieza conserva su forma."},
+ {"The active Part's width (X), height (Y) and depth (Z) in scene units. Drag, or double-click and type an exact value: the Part resizes about its centre (one undo step). With Uniform, the other sides follow in proportion.",
+ "Ancho (X), alto (Y) y profundidad (Z) de la pieza activa en unidades de la escena. Arrastra, o haz doble clic y escribe un valor exacto: la pieza cambia de tamaño alrededor de su centro (un paso de deshacer). Con Uniforme, los demás lados siguen en proporción."},
// --- Extract, Project, Deformation ---
{"E Smt", "E Smt"},
{"Parts too", "También las piezas"},
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index 6fc3b2fa..79e38c9f 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -787,6 +787,48 @@ constexpr Entry kTraditionalChinese[] = {
{"Roll", "翻滾"},
{"Tilt", "傾斜"},
{"Spin", "旋轉"},
+ // --- Deformation > Stack (PanelDeform.cpp) ---
+ {"Turn", "旋轉"},
+ {"Bend", "彎曲"},
+ {"Twist", "扭轉"},
+ {"Taper", "漸細"},
+ {"Shear", "斜切"},
+ {"Round", "變圓"},
+ {"Box", "方塊"},
+ {"Sag", "下垂"},
+ {"Shape", "形狀"},
+ {"Bend & Twist", "彎曲與扭轉"},
+ {"Stack", "堆疊"},
+ {"Add step", "新增步驟"},
+ {"No steps yet: Add step", "尚無步驟:新增步驟"},
+ {"Direction", "方向"},
+ {"Keep volume", "保持體積"},
+ {"Repeat", "重複"},
+ {"Apply Selected", "套用所選"},
+ {"Add a deformation to the stack: Transform (Move, Turn, Scale, Squash), Bend & Twist (Bend, Twist, Taper, Shear), Shape (Round, Box, Flatten, Sag, Depth) or Surface (Polish, Relax, Smooth, Balloon). The steps run in order on the whole Part.",
+ "在堆疊中加入一個變形:變換(移動、旋轉、縮放、壓縮)、彎曲與扭轉(彎曲、扭轉、漸細、斜切)、形狀(變圓、方塊、平面化、下垂、深度)或表面(Polish、Relax、平滑、Balloon)。各步驟依序作用於整個部件。"},
+ {"Add the selected step again right after it (twice the twist, a second bend...).",
+ "在所選步驟之後再加入一次(兩倍的扭轉、第二次彎曲……)。"},
+ {"An axis the selected step works along (several: one after the other, or together for Move, Scale, Round and Box).",
+ "所選步驟作用的軸(多個時依序作用;移動、縮放、變圓與方塊則一起作用)。"},
+ {"Ease the step out toward the ends of the Part instead of an even change along it (a bend that curves most in the middle, a cut with a rounded edge).",
+ "讓步驟朝部件兩端逐漸變小,而不是均勻變化(中間彎得最多的彎曲、邊緣圓滑的切面)。"},
+ {"Keep only the selected step on the Part (one undo step) and take it off the stack; the rest stay to edit.",
+ "只把所選步驟保留在部件上(一個復原步驟)並從堆疊中移除;其餘步驟仍可編輯。"},
+ {"Keep the stack's result on the Part (one undo step) and start a new stack. With Preview on, what you see is what stays.",
+ "把堆疊的結果保留在部件上(一個復原步驟)並開始新的堆疊。開啟預覽時,所見即所留。"},
+ {"Show the stack on the Part as you edit it. It is applied for real (one undo step), so it saves and exports like any change; Reset takes it back.",
+ "編輯時在部件上顯示堆疊的效果。它會真正套用(一個復原步驟),因此會像其他修改一樣被儲存與匯出;重設可將其撤回。"},
+ {"Take the preview back off the Part and empty the stack.", "把預覽從部件上撤回並清空堆疊。"},
+ {"Take the selected step off the stack.", "從堆疊中移除所選步驟。"},
+ {"Which way the step bends or leans, in degrees around its axis: 0 is toward +Y (toward +X for the Y axis).",
+ "步驟彎曲或傾斜的方向,以繞其軸的角度表示:0 朝向 +Y(Y 軸時朝向 +X)。"},
+ {"Uniform",
+ "等比"},
+ {"Resizing one side resizes the others in proportion, keeping the Part's shape.",
+ "調整一邊的尺寸時,其他邊按比例跟著調整,部件保持原來的形狀。"},
+ {"The active Part's width (X), height (Y) and depth (Z) in scene units. Drag, or double-click and type an exact value: the Part resizes about its centre (one undo step). With Uniform, the other sides follow in proportion.",
+ "作用中部件的寬度(X)、高度(Y)與深度(Z),以場景單位表示。拖曳,或按兩下輸入精確數值:部件會以其中心調整尺寸(一個復原步驟)。開啟等比時,其他邊按比例跟著調整。"},
// --- Extract, Project, Deformation ---
{"E Smt", "E Smt"},
{"Parts too", "連同其他部件"},
diff --git a/src/app/PanelDeform.cpp b/src/app/PanelDeform.cpp
new file mode 100644
index 00000000..5e97993b
--- /dev/null
+++ b/src/app/PanelDeform.cpp
@@ -0,0 +1,294 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tool > Deformation > Stack (docs/design/deform-panel.md, foirgairwolf on Discord): a list of whole-Part shape operations
+// (core/Deform.h) to stack up, each with its amount, axes, direction and Soft; the preview is the stack really
+// applied as one undo step (deform_stack), redone after each change while it is still the last step; Apply keeps
+// it, Apply Selected keeps one step, Reset takes it back.
+#include "app/App.h"
+#include "app/Demo.h"
+#include "app/I18n.h"
+#include "app/Palettes.h"
+#include "app/Ui.h"
+
+#include <algorithm>
+#include <cstdio>
+#include <string>
+
+namespace sf {
+
+namespace {
+
+// The add menu's groups, in our order.
+struct OpGroup {
+ const char* name;
+ std::initializer_list<DeformOp> ops;
+};
+const OpGroup kGroups[] = {
+ {"Transform", {DeformOp::Move, DeformOp::Turn, DeformOp::Scale, DeformOp::Squash}},
+ {"Bend & Twist", {DeformOp::Bend, DeformOp::Twist, DeformOp::Taper, DeformOp::Shear}},
+ {"Shape", {DeformOp::Round, DeformOp::Box, DeformOp::Flatten, DeformOp::Sag, DeformOp::Depth}},
+ {"Surface", {DeformOp::Polish, DeformOp::Relax, DeformOp::Smooth, DeformOp::Balloon}},
+};
+
+// Above this many vertices the preview follows a slider when it is let go, not while it moves.
+constexpr size_t kLiveVertices = 1000000;
+
+// "Bend 45 Y Soft" for the list.
+std::string stepLabel(const DeformStep& st) {
+ char amount[32];
+ std::snprintf(amount, sizeof amount, "%.0f", double(st.options.amount));
+ std::string s = std::string(tr(deformName(st.op))) + " " + amount;
+ if (deformUsesAxes(st.op)) {
+ std::string axes = axesLetters(st.options.axes);
+ for (char& c : axes) c = char(c - 'a' + 'A');
+ s += " " + axes;
+ }
+ if (st.options.soft && deformUsesSoft(st.op)) s += std::string(" ") + tr("Soft");
+ return s;
+}
+
+} // namespace
+
+bool App::deformStackUndoPreview() {
+ DeformStackUi& ds = deformStack_;
+ if (!ds.previewed) return false;
+ ds.previewed = false;
+ // Only while it is still the last step on the same Part: otherwise it is simply kept.
+ if (doc_.undo.revision() != ds.revision || doc_.activePartInfo().id != ds.part) return false;
+ runCommand("undo");
+ return true;
+}
+
+void App::deformStackRun(const std::vector<DeformStep>& steps) {
+ if (steps.empty()) return;
+ Args a{{"ops", deformStackText(steps)}};
+ if (gizmo_.mode != GizmoMode::Off && gizmo_.pivotPlaced) { // the gizmo's pivot, when it was placed
+ char p[96];
+ std::snprintf(p, sizeof p, "%g,%g,%g", double(gizmo_.pivot.x), double(gizmo_.pivot.y), double(gizmo_.pivot.z));
+ a["pivot"] = std::string(p);
+ }
+ runCommand("deform_stack", a);
+}
+
+void App::deformStackRefresh() {
+ DeformStackUi& ds = deformStack_;
+ deformStackUndoPreview();
+ if (!ds.preview) return;
+ std::vector<DeformStep> on;
+ for (size_t i = 0; i < ds.steps.size(); ++i)
+ if (ds.on[i]) on.push_back(ds.steps[i]);
+ if (on.empty()) return;
+ const uint64_t before = doc_.undo.revision();
+ deformStackRun(on);
+ if (!lastCommandOk_ || doc_.undo.revision() == before) return;
+ ds.previewed = true;
+ ds.revision = doc_.undo.revision();
+ ds.part = doc_.activePartInfo().id;
+}
+
+void App::deformStackApply(bool selectedOnly) {
+ DeformStackUi& ds = deformStack_;
+ if (selectedOnly) {
+ if (ds.selected < 0 || ds.selected >= int(ds.steps.size())) return;
+ deformStackUndoPreview();
+ deformStackRun({ds.steps[size_t(ds.selected)]});
+ ds.steps.erase(ds.steps.begin() + ds.selected);
+ ds.on.erase(ds.on.begin() + ds.selected);
+ ds.selected = std::min(ds.selected, int(ds.steps.size()) - 1);
+ deformStackRefresh(); // the rest preview again on top
+ return;
+ }
+ // The preview (current or not) is already on the Part: it stays. Without one, run the stack now.
+ const bool kept = ds.previewed;
+ ds.previewed = false;
+ if (!kept) {
+ std::vector<DeformStep> on;
+ for (size_t i = 0; i < ds.steps.size(); ++i)
+ if (ds.on[i]) on.push_back(ds.steps[i]);
+ deformStackRun(on);
+ }
+ ds.steps.clear();
+ ds.on.clear();
+ ds.selected = -1;
+}
+
+void App::deformStackReset() {
+ DeformStackUi& ds = deformStack_;
+ deformStackUndoPreview();
+ ds.steps.clear();
+ ds.on.clear();
+ ds.selected = -1;
+}
+
+void App::deformStackAdd(DeformOp op) {
+ DeformStackUi& ds = deformStack_;
+ DeformStep st;
+ st.op = op;
+ float lo, hi;
+ deformRange(op, lo, hi, st.options.amount);
+ // A new step starts on the axes of the step before it (most stacks work along one axis).
+ if (!ds.steps.empty()) st.options.axes = ds.steps.back().options.axes;
+ ds.steps.push_back(st);
+ ds.on.push_back(1);
+ ds.selected = int(ds.steps.size()) - 1;
+ deformStackRefresh();
+}
+
+void App::drawDeformSize() {
+ DeformSizeUi& sz = deformSize_;
+ const Mesh& mesh = doc_.mesh;
+ if (sz.revision != doc_.undo.revision() || sz.part != doc_.activePartInfo().id || sz.vertices != mesh.vertexCount()) {
+ const AABB box = mesh.vertexCount() ? mesh.bounds() : AABB{glm::vec3(0.0f), glm::vec3(0.0f)};
+ sz.revision = doc_.undo.revision();
+ sz.part = doc_.activePartInfo().id;
+ sz.vertices = mesh.vertexCount();
+ sz.size = sz.edit = box.max - box.min;
+ }
+ Demo::pushScope("Size");
+ tray::GroupLabel(*this, "Size");
+ const ImGuiStyle& style = ImGui::GetStyle();
+ const float lock = ImGui::CalcTextSize(tr("Uniform")).x + ImGui::GetFrameHeight() + style.ItemInnerSpacing.x;
+ const float each = (ImGui::GetContentRegionAvail().x - lock - 3.0f * style.ItemSpacing.x) / 3.0f;
+ static const char* const kIds[3] = {"##deform_size_x", "##deform_size_y", "##deform_size_z"};
+ static const char* const kFormats[3] = {"X %.4g", "Y %.4g", "Z %.4g"};
+ int edited = -1;
+ for (int a = 0; a < 3; ++a) {
+ if (a) ImGui::SameLine();
+ ImGui::SetNextItemWidth(each);
+ const float speed = std::max(sz.size[a], 1e-3f) * 0.002f;
+ ImGui::DragFloat(kIds[a], &sz.edit[a], speed, 0.0f, 1e9f, kFormats[a], ImGuiSliderFlags_AlwaysClamp);
+ if (ImGui::IsItemDeactivatedAfterEdit()) edited = a;
+ ui::HelpText("Size", nullptr,
+ "The active Part's width (X), height (Y) and depth (Z) in scene units. Drag, or double-click and "
+ "type an exact value: the Part resizes about its centre (one undo step). With Uniform, the other "
+ "sides follow in proportion.",
+ "Tool > Deformation > Size");
+ }
+ ImGui::SameLine();
+ ui::Checkbox((std::string(tr("Uniform")) + "##deform_size_uniform").c_str(), &sz.uniform);
+ ui::HelpText("Uniform", nullptr, "Resizing one side resizes the others in proportion, keeping the Part's shape.",
+ "Tool > Deformation > Size");
+ if (edited >= 0 && sz.edit[edited] > 0.0f && sz.edit[edited] != sz.size[edited]) {
+ Args a;
+ if (sz.uniform && sz.size[edited] > 0.0f) {
+ const glm::vec3 to = sz.size * (sz.edit[edited] / sz.size[edited]);
+ a = {{"x", double(to.x)}, {"y", double(to.y)}, {"z", double(to.z)}};
+ } else {
+ a[std::string(1, char('x' + edited))] = double(sz.edit[edited]);
+ }
+ runCommand("deform_size", a);
+ sz.revision = ~uint64_t(0); // read the new size back
+ } else if (edited >= 0) {
+ sz.edit = sz.size;
+ }
+ Demo::popScope();
+}
+
+void App::drawDeformStack() {
+ DeformStackUi& ds = deformStack_;
+ // Another undo step since the preview: it is part of the history now (kept, never undone behind your back).
+ if (ds.previewed && (doc_.undo.revision() != ds.revision || doc_.activePartInfo().id != ds.part)) ds.previewed = false;
+ Demo::pushScope("Stack");
+ tray::GroupLabel(*this, "Stack");
+ const ImGuiStyle& style = ImGui::GetStyle();
+ const float half = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) * 0.5f;
+
+ // Add: one menu, grouped.
+ ImGui::SetNextItemWidth(half);
+ if (ImGui::BeginCombo("##deform_stack_add", tr("Add step"))) {
+ for (const OpGroup& g : kGroups) {
+ ImGui::TextDisabled("%s", tr(g.name));
+ ImGui::Indent();
+ for (DeformOp op : g.ops) {
+ const std::string item = std::string(tr(deformName(op))) + "##deform_add_" + deformName(op);
+ if (ImGui::Selectable(item.c_str())) deformStackAdd(op);
+ }
+ ImGui::Unindent();
+ }
+ ImGui::EndCombo();
+ }
+ ui::HelpText("Add step", nullptr,
+ "Add a deformation to the stack: Transform (Move, Turn, Scale, Squash), Bend & Twist (Bend, Twist, "
+ "Taper, Shear), Shape (Round, Box, Flatten, Sag, Depth) or Surface (Polish, Relax, Smooth, Balloon). "
+ "The steps run in order on the whole Part.",
+ "Tool > Deformation > Stack");
+ ImGui::SameLine();
+ if (ui::Checkbox((std::string(tr("Preview")) + "##deform_stack_preview").c_str(), &ds.preview)) {
+ if (ds.preview) deformStackRefresh();
+ else deformStackUndoPreview();
+ }
+ ui::HelpText("Preview", nullptr,
+ "Show the stack on the Part as you edit it. It is applied for real (one undo step), so it saves and "
+ "exports like any change; Reset takes it back.",
+ "Tool > Deformation > Stack");
+
+ // The list: on/off and the step; click a step to edit it.
+ if (ds.steps.empty()) {
+ ImGui::TextDisabled("%s", tr("No steps yet: Add step"));
+ } else {
+ for (size_t i = 0; i < ds.steps.size(); ++i) {
+ ImGui::PushID(int(i));
+ bool on = ds.on[i] != 0;
+ if (ui::Checkbox("##on", &on)) {
+ ds.on[i] = on;
+ deformStackRefresh();
+ }
+ ImGui::SameLine();
+ const std::string label = stepLabel(ds.steps[i]) + "##deform_step";
+ if (ImGui::Selectable(label.c_str(), ds.selected == int(i))) ds.selected = int(i);
+ ImGui::PopID();
+ }
+ }
+
+ // The selected step's settings.
+ if (ds.selected >= 0 && ds.selected < int(ds.steps.size())) {
+ DeformStep& st = ds.steps[size_t(ds.selected)];
+ float lo, hi, def;
+ deformRange(st.op, lo, hi, def);
+ const bool live = doc_.mesh.vertexCount() < kLiveVertices;
+ bool changed = false;
+ const std::string format = std::string(tr(deformName(st.op))) + " %.0f";
+ ImGui::SetNextItemWidth(-1);
+ const bool moved = ui::SliderInside("##deform_step_amount", &st.options.amount, lo, hi, format.c_str());
+ changed |= live ? moved : ImGui::IsItemDeactivatedAfterEdit();
+ if (deformUsesAxes(st.op))
+ ui::Segmented(*this, {"deformation.stack_x", "deformation.stack_y", "deformation.stack_z"}, -1.0f);
+ if (deformUsesDirection(st.op)) {
+ ImGui::SetNextItemWidth(-1);
+ const bool d = ui::SliderInside("##deform_step_direction", &st.options.direction, 0.0f, 360.0f,
+ (std::string(tr("Direction")) + " %.0f").c_str());
+ changed |= live ? d : ImGui::IsItemDeactivatedAfterEdit();
+ ui::HelpText("Direction", nullptr,
+ "Which way the step bends or leans, in degrees around its axis: 0 is toward +Y (toward +X "
+ "for the Y axis).",
+ "Tool > Deformation > Stack");
+ }
+ if (deformUsesSoft(st.op)) {
+ changed |= ui::Checkbox((std::string(tr("Soft")) + "##deform_step_soft").c_str(), &st.options.soft);
+ ui::HelpText("Soft", nullptr,
+ "Ease the step out toward the ends of the Part instead of an even change along it (a bend "
+ "that curves most in the middle, a cut with a rounded edge).",
+ "Tool > Deformation > Stack");
+ }
+ if (st.op == DeformOp::Smooth)
+ changed |= ui::Checkbox((std::string(tr("Keep volume")) + "##deform_step_volume").c_str(), &st.options.keepVolume);
+ if (changed) deformStackRefresh();
+ ui::ActionButton(*this, "deformation.stack_repeat", ImVec2(half, 0));
+ ui::HelpAction(*this, "deformation.stack_repeat");
+ ImGui::SameLine();
+ ui::ActionButton(*this, "deformation.stack_remove", ImVec2(-1, 0));
+ ui::HelpAction(*this, "deformation.stack_remove");
+ ui::ActionButton(*this, "deformation.stack_apply_selected", ImVec2(-1, 0));
+ ui::HelpAction(*this, "deformation.stack_apply_selected");
+ }
+
+ ui::ActionButton(*this, "deformation.stack_apply", ImVec2(half, 0));
+ ui::HelpAction(*this, "deformation.stack_apply");
+ ImGui::SameLine();
+ ui::ActionButton(*this, "deformation.stack_reset", ImVec2(-1, 0));
+ ui::HelpAction(*this, "deformation.stack_reset");
+ Demo::popScope();
+}
+
+} // namespace sf
diff --git a/src/app/PanelExtract.cpp b/src/app/PanelExtract.cpp
index df494219..9801da35 100644
--- a/src/app/PanelExtract.cpp
+++ b/src/app/PanelExtract.cpp
@@ -114,6 +114,8 @@ void App::drawDeformationContents() {
"Deformation > Smooth smooths without shrinking the form (Taubin smoothing) instead of the plain "
"smooth, which also shrinks it.",
"Tool > Deformation");
+ drawDeformSize(); // PanelDeform.cpp
+ drawDeformStack();
}
} // namespace sf
diff --git a/src/core/Deform.cpp b/src/core/Deform.cpp
index a8f63ee9..30805e01 100644
--- a/src/core/Deform.cpp
+++ b/src/core/Deform.cpp
@@ -4,21 +4,144 @@
#include "core/Commands.h"
#include "core/Document.h"
+#include "core/PathStroke.h"
#include "core/ThreadPool.h"
+#include <glm/gtc/quaternion.hpp>
+
#include <algorithm>
+#include <cctype>
#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <limits>
+#include <sstream>
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";
+namespace {
+
+struct OpInfo {
+ DeformOp op;
+ const char* name;
+ const char* command;
+ float lo, hi, def;
+};
+// Own ranges (docs/design/deform-panel.md): degrees for Turn, Bend and Twist, percent for the rest.
+const OpInfo kOps[kDeformOpCount] = {
+ {DeformOp::Polish, "Polish", "deform_polish", 0, 100, 50}, {DeformOp::Relax, "Relax", "deform_relax", 0, 100, 50},
+ {DeformOp::Smooth, "Smooth", "deform_smooth", 0, 100, 50}, {DeformOp::Balloon, "Balloon", "deform_balloon", -100, 100, 50},
+ {DeformOp::Move, "Move", "deform_move", -100, 100, 20}, {DeformOp::Turn, "Turn", "deform_turn", -180, 180, 45},
+ {DeformOp::Scale, "Scale", "deform_scale", -100, 100, 25}, {DeformOp::Squash, "Squash", "deform_squash", -100, 100, 30},
+ {DeformOp::Bend, "Bend", "deform_bend", -180, 180, 45}, {DeformOp::Twist, "Twist", "deform_twist", -360, 360, 90},
+ {DeformOp::Taper, "Taper", "deform_taper", -100, 100, 40}, {DeformOp::Shear, "Shear", "deform_shear", -100, 100, 30},
+ {DeformOp::Round, "Round", "deform_round", -100, 100, 50}, {DeformOp::Box, "Box", "deform_box", -100, 100, 50},
+ {DeformOp::Flatten, "Flatten", "deform_flatten", -100, 100, 20}, {DeformOp::Sag, "Sag", "deform_sag", -100, 100, 30},
+ {DeformOp::Depth, "Depth", "deform_depth", -90, 90, 40},
+};
+const OpInfo& info(DeformOp op) { return kOps[size_t(op)]; }
+
+} // namespace
+
+const char* deformName(DeformOp op) { return info(op).name; }
+const char* deformCommand(DeformOp op) { return info(op).command; }
+
+bool deformFromName(const std::string& name, DeformOp& op) {
+ std::string n;
+ for (char c : name) n += char(std::tolower(static_cast<unsigned char>(c)));
+ if (n.rfind("deform_", 0) == 0) n = n.substr(7);
+ for (const OpInfo& i : kOps) {
+ std::string m;
+ for (const char* c = i.name; *c; ++c) m += char(std::tolower(static_cast<unsigned char>(*c)));
+ if (m == n) {
+ op = i.op;
+ return true;
+ }
}
- return "Deform";
+ return false;
+}
+
+void deformRange(DeformOp op, float& lo, float& hi, float& def) {
+ lo = info(op).lo;
+ hi = info(op).hi;
+ def = info(op).def;
+}
+
+bool deformUsesDirection(DeformOp op) { return op == DeformOp::Bend || op == DeformOp::Shear; }
+bool deformUsesSoft(DeformOp op) {
+ return op == DeformOp::Bend || op == DeformOp::Twist || op == DeformOp::Taper || op == DeformOp::Shear ||
+ op == DeformOp::Flatten;
+}
+bool deformUsesAxes(DeformOp op) { return int(op) >= int(DeformOp::Move); }
+
+std::string axesLetters(uint8_t axes) {
+ std::string s;
+ for (int a = 0; a < 3; ++a)
+ if (axes & (1 << a)) s += char('x' + a);
+ return s;
+}
+
+bool parseDeformStack(const std::string& text, std::vector<DeformStep>& steps, std::string& error) {
+ steps.clear();
+ size_t start = 0;
+ while (start <= text.size()) {
+ size_t end = text.find(';', start);
+ if (end == std::string::npos) end = text.size();
+ std::istringstream in(text.substr(start, end - start));
+ start = end + 1;
+ std::string word;
+ if (!(in >> word)) continue;
+ DeformStep st;
+ if (!deformFromName(word, st.op)) {
+ error = "Unknown deformation '" + word + "'";
+ return false;
+ }
+ float lo, hi;
+ deformRange(st.op, lo, hi, st.options.amount);
+ bool haveAmount = false;
+ while (in >> word) {
+ char* e = nullptr;
+ const float v = std::strtof(word.c_str(), &e);
+ if (!haveAmount && e && *e == '\0' && e != word.c_str()) {
+ st.options.amount = std::clamp(v, lo, hi);
+ haveAmount = true;
+ } else if (word == "soft") {
+ st.options.soft = true;
+ } else if (word == "volume") {
+ st.options.keepVolume = true;
+ } else if (word == "nomask") {
+ st.options.useMask = false;
+ } else if (word.rfind("dir=", 0) == 0) {
+ st.options.direction = std::strtof(word.c_str() + 4, nullptr);
+ } else if (word.find_first_not_of("xyzXYZ") == std::string::npos) {
+ st.options.axes = 0;
+ for (char c : word) st.options.axes |= uint8_t(1 << (std::tolower(static_cast<unsigned char>(c)) - 'x'));
+ } else {
+ error = "Bad word '" + word + "' in deformation '" + deformName(st.op) + "'";
+ return false;
+ }
+ }
+ steps.push_back(st);
+ }
+ if (steps.empty()) error = "No deformations";
+ return !steps.empty();
+}
+
+std::string deformStackText(const std::vector<DeformStep>& steps) {
+ std::ostringstream out;
+ for (size_t i = 0; i < steps.size(); ++i) {
+ const DeformStep& st = steps[i];
+ if (i) out << "; ";
+ std::string n = deformName(st.op);
+ for (char& c : n) c = char(std::tolower(static_cast<unsigned char>(c)));
+ out << n << ' ' << st.options.amount;
+ if (deformUsesAxes(st.op)) out << ' ' << axesLetters(st.options.axes);
+ if (st.options.soft && deformUsesSoft(st.op)) out << " soft";
+ if (st.options.direction != 0.0f && deformUsesDirection(st.op)) out << " dir=" << st.options.direction;
+ if (st.options.keepVolume && st.op == DeformOp::Smooth) out << " volume";
+ if (!st.options.useMask) out << " nomask";
+ }
+ return out.str();
}
namespace {
@@ -85,9 +208,11 @@ void passes(float amount, int most, int& count, float& each) {
} // 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;
+namespace {
+
+// Polish, Relax, Smooth and Balloon on P (open borders stay).
+void surfaceOp(const Mesh& m, std::vector<vec3>& P, DeformOp op, const DeformOptions& o) {
+ std::vector<vec3> Q, N;
const std::vector<float> k = freedom(m, o.useMask);
int count = 0;
float each = 0.0f;
@@ -183,31 +308,282 @@ std::vector<vec3> deformPositions(const Mesh& m, DeformOp op, const DeformOption
}
break;
}
+ default: break;
+ }
+}
+
+// The eased profile: u (3 - u^2) / 2, flat at the ends; plain u otherwise.
+inline float profile(float u, bool soft) {
+ if (!soft) return u;
+ u = std::clamp(u, -1.0f, 1.0f);
+ return u * (3.0f - u * u) * 0.5f;
+}
+
+// Unit axis a (0-2) and two directions across it: e1 (+Y for X and Z, +X for Y) and e2 = a x e1.
+void frameOf(int a, vec3& axis, vec3& e1, vec3& e2) {
+ axis = vec3(0.0f);
+ axis[a] = 1.0f;
+ e1 = a == 1 ? vec3(1, 0, 0) : vec3(0, 1, 0);
+ e2 = glm::cross(axis, e1);
+}
+
+// The largest |q . dir| over Q (never 0).
+float extentAlong(const std::vector<vec3>& Q, const vec3& c, const vec3& dir) {
+ float e = 0.0f;
+ for (const vec3& p : Q) e = std::max(e, std::abs(glm::dot(p - c, dir)));
+ return std::max(e, 1e-12f);
+}
+
+// One pass of an operation on Q (every vertex, unweighted) about c.
+template <class F>
+void mapAll(std::vector<vec3>& Q, F&& f) {
+ poolFor(Q.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) Q[i] = f(Q[i]);
+ }, kGrain);
+}
+
+// Move ... Depth on P: the unweighted result of every pass, then blended in by each vertex's weight.
+void shapeOp(const Mesh& m, std::vector<vec3>& P, DeformOp op, const DeformOptions& o) {
+ if (P.empty() || o.axes == 0) return;
+ vec3 c = o.pivot;
+ if (!o.hasPivot) {
+ AABB box;
+ for (const vec3& p : P) box.expand(p);
+ c = box.center();
+ }
+ const float t = o.amount / 100.0f;
+ const float radians = glm::radians(o.amount);
+ std::vector<vec3> Q = P;
+ const bool vectorOp = op == DeformOp::Move || op == DeformOp::Scale || op == DeformOp::Round || op == DeformOp::Box;
+ if (vectorOp) {
+ vec3 sel(0.0f);
+ for (int a = 0; a < 3; ++a)
+ if (o.axes & (1 << a)) sel[a] = 1.0f;
+ switch (op) {
+ case DeformOp::Move: {
+ vec3 d(0.0f);
+ for (int a = 0; a < 3; ++a)
+ if (sel[a] > 0.0f) {
+ vec3 dir(0.0f);
+ dir[a] = 1.0f;
+ d[a] = t * extentAlong(Q, c, dir);
+ }
+ mapAll(Q, [&](const vec3& p) { return p + d; });
+ break;
+ }
+ case DeformOp::Scale: {
+ const vec3 f = glm::mix(vec3(1.0f), vec3(std::exp2(t)), sel);
+ mapAll(Q, [&](const vec3& p) { return c + (p - c) * f; });
+ break;
+ }
+ default: { // Round, Box: the chosen components toward the sphere (cube) of their mean radius
+ const bool box = op == DeformOp::Box;
+ auto radius = [&](const vec3& q) {
+ const vec3 s = q * sel;
+ return box ? std::max(std::abs(s.x), std::max(std::abs(s.y), std::abs(s.z))) : glm::length(s);
+ };
+ double sum = 0.0;
+ for (const vec3& p : Q) sum += double(radius(p - c));
+ const float r = float(sum / double(Q.size()));
+ mapAll(Q, [&](const vec3& p) {
+ const vec3 q = p - c;
+ const float l = radius(q);
+ if (l < 1e-20f) return p;
+ const vec3 s = q * sel;
+ return p + (s * (r / l) - s) * t;
+ });
+ break;
+ }
+ }
+ } else {
+ for (int a = 0; a < 3; ++a) {
+ if (!(o.axes & (1 << a))) continue;
+ vec3 axis, e1, e2;
+ frameOf(a, axis, e1, e2);
+ const float th = glm::radians(o.direction);
+ const vec3 b = std::cos(th) * e1 + std::sin(th) * e2; // Bend, Shear: toward b
+ const vec3 n3 = glm::cross(axis, b);
+ const float ext = extentAlong(Q, c, axis);
+ switch (op) {
+ case DeformOp::Turn: {
+ const glm::mat3 R = glm::mat3_cast(glm::angleAxis(radians, axis));
+ mapAll(Q, [&](const vec3& p) { return c + R * (p - c); });
+ break;
+ }
+ case DeformOp::Squash: {
+ const float f = std::exp2(-t), g = 1.0f / std::sqrt(f);
+ mapAll(Q, [&](const vec3& p) {
+ const vec3 q = p - c;
+ const float y = q[a];
+ vec3 r = q * g;
+ r[a] = y * f;
+ return c + r;
+ });
+ break;
+ }
+ case DeformOp::Twist: {
+ const float half = 0.5f * radians;
+ mapAll(Q, [&](const vec3& p) {
+ const vec3 q = p - c;
+ const float phi = half * profile(q[a] / ext, o.soft);
+ const float x = glm::dot(q, e1), z = glm::dot(q, e2), cs = std::cos(phi), sn = std::sin(phi);
+ return c + axis * q[a] + e1 * (x * cs - z * sn) + e2 * (x * sn + z * cs);
+ });
+ break;
+ }
+ case DeformOp::Taper: {
+ mapAll(Q, [&](const vec3& p) {
+ const vec3 q = p - c;
+ const float f = std::max(0.0f, 1.0f + t * profile(q[a] / ext, o.soft));
+ return c + axis * q[a] + (q - axis * q[a]) * f;
+ });
+ break;
+ }
+ case DeformOp::Shear: {
+ mapAll(Q, [&](const vec3& p) { return p + b * (t * ext * profile((p - c)[a] / ext, o.soft)); });
+ break;
+ }
+ case DeformOp::Depth: {
+ const float tt = std::clamp(t, -0.9f, 0.9f);
+ mapAll(Q, [&](const vec3& p) {
+ const vec3 q = p - c;
+ const float f = 1.0f / (1.0f - 0.5f * tt * std::clamp(q[a] / ext, -1.0f, 1.0f));
+ return c + axis * q[a] + (q - axis * q[a]) * f;
+ });
+ break;
+ }
+ case DeformOp::Sag: {
+ float R = 0.0f;
+ for (const vec3& p : Q) {
+ const vec3 q = p - c;
+ R = std::max(R, glm::length(q - axis * q[a]));
+ }
+ R = std::max(R, 1e-12f);
+ mapAll(Q, [&](const vec3& p) {
+ const vec3 q = p - c;
+ const float r = glm::length(q - axis * q[a]) / R;
+ return p - axis * (t * 0.5f * R * r * r);
+ });
+ break;
+ }
+ case DeformOp::Flatten: {
+ float lo = std::numeric_limits<float>::max(), hi = std::numeric_limits<float>::lowest();
+ for (const vec3& p : Q) {
+ lo = std::min(lo, p[a]);
+ hi = std::max(hi, p[a]);
+ }
+ const float depth = hi - lo, k = o.soft ? 0.08f * depth : 0.0f;
+ const bool top = t >= 0.0f;
+ const float level = top ? hi - std::abs(t) * depth : lo + std::abs(t) * depth;
+ mapAll(Q, [&](vec3 p) {
+ // The + side cut at level (the - side for a negative amount); Soft: a polynomial smooth min.
+ const float x = top ? p[a] : -p[a], L = top ? level : -level;
+ float y = std::min(x, L);
+ if (k > 0.0f) {
+ const float h = std::clamp(0.5f + 0.5f * (L - x) / k, 0.0f, 1.0f);
+ y = glm::mix(L, x, h) - k * h * (1.0f - h);
+ }
+ p[a] = top ? y : -y;
+ return p;
+ });
+ break;
+ }
+ case DeformOp::Bend: {
+ // The axis through c bends into a curve C(y) whose direction turns by phi(y) toward b; each point
+ // keeps its distance x across it (toward b) and z (along n3). Uniform: an arc of radius
+ // 2 ext / Phi; Soft: C tabulated by the midpoint rule.
+ const float half = 0.5f * radians;
+ if (std::abs(half) < 1e-7f) break;
+ constexpr int kSamples = 2048;
+ std::vector<glm::vec2> table;
+ if (o.soft) {
+ table.resize(kSamples + 1);
+ const float dy = 2.0f * ext / kSamples;
+ const int mid = kSamples / 2;
+ table[size_t(mid)] = glm::vec2(0.0f);
+ for (int i = mid; i < kSamples; ++i) { // outward from the middle, both ways
+ const float ym = (float(i - mid) + 0.5f) * dy, phi = half * profile(ym / ext, true);
+ table[size_t(i + 1)] = table[size_t(i)] + glm::vec2(std::cos(phi), std::sin(phi)) * dy;
+ const float yn = -ym, phn = half * profile(yn / ext, true);
+ table[size_t(2 * mid - i - 1)] =
+ table[size_t(2 * mid - i)] - glm::vec2(std::cos(phn), std::sin(phn)) * dy;
+ }
+ }
+ const float kc = half / ext; // curvature of the uniform bend
+ mapAll(Q, [&](const vec3& p) {
+ const vec3 q = p - c;
+ const float y = q[a], x = glm::dot(q, b), z = glm::dot(q, n3);
+ const float phi = half * profile(y / ext, o.soft);
+ glm::vec2 C; // (along the axis, toward b)
+ if (o.soft) {
+ const float f = std::clamp((y / ext + 1.0f) * 0.5f * kSamples, 0.0f, float(kSamples));
+ const int i = std::min(int(f), kSamples - 1);
+ C = glm::mix(table[size_t(i)], table[size_t(i + 1)], f - float(i));
+ } else {
+ C = glm::vec2(std::sin(kc * y), 1.0f - std::cos(kc * y)) / kc;
+ }
+ const float cs = std::cos(phi), sn = std::sin(phi);
+ return c + axis * (C.x - x * sn) + b * (C.y + x * cs) + n3 * z;
+ });
+ break;
+ }
+ default: break;
+ }
+ }
}
+ // Weighted in: 1 - mask (useMask), 0 when hidden.
+ const bool hidden = m.hasHidden(), masked = o.useMask && m.hasMask();
+ poolFor(P.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const uint32_t v = uint32_t(i);
+ float w = masked ? 1.0f - m.maskAt(v) : 1.0f;
+ if (hidden && m.vertexHidden(v)) w = 0.0f;
+ P[i] = w >= 1.0f ? Q[i] : P[i] + (Q[i] - P[i]) * w;
+ }
+ }, kGrain);
+}
+
+void runOp(const Mesh& m, std::vector<vec3>& P, DeformOp op, const DeformOptions& o) {
+ if (deformUsesAxes(op)) shapeOp(m, P, op, o);
+ else surfaceOp(m, P, op, o);
+}
+
+} // namespace
+
+std::vector<vec3> deformPositions(const Mesh& m, DeformOp op, const DeformOptions& o) {
+ std::vector<vec3> P = m.positions;
+ if (m.vertexCount() == 0 || m.triangleCount() == 0) return P;
+ runOp(m, P, op, o);
+ return P;
+}
+
+std::vector<vec3> deformStackPositions(const Mesh& m, const std::vector<DeformStep>& steps) {
+ std::vector<vec3> P = m.positions;
+ if (m.vertexCount() == 0 || m.triangleCount() == 0) return P;
+ for (const DeformStep& st : steps) runOp(m, P, st.op, st.options);
return P;
}
size_t deformActivePart(Document& doc, DeformOp op, const DeformOptions& o, std::string& error) {
+ return deformActivePart(doc, {DeformStep{op, o}}, error, deformName(op));
+}
+
+namespace {
+
+// Why the active Part can't be deformed now ("" when it can).
+bool canDeform(Document& doc, const std::string& name, std::string& error) {
+ const Mesh& mesh = doc.mesh;
+ if (doc.sculptor.strokeActive()) error = name + ": finish the stroke first";
+ else if (mesh.vertexCount() == 0 || mesh.triangleCount() == 0) error = name + ": the active Part is empty";
+ else if (!mesh.forgespheres.empty()) error = name + ": the active Part is a Forge Sphere Part (Make Mesh first)";
+ else if (mesh.micro) error = name + ": the active Part has a micro level (Bake Micro or Delete Micro first)";
+ else return true;
+ return false;
+}
+
+// Moves the active Part's vertices to P through the Sculptor as one undo step labelled `name`.
+size_t commitPositions(Document& doc, const std::vector<vec3>& P, const std::string& name, bool masked, 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.forgespheres.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) {
@@ -218,7 +594,7 @@ size_t deformActivePart(Document& doc, DeformOp op, const DeformOptions& o, std:
}
}
if (verts.empty()) {
- error = name + ": nothing moved" + (o.useMask && mesh.hasMask() ? " (is everything masked?)" : "");
+ error = name + ": nothing moved" + (masked && mesh.hasMask() ? " (is everything masked?)" : "");
return 0;
}
if (!doc.sculptor.beginStroke(mesh, name, doc.activeLayer)) {
@@ -231,49 +607,188 @@ size_t deformActivePart(Document& doc, DeformOp op, const DeformOptions& o, std:
return verts.size();
}
+} // namespace
+
+size_t deformActivePart(Document& doc, const std::vector<DeformStep>& steps, std::string& error, const std::string& label) {
+ if (!canDeform(doc, label, error)) return 0;
+ doc.syncBvh();
+ bool masked = false;
+ for (const DeformStep& st : steps) masked |= st.options.useMask;
+ return commitPositions(doc, deformStackPositions(doc.mesh, steps), label, masked, error);
+}
+
+size_t resizeActivePart(Document& doc, const glm::vec3& size, bool useMask, std::string& error) {
+ if (!canDeform(doc, "Size", error)) return 0;
+ const Mesh& m = doc.mesh;
+ const AABB box = m.bounds();
+ const vec3 now = box.max - box.min, c = box.center();
+ vec3 f(1.0f);
+ for (int a = 0; a < 3; ++a)
+ if (size[a] > 0.0f) {
+ if (now[a] < 1e-12f) {
+ error = std::string("Size: the Part is flat along ") + char('X' + a) + ", it can't be stretched to a size";
+ return 0;
+ }
+ f[a] = size[a] / now[a];
+ }
+ doc.syncBvh();
+ std::vector<vec3> P = m.positions;
+ const bool hidden = m.hasHidden(), masked = useMask && m.hasMask();
+ poolFor(P.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const uint32_t v = uint32_t(i);
+ float w = masked ? 1.0f - m.maskAt(v) : 1.0f;
+ if (hidden && m.vertexHidden(v)) w = 0.0f;
+ const vec3 q = c + (P[i] - c) * f;
+ P[i] = w >= 1.0f ? q : P[i] + (q - P[i]) * w;
+ }
+ }, kGrain);
+ return commitPositions(doc, P, "Size", useMask, error);
+}
+
+namespace {
+
+// axes=, direction=, soft=, pivot= into o (shape operations).
+bool shapeArgs(const Args& a, DeformOptions& o, std::string& error) {
+ const std::string axes = argString(a, "axes", "y");
+ o.axes = 0;
+ for (char ch : axes) {
+ const int k = std::tolower(static_cast<unsigned char>(ch)) - 'x';
+ if (k < 0 || k > 2) {
+ error = "Bad axes '" + axes + "' (any of x, y, z)";
+ return false;
+ }
+ o.axes |= uint8_t(1 << k);
+ }
+ if (o.axes == 0) o.axes = DeformY;
+ o.direction = float(argNumber(a, "direction", 0.0));
+ o.soft = argBool(a, "soft", false);
+ const std::string pivot = argString(a, "pivot");
+ if (!pivot.empty()) {
+ if (!parseVec3(pivot, o.pivot)) {
+ error = "Bad pivot '" + pivot + "' (expected x,y,z)";
+ return false;
+ }
+ o.hasPivot = true;
+ }
+ return true;
+}
+
+} // namespace
+
void registerDeformCommands(CommandRegistry& reg) {
using T = ParamSpec::Type;
- struct Spec {
- const char* name;
- DeformOp op;
- const char* what;
+ static const char* const kWhat[kDeformOpCount] = {
+ "Polish the active Part: flatten fine noise and small bumps while keeping flat areas and sharp edges.",
+ "Relax the active Part: even out the spacing of its vertices along the surface without changing its shape.",
+ "Smooth the whole active Part (Laplacian; keep_volume=true for Taubin smoothing, which doesn't shrink it).",
+ "Balloon: fill the active Part out toward a rounder volume; a negative amount lets the air out.",
+ "Move the active Part along the axes by amount percent of its half-size.",
+ "Turn the active Part by amount degrees about each axis in turn (X, then Y, then Z) through the pivot.",
+ "Scale the active Part along the axes: 100 doubles, -100 halves.",
+ "Squash the active Part along each axis, keeping its volume (it widens across): 100 halves the length, "
+ "-100 doubles it.",
+ "Bend the active Part along each axis by amount degrees end to end, toward direction (degrees about the "
+ "axis); soft=true bends the middle most.",
+ "Twist the active Part about each axis by amount degrees end to end; soft=true eases toward the ends.",
+ "Taper the active Part along each axis: the + end grows by amount percent, the - end shrinks by it.",
+ "Shear the active Part along each axis toward direction: 100 leans it 45 degrees.",
+ "Round the active Part: its axes' components move toward a sphere (one axis left out: a cylinder about it); "
+ "negative moves away.",
+ "Box the active Part: its axes' components move toward a cube (one axis left out: a square prism).",
+ "Flatten the active Part: cut its + side flat along each axis by amount percent of its depth (negative: the "
+ "- side); soft=true rounds the edge of the cut.",
+ "Sag the active Part along -axis: parts far from the axis droop (negative lifts them).",
+ "Depth: a perspective along each axis, the + end wider for a positive amount.",
};
- 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: 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 {
+ for (int i = 0; i < kDeformOpCount; ++i) {
+ const DeformOp op = DeformOp(i);
+ float lo, hi, def;
+ deformRange(op, lo, hi, def);
+ char range[96];
+ std::snprintf(range, sizeof range, "How much, %g to %g (default %g).", double(lo), double(hi), double(def));
+ std::vector<ParamSpec> params = {{"amount", T::Number, range, false},
+ {"masked", T::Bool, "Masked parts stay (default true; false ignores the mask).", false}};
+ if (op == DeformOp::Smooth) params.push_back({"keep_volume", T::Bool, "Taubin smoothing (default false).", false});
+ if (deformUsesAxes(op)) {
+ params.push_back({"axes", T::String, "Any of x, y, z (default y).", false});
+ params.push_back({"pivot", T::String, "x,y,z (default: the Part's bounds centre).", false});
+ }
+ if (deformUsesDirection(op))
+ params.push_back({"direction", T::Number, "Degrees about the axis (0: toward +Y, +X for the Y axis).", false});
+ if (deformUsesSoft(op)) params.push_back({"soft", T::Bool, "Eased profile (default false).", false});
+ const std::string tail = deformUsesAxes(op) ? " Mask-aware, hidden faces stay; one undo step."
+ : " Mask-aware (partly masked vertices move partly), hidden faces and "
+ "open borders stay; one undo step.";
+ reg.add({deformCommand(op), std::string(kWhat[i]) + tail, params,
+ [op, lo, hi, def](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.amount = float(std::clamp(argNumber(a, "amount", double(def)), double(lo), double(hi)));
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;
+ if (deformUsesAxes(op) && !shapeArgs(a, o, err)) return {false, err};
+ if (o.amount == 0.0f) return {true, std::string(deformName(op)) + ": amount 0, nothing to do"};
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"};
}});
}
+ reg.add({"deform_size",
+ "Resize the active Part to exact dimensions in scene units about its bounds centre (x, y, z; an axis "
+ "left out keeps its size; uniform=N scales evenly so the largest side is N). Mask-aware; one undo step.",
+ {{"x", T::Number, "Width (X), scene units.", false},
+ {"y", T::Number, "Height (Y), scene units.", false},
+ {"z", T::Number, "Depth (Z), scene units.", false},
+ {"uniform", T::Number, "The largest side, scene units, the others in proportion.", false},
+ {"masked", T::Bool, "Masked parts stay (default true).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ glm::vec3 size(argNumber(a, "x", 0.0), argNumber(a, "y", 0.0), argNumber(a, "z", 0.0));
+ if (const double u = argNumber(a, "uniform", 0.0); u > 0.0 && doc.mesh.vertexCount() > 0) {
+ const AABB box = doc.mesh.bounds();
+ const vec3 now = box.max - box.min;
+ const float big = std::max(now.x, std::max(now.y, now.z));
+ if (big > 1e-12f) size = now * float(u / big);
+ }
+ for (int k = 0; k < 3; ++k)
+ if (!std::isfinite(size[k]) || size[k] < 0.0f) return {false, "Size: give positive sizes"};
+ if (size == glm::vec3(0.0f)) return {false, "Size: give x, y, z or uniform"};
+ std::string err;
+ const size_t moved = resizeActivePart(doc, size, argBool(a, "masked", true), err);
+ if (moved == 0) return {false, err};
+ const AABB box = doc.mesh.bounds();
+ const vec3 now = box.max - box.min;
+ char msg[160];
+ std::snprintf(msg, sizeof msg, "Size %.4g x %.4g x %.4g: moved %zu vertices", double(now.x), double(now.y),
+ double(now.z), moved);
+ return {true, msg};
+ }});
+ reg.add({"deform_stack",
+ "Run several whole-Part deformations in order as one undo step, e.g. ops=\"bend 40 y soft dir=90; twist "
+ "90 y; taper -30 xz\" (name, amount, axes letters, soft, dir=degrees, volume for Smooth, nomask; "
+ "names: polish relax smooth balloon move turn scale squash bend twist taper shear round box flatten sag "
+ "depth).",
+ {{"ops", T::String, "The steps, separated by ';'.", true},
+ {"pivot", T::String, "x,y,z for every shape step (default: the Part's bounds centre at each step).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::vector<DeformStep> steps;
+ std::string err;
+ if (!parseDeformStack(argString(a, "ops"), steps, err)) return {false, err};
+ const std::string pivot = argString(a, "pivot");
+ if (!pivot.empty()) {
+ glm::vec3 p;
+ if (!parseVec3(pivot, p)) return {false, "Bad pivot '" + pivot + "' (expected x,y,z)"};
+ for (DeformStep& st : steps) {
+ st.options.pivot = p;
+ st.options.hasPivot = true;
+ }
+ }
+ const size_t moved = deformActivePart(doc, steps, err);
+ if (moved == 0) return {false, err};
+ return {true, "Deform stack (" + std::to_string(steps.size()) + (steps.size() == 1 ? " step" : " steps") +
+ "): moved " + std::to_string(moved) + " vertices"};
+ }});
}
} // namespace sf
diff --git a/src/core/Deform.h b/src/core/Deform.h
index 8d25c6f0..4f3c0e12 100644
--- a/src/core/Deform.h
+++ b/src/core/Deform.h
@@ -13,10 +13,18 @@
// 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).
+// And shape operations (docs/design/deform-panel.md, foirgairwolf on Discord), each about a pivot (the Part's bounds centre
+// by default) along the chosen axes, borders moving with the rest:
+// Transform - Move, Turn, Scale, Squash (scale along an axis, keeping the volume).
+// Bend & Twist - Bend, Twist, Taper, Shear, each along an axis; Soft eases the effect out toward the ends.
+// Shape - Round (toward a sphere or cylinder), Box, Flatten (cut one side flat), Sag (outer parts droop
+// along -axis), Depth (a perspective along the axis).
+// Several run in order as one step (deformStackPositions, the deform_stack command).
#pragma once
#include "core/Mesh.h"
+#include <cstdint>
#include <string>
#include <vector>
@@ -25,24 +33,62 @@ namespace sf {
class CommandRegistry;
struct Document;
-enum class DeformOp { Polish, Relax, Smooth, Balloon };
-const char* deformName(DeformOp op); // "Polish", "Relax", "Smooth", "Balloon"
+enum class DeformOp {
+ Polish, Relax, Smooth, Balloon, // Surface
+ Move, Turn, Scale, Squash, // Transform
+ Bend, Twist, Taper, Shear, // Bend & Twist
+ Round, Box, Flatten, Sag, Depth, // Shape
+};
+constexpr int kDeformOpCount = 17;
+const char* deformName(DeformOp op); // "Polish", ... "Depth"
+const char* deformCommand(DeformOp op); // "deform_polish", ... "deform_depth"
+bool deformFromName(const std::string& name, DeformOp& op); // a name or command, any case
+// The amount's range and default ("Turn" in degrees, the rest mostly percent).
+void deformRange(DeformOp op, float& lo, float& hi, float& def);
+bool deformUsesDirection(DeformOp op); // Bend, Shear
+bool deformUsesSoft(DeformOp op); // Bend, Twist, Taper, Shear, Flatten
+bool deformUsesAxes(DeformOp op); // every shape operation (not Polish, Relax, Smooth, Balloon)
+
+enum DeformAxis : uint8_t { DeformX = 1, DeformY = 2, DeformZ = 4 };
struct DeformOptions {
- float amount = 50.0f; // 0-100 (Balloon -100..100)
+ float amount = 50.0f; // see deformRange
bool keepVolume = false; // Smooth: Taubin smoothing
bool useMask = true; // false: the mask is ignored (hidden faces are still kept)
+ uint8_t axes = DeformY; // DeformAxis bits; shape operations only
+ float direction = 0.0f; // Bend, Shear: degrees about the axis (0: +Y for X and Z, +X for Y)
+ bool soft = false; // Bend, Twist, Taper, Shear, Flatten: eased profile
+ bool hasPivot = false; // false: the Part's bounds centre
+ glm::vec3 pivot{0.0f};
};
+struct DeformStep {
+ DeformOp op = DeformOp::Bend;
+ DeformOptions options;
+};
+// "bend 40 y soft dir=90; twist 90 xz" (axes letters, "soft", "dir=", ";" between steps) <-> steps.
+bool parseDeformStack(const std::string& text, std::vector<DeformStep>& steps, std::string& error);
+std::string deformStackText(const std::vector<DeformStep>& steps);
+std::string axesLetters(uint8_t axes); // "xz"
+
// 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);
+// Every step in order, each on the result of the one before (each with its own mask setting).
+std::vector<glm::vec3> deformStackPositions(const Mesh& mesh, const std::vector<DeformStep>& steps);
// 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);
+// The steps as one undo step labelled `label`.
+size_t deformActivePart(Document& doc, const std::vector<DeformStep>& steps, std::string& error,
+ const std::string& label = "Deform stack");
+
+// Resizes the active Part to `size` (scene units per axis; <= 0 keeps that axis) about its bounds centre, weighted
+// by 1 - mask when `useMask`, as one undo step ("Size").
+size_t resizeActivePart(Document& doc, const glm::vec3& size, bool useMask, std::string& error);
-// deform_polish, deform_relax, deform_smooth, deform_balloon.
+// deform_<op> for every operation, deform_size and deform_stack.
void registerDeformCommands(CommandRegistry& registry);
} // namespace sf
diff --git a/tests/test_deform_panel.cpp b/tests/test_deform_panel.cpp
new file mode 100644
index 00000000..edc90733
--- /dev/null
+++ b/tests/test_deform_panel.cpp
@@ -0,0 +1,298 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The Deform panel's shape operations (core/Deform.h, docs/design/deform-panel.md, foirgairwolf on Discord): exact math on
+// small meshes, axis combinations, Soft, the mask, the stack text and the one-undo-step stack command.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Deform.h"
+#include "core/Primitives.h"
+
+#include <glm/gtc/quaternion.hpp>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+
+using namespace sf;
+using glm::vec3;
+
+namespace {
+
+DeformOptions opts(float amount, uint8_t axes, bool soft = false, float direction = 0.0f) {
+ DeformOptions o;
+ o.amount = amount;
+ o.axes = axes;
+ o.soft = soft;
+ o.direction = direction;
+ return o;
+}
+
+bool near(const vec3& a, const vec3& b, float eps = 1e-4f) { return glm::distance(a, b) < eps; }
+
+// A cube of side 2 centred on the origin (pivot = origin, ext = 1 on every axis).
+const Mesh& cube() {
+ static const Mesh m = makeCube(6, 2.0f);
+ return m;
+}
+
+} // namespace
+
+TEST(deform_panel_transform_ops) {
+ const Mesh& m = cube();
+ // Move: amount percent of the half-size, on the chosen axes only.
+ std::vector<vec3> P = deformPositions(m, DeformOp::Move, opts(50, DeformX | DeformZ));
+ for (size_t i = 0; i < P.size(); ++i) CHECK(near(P[i], m.positions[i] + vec3(0.5f, 0.0f, 0.5f)));
+ // Turn: degrees about the axis through the centre.
+ P = deformPositions(m, DeformOp::Turn, opts(90, DeformY));
+ const glm::quat q = glm::angleAxis(glm::radians(90.0f), vec3(0, 1, 0));
+ for (size_t i = 0; i < P.size(); ++i) CHECK(near(P[i], q * m.positions[i]));
+ // Scale: 100 doubles the chosen components.
+ P = deformPositions(m, DeformOp::Scale, opts(100, DeformX | DeformY));
+ for (size_t i = 0; i < P.size(); ++i) CHECK(near(P[i], m.positions[i] * vec3(2, 2, 1)));
+ // Squash: half as tall, sqrt(2) as wide: the volume stays.
+ P = deformPositions(m, DeformOp::Squash, opts(100, DeformY));
+ const float w = std::sqrt(2.0f);
+ for (size_t i = 0; i < P.size(); ++i) CHECK(near(P[i], m.positions[i] * vec3(w, 0.5f, w)));
+}
+
+TEST(deform_panel_bend_is_an_arc) {
+ // A strip along X bends toward +Y: every vertex of the centre line lands on the circle of radius 2 ext / angle.
+ Mesh m = makePlane(16, 2.0f); // y = 0
+ const float angle = 90.0f, R = 2.0f / glm::radians(angle);
+ const std::vector<vec3> P = deformPositions(m, DeformOp::Bend, opts(angle, DeformX));
+ for (size_t i = 0; i < P.size(); ++i) {
+ CHECK(std::abs(glm::distance(vec3(P[i].x, P[i].y, 0.0f), vec3(0.0f, R, 0.0f)) - R) < 1e-4f);
+ CHECK(std::abs(P[i].z - m.positions[i].z) < 1e-6f); // across the bend, nothing changes
+ // The ends turn by half the angle each: x = R sin 45, y = R (1 - cos 45).
+ if (std::abs(m.positions[i].x - 1.0f) < 1e-5f)
+ CHECK(near(vec3(P[i].x, P[i].y, 0), vec3(R * std::sin(glm::radians(45.0f)), R * (1 - std::cos(glm::radians(45.0f))), 0)));
+ }
+ // Direction 180 bends the other way; a negative angle is the same.
+ const std::vector<vec3> D = deformPositions(m, DeformOp::Bend, opts(angle, DeformX, false, 180.0f));
+ const std::vector<vec3> N = deformPositions(m, DeformOp::Bend, opts(-angle, DeformX));
+ for (size_t i = 0; i < P.size(); ++i) {
+ CHECK(near(D[i], vec3(P[i].x, -P[i].y, P[i].z)));
+ CHECK(near(N[i], D[i]));
+ }
+ // Soft: the centre line keeps its length, the middle stays put, and the ends turn less steeply at the tips.
+ const std::vector<vec3> S = deformPositions(m, DeformOp::Bend, opts(angle, DeformX, true));
+ std::vector<std::pair<float, vec3>> row;
+ for (size_t i = 0; i < S.size(); ++i)
+ if (std::abs(m.positions[i].z) < 1e-5f) row.push_back({m.positions[i].x, S[i]});
+ std::sort(row.begin(), row.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
+ float length = 0.0f;
+ for (size_t i = 1; i < row.size(); ++i) length += glm::distance(row[i].second, row[i - 1].second);
+ CHECK(std::abs(length - 2.0f) < 4e-3f); // chords of the 16 segments, a little under the arc
+ CHECK(near(row[row.size() / 2].second, vec3(0.0f)));
+}
+
+TEST(deform_panel_twist_taper_shear_depth) {
+ const Mesh& m = cube();
+ // Twist 180 about Y: the top turns +90, the bottom -90, the middle stays.
+ std::vector<vec3> P = deformPositions(m, DeformOp::Twist, opts(180, DeformY));
+ for (size_t i = 0; i < P.size(); ++i) {
+ const float y = m.positions[i].y;
+ const glm::quat q = glm::angleAxis(glm::radians(90.0f * y), vec3(0, 1, 0));
+ CHECK(near(P[i], q * m.positions[i]));
+ }
+ // Taper 50 along Y: the top 1.5 times as wide, the bottom half.
+ P = deformPositions(m, DeformOp::Taper, opts(50, DeformY));
+ for (size_t i = 0; i < P.size(); ++i) {
+ const vec3 p = m.positions[i];
+ const float f = 1.0f + 0.5f * p.y;
+ CHECK(near(P[i], vec3(p.x * f, p.y, p.z * f)));
+ }
+ // Shear 100 along Y: leans 45 degrees toward +X (direction 0 for the Y axis).
+ P = deformPositions(m, DeformOp::Shear, opts(100, DeformY));
+ for (size_t i = 0; i < P.size(); ++i) CHECK(near(P[i], m.positions[i] + vec3(m.positions[i].y, 0, 0)));
+ // Soft ends at the same place but moves the middle more steeply.
+ P = deformPositions(m, DeformOp::Shear, opts(100, DeformY, true));
+ for (size_t i = 0; i < P.size(); ++i) {
+ const float y = m.positions[i].y;
+ CHECK(near(P[i], m.positions[i] + vec3(y * (3 - y * y) * 0.5f, 0, 0)));
+ }
+ // Depth: the + end wider, the - end narrower, the axis itself unchanged.
+ P = deformPositions(m, DeformOp::Depth, opts(40, DeformY));
+ for (size_t i = 0; i < P.size(); ++i) {
+ const vec3 p = m.positions[i];
+ const float f = 1.0f / (1.0f - 0.2f * p.y);
+ CHECK(near(P[i], vec3(p.x * f, p.y, p.z * f)));
+ }
+}
+
+TEST(deform_panel_shape_ops) {
+ // Round on a cube: every vertex at the same distance from the centre; on XZ only: a cylinder about Y.
+ const Mesh& m = cube();
+ std::vector<vec3> P = deformPositions(m, DeformOp::Round, opts(100, DeformX | DeformY | DeformZ));
+ const float r = glm::length(P[0]);
+ for (const vec3& p : P) CHECK(std::abs(glm::length(p) - r) < 1e-4f);
+ P = deformPositions(m, DeformOp::Round, opts(100, DeformX | DeformZ));
+ const float rc = glm::length(glm::vec2(P[0].x, P[0].z));
+ for (size_t i = 0; i < P.size(); ++i) {
+ // (the centres of the top and bottom faces sit on the axis: they have no direction to go and stay)
+ if (glm::length(glm::vec2(m.positions[i].x, m.positions[i].z)) > 1e-6f)
+ CHECK(std::abs(glm::length(glm::vec2(P[i].x, P[i].z)) - rc) < 1e-4f);
+ CHECK(P[i].y == m.positions[i].y);
+ }
+ // Box on a sphere: the same max-norm everywhere.
+ const Mesh s = makeIcosphere(3, 1.0f);
+ P = deformPositions(s, DeformOp::Box, opts(100, DeformX | DeformY | DeformZ));
+ auto maxNorm = [](const vec3& p) { return std::max(std::abs(p.x), std::max(std::abs(p.y), std::abs(p.z))); };
+ for (const vec3& p : P) CHECK(std::abs(maxNorm(p) - maxNorm(P[0])) < 1e-4f);
+ // Flatten 50 along Y cuts the top half off at the middle; -50 the bottom half; the rest stays.
+ P = deformPositions(s, DeformOp::Flatten, opts(50, DeformY));
+ for (size_t i = 0; i < P.size(); ++i)
+ CHECK(near(P[i], vec3(s.positions[i].x, std::min(s.positions[i].y, 0.0f), s.positions[i].z), 1e-5f));
+ P = deformPositions(s, DeformOp::Flatten, opts(-50, DeformY));
+ for (size_t i = 0; i < P.size(); ++i) CHECK(P[i].y >= -1e-5f);
+ // Soft rounds the cut's edge but stays under the plane.
+ P = deformPositions(s, DeformOp::Flatten, opts(50, DeformY, true));
+ for (const vec3& p : P) CHECK(p.y <= 1e-5f);
+ // Sag on a flat plane: the far corners droop by half the radius, the middle stays.
+ const Mesh plane = makePlane(8, 2.0f);
+ P = deformPositions(plane, DeformOp::Sag, opts(100, DeformY));
+ const float R = std::sqrt(2.0f);
+ for (size_t i = 0; i < P.size(); ++i) {
+ const vec3 p = plane.positions[i];
+ const float d = glm::length(glm::vec2(p.x, p.z));
+ CHECK(near(P[i], vec3(p.x, -0.5f * R * (d / R) * (d / R), p.z)));
+ }
+}
+
+TEST(deform_panel_axes_mask_hidden_pivot) {
+ const Mesh& c = cube();
+ // Two axes run one after the other, X then Z.
+ std::vector<vec3> both = deformPositions(c, DeformOp::Turn, opts(90, DeformX | DeformZ));
+ const glm::quat q = glm::angleAxis(glm::radians(90.0f), vec3(0, 0, 1)) * glm::angleAxis(glm::radians(90.0f), vec3(1, 0, 0));
+ for (size_t i = 0; i < both.size(); ++i) CHECK(near(both[i], q * c.positions[i]));
+ // No axis: nothing.
+ CHECK(deformPositions(c, DeformOp::Twist, opts(90, 0)) == c.positions);
+ // The mask holds what it covers; half masked moves half; hidden stays; borders of an open plane move.
+ Mesh m = c;
+ std::vector<float>& mask = m.ensureMask();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) mask[v] = m.positions[v].y > 0.5f ? 1.0f : m.positions[v].y < -0.5f ? 0.5f : 0.0f;
+ std::vector<vec3> P = deformPositions(m, DeformOp::Move, opts(100, DeformX));
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ const float expect = 1.0f - mask[v];
+ CHECK(near(P[v], m.positions[v] + vec3(expect, 0, 0)));
+ }
+ DeformOptions o = opts(100, DeformX);
+ o.useMask = false;
+ P = deformPositions(m, DeformOp::Move, o);
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) CHECK(near(P[v], m.positions[v] + vec3(1, 0, 0)));
+ const Mesh plane = makePlane(8, 2.0f);
+ P = deformPositions(plane, DeformOp::Move, opts(100, DeformY | DeformX));
+ for (size_t i = 0; i < P.size(); ++i) CHECK(P[i] != plane.positions[i]);
+ // A pivot: Turn about (1,0,0) keeps that point.
+ o = opts(90, DeformY);
+ o.hasPivot = true;
+ o.pivot = vec3(1, 0, 0);
+ P = deformPositions(c, DeformOp::Turn, o);
+ const glm::quat qy = glm::angleAxis(glm::radians(90.0f), vec3(0, 1, 0));
+ for (size_t i = 0; i < P.size(); ++i) CHECK(near(P[i], vec3(1, 0, 0) + qy * (c.positions[i] - vec3(1, 0, 0))));
+}
+
+TEST(deform_panel_stack_text_and_command) {
+ std::vector<DeformStep> steps;
+ std::string err;
+ CHECK(parseDeformStack("bend 40 y soft dir=90; Twist 90 XZ;deform_smooth 30 volume nomask", steps, err));
+ CHECK(steps.size() == 3);
+ CHECK(steps[0].op == DeformOp::Bend && steps[0].options.amount == 40.0f && steps[0].options.soft &&
+ steps[0].options.direction == 90.0f && steps[0].options.axes == DeformY);
+ CHECK(steps[1].op == DeformOp::Twist && steps[1].options.axes == (DeformX | DeformZ) && !steps[1].options.soft);
+ CHECK(steps[2].op == DeformOp::Smooth && steps[2].options.keepVolume && !steps[2].options.useMask);
+ CHECK(deformStackText(steps) == "bend 40 y soft dir=90; twist 90 xz; smooth 30 volume nomask");
+ std::vector<DeformStep> again;
+ CHECK(parseDeformStack(deformStackText(steps), again, err) && again.size() == 3);
+ CHECK(!parseDeformStack("wobble 3", steps, err) && err.find("wobble") != std::string::npos);
+ CHECK(!parseDeformStack("bend 30 q", steps, err));
+ CHECK(!parseDeformStack(" ; ", steps, err));
+ // Amounts clamp to the range; a missing amount takes the default.
+ CHECK(parseDeformStack("turn 999; taper", steps, err) && steps[0].options.amount == 180.0f && steps[1].options.amount == 40.0f);
+ for (int i = 0; i < kDeformOpCount; ++i) {
+ DeformOp op;
+ CHECK(deformFromName(deformName(DeformOp(i)), op) && op == DeformOp(i));
+ CHECK(deformFromName(deformCommand(DeformOp(i)), op) && op == DeformOp(i));
+ }
+
+ // deform_stack: the steps in order, one undo step, the same as running them on positions.
+ Document d = makeDoc(makeCube(6, 2.0f));
+ const std::vector<vec3> before = d.mesh.positions;
+ CHECK(parseDeformStack("taper 30 y; bend 60 y soft; turn 20 x", steps, err));
+ const std::vector<vec3> expect = deformStackPositions(d.mesh, steps);
+ CommandRegistry reg;
+ const CommandResult r = reg.execute(d, "deform_stack", {{"ops", std::string("taper 30 y; bend 60 y soft; turn 20 x")}});
+ CHECK(r.ok && r.message.find("3 steps") != std::string::npos);
+ CHECK(d.undo.undoCount() == 1);
+ for (size_t i = 0; i < expect.size(); ++i) CHECK(near(d.mesh.positions[i], expect[i]));
+ CHECK(d.undo.undo(d.mesh, d.bvh));
+ CHECK(d.mesh.positions == before);
+ CHECK(!reg.execute(d, "deform_stack", {{"ops", std::string("bend 30 y")}, {"pivot", std::string("1,2")}}).ok);
+ // Every operation's own command runs on its defaults; each is one undo step.
+ for (int i = 0; i < kDeformOpCount; ++i) {
+ const size_t n = d.undo.undoCount();
+ const CommandResult ri = reg.execute(d, deformCommand(DeformOp(i)), {{"axes", std::string("xy")}});
+ CHECK(ri.ok);
+ CHECK(d.undo.undoCount() == n + 1);
+ }
+ CHECK(!reg.execute(d, "deform_bend", {{"axes", std::string("w")}}).ok);
+ // Everything masked: an error, nothing recorded.
+ d.mesh.ensureMask();
+ std::fill(d.mesh.mask.begin(), d.mesh.mask.end(), 1.0f);
+ const size_t n = d.undo.undoCount();
+ CHECK(!reg.execute(d, "deform_stack", {{"ops", std::string("bend 30 y")}}).ok);
+ CHECK(d.undo.undoCount() == n);
+}
+
+TEST(deform_panel_large_mesh_timing) {
+ // SF_DEFORM_BENCH=1 (2.6M vertices) or 2 (10.5M): each shape operation applied to the whole Part.
+ if (!std::getenv("SF_DEFORM_BENCH")) return;
+ Document d = makeDoc(makeIcosphere(std::atoi(std::getenv("SF_DEFORM_BENCH")) > 1 ? 10 : 9, 1.0f));
+ std::printf("bench mesh: %zu vertices\n", d.mesh.vertexCount());
+ using clock = std::chrono::steady_clock;
+ for (int i = int(DeformOp::Move); i < kDeformOpCount; ++i) {
+ DeformOptions o;
+ float lo, hi;
+ deformRange(DeformOp(i), lo, hi, o.amount);
+ o.soft = true;
+ const auto t0 = clock::now();
+ const std::vector<vec3> P = deformPositions(d.mesh, DeformOp(i), o);
+ const double pos = std::chrono::duration<double, std::milli>(clock::now() - t0).count();
+ std::string err;
+ const auto t1 = clock::now();
+ const size_t moved = deformActivePart(d, DeformOp(i), o, err);
+ const double ms = std::chrono::duration<double, std::milli>(clock::now() - t1).count();
+ std::printf("deform %s: positions %.0f ms, apply %zu vertices %.0f ms\n", deformName(DeformOp(i)), pos, moved, ms);
+ }
+}
+
+TEST(deform_panel_size_in_scene_units) {
+ // A 2 x 2 x 2 cube centred at (1, 0, 0): exact sizes about its centre, axes left out keep theirs, one undo step.
+ Mesh cubeMesh = makeCube(4, 2.0f);
+ for (vec3& p : cubeMesh.positions) p.x += 1.0f;
+ Document d = makeDoc(cubeMesh);
+ const std::vector<vec3> before = d.mesh.positions;
+ CommandRegistry reg;
+ CommandResult r = reg.execute(d, "deform_size", {{"x", 5.0}, {"z", 0.5}});
+ CHECK(r.ok && r.message.find("Size 5 x 2 x 0.5") == 0);
+ AABB b = d.mesh.bounds();
+ CHECK(near(b.min, vec3(-1.5f, -1.0f, -0.25f)) && near(b.max, vec3(3.5f, 1.0f, 0.25f)));
+ CHECK(d.undo.undoCount() == 1);
+ CHECK(d.undo.undo(d.mesh, d.bvh) && d.mesh.positions == before);
+ // uniform: the largest side to 4, the others in proportion.
+ CHECK(reg.execute(d, "deform_size", {{"x", 4.0}, {"y", 2.0}}).ok);
+ CHECK(reg.execute(d, "deform_size", {{"uniform", 8.0}}).ok);
+ b = d.mesh.bounds();
+ CHECK(near(b.max - b.min, vec3(8.0f, 4.0f, 4.0f)));
+ // Nothing given, a negative size, or a flat side to stretch: errors, nothing recorded.
+ const size_t n = d.undo.undoCount();
+ CHECK(!reg.execute(d, "deform_size", {}).ok);
+ CHECK(!reg.execute(d, "deform_size", {{"x", -1.0}}).ok);
+ Document flat = makeDoc(makePlane(4, 2.0f));
+ CHECK(!reg.execute(flat, "deform_size", {{"y", 1.0}}).ok);
+ CHECK(reg.execute(flat, "deform_size", {{"uniform", 1.0}}).ok); // the flat side stays flat
+ CHECK(d.undo.undoCount() == n);
+}
diff --git a/tests/ui/deformation_ops.sfui b/tests/ui/deformation_ops.sfui
index a4a5a3dc..a6565c2d 100644
--- a/tests/ui/deformation_ops.sfui
+++ b/tests/ui/deformation_ops.sfui
@@ -48,3 +48,44 @@ click "Deformation/Balloon"
expect_status "everything masked"
expect_value moved == 0
run mask_clear
+
+# The stack (docs/design/deform-panel.md): add steps, the preview follows, Apply is one undo step, Reset takes it back.
+expect "##deform_stack_add"
+expect_text No steps yet
+click "##deform_stack_add"
+click "Stack/Bend##deform_add_Bend"
+expect_status "Deform stack (1 step)"
+expect_value moved > 0
+expect "##deform_step_amount"
+expect "##deform_step_direction"
+expect "Stack/X"
+shot stack-bend
+click "##deform_stack_add"
+click "Stack/Twist##deform_add_Twist"
+expect_status "Deform stack (2 steps)"
+click "Stack/Repeat"
+expect_status "Deform stack (3 steps)"
+click "Stack/Remove"
+expect_status "Deform stack (2 steps)"
+# Reset: back where it was, the list empty.
+click "Stack/Reset"
+expect_value moved == 0
+expect_text No steps yet
+# Apply keeps the preview; one undo takes the whole stack back.
+click "##deform_stack_add"
+click "Stack/Taper##deform_add_Taper"
+click "##deform_stack_add"
+click "Stack/Round##deform_add_Round"
+click "Stack/Apply"
+expect_value moved > 0
+expect_text No steps yet
+key ctrl+z
+expect_value moved == 0
+
+# Size: the Part's dimensions in scene units; typing one resizes it (Uniform: in proportion), one undo step.
+expect "Size/##deform_size_x"
+expect "Size/Uniform##deform_size_uniform"
+run deform_size uniform=3
+expect_status "Size 3"
+key ctrl+z
+expect_value moved == 0