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.

Transform core: move, rotate and scale a SubTool or its unmasked part, with a soft falloff, layers, symmetry and one undo step

islandmed2908ab19d4cf
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4c70174e..cd4b8991 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -35,6 +35,8 @@ add_library(sculptforge_core STATIC
src/core/Polygroups.cpp
src/core/ScreenSelect.cpp
src/core/SubTools.cpp
+ src/core/MeshTransform.cpp
+ src/core/TransformCommands.cpp
src/core/Decimate.cpp
src/core/Script.cpp
src/core/Json.cpp
diff --git a/src/core/BVH.cpp b/src/core/BVH.cpp
index 9afa49c6..be742caf 100644
--- a/src/core/BVH.cpp
+++ b/src/core/BVH.cpp
@@ -257,4 +257,16 @@ void BVH::refit(const Mesh& mesh, std::span<const uint32_t> movedVerts) {
}
}
+void BVH::refitAll(const Mesh& mesh) {
+ for (size_t i = nodes_.size(); i-- > 0;) { // children always have larger indices
+ Node& n = nodes_[i];
+ if (n.count > 0) {
+ recomputeLeaf(mesh, n);
+ } else {
+ n.box = nodes_[n.first].box;
+ n.box.expand(nodes_[n.first + 1].box);
+ }
+ }
+}
+
} // namespace sf
diff --git a/src/core/BVH.h b/src/core/BVH.h
index 00053721..e006d43f 100644
--- a/src/core/BVH.h
+++ b/src/core/BVH.h
@@ -31,6 +31,8 @@ public:
// Updates bounds after the given vertices moved. Bounds only ever grow
// conservatively for ancestors, which keeps queries correct.
void refit(const Mesh& mesh, std::span<const uint32_t> movedVerts);
+ // Recomputes every box (same tree) after most of the mesh moved, e.g. a whole SubTool transformed.
+ void refitAll(const Mesh& mesh);
size_t nodeCount() const { return nodes_.size(); }
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 06c299ca..9f1c1b11 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -8,6 +8,7 @@
#include "core/EnginePresets.h"
#include "core/ImageTo3D.h"
#include "core/Masking.h"
+#include "core/MeshTransform.h"
#include "core/PathStroke.h"
#include "core/Polygroups.h"
#include "core/SubTools.h"
@@ -753,6 +754,7 @@ CommandRegistry::CommandRegistry() {
registerMaskingCommands(*this);
registerPolygroupCommands(*this);
registerSubToolCommands(*this);
+ registerTransformCommands(*this); // transform (core/MeshTransform.h)
registerPaintCommands(*this); // core/Polypaint.cpp
registerGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)
registerProjectCommands(*this); // keep last (core/Project.cpp)
diff --git a/src/core/MeshTransform.cpp b/src/core/MeshTransform.cpp
new file mode 100644
index 00000000..3bf68cab
--- /dev/null
+++ b/src/core/MeshTransform.cpp
@@ -0,0 +1,350 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/MeshTransform.h"
+
+#include "core/Document.h"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+#include <queue>
+#include <thread>
+
+namespace sf {
+
+namespace {
+
+// Runs fn(begin, end) over [0, n) on several threads when there is enough work.
+template <class Fn>
+void parallelRange(size_t n, Fn fn) {
+ const size_t threads = n < 100000 ? 1 : std::clamp<size_t>(std::thread::hardware_concurrency(), 1, 16);
+ if (threads <= 1) {
+ fn(size_t(0), n);
+ return;
+ }
+ std::vector<std::thread> pool;
+ const size_t chunk = (n + threads - 1) / threads;
+ for (size_t b = 0; b < n; b += chunk) pool.emplace_back([=] { fn(b, std::min(n, b + chunk)); });
+ for (auto& t : pool) t.join();
+}
+
+// Angle (radians, 0..2pi) and unit axis of a rotation, without folding angles over 180 degrees onto the short
+// way round (a 270 degree ring drag at half weight turns 135 degrees, not -45).
+void angleAxis(const glm::quat& q, float& angle, glm::vec3& axis) {
+ const float s = std::sqrt(std::max(0.0f, 1.0f - q.w * q.w));
+ angle = 2.0f * std::acos(std::clamp(q.w, -1.0f, 1.0f));
+ axis = s > 1e-7f ? glm::vec3(q.x, q.y, q.z) / s : glm::vec3(1, 0, 0);
+}
+
+} // namespace
+
+bool MeshTransform::identity() const {
+ return translate == glm::vec3(0.0f) && scale == glm::vec3(1.0f) &&
+ (std::abs(rotate.w) >= 1.0f || (rotate.x == 0.0f && rotate.y == 0.0f && rotate.z == 0.0f));
+}
+
+void MeshTransform::at(float w, glm::mat3& linear, glm::vec3& offset) const {
+ float angle;
+ glm::vec3 axis;
+ angleAxis(rotate, angle, axis);
+ linear = angle * w != 0.0f ? glm::mat3_cast(glm::angleAxis(angle * w, axis)) : glm::mat3(1.0f);
+ const glm::vec3 s = glm::mix(glm::vec3(1.0f), scale, w);
+ if (s != glm::vec3(1.0f)) {
+ glm::mat3 d(1.0f);
+ d[0][0] = s.x;
+ d[1][1] = s.y;
+ d[2][2] = s.z;
+ linear = linear * frame * d * glm::transpose(frame);
+ }
+ offset = pivot + w * translate - linear * pivot;
+}
+
+glm::vec3 MeshTransform::apply(const glm::vec3& p) const {
+ glm::mat3 l;
+ glm::vec3 o;
+ at(1.0f, l, o);
+ return l * p + o;
+}
+
+glm::quat eulerRotation(const glm::vec3& degrees, const glm::mat3& axes) {
+ const glm::quat qx = glm::angleAxis(glm::radians(degrees.x), axes[0]);
+ const glm::quat qy = glm::angleAxis(glm::radians(degrees.y), axes[1]);
+ const glm::quat qz = glm::angleAxis(glm::radians(degrees.z), axes[2]);
+ return glm::normalize(qz * qy * qx);
+}
+
+glm::vec3 eulerDegrees(const glm::quat& q) {
+ // R = Rz(c) Ry(b) Rx(a); glm matrices are m[column][row].
+ const glm::mat3 m = glm::mat3_cast(q);
+ const float b = std::asin(std::clamp(-m[0][2], -1.0f, 1.0f));
+ float a, c;
+ if (std::abs(m[0][2]) < 0.99999f) {
+ a = std::atan2(m[1][2], m[2][2]);
+ c = std::atan2(m[0][1], m[0][0]);
+ } else { // gimbal lock: put it all in X
+ a = std::atan2(-m[2][1], m[1][1]);
+ c = 0.0f;
+ }
+ return glm::degrees(glm::vec3(a, b, c));
+}
+
+std::vector<float> transformWeights(const Mesh& mesh, bool useMask, float falloff) {
+ const size_t nv = mesh.vertexCount();
+ const bool masked = useMask && mesh.hasMask();
+ if (!masked && !mesh.hasHidden()) return {};
+ std::vector<float> w(nv, 1.0f);
+ if (masked)
+ for (size_t v = 0; v < nv; ++v) w[v] = std::clamp(1.0f - mesh.mask[v], 0.0f, 1.0f);
+ const float reach = masked && falloff > 0.0f ? falloff * glm::length(mesh.bounds().extent()) : 0.0f;
+ if (reach > 0.0f) {
+ // Distance along the edges from the masked part (multi-source Dijkstra from its border, stopping at
+ // `reach`), then a smoothstep ramp: only the band next to the mask is visited.
+ constexpr float kFar = std::numeric_limits<float>::max();
+ std::vector<float> dist(nv, kFar);
+ using Item = std::pair<float, uint32_t>;
+ std::priority_queue<Item, std::vector<Item>, std::greater<Item>> heap;
+ for (uint32_t v = 0; v < nv; ++v) {
+ if (mesh.mask[v] < 0.5f) continue;
+ dist[v] = 0.0f;
+ for (uint32_t n : mesh.neighbors(v))
+ if (mesh.mask[n] < 0.5f) {
+ heap.push({0.0f, v});
+ break;
+ }
+ }
+ while (!heap.empty()) {
+ const auto [d, v] = heap.top();
+ heap.pop();
+ if (d > dist[v]) continue;
+ for (uint32_t n : mesh.neighbors(v)) {
+ const float nd = d + glm::length(mesh.positions[n] - mesh.positions[v]);
+ if (nd < dist[n] && nd < reach) {
+ dist[n] = nd;
+ heap.push({nd, n});
+ }
+ }
+ }
+ for (size_t v = 0; v < nv; ++v) {
+ if (dist[v] == kFar) continue;
+ const float t = std::clamp(dist[v] / reach, 0.0f, 1.0f);
+ w[v] *= t * t * (3.0f - 2.0f * t);
+ }
+ }
+ if (mesh.hasHidden())
+ for (size_t v = 0; v < nv; ++v)
+ if (mesh.vertexHidden(uint32_t(v))) w[v] = 0.0f;
+ if (std::all_of(w.begin(), w.end(), [](float x) { return x >= 1.0f; })) return {};
+ return w;
+}
+
+AABB transformBounds(const Mesh& mesh, const std::vector<float>& weights) {
+ AABB box;
+ if (weights.size() != mesh.vertexCount()) return mesh.bounds();
+ float most = 0.0f;
+ for (float w : weights) most = std::max(most, w);
+ if (most <= 0.0f) return mesh.bounds();
+ const float cut = std::min(0.5f, most * 0.5f);
+ for (size_t v = 0; v < weights.size(); ++v)
+ if (weights[v] >= cut) box.expand(mesh.positions[v]);
+ return box.valid() ? box : mesh.bounds();
+}
+
+glm::vec3 transformCenter(const Mesh& mesh, const std::vector<float>& weights) {
+ const AABB box = transformBounds(mesh, weights);
+ return box.valid() ? box.center() : glm::vec3(0.0f);
+}
+
+bool TransformSession::begin(const Mesh& mesh, std::vector<float> weights, Symmetry mirror, const glm::vec3& pivot) {
+ *this = TransformSession();
+ const size_t nv = mesh.vertexCount();
+ const bool weighted = weights.size() == nv;
+ std::vector<uint16_t> full(weighted ? nv : 0, 0); // every vertex's level (0 = still)
+ for (uint32_t v = 0; v < nv; ++v) {
+ const int l = weighted ? int(std::lround(std::clamp(weights[v], 0.0f, 1.0f) * kLevels)) : kLevels;
+ if (l <= 0) continue;
+ verts_.push_back(v);
+ level_.push_back(uint16_t(l));
+ if (weighted) full[v] = uint16_t(l);
+ }
+ if (verts_.empty()) return false;
+
+ // Symmetry only makes sense for a part of the mesh, on a side of the plane.
+ Symmetry sym{false, false, false};
+ if (weighted) {
+ constexpr float eps = 1e-5f;
+ sym.x = mirror.x && std::abs(pivot.x) > eps;
+ sym.y = mirror.y && std::abs(pivot.y) > eps;
+ sym.z = mirror.z && std::abs(pivot.z) > eps;
+ }
+ mirrors_ = Sculptor::mirrors(sym);
+ side_.assign(verts_.size(), 0);
+ std::vector<uint8_t> sideOf(mirrors_.size() > 1 ? nv : 0, 0);
+ if (mirrors_.size() > 1) {
+ const bool on[3] = {sym.x, sym.y, sym.z};
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ const glm::vec3& p = mesh.positions[verts_[i]];
+ glm::vec3 s(1.0f);
+ for (int a = 0; a < 3; ++a)
+ if (on[a] && p[a] * pivot[a] < 0.0f) s[a] = -1.0f;
+ for (size_t m = 0; m < mirrors_.size(); ++m)
+ if (mirrors_[m] == s) side_[i] = uint8_t(m);
+ sideOf[verts_[i]] = side_[i];
+ }
+ }
+
+ // Normals of a rigidly moved vertex just turn; where neighbours move differently they are recomputed.
+ if (weighted) {
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ const uint32_t v = verts_[i];
+ bool edge = level_[i] < kLevels;
+ for (uint32_t n : mesh.neighbors(v)) {
+ if (edge) break;
+ edge = full[n] != level_[i] || (!sideOf.empty() && sideOf[n] != side_[i]);
+ }
+ if (edge) boundary_.push_back(v);
+ }
+ }
+
+ usedLevels_.assign(kLevels + 1, 0);
+ for (uint16_t l : level_) usedLevels_[l] = 1;
+ layered_ = !mesh.layers.empty();
+ const auto& src = mesh.basePositions();
+ base_.resize(verts_.size());
+ normals_.resize(verts_.size());
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ base_[i] = src[verts_[i]];
+ normals_[i] = mesh.normals[verts_[i]];
+ }
+ deltas_.resize(mesh.layers.size());
+ for (size_t l = 0; l < mesh.layers.size(); ++l) {
+ deltas_[l].resize(verts_.size());
+ for (size_t i = 0; i < verts_.size(); ++i) deltas_[l][i] = mesh.layers[l].delta[verts_[i]];
+ }
+ active_ = true;
+ return true;
+}
+
+void TransformSession::apply(Mesh& mesh, const MeshTransform& t) {
+ if (!active_) return;
+ const size_t stride = size_t(kLevels) + 1;
+ table_.resize(mirrors_.size() * stride);
+ for (size_t m = 0; m < mirrors_.size(); ++m) {
+ const glm::vec3 d = mirrors_[m];
+ const glm::mat3 D(glm::vec3(d.x, 0, 0), glm::vec3(0, d.y, 0), glm::vec3(0, 0, d.z));
+ for (int l = 0; l <= kLevels; ++l) {
+ if (!usedLevels_[size_t(l)]) continue;
+ const float w = l == kLevels ? 1.0f : float(l) / float(kLevels);
+ Level& e = table_[m * stride + size_t(l)];
+ t.at(w, e.linear, e.offset);
+ e.translateOnly = e.linear == glm::mat3(1.0f);
+ if (e.translateOnly) e.offset = w * t.translate; // exact: p + w * t
+ if (m > 0) {
+ e.linear = D * e.linear * D;
+ e.offset = d * e.offset;
+ }
+ e.normal = e.translateOnly ? glm::mat3(1.0f) : glm::transpose(glm::inverse(e.linear));
+ }
+ }
+ std::vector<glm::vec3>& target = layered_ ? mesh.base : mesh.positions;
+ const bool exactNormals = verts_.size() < 200000; // big drags turn normals and fix them in finish()
+ parallelRange(verts_.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const Level& L = table_[side_[i] * stride + level_[i]];
+ const uint32_t v = verts_[i];
+ if (L.translateOnly) {
+ target[v] = base_[i] + L.offset;
+ for (size_t k = 0; k < deltas_.size(); ++k) mesh.layers[k].delta[v] = deltas_[k][i];
+ if (!exactNormals) mesh.normals[v] = normals_[i];
+ continue;
+ }
+ target[v] = L.linear * base_[i] + L.offset;
+ for (size_t k = 0; k < deltas_.size(); ++k) mesh.layers[k].delta[v] = L.linear * deltas_[k][i];
+ if (!exactNormals) {
+ const glm::vec3 n = L.normal * normals_[i];
+ const float len = glm::length(n);
+ mesh.normals[v] = len > 1e-20f ? n / len : normals_[i];
+ }
+ }
+ });
+ if (layered_) mesh.evaluate(verts_);
+ if (exactNormals) mesh.updateNormals(verts_);
+ else if (!boundary_.empty()) mesh.updateNormals(boundary_);
+ mesh.markDirty(verts_.front());
+ mesh.markDirty(verts_.back());
+ moved_ = !t.identity();
+}
+
+void TransformSession::writeBack(Mesh& mesh) {
+ std::vector<glm::vec3>& target = layered_ ? mesh.base : mesh.positions;
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ target[verts_[i]] = base_[i];
+ for (size_t k = 0; k < deltas_.size(); ++k) mesh.layers[k].delta[verts_[i]] = deltas_[k][i];
+ }
+ if (layered_) mesh.evaluate(verts_);
+ mesh.updateNormals(verts_);
+}
+
+void TransformSession::restore(Mesh& mesh) {
+ if (!active_) return;
+ writeBack(mesh);
+ moved_ = false;
+}
+
+UndoRecord TransformSession::finish(Mesh& mesh, BVH& bvh, std::string label) {
+ UndoRecord r;
+ if (!active_) return r;
+ active_ = false;
+ if (!moved_) {
+ writeBack(mesh); // an identity transform: leave the mesh exactly as it was
+ return r;
+ }
+ // Keeps the mesh's face-normal cache right for later strokes (big drags only turned the normals).
+ if (verts_.size() >= 200000) mesh.updateNormals(verts_);
+ if (verts_.size() * 4 > mesh.vertexCount()) bvh.refitAll(mesh);
+ else bvh.refit(mesh, verts_);
+ r.label = std::move(label);
+ r.layer = -1;
+ r.positions.indices = verts_;
+ r.positions.values = std::move(base_);
+ for (auto& d : deltas_) {
+ UndoChannel<glm::vec3> ch;
+ ch.indices = verts_;
+ ch.values = std::move(d);
+ r.layerOffsets.push_back(std::move(ch));
+ }
+ *this = TransformSession();
+ return r;
+}
+
+void TransformSession::cancel(Mesh& mesh, BVH& bvh) {
+ if (!active_) return;
+ writeBack(mesh);
+ if (verts_.size() * 4 > mesh.vertexCount()) bvh.refitAll(mesh);
+ else bvh.refit(mesh, verts_);
+ *this = TransformSession();
+}
+
+size_t transformSubtool(Document& doc, int index, const MeshTransform& t, bool useMask, float falloff, Symmetry mirror,
+ const std::string& label) {
+ if (index < 0 || index >= doc.subtoolCount()) return 0;
+ const bool active = index == doc.activeSubtool;
+ SubTool& info = doc.subtools[size_t(index)];
+ Mesh& mesh = active ? doc.mesh : info.mesh;
+ BVH& bvh = active ? doc.bvh : info.bvh;
+ UndoStack& undo = active ? doc.undo : info.undo;
+ if (active) doc.syncBvh();
+ else if (info.bvhDirty) {
+ info.bvh.build(info.mesh);
+ info.bvhDirty = false;
+ }
+ TransformSession s;
+ if (!s.begin(mesh, transformWeights(mesh, useMask, falloff), mirror, t.pivot)) return 0;
+ const size_t n = s.movingVertices();
+ s.apply(mesh, t);
+ UndoRecord r = s.finish(mesh, bvh, label);
+ if (r.empty()) return 0;
+ undo.push(std::move(r));
+ return n;
+}
+
+} // namespace sf
diff --git a/src/core/MeshTransform.h b/src/core/MeshTransform.h
new file mode 100644
index 00000000..f4600f3b
--- /dev/null
+++ b/src/core/MeshTransform.h
@@ -0,0 +1,117 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Moving, rotating and scaling a SubTool, or only its unmasked part (ZBrush Gizmo 3D / Transpose): the core
+// of the app's Gizmo mode (W Move, E Scale, R Rotate) and of the `transform` command.
+//
+// A transform is a translation, a rotation and a per-axis scale about a pivot, with the rotation and scale
+// expressed in the gizmo's axes (`frame`: world axes, or the surface the pivot was snapped to). Every vertex
+// takes it with a weight from the mask: 1 - mask, eased in over a distance from the masked part (`falloff`) so
+// a hard mask still bends softly at a joint (posing: mask the body, rotate the arm at the shoulder). A vertex with
+// weight w moves by w * translate, turns by the rotation slerped to w and scales by mix(1, scale, w).
+// Hidden vertices never move.
+//
+// Sculpt layers move with the surface: the base takes the whole transform and every layer's offsets the
+// linear part, so positions == base + sum(weight * offset) still holds and the layers keep working.
+// Topology, UVs, quads, polygroups, polypaint and textures are left as they are.
+#pragma once
+
+#include "core/BVH.h"
+#include "core/Mesh.h"
+#include "core/Sculpt.h"
+#include "core/Undo.h"
+
+#include <glm/gtc/quaternion.hpp>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class CommandRegistry;
+struct Document;
+
+struct MeshTransform {
+ glm::vec3 pivot{0.0f};
+ glm::mat3 frame{1.0f}; // orthonormal gizmo axes (columns); rotate and scale act along them
+ glm::vec3 translate{0.0f}; // world units
+ glm::quat rotate{1, 0, 0, 0}; // world-space rotation about the pivot
+ glm::vec3 scale{1.0f}; // along frame[0], frame[1], frame[2]; must be > 0
+
+ bool identity() const;
+ // The transform at weight `w` (0 = nothing, 1 = all of it) as p' = linear * p + offset.
+ void at(float w, glm::mat3& linear, glm::vec3& offset) const;
+ glm::vec3 apply(const glm::vec3& p) const; // full weight
+};
+
+// Rotation by Euler angles in degrees about axes[0], then axes[1], then axes[2] (the splat_rotate order).
+glm::quat eulerRotation(const glm::vec3& degrees, const glm::mat3& axes = glm::mat3(1.0f));
+// Euler angles in degrees (the inverse of eulerRotation with world axes), for showing a rotation as numbers.
+glm::vec3 eulerDegrees(const glm::quat& q);
+
+// Per-vertex weights of a transform: 1 - mask (when `useMask`), 0 on hidden vertices. With a `falloff` (a
+// fraction of the mesh's bounding box diagonal) the weight eases in (smoothstep) over that distance along the
+// surface from the masked part (mask >= 0.5), which itself stays still: a soft joint whatever the resolution.
+// Empty means "every vertex, fully" (no mask, nothing hidden).
+std::vector<float> transformWeights(const Mesh& mesh, bool useMask, float falloff);
+// Centre of the bounds of the vertices that move (weight >= 0.5, or the heaviest ones when none reach it);
+// the bounds centre of the visible mesh for empty weights. Falls back to the whole mesh's centre.
+glm::vec3 transformCenter(const Mesh& mesh, const std::vector<float>& weights);
+// Bounds of the same vertices.
+AABB transformBounds(const Mesh& mesh, const std::vector<float>& weights);
+
+// One interactive transform (a gizmo drag) or one command: remembers the vertices that move, then applies
+// any transform to those originals (so a drag never accumulates error), and finishes with one undo step.
+// Only moved vertices are touched: their normals, the GPU dirty range (Mesh::markDirty) and the BVH.
+class TransformSession {
+public:
+ // `weights` as from transformWeights (empty = all). `mirror`: with a mask, the parts on the far side of
+ // each enabled symmetry plane (through the origin, as for brushes) from the pivot take the mirrored
+ // transform, so both arms pose together. Ignored for unmasked transforms and pivots on the plane.
+ // False (and nothing to do) when no vertex can move.
+ bool begin(const Mesh& mesh, std::vector<float> weights, Symmetry mirror, const glm::vec3& pivot);
+ void apply(Mesh& mesh, const MeshTransform& t);
+ void restore(Mesh& mesh); // back to the originals (the session stays open)
+ // Refits the BVH and returns the undo step (empty when nothing moved). Ends the session.
+ UndoRecord finish(Mesh& mesh, BVH& bvh, std::string label);
+ void cancel(Mesh& mesh, BVH& bvh); // restore + end without an undo step
+
+ bool active() const { return active_; }
+ size_t movingVertices() const { return verts_.size(); }
+ bool mirrored() const { return mirrors_.size() > 1; }
+
+private:
+ struct Level {
+ glm::mat3 linear{1.0f}, normal{1.0f};
+ glm::vec3 offset{0.0f};
+ bool translateOnly = true;
+ };
+ void writeBack(Mesh& mesh);
+
+ bool active_ = false;
+ bool layered_ = false;
+ std::vector<uint32_t> verts_; // vertices with weight > 0
+ std::vector<uint16_t> level_; // their weight, quantized to kLevels
+ std::vector<uint8_t> side_; // index into mirrors_
+ std::vector<uint32_t> boundary_; // vertices whose normals are recomputed (partial weight or a still neighbour)
+ std::vector<glm::vec3> base_, normals_; // originals: Mesh::layerTarget(-1) and normals
+ std::vector<std::vector<glm::vec3>> deltas_; // originals of each sculpt layer's offsets
+ std::vector<glm::vec3> mirrors_; // sign vectors; [0] = (1,1,1)
+ std::vector<uint8_t> usedLevels_; // which quantized weights occur
+ std::vector<Level> table_; // mirrors_.size() * (kLevels + 1)
+ bool moved_ = false;
+
+public:
+ static constexpr int kLevels = 4096;
+};
+
+// Transforms SubTool `index` of `doc` (active or not) as one undoable step on that SubTool. Returns the number
+// of vertices that moved.
+size_t transformSubtool(Document& doc, int index, const MeshTransform& t, bool useMask, float falloff, Symmetry mirror,
+ const std::string& label);
+
+// transform (translate, rotate, scale, pivot, orient, masked, falloff, symmetry, all).
+void registerTransformCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/TransformCommands.cpp b/src/core/TransformCommands.cpp
new file mode 100644
index 00000000..4e45f1cd
--- /dev/null
+++ b/src/core/TransformCommands.cpp
@@ -0,0 +1,141 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The `transform` command (core/MeshTransform.h): what a Gizmo 3D drag does, for scripts, the console and AI.
+#include "core/Commands.h"
+#include "core/MeshTransform.h"
+#include "core/PathStroke.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <cstdio>
+
+namespace sf {
+
+namespace {
+
+using T = ParamSpec::Type;
+
+std::string lower(std::string s) {
+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return s;
+}
+
+// A vector argument written "x,y,z" (or one number for all three when `uniform`).
+bool vecArg(const Args& a, const std::string& key, glm::vec3& out, bool uniform, std::string& error) {
+ auto it = a.find(key);
+ if (it == a.end()) return true;
+ if (auto* d = std::get_if<double>(&it->second)) {
+ if (!uniform) {
+ error = "Bad " + key + " (expected x,y,z)";
+ return false;
+ }
+ out = glm::vec3(float(*d));
+ return true;
+ }
+ const std::string s = argString(a, key);
+ if (parseVec3(s, out)) return true;
+ if (uniform) {
+ char* end = nullptr;
+ const float v = std::strtof(s.c_str(), &end);
+ if (end != s.c_str() && *end == '\0' && std::isfinite(v)) {
+ out = glm::vec3(v);
+ return true;
+ }
+ }
+ error = "Bad " + key + " '" + s + "' (expected x,y,z" + (uniform ? " or one number)" : ")");
+ return false;
+}
+
+std::string fmt(const glm::vec3& v) {
+ char buf[96];
+ std::snprintf(buf, sizeof buf, "%g,%g,%g", double(v.x), double(v.y), double(v.z));
+ return buf;
+}
+
+CommandResult runTransform(Document& doc, const Args& a) {
+ std::string err;
+ glm::vec3 translate(0.0f), rotate(0.0f), scale(1.0f), orient(0.0f);
+ if (!vecArg(a, "translate", translate, false, err) || !vecArg(a, "rotate", rotate, false, err) ||
+ !vecArg(a, "scale", scale, true, err) || !vecArg(a, "orient", orient, false, err))
+ return {false, err};
+ if (scale.x <= 0.0f || scale.y <= 0.0f || scale.z <= 0.0f)
+ return {false, "Scale must be above 0 (mirroring would turn the surface inside out)"};
+ const bool useMask = argBool(a, "masked", true);
+ const float falloff = std::clamp(float(argNumber(a, "falloff", 0)), 0.0f, 1.0f);
+ const bool all = argBool(a, "all", false);
+ Symmetry sym{false, false, false};
+ for (char c : lower(argString(a, "symmetry"))) {
+ if (c == 'x') sym.x = true;
+ else if (c == 'y') sym.y = true;
+ else if (c == 'z') sym.z = true;
+ else if (c != ',' && c != ' ') return {false, "Bad symmetry (expected axes such as x or xz)"};
+ }
+
+ std::vector<int> targets;
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ if (all ? doc.subtools[size_t(i)].visible || i == doc.activeSubtool : i == doc.activeSubtool) targets.push_back(i);
+
+ MeshTransform t;
+ t.translate = translate;
+ if (lower(argString(a, "orient", "world")) != "world") t.frame = glm::mat3_cast(eulerRotation(orient));
+ t.rotate = eulerRotation(rotate, t.frame);
+ t.scale = scale;
+ const std::string pivot = lower(argString(a, "pivot", "center"));
+ if (pivot == "center" || pivot == "centre") {
+ AABB box;
+ for (int i : targets) {
+ const Mesh& m = doc.subtoolMesh(i);
+ if (m.vertexCount() == 0) continue;
+ const AABB b = transformBounds(m, transformWeights(m, useMask, falloff));
+ if (b.valid()) box.expand(b);
+ }
+ t.pivot = box.valid() ? box.center() : glm::vec3(0.0f);
+ } else if (pivot == "origin") {
+ t.pivot = glm::vec3(0.0f);
+ } else if (!parseVec3(pivot, t.pivot)) {
+ return {false, "Bad pivot '" + pivot + "' (expected center, origin or x,y,z)"};
+ }
+ if (t.identity()) return {true, "Nothing to do: the transform changes nothing"};
+
+ size_t moved = 0;
+ for (int i : targets) moved += transformSubtool(doc, i, t, useMask, falloff, sym, "Transform");
+ if (moved == 0)
+ return {false, useMask && doc.mesh.hasMask() ? "Nothing moved: everything is masked (masked=0 ignores the mask)"
+ : "Nothing moved: the SubTool is empty or hidden"};
+ std::string msg = "Transformed " + std::to_string(moved) + " vertices";
+ if (targets.size() > 1) msg += " in " + std::to_string(targets.size()) + " SubTools";
+ msg += " about " + fmt(t.pivot);
+ return {true, msg};
+}
+
+} // namespace
+
+void registerTransformCommands(CommandRegistry& reg) {
+ reg.add({"transform",
+ "Move, rotate and scale the active SubTool, or only its unmasked part (the Gizmo 3D as a command): "
+ "p' = pivot + translate + R * S * (p - pivot). Masked vertices stay, partly masked ones move partly; "
+ "falloff eases it in from the mask's edge (a soft joint for posing). One undo step per SubTool.",
+ {{"translate", T::String, "Movement x,y,z in world units. Default 0,0,0.", false},
+ {"rotate", T::String, "Rotation in degrees about the X, then Y, then Z axis (of orient). Default 0,0,0.",
+ false},
+ {"scale", T::String, "Scale factor: one number, or x,y,z along the axes of orient. Default 1.", false},
+ {"pivot", T::String,
+ "Where to rotate and scale about: center (default: centre of what moves), origin, or x,y,z.", false},
+ {"orient", T::String, "Axes for rotate and scale: world (default), or x,y,z Euler degrees.", false},
+ {"masked", T::Bool, "Leave masked vertices where they are (default true; false moves everything).",
+ false},
+ {"falloff", T::Number,
+ "Soft joint: ease the movement in over this distance from the masked part, as a fraction of the "
+ "SubTool's size (0-1, e.g. 0.1; default 0 = the mask as it is).",
+ false},
+ {"symmetry", T::String,
+ "Mirror a masked transform across these planes through the origin, e.g. x: the unmasked part on the "
+ "other side of the plane takes the mirrored transform (both arms pose together).",
+ false},
+ {"all", T::Bool, "Transform every visible SubTool (ZBrush Transpose All). Default false.", false}},
+ runTransform});
+}
+
+} // namespace sf
diff --git a/src/core/Undo.cpp b/src/core/Undo.cpp
index 28e96a42..7873593b 100644
--- a/src/core/Undo.cpp
+++ b/src/core/Undo.cpp
@@ -10,6 +10,7 @@ size_t UndoRecord::approxBytes() const {
size_t bytes = positions.bytes() + mask.bytes() + colors.bytes() + paintAlpha.bytes() + hidden.bytes() +
polygroups.bytes() + (paint ? paint->bytes() : 0) +
(textureTiles ? textureTiles->bytes() : 0) + (texture ? texture->bytes() : 0);
+ for (const auto& l : layerOffsets) bytes += l.bytes();
if (mesh)
bytes += mesh->vertexCount() * ((2 + (mesh->base.empty() ? 0 : 1 + mesh->layers.size())) * sizeof(glm::vec3) +
8 * sizeof(uint32_t)) +
@@ -154,9 +155,13 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {
}
if (!r.positions.empty()) {
r.positions.swapWith(mesh.layerTarget(r.layer));
+ for (size_t i = 0; i < r.layerOffsets.size() && i < mesh.layers.size(); ++i)
+ r.layerOffsets[i].swapWith(mesh.layers[i].delta);
mesh.evaluate(r.positions.indices);
mesh.updateNormals(r.positions.indices);
- bvh.refit(mesh, r.positions.indices);
+ // Refits only grow boxes: after moving much of the mesh (a transform), tighten the whole tree instead.
+ if (r.positions.indices.size() * 4 > mesh.vertexCount()) bvh.refitAll(mesh);
+ else bvh.refit(mesh, r.positions.indices);
}
if (!r.mask.empty()) {
r.mask.swapWith(mesh.ensureMask());
diff --git a/src/core/Undo.h b/src/core/Undo.h
index fe30db2f..370f85a2 100644
--- a/src/core/Undo.h
+++ b/src/core/Undo.h
@@ -86,7 +86,8 @@ inline constexpr int kActivePaintLayer = -2;
// One undoable step: any mix of sparse channels, or a full mesh snapshot
// (topology/layer-set changes; the snapshot holds every attribute).
// - positions: the stroke's target array (positions, layer base or a layer's
-// offsets; see Mesh::layerTarget), selected by `layer`
+// offsets; see Mesh::layerTarget), selected by `layer`; layerOffsets: every
+// layer's offsets too (transforms)
// - mask / colors: per-vertex mask and polypaint. `colors` holds the paint
// target of `paintLayer` (Mesh::colors without paint layers, else Base for
// -1 or that layer's colours, with its coverage in `paintAlpha`)
@@ -99,6 +100,9 @@ struct UndoRecord {
std::string label;
int layer = -1;
UndoChannel<glm::vec3> positions;
+ // Transforms (core/MeshTransform.h) move the base and every sculpt layer together: with `positions` on the
+ // base (layer -1), layerOffsets[i] holds the old offsets of layer i for the same vertices.
+ std::vector<UndoChannel<glm::vec3>> layerOffsets;
UndoChannel<float> mask;
UndoChannel<glm::vec3> colors;
int paintLayer = -1;
diff --git a/tests/test_transform.cpp b/tests/test_transform.cpp
new file mode 100644
index 00000000..685062bd
--- /dev/null
+++ b/tests/test_transform.cpp
@@ -0,0 +1,395 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Transforms (core/MeshTransform.h, the Gizmo 3D and the `transform` command): exact results, masked parts with a
+// smooth falloff, sculpt layers, symmetry, All SubTools, attributes left alone and bit-for-bit undo.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/MeshTransform.h"
+#include "core/Primitives.h"
+#include "core/SubTools.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+
+using namespace sf;
+
+namespace {
+
+const CommandRegistry& registry() {
+ static CommandRegistry r;
+ return r;
+}
+
+CommandResult run(Document& d, const std::string& name, const Args& a = {}) { return registry().execute(d, name, a); }
+
+template <class V> bool sameBits(const std::vector<V>& a, const std::vector<V>& b) {
+ return a.size() == b.size() && (a.empty() || std::memcmp(a.data(), b.data(), a.size() * sizeof(V)) == 0);
+}
+
+float maxDistance(const std::vector<glm::vec3>& a, const std::vector<glm::vec3>& b) {
+ float d = 0.0f;
+ for (size_t i = 0; i < a.size(); ++i) d = std::max(d, glm::length(a[i] - b[i]));
+ return d;
+}
+
+// Mask = 1 where x < edge.
+void maskBelowX(Mesh& m, float edge) {
+ m.ensureMask();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = m.positions[v].x < edge ? 1.0f : 0.0f;
+}
+
+// A capsule-like arm: a sphere stretched along X.
+Mesh makeArm(int subdivisions = 4) {
+ Mesh m = makeIcosphere(subdivisions, 1.0f);
+ for (auto& p : m.positions) p *= glm::vec3(3.0f, 0.6f, 0.6f);
+ m.recomputeAllNormals();
+ return m;
+}
+
+} // namespace
+
+TEST(transform_translate_is_exact) {
+ Document d = makeDoc(makeIcosphere(3));
+ const auto before = d.mesh.positions;
+ CHECK(run(d, "transform", {{"translate", std::string("0.25,-1,3")}}).ok);
+ bool exact = true;
+ for (size_t v = 0; v < before.size(); ++v) exact = exact && d.mesh.positions[v] == before[v] + glm::vec3(0.25f, -1.0f, 3.0f);
+ CHECK(exact);
+ CHECK(d.undo.canUndo());
+}
+
+TEST(transform_matches_the_formula) {
+ Document d = makeDoc(makeIcosphere(3));
+ const auto before = d.mesh.positions;
+ CHECK(run(d, "transform",
+ {{"translate", std::string("1,2,3")}, {"rotate", std::string("30,-45,60")}, {"scale", std::string("2,1,0.5")},
+ {"pivot", std::string("0.5,0,-0.25")}})
+ .ok);
+ // Independent: p' = pivot + t + Rz Ry Rx S (p - pivot), built from glm matrices.
+ glm::mat4 r(1.0f);
+ r = glm::rotate(r, glm::radians(60.0f), glm::vec3(0, 0, 1));
+ r = glm::rotate(r, glm::radians(-45.0f), glm::vec3(0, 1, 0));
+ r = glm::rotate(r, glm::radians(30.0f), glm::vec3(1, 0, 0));
+ const glm::vec3 pivot(0.5f, 0.0f, -0.25f), t(1, 2, 3), s(2, 1, 0.5f);
+ float err = 0.0f;
+ for (size_t v = 0; v < before.size(); ++v) {
+ const glm::vec3 want = pivot + t + glm::vec3(r * glm::vec4((before[v] - pivot) * s, 0.0f));
+ err = std::max(err, glm::length(d.mesh.positions[v] - want));
+ }
+ CHECK(err < 1e-5f);
+ // Normals follow (a sphere's normals are its directions; scaled non-uniformly they tilt accordingly).
+ float dot = 1.0f;
+ for (size_t v = 0; v < before.size(); ++v) dot = std::min(dot, glm::length(d.mesh.normals[v]));
+ CHECK(dot > 0.999f);
+}
+
+TEST(transform_rotate_and_scale_about_centre) {
+ Document d = makeDoc(makeIcosphere(3));
+ for (auto& p : d.mesh.positions) p += glm::vec3(5, 0, 0);
+ d.mesh.recomputeAllNormals();
+ d.bvh.build(d.mesh);
+ const auto before = d.mesh.positions;
+ CHECK(run(d, "transform", {{"rotate", std::string("0,90,0")}}).ok); // about the centre (5,0,0)
+ float err = 0.0f;
+ for (size_t v = 0; v < before.size(); ++v) {
+ const glm::vec3 q = before[v] - glm::vec3(5, 0, 0);
+ err = std::max(err, glm::length(d.mesh.positions[v] - (glm::vec3(5, 0, 0) + glm::vec3(q.z, q.y, -q.x))));
+ }
+ CHECK(err < 1e-5f);
+ CHECK(run(d, "transform", {{"scale", 2.0}}).ok);
+ const AABB b = d.mesh.bounds();
+ CHECK(std::abs(b.extent().x - 4.0f) < 1e-3f);
+ CHECK(glm::length(b.center() - glm::vec3(5, 0, 0)) < 1e-3f);
+}
+
+TEST(transform_undo_restores_bit_for_bit) {
+ Document d = makeDoc(makeArm());
+ const auto pos = d.mesh.positions, nrm = d.mesh.normals;
+ CHECK(run(d, "transform", {{"rotate", std::string("10,20,30")}, {"translate", std::string("0.1,0.2,0.3")}, {"scale", 1.5}}).ok);
+ const auto moved = d.mesh.positions;
+ CHECK(!sameBits(moved, pos));
+ CHECK(run(d, "undo").ok);
+ CHECK(sameBits(d.mesh.positions, pos));
+ CHECK(sameBits(d.mesh.normals, nrm));
+ CHECK(run(d, "redo").ok);
+ CHECK(sameBits(d.mesh.positions, moved));
+ // Masked, with a falloff: same.
+ CHECK(run(d, "undo").ok);
+ maskBelowX(d.mesh, 0.0f);
+ CHECK(run(d, "transform", {{"rotate", std::string("0,0,40")}, {"pivot", std::string("0,0,0")}, {"falloff", 0.1}}).ok);
+ CHECK(run(d, "undo").ok);
+ CHECK(sameBits(d.mesh.positions, pos));
+ CHECK(sameBits(d.mesh.normals, nrm));
+}
+
+TEST(transform_masked_part_only) {
+ Document d = makeDoc(makeArm());
+ maskBelowX(d.mesh, 0.0f);
+ const auto before = d.mesh.positions;
+ CHECK(run(d, "transform", {{"translate", std::string("0,1,0")}}).ok);
+ bool still = true, full = true;
+ for (size_t v = 0; v < before.size(); ++v) {
+ if (d.mesh.mask[v] >= 1.0f) still = still && d.mesh.positions[v] == before[v];
+ else full = full && d.mesh.positions[v] == before[v] + glm::vec3(0, 1, 0);
+ }
+ CHECK(still);
+ CHECK(full);
+ // masked=0 moves everything.
+ CHECK(run(d, "transform", {{"translate", std::string("0,1,0")}, {"masked", false}}).ok);
+ CHECK(d.mesh.positions[0].y > before[0].y + 0.5f);
+ // Everything masked: nothing to move.
+ std::fill(d.mesh.mask.begin(), d.mesh.mask.end(), 1.0f);
+ CHECK(!run(d, "transform", {{"translate", std::string("0,1,0")}}).ok);
+}
+
+TEST(transform_partial_mask_moves_partly) {
+ Document d = makeDoc(makeIcosphere(2));
+ d.mesh.ensureMask(0.25f); // 75% weight everywhere
+ const auto before = d.mesh.positions;
+ CHECK(run(d, "transform", {{"translate", std::string("4,0,0")}}).ok);
+ float err = 0.0f;
+ for (size_t v = 0; v < before.size(); ++v) err = std::max(err, glm::length(d.mesh.positions[v] - before[v] - glm::vec3(3, 0, 0)));
+ CHECK(err < 1e-2f); // weights are quantized to 1/4096
+}
+
+TEST(transform_falloff_is_smooth) {
+ Mesh arm = makeArm(5);
+ maskBelowX(arm, 0.0f);
+ // Weights: a hard 0/1 step without falloff, a gradual ramp with it.
+ auto steepest = [&](const std::vector<float>& w) {
+ float s = 0.0f;
+ for (uint32_t v = 0; v < arm.vertexCount(); ++v)
+ for (uint32_t n : arm.neighbors(v)) s = std::max(s, std::abs(w[v] - w[n]));
+ return s;
+ };
+ const auto hard = transformWeights(arm, true, 0);
+ const auto soft = transformWeights(arm, true, 0.15f);
+ CHECK(steepest(hard) == 1.0f);
+ CHECK(steepest(soft) < 0.25f);
+ for (float w : soft) CHECK(w >= 0.0f && w <= 1.0f);
+ // Bend the arm 60 degrees at the "elbow": the falloff spreads the bend instead of tearing one row of edges.
+ auto stretch = [&](float falloff) {
+ Document d = makeDoc(arm);
+ CHECK(run(d, "transform", {{"rotate", std::string("0,0,60")}, {"pivot", std::string("0,0,0")}, {"falloff", double(falloff)}}).ok);
+ float worst = 0.0f;
+ for (uint32_t v = 0; v < arm.vertexCount(); ++v)
+ for (uint32_t n : arm.neighbors(v)) {
+ const float a = glm::length(arm.positions[v] - arm.positions[n]);
+ const float b = glm::length(d.mesh.positions[v] - d.mesh.positions[n]);
+ worst = std::max(worst, b / std::max(a, 1e-6f));
+ }
+ // The far end turned the whole 60 degrees.
+ const glm::vec3 tip = d.mesh.positions[size_t(std::max_element(arm.positions.begin(), arm.positions.end(),
+ [](auto& p, auto& q) { return p.x < q.x; }) -
+ arm.positions.begin())];
+ CHECK(std::abs(glm::degrees(std::atan2(tip.y, tip.x)) - 60.0f) < 1.0f);
+ return worst;
+ };
+ const float hardStretch = stretch(0), softStretch = stretch(0.15f);
+ std::printf(" edge stretch at a 60 degree bend: hard mask %.2fx, falloff 0.15 %.2fx\n", double(hardStretch),
+ double(softStretch));
+ // A 60 degree turn eased in over 0.15 of the size still shears the outside of a thick arm (about 2x), but the
+ // hard mask's tearing step (10x) is gone.
+ CHECK(softStretch < hardStretch / 3.0f);
+}
+
+TEST(transform_hidden_never_moves) {
+ Document d = makeDoc(makeIcosphere(3));
+ d.mesh.ensureHidden();
+ for (uint32_t t = 0; t < d.mesh.triangleCount(); ++t) d.mesh.hidden[t] = d.mesh.positions[d.mesh.triangles[t].x].y > 0.0f;
+ const auto before = d.mesh.positions;
+ CHECK(run(d, "transform", {{"translate", std::string("0,0,1")}}).ok);
+ bool ok = true;
+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v)
+ if (d.mesh.vertexHidden(v)) ok = ok && d.mesh.positions[v] == before[v];
+ CHECK(ok);
+}
+
+TEST(transform_sculpt_layers_move_with_the_surface) {
+ Document d = makeDoc(makeIcosphere(3));
+ Mesh& m = d.mesh;
+ m.addLayer("Bump");
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.layers[0].delta[v] = m.normals[v] * 0.1f * float(v % 3);
+ m.setLayerWeight(0, 0.7f);
+ const auto pos = m.positions, base = m.base, delta = m.layers[0].delta;
+ CHECK(run(d, "transform", {{"rotate", std::string("0,0,90")}, {"translate", std::string("1,0,0")}, {"pivot", std::string("origin")}}).ok);
+ auto rot = [](const glm::vec3& p) { return glm::vec3(-p.y, p.x, p.z); };
+ float err = 0.0f;
+ for (size_t v = 0; v < pos.size(); ++v) err = std::max(err, glm::length(m.positions[v] - (rot(pos[v]) + glm::vec3(1, 0, 0))));
+ CHECK(err < 1e-5f);
+ // The layer still works: at weight 0 it's the transformed base.
+ m.setLayerWeight(0, 0.0f);
+ err = 0.0f;
+ for (size_t v = 0; v < pos.size(); ++v) err = std::max(err, glm::length(m.positions[v] - (rot(base[v]) + glm::vec3(1, 0, 0))));
+ CHECK(err < 1e-5f);
+ m.setLayerWeight(0, 0.7f);
+ CHECK(run(d, "undo").ok);
+ CHECK(sameBits(m.base, base));
+ CHECK(sameBits(m.layers[0].delta, delta));
+}
+
+TEST(transform_leaves_topology_and_attributes) {
+ Document d = makeDoc(makeCube(6));
+ Mesh& m = d.mesh;
+ m.uvs.resize(m.triangleCount() * 3);
+ for (size_t i = 0; i < m.uvs.size(); ++i) m.uvs[i] = glm::vec2(float(i % 7) / 7.0f, float(i % 5) / 5.0f);
+ m.ensureColors(glm::vec3(0.2f, 0.4f, 0.6f));
+ const auto tris = m.triangles;
+ const auto uvs = m.uvs;
+ const auto quads = m.quadPartners;
+ const auto groups = m.polygroups;
+ const auto colors = m.colors;
+ CHECK(m.quadCount() > 0);
+ CHECK(run(d, "transform", {{"rotate", std::string("15,25,35")}, {"scale", 1.3}}).ok);
+ CHECK(m.triangles == tris);
+ CHECK(sameBits(m.uvs, uvs));
+ CHECK(m.quadPartners == quads);
+ CHECK(m.polygroups == groups);
+ CHECK(sameBits(m.colors, colors));
+}
+
+TEST(transform_symmetry_mirrors_a_masked_pose) {
+ // A bar along X with both ends free: rotating the right end at x=1 with X symmetry turns the left end the
+ // mirrored way, so the result stays symmetric.
+ Mesh bar = makeArm(4);
+ bar.ensureMask();
+ for (uint32_t v = 0; v < bar.vertexCount(); ++v) bar.mask[v] = std::abs(bar.positions[v].x) < 1.0f ? 1.0f : 0.0f;
+ Document d = makeDoc(bar);
+ CHECK(run(d, "transform", {{"rotate", std::string("0,0,30")}, {"pivot", std::string("1,0,0")}, {"symmetry", std::string("x")}}).ok);
+ // Every vertex's mirror image (found on the original) ended up mirrored.
+ float err = 0.0f;
+ int pairs = 0;
+ for (uint32_t v = 0; v < bar.vertexCount(); ++v) {
+ const glm::vec3 p = bar.positions[v];
+ if (p.x <= 1.0f) continue;
+ for (uint32_t u = 0; u < bar.vertexCount(); ++u) {
+ const glm::vec3 q = bar.positions[u];
+ if (glm::length(q - glm::vec3(-p.x, p.y, p.z)) > 1e-4f) continue;
+ const glm::vec3 a = d.mesh.positions[v], b = d.mesh.positions[u];
+ err = std::max(err, glm::length(a - glm::vec3(-b.x, b.y, b.z)));
+ ++pairs;
+ break;
+ }
+ }
+ CHECK(pairs > 10);
+ CHECK(err < 1e-4f);
+ // The right end went up, so the left one did too.
+ CHECK(d.mesh.bounds().max.y > bar.bounds().max.y + 0.2f);
+}
+
+TEST(transform_all_subtools) {
+ Document d = makeDoc(makeIcosphere(2));
+ d.addSubtool(makeCube(4), "Box", false);
+ const auto a = d.subtoolMesh(0).positions, b = d.subtoolMesh(1).positions;
+ CHECK(run(d, "transform", {{"translate", std::string("0,2,0")}, {"all", true}}).ok);
+ CHECK(d.subtoolMesh(0).positions[0] == a[0] + glm::vec3(0, 2, 0));
+ CHECK(d.subtoolMesh(1).positions[0] == b[0] + glm::vec3(0, 2, 0));
+ // One undo step in each SubTool.
+ CHECK(d.undo.canUndo());
+ CHECK(d.subtools[1].undo.canUndo());
+ d.selectSubtool(1);
+ CHECK(run(d, "undo").ok);
+ CHECK(sameBits(d.mesh.positions, b));
+ // Without all=1 only the active one moves.
+ CHECK(run(d, "transform", {{"translate", std::string("1,0,0")}}).ok);
+ CHECK(d.subtoolMesh(0).positions[0] == a[0] + glm::vec3(0, 2, 0));
+}
+
+TEST(transform_session_never_accumulates) {
+ // A drag applies many transforms to the same originals; the end result equals one direct transform.
+ Mesh arm = makeArm(4);
+ maskBelowX(arm, 0.0f);
+ Document a = makeDoc(arm), b = makeDoc(arm);
+ MeshTransform t;
+ t.pivot = glm::vec3(0.0f);
+ TransformSession s;
+ const auto w = transformWeights(a.mesh, true, 0.1f);
+ CHECK(s.begin(a.mesh, w, Symmetry{false, false, false}, t.pivot));
+ for (int i = 1; i <= 40; ++i) {
+ t.rotate = glm::angleAxis(glm::radians(float(i) * 2.0f), glm::vec3(0, 0, 1));
+ t.translate = glm::vec3(0.01f * float(i), 0, 0);
+ s.apply(a.mesh, t);
+ }
+ a.undo.push(s.finish(a.mesh, a.bvh, "Rotate"));
+ CHECK(transformSubtool(b, 0, t, true, 0.1f, Symmetry{false, false, false}, "Rotate") > 0);
+ CHECK(sameBits(a.mesh.positions, b.mesh.positions));
+ CHECK(maxDistance(a.mesh.normals, b.mesh.normals) < 1e-5f);
+ // An identity drag (click without moving) leaves no undo step and no change.
+ Document c = makeDoc(arm);
+ TransformSession idle;
+ CHECK(idle.begin(c.mesh, {}, Symmetry{}, glm::vec3(0.0f)));
+ idle.apply(c.mesh, MeshTransform{});
+ CHECK(idle.finish(c.mesh, c.bvh, "Move").empty());
+ CHECK(sameBits(c.mesh.positions, arm.positions));
+}
+
+TEST(transform_bvh_follows) {
+ Document d = makeDoc(makeIcosphere(3));
+ CHECK(run(d, "transform", {{"translate", std::string("10,0,0")}}).ok);
+ RayHit hit;
+ CHECK(d.bvh.raycast(d.mesh, glm::vec3(10, 0, 5), glm::vec3(0, 0, -1), hit));
+ CHECK(std::abs(hit.position.z - 1.0f) < 0.05f);
+ CHECK(!d.bvh.raycast(d.mesh, glm::vec3(0, 0, 5), glm::vec3(0, 0, -1), hit));
+ CHECK(run(d, "undo").ok);
+ CHECK(d.bvh.raycast(d.mesh, glm::vec3(0, 0, 5), glm::vec3(0, 0, -1), hit));
+}
+
+TEST(transform_command_errors) {
+ Document d = makeDoc(makeIcosphere(2));
+ CHECK(!run(d, "transform", {{"scale", 0.0}}).ok);
+ CHECK(!run(d, "transform", {{"scale", std::string("1,-1,1")}}).ok);
+ CHECK(!run(d, "transform", {{"pivot", std::string("nowhere")}, {"translate", std::string("1,0,0")}}).ok);
+ CHECK(!run(d, "transform", {{"translate", std::string("1,0")}}).ok);
+ CHECK(!run(d, "transform", {{"symmetry", std::string("w")}, {"translate", std::string("1,0,0")}}).ok);
+ CHECK(run(d, "transform").ok); // nothing to do is fine
+ CHECK(!d.undo.canUndo());
+}
+
+TEST(transform_euler_round_trip) {
+ for (const glm::vec3 e : {glm::vec3(10, 20, 30), glm::vec3(-45, 80, 170), glm::vec3(0, 0, -90)}) {
+ const glm::vec3 back = eulerDegrees(eulerRotation(e));
+ CHECK(glm::length(back - e) < 1e-2f);
+ }
+}
+
+TEST(transform_perf_million_triangles) {
+ // 1.3M triangles: a whole-SubTool drag frame and a masked (posing) drag frame, plus begin / finish.
+ Mesh m = makeIcosphere(8);
+ maskBelowX(m, 0.3f);
+ Document d = makeDoc(std::move(m));
+ using clock = std::chrono::steady_clock;
+ auto ms = [](clock::time_point a) { return std::chrono::duration<double, std::milli>(clock::now() - a).count(); };
+ for (int masked = 0; masked < 2; ++masked) {
+ auto t0 = clock::now();
+ const auto w = transformWeights(d.mesh, masked != 0, masked ? 0.1f : 0.0f);
+ TransformSession s;
+ CHECK(s.begin(d.mesh, w, Symmetry{}, transformCenter(d.mesh, w)));
+ const double begin = ms(t0);
+ MeshTransform t;
+ t.pivot = transformCenter(d.mesh, w);
+ t0 = clock::now();
+ const int frames = 10;
+ for (int i = 1; i <= frames; ++i) {
+ t.rotate = glm::angleAxis(glm::radians(float(i)), glm::vec3(0, 1, 0));
+ s.apply(d.mesh, t);
+ }
+ const double frame = ms(t0) / frames;
+ const size_t moving = s.movingVertices();
+ t0 = clock::now();
+ d.undo.push(s.finish(d.mesh, d.bvh, "Rotate"));
+ const double finish = ms(t0);
+ t0 = clock::now();
+ CHECK(run(d, "undo").ok);
+ const double undo = ms(t0);
+ std::printf(" %zu tris, %s: begin %.1f ms, %.1f ms per drag frame (%zu verts), finish %.1f ms, undo %.1f ms\n",
+ d.mesh.triangleCount(), masked ? "masked + falloff 0.1" : "whole SubTool", begin, frame,
+ moving, finish, undo);
+ }
+}