Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Gizmo 3D: W Move, E Scale, R Rotate (Q Draw) with handles over the canvas, pivot tools and numeric entry
islandmede71b29d099d7
diff --git a/CMakeLists.txt b/CMakeLists.txtindex cd4b8991..add7587b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -162,6 +162,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/PanelPolypaint.cppsrc/app/PanelPaintLayers.cppsrc/app/PanelTexture.cpp+ src/app/Gizmo.cppsrc/app/PanelGoz.cppsrc/app/PanelProject.cppsrc/app/PanelSubTools.cppdiff --git a/docs/guide/shortcuts.md b/docs/guide/shortcuts.mdindex 22c06d98..a2b626a6 100644--- a/docs/guide/shortcuts.md+++ b/docs/guide/shortcuts.md@@ -104,7 +104,7 @@ action registry, the same source as the Controls window.| Action | Keys | What it does ||---|---|---|| Fullscreen | <kbd>F11</kbd> | Fill the screen with SculptForge (again: back to a window). |-| Wireframe | <kbd>W</kbd> or <kbd>Shift</kbd>+<kbd>F</kbd> | Show the mesh's polygons (quads and triangles) over the surface (ZBrush PolyFrame). |+| Wireframe | <kbd>Shift</kbd>+<kbd>F</kbd> | Show the mesh's polygons (quads and triangles) over the surface (ZBrush PolyFrame). |### Script@@ -122,7 +122,11 @@ action registry, the same source as the Controls window.| Action | Keys | What it does ||---|---|---|+| Draw | <kbd>Q</kbd> | Draw mode: brushes sculpt and paint (leaves the Gizmo 3D). || Frame | <kbd>F</kbd> | Fit the whole model in the view. |+| Move | <kbd>W</kbd> | Gizmo 3D, Move: drag an arrow to move along an axis, a square to move in a plane, the centre to move in the view. Masked parts stay; Shift snaps to the grid; Alt+drag moves only the gizmo. W again: back to Draw. |+| Rotate | <kbd>R</kbd> | Gizmo 3D, Rotate: drag a ring to turn about that axis, the outer ring to turn in the view. Mask the body and put the pivot at a joint to pose a limb. Shift snaps to 15 degrees. R again: back to Draw. |+| Scale | <kbd>E</kbd> | Gizmo 3D, Scale: drag a box to stretch along an axis or the centre to scale evenly (right or up: bigger). Shift snaps to 10% steps. E again: back to Draw. || X | <kbd>X</kbd> | Mirror strokes across X (left and right). |<!-- END GENERATED: shortcuts -->diff --git a/docs/project-format.md b/docs/project-format.mdindex ff9bf2c2..b2a1f419 100644--- a/docs/project-format.md+++ b/docs/project-format.md@@ -8,7 +8,9 @@ read by `loadProject` (src/core/Project.cpp). Commands: `save_project path=...`,- `manifest.json`: always first. `format` = `"SculptForge project"`, `version` (integer, currently 3),`app_version`, then `subtools` (one entry per SubTool, in list order), `active_subtool` (index),`brushes` (recipe JSON), `active_brush` (name), optional `splats`, and app-owned keys (`camera`,- `render`, `brush`, `symmetry`).+ `render`, `brush`, `symmetry`, `gizmo`). `gizmo` (added in 0.5 without a version bump; older readers+ ignore it) holds the Gizmo 3D's `pivot`, `pivot_placed`, `orient_surface`, `axis_x` / `axis_y` (its+ surface axes), `use_mask`, `all_subtools` and `falloff`.- Each `subtools[i]` holds `name`, `visible` (bool), `mesh`, `layers`, `active_layer` (sculpt layerstrokes go into, -1 = base) and, for a mesh that came from ZBrush, `goz_name` (the GoZ object namethat `goz_send` / `goz_receive` match on).diff --git a/src/app/App.cpp b/src/app/App.cppindex 598b35e1..c73633b4 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -667,6 +667,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {if (button == SDL_BUTTON_LEFT) {if (polygroupMouseDown(x, y, mod)) return;if (maskSelectMouseDown(x, y, mod)) return;+ if (gizmoMouseDown(x, y, mod)) return; // Gizmo 3D handles, pivot clicks (Gizmo.cpp)// Alt+click on another SubTool selects it (ZBrush); Alt+drag stays an inverted stroke or a pan.if ((mod & SDL_KMOD_ALT) && !ctrlDown(mod) && !(mod & SDL_KMOD_SHIFT) && doc_.subtoolCount() > 1) {const int target = pickSubtool(x, y);@@ -727,6 +728,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {case Drag::MaskCanvas: maskCanvasMove(x, y); break;case Drag::SubToolClick: subtoolClickMove(x, y); break;case Drag::Select: selectionMove(x, y); break;+ case Drag::Gizmo: gizmoDragTo(x, y); break;case Drag::None: break;}}@@ -750,6 +752,7 @@ void App::onMouseUp() {if (drag_ == Drag::Stroke) endStroke();if (drag_ == Drag::MaskCanvas) maskCanvasRelease();if (drag_ == Drag::SubToolClick) subtoolClickRelease();+ gizmoRelease();drag_ = Drag::None;dragFromPen_ = false;penNavButton_ = 0;@@ -1187,8 +1190,10 @@ void App::drawUi() {IM_COL32(255, 190, 120, 255), banner.c_str());}const ImVec2 mouse(mouseX_, mouseY_);+ drawGizmo(); // Gizmo 3D handles and panel (Gizmo.cpp)+ // In Gizmo mode the brush ring shows only while Ctrl masks.if (((!ImGui::GetIO().WantCaptureMouse && canvasRect().contains(mouse.x, mouse.y)) || drag_ == Drag::Stroke) &&- !hideBrushCursor_ && drag_ != Drag::Select)+ !hideBrushCursor_ && drag_ != Drag::Select && (!gizmoActive() || drag_ == Drag::Stroke || ctrlDown(inputMods())))drawBrushCursor();drawSelectionOverlay();drawBrushLibraryPopups();diff --git a/src/app/App.h b/src/app/App.hindex 0dfc4869..aec46082 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -19,6 +19,7 @@#include "core/Commands.h"#include "core/Image.h"#include "core/Document.h"+#include "core/MeshTransform.h"#include "core/AutoUv.h"#include "core/Stroke.h"#include "core/Tablet.h"@@ -94,7 +95,7 @@ public:void queueFile(FileAction action, std::string path);private:- enum class Drag { None, Stroke, Orbit, Pan, Zoom, MaskCanvas, SubToolClick, Select };+ enum class Drag { None, Stroke, Orbit, Pan, Zoom, MaskCanvas, SubToolClick, Select, Gizmo };void handleEvent(const SDL_Event& e);void onMouseDown(float x, float y, Uint8 button);@@ -664,6 +665,84 @@ private:friend class UserGuide; // reads the UI scale, writes the status lineUserGuide guide_;// ---- end User Guide (G) ----+ // ---- Gizmo 3D (Gizmo.cpp, core/MeshTransform.h): W Move, E Scale, R Rotate, Q back to Draw ----+public:+ enum class GizmoMode { Off, Move, Scale, Rotate };+ enum class GizmoHandle {+ None,+ MoveX, MoveY, MoveZ, // axis arrows+ PlaneYZ, PlaneXZ, PlaneXY, // plane squares (named by the plane they move in)+ MoveView, // the centre ring: free move in the view plane+ RotateX, RotateY, RotateZ, RotateView,+ ScaleX, ScaleY, ScaleZ, ScaleUniform,+ Count+ };++private:+ void registerGizmoActions();+ void setGizmoMode(GizmoMode mode);+ bool gizmoActive() const { return gizmo_.mode != GizmoMode::Off; }+ bool gizmoMouseDown(float x, float y, SDL_Keymod mod); // true if it took the click+ void gizmoDragTo(float x, float y);+ void gizmoRelease();+ void drawGizmo(); // the handles over the canvas, and the Gizmo 3D panel+ void drawGizmoPanel();+ void drawGizmoContents(bool compact); // Transform palette > Gizmo 3D and the floating panel+ void updateGizmoPivot(); // follows the moving part's centre until the pivot is placed+ void resetGizmoPivot();+ void snapGizmoPivot(const RayHit& hit, int subtool);+ void applyGizmoNumbers(); // the panel's Move / Rotate / Scale fields, as a transform command+ glm::mat3 gizmoFrame() const;+ float gizmoWorldSize() const; // world length of an axis arrow (constant on screen)+ bool gizmoProject(const glm::vec3& p, ImVec2& out) const; // false behind the camera+ GizmoHandle gizmoHandleAt(float x, float y) const;+ bool gizmoHandleScreen(GizmoHandle h, ImVec2& out) const; // a point to grab handle h (UI tests)+ std::vector<int> gizmoTargets() const; // SubTools a drag transforms (the active one, or All)+ void gizmoAfterUndo(bool redo); // the gizmo goes back (or forward) with its own steps+ void rememberGizmoStep(const glm::vec3& before, const glm::mat3& frameBefore, bool surfaceBefore);+ struct GizmoState {+ GizmoMode mode = GizmoMode::Off;+ glm::vec3 pivot{0.0f};+ bool pivotPlaced = false; // Alt+drag, snap or a drag moved it: stop following the centre+ bool orientSurface = false; // axes from the surface the pivot was snapped to (else world)+ glm::mat3 frame{1.0f}; // the surface axes (turn with rotations)+ bool useMask = true, all = false;+ float falloff = 0.0f; // fraction of the size (core/MeshTransform.h)+ bool snapNext = false; // "Pivot to Surface": the next click on the model places the pivot+ uint64_t centreKey = ~uint64_t(0), maskKey = 0;+ GizmoHandle hover = GizmoHandle::None;+ // The drag in progress.+ GizmoHandle handle = GizmoHandle::None;+ bool pivotOnly = false; // Alt: move the pivot / turn the axes, not the model+ glm::vec3 startPivot{0.0f};+ glm::mat3 startFrame{1.0f};+ glm::vec3 grab{0.0f}; // where the drag started on the handle's line / plane+ glm::vec3 grabDir{0.0f}; // rotation: the start direction in the ring's plane+ ImVec2 startMouse{0, 0};+ float lastAngle = 0.0f, angle = 0.0f; // rotation: unwrapped, so a drag can go past 180 degrees+ bool tangent = false; // a ring seen edge-on turns with the drag along its tangent+ ImVec2 tangentDir{0, 0};+ glm::vec3 surfaceNormal{0, 1, 0}; // at the last snap (Surface orientation)+ bool pendingSnap = false; // Alt+press on the model: a click (no drag) puts the pivot there+ RayHit snapHit;+ int snapSubtool = -1;+ MeshTransform current;+ std::vector<int> subtools;+ std::vector<TransformSession> sessions;+ std::string readout; // shown beside the gizmo while dragging ("Rotate 45")+ // Where the gizmo was before and after each of its undo steps (active SubTool, by undo depth).+ struct Step {+ uint32_t subtool = 0;+ size_t depth = 0; // UndoStack::undoCount() right after the step+ glm::vec3 before{0.0f}, after{0.0f};+ glm::mat3 frameBefore{1.0f}, frameAfter{1.0f};+ bool surfaceBefore = false, surfaceAfter = false;+ };+ std::vector<Step> undoSteps, redoSteps;+ // Numeric entry (the panel): applied as one transform about the pivot.+ float move[3] = {0, 0, 0}, rotate[3] = {0, 0, 0}, scale = 100.0f;+ } gizmo_;+ // ---- end Gizmo 3D ----// ---- Tablet (Tablet.cpp, core/Tablet.h, docs/tablet.md) ----// SDL turns pen tip contact into left mouse button events (SDL_PEN_MOUSEID); the pen's own events// add pressure, tilt, the eraser end and the side buttons, which are mapped in Preferences > Tablet.diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 9af3f796..f953c742 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -218,7 +218,7 @@ void App::initActions() {nullptr, nullptr, nullptr, "Make the brush 10% larger (hold to repeat).");add("transform.symmetry_x", "Symmetry X", "Transform", "X", [this] { symmetry_.x = !symmetry_.x; }, ICON_LC_FLIP_HORIZONTAL_2,nullptr, [this] { return symmetry_.x; }, nullptr, "Mirror strokes across the X axis (left / right).");- add("view.wireframe", "Wireframe", "Render", "W / Shift+F", [this] { renderSettings_.wireframe = !renderSettings_.wireframe; },+ add("view.wireframe", "Wireframe", "Render", "Shift+F", [this] { renderSettings_.wireframe = !renderSettings_.wireframe; },ICON_LC_GRID_3X3, nullptr, [this] { return renderSettings_.wireframe; }, nullptr,"Show the mesh's polygons (quads and triangles) over the surface (ZBrush PolyFrame).");add("view.frame", "Frame model", "Transform", "F", [this] { camera_.frame(sceneBounds()); }, ICON_LC_SCAN, nullptr, nullptr,@@ -307,6 +307,7 @@ void App::initActions() {// the same id and own P (Paint), the symmetry toggles and Tab.registerShellActions();registerTextureUiActions(); // Tool > Texture Map, the Vertex / Texture paint target (PanelTexture.cpp)+ registerGizmoActions(); // Q W E R: Draw, and the Gizmo 3D's Move, Scale, Rotate (Gizmo.cpp)// Every command, so the command palette finds anything scriptable.actions_.registerCommands(diff --git a/src/app/Gizmo.cpp b/src/app/Gizmo.cppnew file mode 100644index 00000000..a28c6e89--- /dev/null+++ b/src/app/Gizmo.cpp@@ -0,0 +1,955 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Gizmo 3D (ZBrush's Move W / Scale E / Rotate R, Q back to Draw): a gizmo at the pivot with axis arrows, plane+// squares and a free-move centre (Move), rings and a view ring (Rotate), axis boxes and a uniform centre (Scale).+// Dragging a handle transforms the active SubTool, or only its unmasked part (posing), through a+// TransformSession (core/MeshTransform.h): every frame recomputes from the drag's start, so nothing drifts, and+// the release makes one undo step per SubTool. Shift snaps (15 degrees, the grid, 10%), Alt+drag moves the pivot+// or turns the axes only, Alt+click on the model puts the pivot there. The Gizmo 3D panel adds numeric entry.+#include "app/App.h"+#include "app/Ui.h"++#include <IconsLucide.h>++#include <algorithm>+#include <cmath>+#include <cstdio>++namespace sf {++namespace {++bool ctrlDown(SDL_Keymod mod) { return (mod & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0; } // as App.cpp++constexpr const char* kPath = "Transform > Gizmo 3D";+constexpr float kRadiusPx = 105.0f; // arrow length / ring radius on screen+constexpr float kViewRing = 1.22f; // the view ring, relative to the others+constexpr float kPickPx = 8.0f;+constexpr float kSnapDegrees = 15.0f;++using H = App::GizmoHandle;++int axisOf(H h) {+ switch (h) {+ case H::MoveX: case H::PlaneYZ: case H::RotateX: case H::ScaleX: return 0;+ case H::MoveY: case H::PlaneXZ: case H::RotateY: case H::ScaleY: return 1;+ case H::MoveZ: case H::PlaneXY: case H::RotateZ: case H::ScaleZ: return 2;+ default: return -1;+ }+}+bool isMove(H h) { return h >= H::MoveX && h <= H::MoveView; }+bool isRotate(H h) { return h >= H::RotateX && h <= H::RotateView; }+bool isScale(H h) { return h >= H::ScaleX && h <= H::ScaleUniform; }++ImU32 axisColor(int axis, float alpha = 1.0f) {+ const int a = int(alpha * 255.0f);+ switch (axis) {+ case 0: return IM_COL32(232, 76, 72, a);+ case 1: return IM_COL32(118, 204, 82, a);+ case 2: return IM_COL32(72, 140, 238, a);+ default: return IM_COL32(222, 222, 222, a);+ }+}+constexpr ImU32 kHot = IM_COL32(255, 214, 92, 255);++float dist2(ImVec2 a, ImVec2 b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); }++float segmentDistance(ImVec2 p, ImVec2 a, ImVec2 b) {+ const float vx = b.x - a.x, vy = b.y - a.y, l2 = vx * vx + vy * vy;+ float t = l2 > 0.0f ? ((p.x - a.x) * vx + (p.y - a.y) * vy) / l2 : 0.0f;+ t = std::clamp(t, 0.0f, 1.0f);+ return std::sqrt(dist2(p, ImVec2(a.x + vx * t, a.y + vy * t)));+}++bool insideQuad(ImVec2 p, const ImVec2 q[4]) {+ bool in = false;+ for (int i = 0, j = 3; i < 4; j = i++)+ if ((q[i].y > p.y) != (q[j].y > p.y) && p.x < (q[j].x - q[i].x) * (p.y - q[i].y) / (q[j].y - q[i].y) + q[i].x)+ in = !in;+ return in;+}++// Parameter along the line (p, a) of the point nearest to the ray (o, d).+bool rayLineParam(const glm::vec3& o, const glm::vec3& d, const glm::vec3& p, const glm::vec3& a, float& s) {+ const glm::vec3 w = o - p;+ const float b = glm::dot(d, a), c = glm::dot(d, w), e = glm::dot(a, w);+ const float den = 1.0f - b * b; // |d| = |a| = 1+ if (den < 1e-6f) return false;+ s = (e - b * c) / den;+ return true;+}++bool rayPlane(const glm::vec3& o, const glm::vec3& d, const glm::vec3& p, const glm::vec3& n, glm::vec3& hit) {+ const float den = glm::dot(d, n);+ if (std::abs(den) < 1e-6f) return false;+ const float t = glm::dot(p - o, n) / den;+ hit = o + d * t;+ return true;+}++// A step for Shift-snapped moves: 1, 2 or 5 times a power of ten near a twentieth of the size.+float gridStep(float size) {+ if (!(size > 0.0f)) return 0.1f;+ const float raw = size / 20.0f;+ const float p = std::pow(10.0f, std::floor(std::log10(raw)));+ const float m = raw / p;+ return p * (m < 1.5f ? 1.0f : m < 3.5f ? 2.0f : m < 7.5f ? 5.0f : 10.0f);+}++float snapTo(float v, float step) { return step > 0.0f ? std::round(v / step) * step : v; }++std::string vecText(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;+}++// Axes with Y along the surface normal.+glm::mat3 frameFromNormal(const glm::vec3& normal) {+ const glm::vec3 y = glm::normalize(normal);+ const glm::vec3 x = glm::normalize(glm::cross(y, std::abs(y.z) < 0.9f ? glm::vec3(0, 0, 1) : glm::vec3(1, 0, 0)));+ return glm::mat3(x, y, glm::cross(x, y));+}++} // namespace++// ---------------------------------------------------------------------------+// Actions+// ---------------------------------------------------------------------------++void App::registerGizmoActions() {+ auto add = [this](const char* id, const char* label, const char* icon, const char* palette, const char* shortcut,+ std::function<void()> run, std::function<bool()> checked, const char* description) {+ Action a;+ a.id = id;+ a.label = label;+ a.icon = icon;+ a.palette = palette;+ a.shortcut = shortcut;+ a.run = std::move(run);+ a.checked = std::move(checked);+ a.description = description;+ actions_.add(std::move(a));+ };+ auto mode = [this](GizmoMode m) {+ return [this, m] { setGizmoMode(gizmo_.mode == m && m != GizmoMode::Off ? GizmoMode::Off : m); };+ };+ auto is = [this](GizmoMode m) { return [this, m] { return gizmo_.mode == m; }; };+ add("tool.draw", "Draw", ICON_LC_PENCIL, "Transform", "Q", mode(GizmoMode::Off), is(GizmoMode::Off),+ "Draw mode: brushes sculpt and paint (leaves the Gizmo 3D).");+ add("tool.move", "Move", ICON_LC_MOVE, "Transform", "W", mode(GizmoMode::Move), is(GizmoMode::Move),+ "Gizmo 3D, Move: drag an arrow to move along an axis, a square to move in a plane, the centre to move in "+ "the view. Masked parts stay; Shift snaps to the grid; Alt+drag moves only the gizmo. W again: back to Draw.");+ add("tool.scale", "Scale", ICON_LC_SCALING, "Transform", "E", mode(GizmoMode::Scale), is(GizmoMode::Scale),+ "Gizmo 3D, Scale: drag a box to stretch along an axis or the centre to scale evenly (right or up: bigger). "+ "Shift snaps to 10% steps. E again: back to Draw.");+ add("tool.rotate", "Rotate", ICON_LC_ROTATE_CW, "Transform", "R", mode(GizmoMode::Rotate), is(GizmoMode::Rotate),+ "Gizmo 3D, Rotate: drag a ring to turn about that axis, the outer ring to turn in the view. Mask the body "+ "and put the pivot at a joint to pose a limb. Shift snaps to 15 degrees. R again: back to Draw.");+ add("gizmo.reset_pivot", "Reset", ICON_LC_LOCATE_FIXED, kPath, "", [this] { resetGizmoPivot(); }, nullptr,+ "Put the gizmo back at the centre of what moves (the SubTool, or its unmasked part) with world axes.");+ add("gizmo.snap_pivot", "To Surface", ICON_LC_CROSSHAIR, kPath, "",+ [this] {+ gizmo_.snapNext = !gizmo_.snapNext;+ if (gizmo_.snapNext) status_ = "Click on the model to put the pivot there";+ },+ [this] { return gizmo_.snapNext; },+ "Put the pivot on the surface: click this, then click the model (or Alt+click the model at any time). With "+ "Surface orientation the axes follow the surface there (Y along the normal).");+ add("gizmo.orient_world", "World", ICON_LC_GLOBE, kPath, "",+ [this] { gizmo_.orientSurface = false; }, [this] { return !gizmo_.orientSurface; },+ "The gizmo's axes are the world's X, Y and Z.");+ add("gizmo.orient_surface", "Surface", ICON_LC_LOCATE, kPath, "",+ [this] {+ gizmo_.orientSurface = true;+ gizmo_.frame = frameFromNormal(gizmo_.surfaceNormal);+ },+ [this] { return gizmo_.orientSurface; },+ "The gizmo's axes follow the surface where the pivot was snapped (Y along the normal) and turn with your "+ "rotations, for moving a part along itself.");+ add("gizmo.use_mask", "Mask", ICON_LC_DROPLET, kPath, "", [this] { gizmo_.useMask = !gizmo_.useMask; },+ [this] { return gizmo_.useMask; },+ "Masked parts stay where they are and partly masked parts move partly (on by default). Off: the whole "+ "SubTool moves whatever the mask.");+ add("gizmo.all", "All SubTools", ICON_LC_LAYERS, kPath, "", [this] { gizmo_.all = !gizmo_.all; },+ [this] { return gizmo_.all; },+ "Transform every visible SubTool together (ZBrush Transpose All). Each SubTool gets its own undo step.");+}++void App::setGizmoMode(GizmoMode mode) {+ if (drag_ == Drag::Gizmo) return;+ gizmo_.mode = mode;+ gizmo_.snapNext = false;+ gizmo_.hover = GizmoHandle::None;+ status_ = mode == GizmoMode::Move ? "Move: drag the arrows, squares or centre (Alt+drag: the gizmo only)"+ : mode == GizmoMode::Scale ? "Scale: drag a box or the centre (Shift: 10% steps)"+ : mode == GizmoMode::Rotate ? "Rotate: drag a ring (Shift: 15 degrees); mask first to pose a part"+ : "Draw";+ if (mode != GizmoMode::Off) {+ doc_.syncBvh();+ updateGizmoPivot();+ }+}++// ---------------------------------------------------------------------------+// Pivot+// ---------------------------------------------------------------------------++std::vector<int> App::gizmoTargets() const {+ std::vector<int> out;+ for (int i = 0; i < doc_.subtoolCount(); ++i) {+ const bool visible = doc_.subtools[size_t(i)].visible;+ if (i == doc_.activeSubtool ? visible : gizmo_.all && visible) out.push_back(i);+ }+ return out;+}++void App::updateGizmoPivot() {+ // Recomputed only when the scene changes: a new undo step, another SubTool, the options.+ uint64_t key = uint64_t(doc_.activeSubtoolInfo().id) * 1000003u ^ doc_.undo.revision() * 7919u ^+ doc_.mesh.vertexCount() * 31u ^ (gizmo_.all ? 2u : 0u) ^ (gizmo_.useMask ? 4u : 0u) ^+ uint64_t(doc_.subtoolCount()) << 48;+ if (gizmo_.all)+ for (const SubTool& s : doc_.subtools) key = key * 1099511628211ull ^ s.undo.revision() ^ (s.visible ? 1u : 0u);+ if (key == gizmo_.centreKey) return;+ gizmo_.centreKey = key;+ // A new mask (or another SubTool) means a new part to move: follow its centre again.+ uint64_t maskKey = doc_.activeSubtoolInfo().id;+ const auto& mask = doc_.mesh.mask;+ double sum = 0.0;+ for (size_t v = 0; v < mask.size(); v += 1 + mask.size() / 65536) sum += double(mask[v]) * double(v % 97 + 1);+ maskKey = maskKey * 1000003u ^ uint64_t(sum * 1024.0) ^ uint64_t(mask.size()) << 40;+ if (maskKey != gizmo_.maskKey) {+ gizmo_.maskKey = maskKey;+ gizmo_.pivotPlaced = false;+ }+ if (gizmo_.pivotPlaced) return;+ AABB box;+ for (int i : gizmoTargets()) {+ const Mesh& m = doc_.subtoolMesh(i);+ if (m.vertexCount() == 0) continue;+ box.expand(transformBounds(m, transformWeights(m, gizmo_.useMask, 0.0f)));+ }+ gizmo_.pivot = box.valid() ? box.center() : glm::vec3(0.0f);+}++void App::resetGizmoPivot() {+ gizmo_.pivotPlaced = false;+ gizmo_.orientSurface = false;+ gizmo_.frame = glm::mat3(1.0f);+ gizmo_.centreKey = ~uint64_t(0);+ updateGizmoPivot();+ status_ = "Pivot at the centre, world axes";+}++void App::snapGizmoPivot(const RayHit& hit, int subtool) {+ gizmo_.pivot = hit.position;+ gizmo_.pivotPlaced = true;+ gizmo_.snapNext = false;+ gizmo_.surfaceNormal = glm::length(hit.normal) > 0.0f ? glm::normalize(hit.normal) : glm::vec3(0, 1, 0);+ // The triangle's normal faces either way: turn it toward the viewer.+ if (glm::dot(gizmo_.surfaceNormal, camera_.forward()) > 0.0f) gizmo_.surfaceNormal = -gizmo_.surfaceNormal;+ if (gizmo_.orientSurface) gizmo_.frame = frameFromNormal(gizmo_.surfaceNormal);+ status_ = "Pivot on " + doc_.subtools[size_t(subtool)].name + " at " + vecText(hit.position);+}++glm::mat3 App::gizmoFrame() const {+ if (drag_ == Drag::Gizmo && !gizmo_.pivotOnly) return gizmo_.startFrame;+ return gizmo_.orientSurface ? gizmo_.frame : glm::mat3(1.0f);+}++float App::gizmoWorldSize() const {+ return kRadiusPx * uiScale_ * camera_.worldPerPixel(gizmo_.pivot, canvasHeight());+}++bool App::gizmoProject(const glm::vec3& p, ImVec2& out) const {+ const glm::vec4 c = camera_.projection() * camera_.view() * glm::vec4(p, 1.0f);+ if (c.w <= 1e-6f) return false;+ const CanvasRect r = canvasRect();+ out = ImVec2(r.x + (c.x / c.w * 0.5f + 0.5f) * r.w, r.y + (0.5f - c.y / c.w * 0.5f) * r.h);+ return true;+}++// ---------------------------------------------------------------------------+// Handles: shapes, picking+// ---------------------------------------------------------------------------++App::GizmoHandle App::gizmoHandleAt(float x, float y) const {+ if (!gizmoActive()) return H::None;+ const glm::vec3 c = gizmo_.pivot;+ const glm::mat3 f = gizmoFrame();+ const float L = gizmoWorldSize(), pick = kPickPx * uiScale_;+ const ImVec2 m(x, y);+ ImVec2 pc;+ if (!gizmoProject(c, pc)) return H::None;+ const glm::vec3 toEye = -camera_.forward();+ H best = H::None;+ float bestD = pick;+ auto consider = [&](H h, float d) {+ if (d < bestD) {+ bestD = d;+ best = h;+ }+ };+ if (gizmo_.mode == GizmoMode::Move || gizmo_.mode == GizmoMode::Scale) {+ const bool move = gizmo_.mode == GizmoMode::Move;+ // The centre first: it wins over the arrows' roots.+ const float centre = (move ? 12.0f : 11.0f) * uiScale_;+ if (std::sqrt(dist2(m, pc)) < centre) return move ? H::MoveView : H::ScaleUniform;+ for (int i = 0; i < 3; ++i) {+ ImVec2 a, b;+ if (!gizmoProject(c + f[i] * (0.2f * L), a) || !gizmoProject(c + f[i] * L, b)) continue;+ if (std::sqrt(dist2(a, b)) < 10.0f * uiScale_) continue; // pointing at the viewer+ consider(H(int(move ? H::MoveX : H::ScaleX) + i), segmentDistance(m, a, b));+ }+ if (move)+ for (int i = 0; i < 3; ++i) {+ if (std::abs(glm::dot(f[i], toEye)) < 0.15f) continue; // seen edge-on+ const glm::vec3 u = f[(i + 1) % 3], v = f[(i + 2) % 3];+ ImVec2 q[4];+ const float lo = 0.28f * L, hi = 0.48f * L;+ if (!gizmoProject(c + u * lo + v * lo, q[0]) || !gizmoProject(c + u * hi + v * lo, q[1]) ||+ !gizmoProject(c + u * hi + v * hi, q[2]) || !gizmoProject(c + u * lo + v * hi, q[3]))+ continue;+ if (insideQuad(m, q)) consider(H(int(H::PlaneYZ) + i), pick * 0.5f);+ }+ return best;+ }+ // Rotate: the axis rings (front halves first), then the view ring.+ for (int i = 0; i < 3; ++i) {+ glm::vec3 u = f[(i + 1) % 3], v = f[(i + 2) % 3];+ ImVec2 prev;+ bool havePrev = false;+ for (int k = 0; k <= 64; ++k) {+ const float t = float(k) / 64.0f * 6.2831853f;+ const glm::vec3 r = u * std::cos(t) + v * std::sin(t);+ ImVec2 p;+ if (!gizmoProject(c + r * L, p)) {+ havePrev = false;+ continue;+ }+ if (havePrev) {+ const bool front = glm::dot(r, toEye) > -0.05f;+ consider(H(int(H::RotateX) + i), segmentDistance(m, prev, p) + (front ? 0.0f : pick * 0.6f));+ }+ prev = p;+ havePrev = true;+ }+ }+ const float ring = kRadiusPx * kViewRing * uiScale_;+ consider(H::RotateView, std::abs(std::sqrt(dist2(m, pc)) - ring));+ return best;+}++bool App::gizmoHandleScreen(GizmoHandle h, ImVec2& out) const {+ // Look along the handle for a point where it is the one picked.+ const glm::vec3 c = gizmo_.pivot;+ const glm::mat3 f = gizmoFrame();+ const float L = gizmoWorldSize();+ const int axis = axisOf(h);+ std::vector<glm::vec3> tries;+ ImVec2 pc;+ if (!gizmoProject(c, pc)) return false;+ if (h == H::MoveView || h == H::ScaleUniform) {+ out = pc;+ return gizmoHandleAt(out.x, out.y) == h;+ }+ if (h == H::RotateView) {+ for (int k = 0; k < 16; ++k) {+ const float t = float(k) / 16.0f * 6.2831853f + 0.4f;+ const float r = kRadiusPx * kViewRing * uiScale_;+ const ImVec2 p(pc.x + r * std::cos(t), pc.y - r * std::sin(t));+ if (gizmoHandleAt(p.x, p.y) == h) {+ out = p;+ return true;+ }+ }+ return false;+ }+ if (isRotate(h)) {+ const glm::vec3 u = f[(axis + 1) % 3], v = f[(axis + 2) % 3];+ float bestScore = -1e9f;+ bool found = false;+ for (int k = 0; k < 48; ++k) {+ const float t = float(k) / 48.0f * 6.2831853f;+ const glm::vec3 r = u * std::cos(t) + v * std::sin(t);+ ImVec2 p;+ if (!gizmoProject(c + r * L, p) || gizmoHandleAt(p.x, p.y) != h) continue;+ const float score = glm::dot(r, -camera_.forward()); // the most front-facing point+ if (score > bestScore) {+ bestScore = score;+ out = p;+ found = true;+ }+ }+ return found;+ }+ if (h >= H::PlaneYZ && h <= H::PlaneXY) {+ const glm::vec3 u = f[(axis + 1) % 3], v = f[(axis + 2) % 3];+ return gizmoProject(c + (u + v) * (0.38f * L), out) && gizmoHandleAt(out.x, out.y) == h;+ }+ for (float s : {0.75f, 0.9f, 0.6f, 0.45f}) {+ if (gizmoProject(c + f[axis] * (s * L), out) && gizmoHandleAt(out.x, out.y) == h) return true;+ }+ return false;+}++// ---------------------------------------------------------------------------+// Dragging+// ---------------------------------------------------------------------------++bool App::gizmoMouseDown(float x, float y, SDL_Keymod mod) {+ if (!gizmoActive() || ctrlDown(mod)) return false; // Ctrl still masks, as in ZBrush+ if (previewLod_ >= 0) clearLods();+ updateGizmoPivot();+ const bool alt = (mod & SDL_KMOD_ALT) != 0;+ const GizmoHandle h = gizmoHandleAt(x, y);+ if (h == H::None) {+ RayHit hit;+ const int st = pickSubtool(x, y, &hit);+ if (st >= 0 && gizmo_.snapNext) {+ snapGizmoPivot(hit, st);+ return true;+ }+ if (alt && st >= 0 && st != doc_.activeSubtool) return false; // Alt+click selects another SubTool+ if (alt && st >= 0) { // a click puts the pivot here, a drag pans+ gizmo_.pendingSnap = true;+ gizmo_.snapHit = hit;+ gizmo_.snapSubtool = st;+ gizmo_.startMouse = ImVec2(x, y);+ }+ // Off the handles the mouse navigates, wherever it is.+ drag_ = alt ? Drag::Pan : Drag::Orbit;+ panFromAlt_ = alt;+ return true;+ }++ gizmo_.handle = h;+ gizmo_.pivotOnly = alt;+ gizmo_.startPivot = gizmo_.pivot;+ gizmo_.startFrame = gizmo_.orientSurface ? gizmo_.frame : glm::mat3(1.0f);+ gizmo_.startMouse = ImVec2(x, y);+ gizmo_.angle = gizmo_.lastAngle = 0.0f;+ gizmo_.tangent = false;+ gizmo_.current = MeshTransform{};+ gizmo_.readout.clear();+ if (gizmo_.pivotOnly && isScale(h)) {+ status_ = "Alt+drag moves the pivot (Move) or turns the axes (Rotate); scaling it does nothing";+ gizmo_.handle = H::None;+ return true;+ }+ glm::vec3 o, d;+ canvasRay(x, y, o, d);+ const glm::mat3& f = gizmo_.startFrame;+ const glm::vec3 c = gizmo_.pivot;+ const int axis = axisOf(h);+ if (h >= H::MoveX && h <= H::MoveZ) {+ float s = 0.0f;+ rayLineParam(o, d, c, f[axis], s);+ gizmo_.grab = glm::vec3(s, 0, 0);+ } else if (h >= H::PlaneYZ && h <= H::MoveView) {+ const glm::vec3 n = h == H::MoveView ? camera_.forward() : f[axis];+ if (!rayPlane(o, d, c, n, gizmo_.grab)) gizmo_.grab = c;+ } else if (isRotate(h)) {+ const glm::vec3 a = h == H::RotateView ? camera_.forward() : f[axis];+ glm::vec3 hit;+ if (h != H::RotateView && std::abs(glm::dot(a, camera_.forward())) < 0.25f) {+ // Edge-on ring: turn by the drag along the ring's tangent at the grabbed point.+ gizmo_.tangent = true;+ glm::vec3 r = glm::vec3(0.0f);+ if (rayPlane(o, d, c, a, hit)) r = hit - c;+ r -= a * glm::dot(r, a);+ if (glm::length(r) < 1e-6f) r = glm::cross(a, camera_.forward());+ r = glm::normalize(r) * gizmoWorldSize();+ ImVec2 p0, p1;+ const glm::vec3 tangent = glm::cross(a, r);+ if (gizmoProject(c + r, p0) && gizmoProject(c + r + tangent * 0.05f, p1)) {+ const float len = std::sqrt(dist2(p0, p1));+ gizmo_.tangentDir = len > 1e-4f ? ImVec2((p1.x - p0.x) / len, (p1.y - p0.y) / len) : ImVec2(1, 0);+ }+ } else if (rayPlane(o, d, c, a, hit) && glm::length(hit - c) > 1e-6f) {+ gizmo_.grabDir = glm::normalize(hit - c);+ } else {+ gizmo_.grabDir = glm::normalize(glm::cross(a, camera_.forward()));+ }+ }++ gizmo_.subtools.clear();+ gizmo_.sessions.clear();+ if (!gizmo_.pivotOnly) {+ for (int i : gizmoTargets()) {+ Mesh& m = doc_.subtoolMesh(i);+ SubTool& s = doc_.subtools[size_t(i)];+ if (i != doc_.activeSubtool && s.bvhDirty) {+ s.bvh.build(s.mesh);+ s.bvhDirty = false;+ }+ TransformSession session;+ if (!session.begin(m, transformWeights(m, gizmo_.useMask, gizmo_.falloff), symmetry_, gizmo_.pivot))+ continue;+ gizmo_.subtools.push_back(i);+ gizmo_.sessions.push_back(std::move(session));+ }+ if (gizmo_.sessions.empty()) {+ status_ = gizmo_.useMask && doc_.mesh.hasMask() ? "Nothing to move: everything is masked (Ctrl+click the "+ "background to invert the mask)"+ : "Nothing to move: the SubTool is hidden or empty";+ gizmo_.handle = H::None;+ return true;+ }+ playingLayer_ = -1;+ }+ drag_ = Drag::Gizmo;+ return true;+}++void App::gizmoDragTo(float x, float y) {+ const GizmoHandle h = gizmo_.handle;+ if (h == H::None) return;+ glm::vec3 o, d;+ canvasRay(x, y, o, d);+ const bool snap = (inputMods() & SDL_KMOD_SHIFT) != 0;+ const glm::mat3& f = gizmo_.startFrame;+ const glm::vec3 c = gizmo_.startPivot;+ const int axis = axisOf(h);+ float size = 0.0f;+ for (int i : gizmo_.subtools.empty() ? gizmoTargets() : gizmo_.subtools)+ size = std::max(size, glm::length(doc_.subtoolMesh(i).bounds().extent()));+ const float grid = gridStep(size);+ MeshTransform t;+ t.pivot = c;+ t.frame = f;+ char buf[160] = "";+ if (h >= H::MoveX && h <= H::MoveZ) {+ float s = gizmo_.grab.x;+ rayLineParam(o, d, c, f[axis], s);+ float delta = s - gizmo_.grab.x;+ if (snap) delta = snapTo(delta, grid);+ t.translate = f[axis] * delta;+ std::snprintf(buf, sizeof buf, "%c %+.3f", "XYZ"[axis], double(delta));+ } else if (h >= H::PlaneYZ && h <= H::MoveView) {+ const glm::vec3 n = h == H::MoveView ? camera_.forward() : f[axis];+ glm::vec3 hit;+ if (!rayPlane(o, d, c, n, hit)) return;+ glm::vec3 delta = hit - gizmo_.grab;+ if (snap) { // whole grid steps along the gizmo's axes+ glm::vec3 local = glm::transpose(f) * delta;+ for (int i = 0; i < 3; ++i) local[i] = snapTo(local[i], grid);+ if (h != H::MoveView) local[axis] = 0.0f;+ delta = f * local;+ }+ t.translate = delta;+ const glm::vec3 local = glm::transpose(f) * delta;+ std::snprintf(buf, sizeof buf, "%+.3f %+.3f %+.3f", double(local.x), double(local.y), double(local.z));+ } else if (isRotate(h)) {+ const glm::vec3 a = h == H::RotateView ? camera_.forward() : f[axis];+ if (gizmo_.tangent) {+ const float along = (x - gizmo_.startMouse.x) * gizmo_.tangentDir.x + (y - gizmo_.startMouse.y) * gizmo_.tangentDir.y;+ gizmo_.angle = along / (kRadiusPx * uiScale_);+ } else {+ glm::vec3 hit;+ if (rayPlane(o, d, c, a, hit) && glm::length(hit - c) > 1e-6f) {+ const glm::vec3 v = glm::normalize(hit - c);+ const float raw = std::atan2(glm::dot(glm::cross(gizmo_.grabDir, v), a), glm::dot(gizmo_.grabDir, v));+ float step = raw - gizmo_.lastAngle;+ while (step > 3.14159265f) step -= 6.2831853f;+ while (step < -3.14159265f) step += 6.2831853f;+ gizmo_.angle += step;+ gizmo_.lastAngle = raw;+ }+ }+ float angle = gizmo_.angle;+ if (snap) angle = glm::radians(snapTo(glm::degrees(angle), kSnapDegrees));+ t.rotate = glm::angleAxis(angle, a);+ std::snprintf(buf, sizeof buf, "%s %+.1f deg", h == H::RotateView ? "View" : axis == 0 ? "X" : axis == 1 ? "Y" : "Z",+ double(glm::degrees(angle)));+ } else if (isScale(h)) {+ float s;+ if (h == H::ScaleUniform) {+ s = 1.0f + ((x - gizmo_.startMouse.x) - (y - gizmo_.startMouse.y)) / (kRadiusPx * uiScale_);+ } else {+ ImVec2 p0, p1;+ if (!gizmoProject(c, p0) || !gizmoProject(c + f[axis] * gizmoWorldSize(), p1)) return;+ const float len = std::max(1.0f, std::sqrt(dist2(p0, p1)));+ const ImVec2 dir((p1.x - p0.x) / len, (p1.y - p0.y) / len);+ s = 1.0f + ((x - gizmo_.startMouse.x) * dir.x + (y - gizmo_.startMouse.y) * dir.y) / len;+ }+ if (snap) s = snapTo(s, 0.1f);+ s = std::max(s, 0.01f);+ t.scale = h == H::ScaleUniform ? glm::vec3(s) : glm::vec3(1.0f);+ if (h != H::ScaleUniform) t.scale[axis] = s;+ std::snprintf(buf, sizeof buf, "%s %.0f%%", h == H::ScaleUniform ? "All" : axis == 0 ? "X" : axis == 1 ? "Y" : "Z",+ double(s * 100.0f));+ }+ gizmo_.readout = buf;+ if (gizmo_.pivotOnly) {+ if (isMove(h)) gizmo_.pivot = c + t.translate;+ if (isRotate(h)) {+ gizmo_.orientSurface = true;+ gizmo_.frame = glm::mat3_cast(t.rotate) * f;+ }+ gizmo_.pivotPlaced = true;+ return;+ }+ gizmo_.current = t;+ for (size_t i = 0; i < gizmo_.sessions.size(); ++i) gizmo_.sessions[i].apply(doc_.subtoolMesh(gizmo_.subtools[i]), t);+}++void App::gizmoRelease() {+ if (gizmo_.pendingSnap) {+ gizmo_.pendingSnap = false;+ if (dist2(gizmo_.startMouse, ImVec2(mouseX_, mouseY_)) < 16.0f && gizmo_.snapSubtool == doc_.activeSubtool)+ snapGizmoPivot(gizmo_.snapHit, gizmo_.snapSubtool);+ }+ if (drag_ != Drag::Gizmo) return;+ const GizmoHandle h = gizmo_.handle;+ const std::string readout = std::move(gizmo_.readout);+ gizmo_.handle = H::None;+ gizmo_.readout.clear();+ if (gizmo_.pivotOnly || gizmo_.sessions.empty()) return;+ const char* label = isRotate(h) ? "Gizmo Rotate" : isScale(h) ? "Gizmo Scale" : "Gizmo Move";+ size_t moved = 0;+ for (size_t i = 0; i < gizmo_.sessions.size(); ++i) {+ const int st = gizmo_.subtools[i];+ const bool active = st == doc_.activeSubtool;+ SubTool& s = doc_.subtools[size_t(st)];+ const size_t n = gizmo_.sessions[i].movingVertices();+ UndoRecord r = gizmo_.sessions[i].finish(active ? doc_.mesh : s.mesh, active ? doc_.bvh : s.bvh, label);+ if (r.empty()) continue;+ (active ? doc_.undo : s.undo).push(std::move(r));+ moved += n;+ }+ gizmo_.sessions.clear();+ gizmo_.subtools.clear();+ if (moved == 0) return;+ // The gizmo moves and turns with what it moved.+ const MeshTransform& t = gizmo_.current;+ const glm::mat3 frameBefore = gizmo_.frame;+ const bool surfaceBefore = gizmo_.orientSurface;+ gizmo_.pivot = t.pivot + t.translate;+ gizmo_.pivotPlaced = true;+ if (gizmo_.orientSurface && isRotate(h)) gizmo_.frame = glm::mat3_cast(t.rotate) * gizmo_.startFrame;+ rememberGizmoStep(t.pivot, frameBefore, surfaceBefore);+ // The console shows the drag as the command that repeats it (Copy session as script replays it).+ Args args;+ if (t.translate != glm::vec3(0.0f)) args["translate"] = vecText(t.translate);+ const glm::mat3 local = glm::transpose(t.frame) * glm::mat3_cast(t.rotate) * t.frame;+ if (isRotate(h)) args["rotate"] = vecText(eulerDegrees(glm::quat_cast(local)));+ if (t.scale != glm::vec3(1.0f))+ args["scale"] = t.scale.x == t.scale.y && t.scale.y == t.scale.z ? vecText(t.scale).substr(0, vecText(t.scale).find(','))+ : vecText(t.scale);+ args["pivot"] = vecText(t.pivot);+ if (t.frame != glm::mat3(1.0f)) args["orient"] = vecText(eulerDegrees(glm::quat_cast(t.frame)));+ if (!gizmo_.useMask) args["masked"] = false;+ if (gizmo_.falloff > 0.0f) args["falloff"] = double(gizmo_.falloff);+ std::string sym;+ if (symmetry_.x) sym += 'x';+ if (symmetry_.y) sym += 'y';+ if (symmetry_.z) sym += 'z';+ if (!sym.empty() && doc_.mesh.hasMask() && gizmo_.useMask) args["symmetry"] = sym;+ if (gizmo_.all) args["all"] = true;+ status_ = std::string(label) + " " + readout + ": " + std::to_string(moved) + " vertices";+ consoleEcho("transform", args, {true, status_});+ updateTitle();+}++void App::rememberGizmoStep(const glm::vec3& before, const glm::mat3& frameBefore, bool surfaceBefore) {+ GizmoState::Step st;+ st.subtool = doc_.activeSubtoolInfo().id;+ st.depth = doc_.undo.undoCount();+ st.before = before;+ st.after = gizmo_.pivot;+ st.frameBefore = frameBefore;+ st.frameAfter = gizmo_.frame;+ st.surfaceBefore = surfaceBefore;+ st.surfaceAfter = gizmo_.orientSurface;+ gizmo_.undoSteps.push_back(st);+ gizmo_.redoSteps.clear();+ if (gizmo_.undoSteps.size() > 256) gizmo_.undoSteps.erase(gizmo_.undoSteps.begin());+}++void App::gizmoAfterUndo(bool redo) {+ const uint32_t id = doc_.activeSubtoolInfo().id;+ const size_t depth = doc_.undo.undoCount();+ auto& from = redo ? gizmo_.redoSteps : gizmo_.undoSteps;+ auto& to = redo ? gizmo_.undoSteps : gizmo_.redoSteps;+ // Undo took the stack from st.depth to st.depth - 1; redo brought it back to st.depth.+ if (from.empty() || from.back().subtool != id || from.back().depth != (redo ? depth : depth + 1)) return;+ const GizmoState::Step st = from.back();+ from.pop_back();+ to.push_back(st);+ gizmo_.pivot = redo ? st.after : st.before;+ gizmo_.frame = redo ? st.frameAfter : st.frameBefore;+ gizmo_.orientSurface = redo ? st.surfaceAfter : st.surfaceBefore;+ gizmo_.pivotPlaced = true;+}++void App::applyGizmoNumbers() {+ updateGizmoPivot();+ const glm::vec3 move(gizmo_.move[0], gizmo_.move[1], gizmo_.move[2]);+ const glm::vec3 rot(gizmo_.rotate[0], gizmo_.rotate[1], gizmo_.rotate[2]);+ const float scale = gizmo_.scale / 100.0f;+ if (!(scale > 0.0f)) {+ status_ = "Scale must be above 0%";+ return;+ }+ const glm::mat3 f = gizmoFrame();+ Args args;+ args["translate"] = vecText(move);+ args["rotate"] = vecText(rot);+ args["scale"] = double(scale);+ args["pivot"] = vecText(gizmo_.pivot);+ if (f != glm::mat3(1.0f)) args["orient"] = vecText(eulerDegrees(glm::quat_cast(f)));+ args["masked"] = gizmo_.useMask;+ if (gizmo_.falloff > 0.0f) args["falloff"] = double(gizmo_.falloff);+ std::string sym;+ if (symmetry_.x) sym += 'x';+ if (symmetry_.y) sym += 'y';+ if (symmetry_.z) sym += 'z';+ if (!sym.empty()) args["symmetry"] = sym;+ if (gizmo_.all) args["all"] = true;+ const glm::vec3 pivot = gizmo_.pivot;+ const glm::mat3 frameBefore = gizmo_.frame;+ const bool surfaceBefore = gizmo_.orientSurface;+ runCommand("transform", args);+ if (!lastCommandOk_ || !doc_.undo.canUndo()) return;+ gizmo_.pivot = pivot + move;+ gizmo_.pivotPlaced = true;+ if (gizmo_.orientSurface) gizmo_.frame = glm::mat3_cast(eulerRotation(rot, f)) * f;+ rememberGizmoStep(pivot, frameBefore, surfaceBefore);+}++// ---------------------------------------------------------------------------+// Drawing+// ---------------------------------------------------------------------------++void App::drawGizmo() {+ if (!gizmoActive()) return;+ if (drag_ != Drag::Gizmo) updateGizmoPivot();+ drawGizmoPanel();+ if (!doc_.activeSubtoolInfo().visible) return;+ const ImVec2 mouse(mouseX_, mouseY_);+ const bool overCanvas = !ImGui::GetIO().WantCaptureMouse && canvasRect().contains(mouse.x, mouse.y);+ gizmo_.hover = drag_ == Drag::Gizmo ? gizmo_.handle+ : drag_ == Drag::None && overCanvas && !ctrlDown(inputMods()) ? gizmoHandleAt(mouse.x, mouse.y)+ : H::None;+ ImDrawList* dl = ImGui::GetBackgroundDrawList(); // under the panels, over the model+ const CanvasRect cr = canvasRect();+ dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);+ const glm::vec3 c = gizmo_.pivot;+ const glm::mat3 f = gizmoFrame();+ const float L = gizmoWorldSize(), s = uiScale_;+ const glm::vec3 toEye = -camera_.forward();+ ImVec2 pc;+ if (!gizmoProject(c, pc)) {+ dl->PopClipRect();+ return;+ }+ const bool dragging = drag_ == Drag::Gizmo && gizmo_.handle != H::None;+ auto colorFor = [&](H h, int axis) {+ if (gizmo_.hover == h) return kHot;+ return axisColor(axis, dragging ? 0.45f : 1.0f);+ };+ const float thick = 2.6f * s;+ const ImU32 shadow = IM_COL32(0, 0, 0, 110);++ if (gizmo_.mode == GizmoMode::Move || gizmo_.mode == GizmoMode::Scale) {+ const bool move = gizmo_.mode == GizmoMode::Move;+ if (move) // plane squares, behind the arrows+ for (int i = 0; i < 3; ++i) {+ if (std::abs(glm::dot(f[i], toEye)) < 0.15f) continue;+ const glm::vec3 u = f[(i + 1) % 3], v = f[(i + 2) % 3];+ ImVec2 q[4];+ const float lo = 0.28f * L, hi = 0.48f * L;+ if (!gizmoProject(c + u * lo + v * lo, q[0]) || !gizmoProject(c + u * hi + v * lo, q[1]) ||+ !gizmoProject(c + u * hi + v * hi, q[2]) || !gizmoProject(c + u * lo + v * hi, q[3]))+ continue;+ const H h = H(int(H::PlaneYZ) + i);+ const ImU32 col = colorFor(h, i);+ dl->AddConvexPolyFilled(q, 4, (col & 0x00ffffff) | (gizmo_.hover == h ? 0x90000000u : 0x50000000u));+ dl->AddPolyline(q, 4, col, ImDrawFlags_Closed, 1.5f * s);+ }+ // Arrows / boxes, far ones first.+ int order[3] = {0, 1, 2};+ std::sort(order, order + 3, [&](int a, int b) { return glm::dot(f[a], toEye) < glm::dot(f[b], toEye); });+ for (int i : order) {+ ImVec2 a, b;+ if (!gizmoProject(c + f[i] * (0.2f * L), a) || !gizmoProject(c + f[i] * L, b)) continue;+ const float len = std::sqrt(dist2(a, b));+ if (len < 10.0f * s) continue;+ const H h = H(int(move ? H::MoveX : H::ScaleX) + i);+ const ImU32 col = colorFor(h, i);+ const ImVec2 dir((b.x - a.x) / len, (b.y - a.y) / len), nrm(-dir.y, dir.x);+ dl->AddLine(a, b, shadow, thick + 2.0f * s);+ dl->AddLine(a, b, col, thick);+ if (move) {+ const float head = 15.0f * s, w = 6.0f * s;+ const ImVec2 tip(b.x + dir.x * head, b.y + dir.y * head);+ dl->AddTriangleFilled(tip, ImVec2(b.x + nrm.x * w, b.y + nrm.y * w), ImVec2(b.x - nrm.x * w, b.y - nrm.y * w), col);+ } else {+ const float h2 = 6.0f * s;+ dl->AddRectFilled(ImVec2(b.x - h2, b.y - h2), ImVec2(b.x + h2, b.y + h2), col);+ dl->AddRect(ImVec2(b.x - h2, b.y - h2), ImVec2(b.x + h2, b.y + h2), shadow, 0.0f, 0, 1.0f);+ }+ dl->AddText(smallFont(), 12.0f * s, ImVec2(b.x + dir.x * (move ? 20.0f : 11.0f) * s - 3.0f * s,+ b.y + dir.y * (move ? 20.0f : 11.0f) * s - 7.0f * s),+ col, i == 0 ? "X" : i == 1 ? "Y" : "Z");+ }+ const H centre = move ? H::MoveView : H::ScaleUniform;+ const ImU32 cc = gizmo_.hover == centre ? kHot : IM_COL32(240, 206, 96, dragging ? 140 : 255);+ if (move) {+ dl->AddCircle(pc, 10.0f * s, shadow, 32, thick + 2.0f * s);+ dl->AddCircle(pc, 10.0f * s, cc, 32, thick);+ } else {+ dl->AddCircleFilled(pc, 9.0f * s, cc, 32);+ dl->AddCircle(pc, 9.0f * s, shadow, 32, 1.0f * s);+ }+ } else {+ // Rotate: rings with their back halves dimmed, the view ring outside them.+ for (int i = 0; i < 3; ++i) {+ const glm::vec3 u = f[(i + 1) % 3], v = f[(i + 2) % 3];+ const H h = H(int(H::RotateX) + i);+ const ImU32 col = colorFor(h, i);+ ImVec2 prev;+ bool havePrev = false, prevFront = true;+ for (int k = 0; k <= 96; ++k) {+ const float t = float(k) / 96.0f * 6.2831853f;+ const glm::vec3 r = u * std::cos(t) + v * std::sin(t);+ ImVec2 p;+ if (!gizmoProject(c + r * L, p)) {+ havePrev = false;+ continue;+ }+ const bool front = glm::dot(r, toEye) > -0.02f;+ if (havePrev) {+ if (front && prevFront) {+ dl->AddLine(prev, p, shadow, thick + 2.0f * s);+ dl->AddLine(prev, p, col, thick);+ } else {+ dl->AddLine(prev, p, (col & 0x00ffffff) | 0x48000000u, 1.5f * s);+ }+ }+ prev = p;+ prevFront = front;+ havePrev = true;+ }+ }+ const ImU32 vc = gizmo_.hover == H::RotateView ? kHot : IM_COL32(222, 222, 222, dragging ? 110 : 220);+ dl->AddCircle(pc, kRadiusPx * kViewRing * s, shadow, 96, thick + 2.0f * s);+ dl->AddCircle(pc, kRadiusPx * kViewRing * s, vc, 96, thick);+ if (dragging && isRotate(gizmo_.handle) && !gizmo_.tangent) {+ // The swept angle as a pie, so the turn reads at a glance.+ const glm::vec3 a = gizmo_.handle == H::RotateView ? camera_.forward() : f[axisOf(gizmo_.handle)];+ const float ang = glm::degrees(gizmo_.current.rotate.w < 1.0f ? 2.0f * std::acos(std::clamp(gizmo_.current.rotate.w, -1.0f, 1.0f)) : 0.0f);+ const float signedAng = glm::dot(glm::vec3(gizmo_.current.rotate.x, gizmo_.current.rotate.y, gizmo_.current.rotate.z), a) < 0 ? -ang : ang;+ std::vector<ImVec2> pie{pc};+ const int steps = std::max(2, int(std::abs(signedAng) / 4.0f));+ const float radius = gizmo_.handle == H::RotateView ? L * kViewRing : L;+ for (int k = 0; k <= steps; ++k) {+ const glm::quat q = glm::angleAxis(glm::radians(signedAng) * float(k) / float(steps), a);+ ImVec2 p;+ if (gizmoProject(c + (q * gizmo_.grabDir) * radius, p)) pie.push_back(p);+ }+ if (pie.size() >= 3) {+ for (size_t k = 1; k + 1 < pie.size(); ++k) dl->AddTriangleFilled(pie[0], pie[k], pie[k + 1], IM_COL32(255, 214, 92, 50));+ dl->AddLine(pie[0], pie[1], kHot, 1.5f * s);+ dl->AddLine(pie[0], pie.back(), kHot, 1.5f * s);+ }+ }+ }+ // The pivot.+ dl->AddCircleFilled(pc, 3.5f * s, IM_COL32(255, 255, 255, 230), 16);+ dl->AddCircle(pc, 3.5f * s, shadow, 16, 1.0f);+ if (!gizmo_.readout.empty()) {+ const ImVec2 at(pc.x + 18.0f * s, pc.y + kRadiusPx * s * 0.55f);+ const ImVec2 size = ImGui::CalcTextSize(gizmo_.readout.c_str());+ dl->AddRectFilled(ImVec2(at.x - 5 * s, at.y - 3 * s), ImVec2(at.x + size.x + 5 * s, at.y + size.y + 3 * s),+ IM_COL32(20, 20, 22, 210), 4.0f * s);+ dl->AddText(at, kHot, gizmo_.readout.c_str());+ }+ if (gizmo_.pivotOnly && drag_ == Drag::Gizmo) {+ const char* hint = "Moving the gizmo only";+ dl->AddText(ImVec2(pc.x + 18.0f * s, pc.y - kRadiusPx * s * 0.7f), IM_COL32(230, 230, 230, 230), hint);+ }+ dl->PopClipRect();+}++void App::drawGizmoPanel() {+ const CanvasRect c = canvasRect();+ ImGui::SetNextWindowPos(ImVec2(c.x + 12.0f * uiScale_, c.y + c.h - 12.0f * uiScale_), ImGuiCond_FirstUseEver,+ ImVec2(0.0f, 1.0f));+ ImGui::SetNextWindowSize(ImVec2(270.0f * uiScale_, 0.0f), ImGuiCond_Always);+ if (ImGui::Begin("Gizmo 3D", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) {+ drawGizmoContents(true);+ }+ ImGui::End();+}++void App::drawGizmoContents(bool compact) {+ ui::Segmented(*this, {"tool.draw", "tool.move", "tool.scale", "tool.rotate"});+ if (!compact && !gizmoActive()) {+ ImGui::TextDisabled("Q W E R: Draw, Move, Scale, Rotate");+ return;+ }+ // Pivot.+ ImGui::SetNextItemWidth(-1.0f);+ float pivot[3] = {gizmo_.pivot.x, gizmo_.pivot.y, gizmo_.pivot.z};+ if (ImGui::DragFloat3("##pivot", pivot, 0.005f, 0.0f, 0.0f, "%.3f")) {+ gizmo_.pivot = glm::vec3(pivot[0], pivot[1], pivot[2]);+ gizmo_.pivotPlaced = true;+ }+ ui::HelpText("Pivot", nullptr,+ "Where the gizmo sits: rotation and scaling turn about this point. It follows the centre of what "+ "moves until you place it: Alt+drag the gizmo, Alt+click the model, To Surface, or type here.",+ kPath);+ ui::Segmented(*this, {"gizmo.reset_pivot", "gizmo.snap_pivot"});+ ui::Segmented(*this, {"gizmo.orient_world", "gizmo.orient_surface"});+ ui::Segmented(*this, {"gizmo.use_mask", "gizmo.all"});+ float pct = gizmo_.falloff * 100.0f;+ ImGui::SetNextItemWidth(-1.0f);+ if (ui::SliderInside("##gizmo_falloff", &pct, 0.0f, 50.0f, "Falloff %.0f%%")) gizmo_.falloff = pct / 100.0f;+ ui::HelpText("Falloff", nullptr,+ "A soft joint for posing: the movement eases in over this distance from the masked part (a share "+ "of the SubTool's size), so a hard mask edge bends smoothly instead of creasing. 0: the mask as it is.",+ kPath);+ ImGui::Separator();+ // Numeric entry: one transform about the pivot, along the gizmo's axes.+ const float labelW = ImGui::CalcTextSize("Rotate ").x + ImGui::GetStyle().ItemSpacing.x;+ auto row = [&](const char* label, const char* id, float* v, int n, const char* format, const char* help) {+ ImGui::AlignTextToFramePadding();+ ImGui::TextUnformatted(label);+ ImGui::SameLine(labelW + ImGui::GetStyle().WindowPadding.x);+ const float spacing = ImGui::GetStyle().ItemSpacing.x * 0.5f;+ const float w = (ImGui::GetContentRegionAvail().x - spacing * float(n - 1)) / float(n);+ for (int i = 0; i < n; ++i) {+ if (i) ImGui::SameLine(0.0f, spacing);+ ImGui::SetNextItemWidth(w);+ const std::string itemId = std::string("##") + id + (n > 1 ? std::string("_") + "xyz"[i] : std::string());+ ImGui::InputFloat(itemId.c_str(), &v[i], 0.0f, 0.0f, format);+ ui::HelpText(label, nullptr, help, kPath);+ }+ };+ row("Move", "gizmo_move", gizmo_.move, 3, "%.3g", "Distance to move along X, Y and Z (the gizmo's axes) when you press Apply.");+ row("Rotate", "gizmo_rotate", gizmo_.rotate, 3, "%.3g",+ "Degrees to turn about X, then Y, then Z (the gizmo's axes, through the pivot) when you press Apply.");+ row("Scale", "gizmo_scale", &gizmo_.scale, 1, "%.1f%%", "Size to scale to about the pivot when you press Apply (100% = unchanged).");+ const float w = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;+ if (ImGui::Button("Apply", ImVec2(w, 0))) applyGizmoNumbers();+ ui::HelpText("Apply", nullptr,+ "Move, rotate and scale by the numbers above, about the pivot, as one undo step (the transform "+ "command). Masked parts stay; with symmetry on, a masked transform is mirrored.",+ kPath);+ ImGui::SameLine();+ if (ImGui::Button("Clear", ImVec2(w, 0))) {+ std::fill(gizmo_.move, gizmo_.move + 3, 0.0f);+ std::fill(gizmo_.rotate, gizmo_.rotate + 3, 0.0f);+ gizmo_.scale = 100.0f;+ }+ ui::HelpText("Clear", nullptr, "Set Move and Rotate back to 0 and Scale to 100%.", kPath);+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]);+ ImGui::TextWrapped("Shift snaps (15 deg, grid, 10%%). Alt+drag the gizmo: move it only. Alt+click the model: pivot there.");+ ImGui::PopStyleColor();+}++} // namespace sfdiff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 563a96c7..c26c1170 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -401,6 +401,8 @@ void App::drawPalette_Tool() {}void App::drawPalette_Transform() {+ ImGui::TextDisabled("Gizmo 3D");+ drawGizmoContents(false);ImGui::TextDisabled("Symmetry");segmented(*this, {"transform.symmetry_x", "transform.symmetry_y", "transform.symmetry_z"});actionRow(*this, {"view.frame", "subtool.solo"});diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex 02c8d43a..b6ac12db 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -217,6 +217,17 @@ void App::storeProjectSettings() {sym.set("y", symmetry_.y);sym.set("z", symmetry_.z);s.set("symmetry", std::move(sym));++ Json gizmo = Json::object(); // Gizmo 3D (Gizmo.cpp): where the pivot is and the options+ gizmo.set("pivot", vec3Json(gizmo_.pivot));+ gizmo.set("pivot_placed", gizmo_.pivotPlaced);+ gizmo.set("orient_surface", gizmo_.orientSurface);+ gizmo.set("axis_x", vec3Json(gizmo_.frame[0]));+ gizmo.set("axis_y", vec3Json(gizmo_.frame[1]));+ gizmo.set("use_mask", gizmo_.useMask);+ gizmo.set("all_subtools", gizmo_.all);+ gizmo.set("falloff", double(gizmo_.falloff));+ s.set("gizmo", std::move(gizmo));}// Lenient: anything missing keeps its current value.@@ -265,10 +276,33 @@ void App::applyProjectSettings() {readBool(sym, "y", symmetry_.y);readBool(sym, "z", symmetry_.z);}+ if (const Json& g = s["gizmo"]; g.isObject()) {+ gizmo_.centreKey = ~uint64_t(0);+ updateGizmoPivot(); // the opened scene's centre, then the saved pivot over it+ glm::vec3 x = gizmo_.frame[0], y = gizmo_.frame[1];+ readVec3(g["pivot"], gizmo_.pivot);+ readBool(g, "pivot_placed", gizmo_.pivotPlaced);+ readBool(g, "orient_surface", gizmo_.orientSurface);+ readVec3(g["axis_x"], x);+ readVec3(g["axis_y"], y);+ if (glm::length(glm::cross(x, y)) > 1e-3f) { // orthonormal again, whatever the file holds+ x = glm::normalize(x);+ const glm::vec3 z = glm::normalize(glm::cross(x, y));+ gizmo_.frame = glm::mat3(x, glm::cross(z, x), z);+ }+ readBool(g, "use_mask", gizmo_.useMask);+ readBool(g, "all_subtools", gizmo_.all);+ readFloat(g, "falloff", gizmo_.falloff);+ gizmo_.falloff = std::clamp(gizmo_.falloff, 0.0f, 1.0f);+ if (!gizmo_.pivotPlaced) updateGizmoPivot();+ gizmo_.undoSteps.clear();+ gizmo_.redoSteps.clear();+ }}void App::afterCommand(const std::string& name, const Args& args, const CommandResult& r) {if (!r.ok) return;+ if (name == "undo" || name == "redo") gizmoAfterUndo(name == "redo");const std::string path = argString(args, "path", doc_.path);const bool project = name == "open_project" || (name == "open" && isProjectPath(path));if (project) {diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 78c33cd2..722d7ec6 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -340,7 +340,7 @@ void App::registerShellActions() {add({"view.frame", "Frame", ICON_LC_SCAN, "Fit the whole model in the view.", "Transform", "F", "",[this] { camera_.frame(sceneBounds()); }, nullptr, nullptr});flag("view.polyf", "PolyF", ICON_LC_GRID_3X3, "Render", "", &renderSettings_.wireframe,- "Polyframe: show the polygons of the active SubTool (same as W).");+ "Polyframe: show the polygons of the active SubTool (Shift+F).");flag("view.polygroups", "Groups", ICON_LC_SHAPES, "Render", "", &renderSettings_.showPolygroups,"Colour each polygroup of the active SubTool.");flag("view.mask", "Mask", ICON_LC_DROPLET, "Render", "", &renderSettings_.showMask, "Darken masked areas.");diff --git a/src/app/UiLayout.cpp b/src/app/UiLayout.cppindex c4ec2b99..4ffcb644 100644--- a/src/app/UiLayout.cpp+++ b/src/app/UiLayout.cpp@@ -26,7 +26,8 @@ UiLayout standardLayout() {UiLayout l;l.rightTray = {"tool"};l.openSubpalettes = {"tool.subtool"};- l.topShelf = {"ui.lightbox", "sep", "draw.sculpt", "draw.paint", "sep",+ l.topShelf = {"ui.lightbox", "sep", "tool.draw", "tool.move", "tool.scale",+ "tool.rotate", "sep", "draw.sculpt", "draw.paint", "sep","draw.zadd", "draw.zsub", "draw.rgb", "draw.paint_vertex", "draw.paint_texture", "sep", "widget.draw_size","widget.strength", "row", "ui.brush_lab", "draw.front_faces", "sep","transform.symmetry_x", "transform.symmetry_y", "transform.symmetry_z", "sep", "draw.pressure_strength",diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 1d16a240..fa1beb0c 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -19,6 +19,10 @@// or a rectangle from the first point to the last. keep: leave the button down// (for a shot mid-drag); `release` lets go, with the modifiers held then// release release the left button+// gizmo_drag HANDLE DX DY [S] left-drag a Gizmo 3D handle by DX DY pixels with the held modifiers (alt: the+// gizmo only; shift: snapping). HANDLE: move_x move_y move_z plane_yz plane_xz plane_xy+// move_view rotate_x rotate_y rotate_z rotate_view scale_x scale_y scale_z scale_uniform+// gizmo_hover HANDLE move the mouse onto a Gizmo 3D handle (it lights up, for screenshots)// orbit DX DY right-drag on the background, in pixels (with the held modifiers)// run COMMANDS sculptforge-cli commands, e.g. run new_sphere subdivisions=4// drop FILE as if FILE were dropped onto the window (relative to the script's folder)@@ -42,6 +46,7 @@// right_tray_open, left_tray_open, lightbox_open, guide_open, guide_hits (search results), shelves (1 shown), left_tray / right_tray (palettes in// the tray, -1 when closed); OP is == != < <= > >=// moved (vertices moved since `snapshot`), moved_max / moved_sum (distance),+// moved_masked (masked vertices that moved),// moved_out (summed movement along the snapshot's normals: > 0 out, < 0 in),// pen_pressure (raw), brush_pressure (after the curve; 1 for the mouse),// stroking (1 while a stroke is open), cursor_x / cursor_y (the brush cursor, pixels),@@ -56,6 +61,9 @@// texture_painted (texels of the texture composite that aren't white),// texture_mean_r / texture_mean_g / texture_mean_b (mean composite, sRGB 0-255),// auto_uv_running+// gizmo_mode (0 Draw, 1 Move, 2 Scale, 3 Rotate), gizmo_hover (handle under the cursor,+// 0 = none, in gizmo_drag's order from 1), gizmo_falloff, pivot_x / pivot_y / pivot_z,+// center_x / center_y / center_z and size_x / size_y / size_z (active mesh bounds)// (mesh values are the active SubTool's)// snapshot remember the active mesh's vertices (for the moved* values)// remember VALUE NAME keep VALUE's current value as $NAME@@ -235,6 +243,17 @@ double Demo::query(const std::string& name, bool& known) const {const int k = name.back() == 'r' ? 0 : name.back() == 'g' ? 1 : 2;return sum[k] / double(px.size() / 4);}+ if (name == "gizmo_mode") return double(int(app_.gizmo_.mode));+ if (name == "gizmo_hover") return double(int(app_.gizmo_.hover));+ if (name == "gizmo_falloff") return app_.gizmo_.falloff;+ if (name == "pivot_x") return app_.gizmo_.pivot.x;+ if (name == "pivot_y") return app_.gizmo_.pivot.y;+ if (name == "pivot_z") return app_.gizmo_.pivot.z;+ if ((name.rfind("center_", 0) == 0 && name.size() == 8) || (name.rfind("size_", 0) == 0 && name.size() == 6)) {+ const AABB b = m.bounds();+ const int k = name.back() == 'x' ? 0 : name.back() == 'y' ? 1 : 2;+ return name[0] == 'c' ? b.center()[k] : b.extent()[k];+ }if (name == "can_undo") return app_.doc_.undo.canUndo() ? 1.0 : 0.0;if (name == "dirty") return app_.doc_.dirty() ? 1.0 : 0.0;if (name == "splats") return double(app_.doc_.splats.size());@@ -291,6 +310,13 @@ double Demo::query(const std::string& name, bool& known) const {for (uint8_t h : m.hidden) n += h != 0;return double(n);}+ if (name == "moved_masked") { // masked vertices (mask >= 0.5) that moved since `snapshot`+ if (basePositions_.size() != m.vertexCount()) return -1.0;+ double count = 0.0;+ for (size_t v = 0; v < basePositions_.size(); ++v)+ count += m.maskAt(uint32_t(v)) >= 0.5f && glm::length(m.positions[v] - basePositions_[v]) > 1e-6f ? 1.0 : 0.0;+ return count;+ }if (name == "moved" || name == "moved_max" || name == "moved_sum" || name == "moved_out") {if (basePositions_.size() != m.vertexCount()) return -1.0; // no snapshot, or the topology changeddouble count = 0.0, maxD = 0.0, sum = 0.0, out = 0.0;@@ -558,6 +584,45 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& ereturn false;});wait(0.1f);+ } else if (verb == "gizmo_drag" || verb == "gizmo_hover") {+ static const char* kHandles[] = {"move_x", "move_y", "move_z", "plane_yz", "plane_xz",+ "plane_xy", "move_view", "rotate_x", "rotate_y", "rotate_z",+ "rotate_view", "scale_x", "scale_y", "scale_z", "scale_uniform"};+ if (!need(verb == "gizmo_drag" ? 3 : 1)) return false;+ int index = -1;+ for (int i = 0; i < int(std::size(kHandles)); ++i)+ if (w[1] == kHandles[i]) index = i + 1;+ if (index < 0) {+ error = "unknown gizmo handle '" + w[1] + "'";+ return false;+ }+ const auto handle = App::GizmoHandle(index);+ const bool drag = verb == "gizmo_drag";+ const float dx = drag ? num(2, 0) : 0.0f, dy = drag ? num(3, 0) : 0.0f, seconds = drag ? num(4, 0.5f) : 0.0f;+ auto from = std::make_shared<ImVec2>();+ const std::string name = w[1];+ steps_.push_back([this, line, handle, from, name](float t) {+ if (app_.gizmoHandleScreen(handle, *from)) {+ mouseMotion(from->x, from->y);+ return true;+ }+ if (t > 1.0f) fail(line, "gizmo handle " + name + " isn't on screen (is the gizmo in that mode?)");+ return t > 1.0f;+ });+ if (drag) {+ steps_.push_back([this, from, dx, dy, seconds](float t) {+ if (t == 0.0f) return false; // a frame of hover first+ if (!buttonDown_ && t < seconds) mouseButton(true, SDL_BUTTON_LEFT);+ const float u = std::min(t / seconds, 1.0f);+ mouseMotion(from->x + dx * u, from->y + dy * u);+ if (t >= seconds) {+ mouseButton(false, SDL_BUTTON_LEFT);+ return true;+ }+ return false;+ });+ }+ wait(0.1f);} else if (verb == "drag_item") {if (!need(3)) return false;const std::string label = w[1];diff --git a/src/app/UserGuide.cpp b/src/app/UserGuide.cppindex 6c0d073d..2e54692b 100644--- a/src/app/UserGuide.cpp+++ b/src/app/UserGuide.cpp@@ -432,6 +432,9 @@ std::string UserGuide::chapterFor(const std::string& palette, const std::string&if (starts("Generate")) return "generate-3d.md";if (starts("Splats")) return "splats.md";if (starts("Script")) return "scripting.md";+ if (starts("Transform > Gizmo") || idStarts("gizmo.") || actionId == "tool.draw" || actionId == "tool.move" ||+ actionId == "tool.scale" || actionId == "tool.rotate")+ return "gizmo.md";if (starts("Transform")) return idStarts("transform.symmetry") ? "sculpting.md" : "navigation.md";if (starts("Render") || starts("Edit") || starts("Help") || starts("Palettes") || starts("Preferences") ||starts("LightBox"))diff --git a/src/core/Undo.h b/src/core/Undo.hindex 370f85a2..28b835fc 100644--- a/src/core/Undo.h+++ b/src/core/Undo.h@@ -142,6 +142,7 @@ public:bool canRedo() const { return !redo_.empty(); }const std::string& undoLabel() const { return undo_.back().label; }const std::string& redoLabel() const { return redo_.back().label; }+ size_t undoCount() const { return undo_.size(); }// Both rebuild/refit the BVH as needed.bool undo(Mesh& mesh, BVH& bvh);diff --git a/tests/ui/gizmo.sfui b/tests/ui/gizmo.sfuinew file mode 100644index 00000000..ccf7eb36--- /dev/null+++ b/tests/ui/gizmo.sfui@@ -0,0 +1,152 @@+# Gizmo 3D (W Move, E Scale, R Rotate, Q Draw): each mode's handles, axis-locked moves, Shift snapping, Alt+drag+# moving only the gizmo, scaling, posing a capsule arm at the elbow (mask, pivot, soft falloff), undo / redo,+# numeric entry, All SubTools.+run new_sphere subdivisions=5 ; transform scale=3,0.7,0.7 pivot=origin ; subtool_rename to=Arm+key f+orbit -70 -45+expect_value size_x > 5.9+remember center_x cx0+remember center_y cy0+remember center_z cz0++# W: Move mode shows the gizmo and its panel; the top shelf's Move lights up.+key w+expect_value gizmo_mode == 1+expect "Gizmo 3D/Apply"+expect_value wireframe == 0+gizmo_hover move_x+wait 0.2+expect_value gizmo_hover == 1+shot move-mode++# An arrow moves along its axis only.+snapshot+gizmo_drag move_x 90 0+expect_value moved > 1000+expect_value center_y == $cy0+expect_value center_z == $cz0+expect_value can_undo == 1+expect_status Gizmo Move+shot moved-x+remember pivot_x px1+expect_value pivot_x > 0.2+key ctrl+z+expect_value moved == 0+expect_value center_x == $cx0+# The gizmo goes back with the model, and forward again on redo.+expect_value pivot_x < 0.001+key ctrl+shift+z+expect_value pivot_x == $px1+key ctrl+z++# The view-plane centre moves freely; a plane square moves in its plane.+gizmo_drag move_view 60 -40+expect_value moved_max > 0.1+key ctrl+z+gizmo_drag plane_xz 40 30+expect_value center_y == $cy0+key ctrl+z+expect_value moved == 0++# Shift snaps a move to the grid (0.2 for a model this size).+hold shift+gizmo_drag move_y 0 -70+hold none+expect_value center_y > 0.19+remember center_y snapped+expect_value center_y == $snapped+key ctrl+z++# Alt+drag moves only the gizmo; Reset brings it back to the centre.+hold alt+gizmo_drag move_x 80 0+hold none+expect_value moved == 0+expect_value pivot_x > 0.3+expect_value pivot_y < 0.001+expect_value pivot_y > -0.001+shot pivot-moved+click "Reset##gizmo.reset_pivot"+expect_value pivot_x < 0.01+expect_value pivot_x > -0.01++# E: Scale. The centre scales evenly, a box along one axis.+key e+expect_value gizmo_mode == 2+gizmo_hover scale_uniform+shot scale-mode+remember size_y sy0+gizmo_drag scale_uniform 50 -50+expect_value size_y > $sy0*1.4+key ctrl+z+expect_value size_y == $sy0+gizmo_drag scale_y 0 -60+expect_value size_y > $sy0*1.2+remember size_x sx0+expect_value size_x == $sx0+key ctrl+z++# R: Rotate. Pose the forearm: mask the upper arm, Alt+click the elbow for the pivot, soften the joint, turn.+key r+expect_value gizmo_mode == 3+shot rotate-mode+run mask_rect x0=-1 y0=-1 x1=0 y1=1+expect_value masked > 1000+# The gizmo jumps to the centre of the unmasked forearm.+wait 0.1+expect_value pivot_x > 1+hold alt+click_subtool Arm 0.5 0.5+hold none+expect_value pivot_x < 0.8+expect_value pivot_x > -0.8+expect_status Pivot on Arm+drag_item "Gizmo 3D/##gizmo_falloff" 25 0+expect_value gizmo_falloff > 0.05+snapshot+gizmo_hover rotate_z+shot rotate-hover+gizmo_drag rotate_z 0 -90+expect_value moved > 1000+expect_value moved_max > 1+expect_status Gizmo Rotate+shot posed+# The masked upper arm stayed where it was.+expect_value moved_masked == 0+key ctrl+z+expect_value moved == 0+key ctrl+shift+z+expect_value moved > 1000+shot posed-redo+key ctrl+z+run mask_clear++# Numeric entry: type the amounts, Apply runs one transform command about the pivot.+click "Reset##gizmo.reset_pivot"+type "Gizmo 3D/##gizmo_rotate_z" 90+click "Gizmo 3D/Apply"+expect_status Transformed+expect_value size_y > 5.9+expect_value can_undo == 1+shot numeric+key ctrl+z+click "Gizmo 3D/Clear"++# All SubTools moves every visible SubTool together, with an undo step in each.+run subtool_append type=sphere name=Ball+key f+key w+click "All SubTools##gizmo.all"+gizmo_drag move_view 50 40+expect_value edited_subtools == 2+shot all-subtools+click "All SubTools##gizmo.all"++# Q (or W again) goes back to Draw: the gizmo and its panel go away and brushes sculpt again.+key w+expect_value gizmo_mode == 0+key r+key q+expect_value gizmo_mode == 0+expect_not "Gizmo 3D/Apply"+shot draw-modediff --git a/tests/ui/help_console.sfui b/tests/ui/help_console.sfuiindex 3af6ec7e..533f0f1a 100644--- a/tests/ui/help_console.sfui+++ b/tests/ui/help_console.sfui@@ -88,9 +88,9 @@ type "##Command palette" "restore standard"key enterexpect_status "Standard UI restored"expect_value console_open == 0-key w+key shift+fexpect_value wireframe == 1-key w+key shift+fkey f3type "##Command palette" "restore custom"key enterdiff --git a/tests/ui/subtools.sfui b/tests/ui/subtools.sfuiindex 9b8689f6..85b3ec3c 100644--- a/tests/ui/subtools.sfui+++ b/tests/ui/subtools.sfui@@ -139,13 +139,13 @@ click "SubTool##tool.subtool"expect "SubTools/Append"# Wireframe, polygroup colours and the LOD preview are for the active SubTool only.-key w+key shift+fexpect_value wireframe == 1click "Polygroups"click "Show polygroups"shot active-overlaysclick "Show polygroups"-key w+key shift+fclick "Export"click "Generate LOD chain"shot lod-preview