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
SpaceMouse navigation (#6, experimental): 3Dconnexion devices through SDL's joystick API
islandmedd9e4dd944160
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 250f6cf3..dc7daa81 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,6 +30,15 @@ All notable changes to SculptForge are listed here. The format followsor flat whatever the scene says. Both are saved in projects (no format change; older files open with yourpreferred shading) and the scene's choice is a preference (Store Config). Smooth stays the default. Scripts:`set_shading mode=flat`, `subtool_shading mode=smooth name=Eyes`.+- 3Dconnexion SpaceMouse navigation (#6, experimental): the cap's six axes pan, zoom and turn the view about the+ orbit pivot, continuously and at the same speed whatever the frame rate, in every input style and while a pen+ stroke is held. Read through SDL's joystick API (no 3Dconnexion SDK), hot-plug aware, recognised by USB id+ (vendor 256F, and the older Logitech-id SpaceNavigator / SpacePilot / SpaceExplorer / SpaceMouse Pro).+ **Preferences > Input > SpaceMouse**: on/off, speed, dead zone, per-axis invert, Lock rotation to turntable,+ Dominant axis, live axis bars, and an action per button (the two side buttons default to Frame and Front view);+ Store Config keeps them (`spaceMouse` in ui.json). Untested on real hardware; the guide explains what to do when+ 3DxWare (Windows, macOS) or spacenavd (Linux) holds the device. UI tests drive a virtual joystick with a+ SpaceMouse Compact's ids (`spacemouse`, `spacemouse_hold`, `spacemouse_button`, `spacemouse_unplug` steps).### Fixed- The Blender Bridge add-on zip was missing `zbrush_keys.py`, so Blender refused to install it ("cannot import name zbrush_keys", #10). The zip now carries every module, and the packaging check fails if one is left out.- Rotating, panning and zooming with the pen tip on the background only shook the view with some tablets (a Ugeediff --git a/CMakeLists.txt b/CMakeLists.txtindex df673e72..df083736 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -88,6 +88,7 @@ add_library(sculptforge_core STATICsrc/core/Guide.cppsrc/core/UpdateCheck.cppsrc/core/Tablet.cpp+ src/core/SpaceMouse.cppsrc/io/ObjIO.cppsrc/io/FbxIO.cppthird_party/ufbx/ufbx.c@@ -243,6 +244,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/PanelProject.cppsrc/app/PanelSubTools.cppsrc/app/Tablet.cpp+ src/app/SpaceMouse.cppsrc/app/Input.cppsrc/render/GL.cppsrc/render/Camera.cppdiff --git a/docs/guide/navigation.md b/docs/guide/navigation.mdindex becb4a5f..6862172b 100644--- a/docs/guide/navigation.md+++ b/docs/guide/navigation.md@@ -1,7 +1,7 @@# Navigating the view-This chapter explains how to rotate, pan and zoom the camera with a mouse, a pen or the right-shelf buttons,-how to frame the model, and which display toggles help while you sculpt.+This chapter explains how to rotate, pan and zoom the camera with a mouse, a pen, the right-shelf buttons or a+3Dconnexion SpaceMouse, how to frame the model, and which display toggles help while you sculpt.## How the camera works@@ -77,6 +77,69 @@ on a laptop trackpad, or when the model fills the canvas and there is no backgroThe button stays orange while you drag. **Frame** is also in the **Render** and **Transform** palettes.+## SpaceMouse (experimental)++A 3Dconnexion SpaceMouse lets one hand move the view while the other holds the pen. SculptForge reads it+directly as a USB device, without 3Dconnexion's driver or SDK, so this is **experimental**: it has been tested+with simulated input only, not yet with a real SpaceMouse. Tell us how it works with yours+([GitHub issue #6](https://github.com/islandmed/SculptForge/issues/6)).++Plug it in and it works: **Preferences > Input** shows its name under **SpaceMouse (experimental)**, with live+bars for its six axes. The model moves the way you move the cap, and turns about the same point the mouse+orbits around (the camera's target: **Frame** sets it to the scene's centre, and panning moves it).++| Move the cap | The view |+|---|---|+| Push left / right | Pans left / right |+| Pull up / push down | Pans up / down |+| Pull towards you / push away | Zooms in / out |+| Twist | Turns the model around |+| Tilt towards you / away | Tips the model's top towards you / away |+| Roll left / right | Rolls the model on screen (not with **Lock rotation to turntable**) |+| Left side button | **Frame** |+| Right side button | **Front view** |++The speed is the same whatever the frame rate: holding the cap for a second turns the model just as far on a slow+machine as on a fast one. It works in every input style (ZBrush, SculptForge, Blender) and while a stroke is+held: the stroke keeps going, sculpting wherever the pen points on the turned model. Many people stop moving the+pen while they turn the view, and that works best, but you don't have to.++**Preferences > Input > SpaceMouse:**++- **Use SpaceMouse**: off ignores it completely, buttons too.+- **Speed**: how fast the view moves for the same push.+- **Dead zone**: how far the cap must move before anything happens (8% by default), so a hand resting on it+ doesn't drift the view. The live bars turn orange once an axis is past it.+- **Lock rotation to turntable**: the model stays upright; twisting turns it about the world's up axis and+ rolling the cap does nothing.+- **Dominant axis**: only the direction you push the most moves the view, so a twist doesn't also pan a little.+- **Invert**: reverse any of the six moves (Pan X, Zoom, Pan Y, Tilt, Roll, Spin). If a direction feels wrong on+ your model of SpaceMouse, flip it here.+- **Left button**, **Right button** (and **Button 3** onwards on models with more): Frame, Frame SubTool, the+ axis views, Orthographic, Undo, Redo or Nothing.+- **SpaceMouse defaults** puts everything back.++Store Config (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd>) keeps these settings.++**If SculptForge doesn't see it** (Preferences says "No SpaceMouse found"):++- **Windows:** 3Dconnexion's driver, 3DxWare, can keep the device to itself, and may also move the view on its+ own as it does in other programs. Quit 3DxWare (its tray icon, or stop the **3DxService** service in Task+ Manager > Services), unplug the SpaceMouse and plug it back in. Without 3DxWare, Windows treats the SpaceMouse as+ a game controller, which is how SculptForge reads it. If SculptForge sees the SpaceMouse with 3DxWare running,+ give the buttons a job in only one of the two places, or one press does two things.+- **macOS:** the same applies to 3DxWare for Mac: quit it (or uninstall it) and plug the SpaceMouse in again.+- **Linux:** if **spacenavd** is running, it normally opens the device exclusively. SculptForge may still list+ the SpaceMouse but get no motion from it. Stop it while you sculpt (`sudo systemctl stop spacenavd`). SculptForge+ reads the device through `/dev/input` as a joystick: that works when the kernel reports the cap's axes as+ absolute axes, which is how joysticks work. If the kernel reports them as relative motion, as it does for some+ older models, the SpaceMouse doesn't show up at all. Reading it through spacenavd isn't supported yet.++SculptForge recognises 3Dconnexion devices by their USB ids: everything under 3Dconnexion's own vendor id+(SpaceMouse Compact, Wireless, Pro, Enterprise, Module, the Universal Receiver) except the CadMouse and the+keyboards, and the older models sold under Logitech's id (SpaceNavigator, SpacePilot, SpaceExplorer, SpaceMouse+Pro, SpaceBall 5000).+## Framing**Frame** (<kbd>F</kbd>) points the camera at the centre of the scene and moves it back until everything fits:diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.mdindex 8fb455a6..626f52eb 100644--- a/docs/guide/whats-new.md+++ b/docs/guide/whats-new.md@@ -26,6 +26,15 @@ also import a keymap you exported from Blender. See [Blender keys](shortcuts.md#check exactly what a brush did; **This SubTool** keeps one SubTool smooth or flat whatever the scene says. See[Polypaint and materials](polypaint.md).+### SpaceMouse (experimental)++A 3Dconnexion SpaceMouse now moves the view: twist, tilt and push the cap to turn, pan and zoom around the model+with one hand while the other holds the pen, in every input style and even mid-stroke. The two side buttons+frame the model and show the front. **Preferences > Input > SpaceMouse** sets the speed, the dead zone, turntable+rotation, a dominant-axis mode, inverts any axis, and maps the buttons. It reads the device directly, without+3Dconnexion's driver, and hasn't been tried on real hardware yet: see+[SpaceMouse](navigation.md#spacemouse-experimental) if yours doesn't show up.+### Fixes- Pens whose drivers send stray mouse events (a Ugee M708 on Linux) can rotate, pan and zoom on the backgrounddiff --git a/src/app/App.cpp b/src/app/App.cppindex fa54ff1a..7d959554 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -79,10 +79,18 @@ bool App::init(const AppOptions& options) {options_ = options;const bool recording = !options.recordPath.empty() || !options.uiTest.empty();const bool headless = !options.renderPath.empty() || recording;+ // UI tests run in a hidden window that never has focus; SDL drops joystick input without focus otherwise, and+ // the scripted SpaceMouse is a virtual joystick (UiTest.cpp).+ if (!options.uiTest.empty()) SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");if (!SDL_Init(SDL_INIT_VIDEO)) {SDL_Log("SDL_Init failed: %s", SDL_GetError());return false;}+ // Joysticks for a 3Dconnexion SpaceMouse (SpaceMouse.cpp). Not fatal: the app works without them.+ if (!headless || !options.uiTest.empty()) {+ if (SDL_InitSubSystem(SDL_INIT_JOYSTICK)) spaceMouseScan();+ else SDL_Log("SDL joystick init failed (no SpaceMouse): %s", SDL_GetError());+ }SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);@@ -268,6 +276,7 @@ void App::shutdown() {flushBrushEdits();if (blenderInitialised_) writeBridgeHeartbeat(blenderExchangeRoot(), true); // the add-on starts a new one+ spaceMouseClose();if (refTexture_) gl::DeleteTextures(1, &refTexture_);gallery_.reset(); // its preview textures need the GL contextthumbs_.clear();@@ -329,8 +338,8 @@ int App::runUiTest(int w, int h, int fps) {bool finalFrame = false;while (frames < fps * 60 * 30) {SDL_Event e;- while (SDL_PollEvent(&e)) {- } // the script provides all input+ while (SDL_PollEvent(&e)) // the script provides all input (its SpaceMouse is a virtual joystick)+ if (e.type >= SDL_EVENT_JOYSTICK_AXIS_MOTION && e.type < SDL_EVENT_GAMEPAD_AXIS_MOTION) spaceMouseEvent(e);if (demo_->finished()) {if (finalFrame) break;finalFrame = true; // one more frame, for a failure screenshot@@ -349,6 +358,7 @@ int App::runUiTest(int w, int h, int fps) {pollSplatTrain();pollSculptable();updateCameraAspect();+ updateSpaceMouse(dt);Demo::beginFrame();ImGui_ImplOpenGL3_NewFrame();@@ -586,6 +596,9 @@ int App::run() {continue;}updateCameraAspect();+ // The SpaceMouse moves the view by its held axes every frame (frame-rate independent); while it does,+ // spaceMouseMoving() is true and a loop that waits for events when idle must keep drawing.+ updateSpaceMouse(dt);ImGui_ImplOpenGL3_NewFrame();ImGui_ImplSDL3_NewFrame();@@ -621,6 +634,12 @@ void App::handleEvent(const SDL_Event& e) {case SDL_EVENT_QUIT:requestQuit();break;+ case SDL_EVENT_JOYSTICK_ADDED:+ case SDL_EVENT_JOYSTICK_REMOVED:+ case SDL_EVENT_JOYSTICK_AXIS_MOTION:+ case SDL_EVENT_JOYSTICK_BUTTON_DOWN:+ spaceMouseEvent(e); // a SpaceMouse (SpaceMouse.cpp)+ break;case SDL_EVENT_WINDOW_CLOSE_REQUESTED:if (e.window.windowID == SDL_GetWindowID(window_)) requestQuit();break;diff --git a/src/app/App.h b/src/app/App.hindex 5608ae41..18dc0dd4 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -24,6 +24,7 @@#include "core/AutoUv.h"#include "core/QRemesh.h"#include "core/Stroke.h"+#include "core/SpaceMouse.h"#include "core/Tablet.h"#include "core/UpdateCheck.h"#include "core/Texture.h"@@ -1141,6 +1142,23 @@ private:};std::vector<TabletTestSample> tabletTest_; // Preferences > Tablet draw-test area// ---- end Tablet ----+ // ---- SpaceMouse (SpaceMouse.cpp, core/SpaceMouse.h, docs/guide/navigation.md) ----+ // A 3Dconnexion SpaceMouse read through SDL's joystick API (no 3Dconnexion SDK): its six axes move the camera+ // every frame, independently of the mouse and pen (a stroke held by the pen keeps going), its buttons run actions.+ void spaceMouseEvent(const SDL_Event& e); // hot-plug and buttons+ void spaceMouseScan(); // take the first SpaceMouse SDL knows about, if none is open+ void spaceMouseClose();+ void updateSpaceMouse(float dt); // once a frame: move the camera by the held axes+ bool spaceMouseMoving() const { return spaceMouseMoving_; } // keep frames coming while the cap is pushed+ void drawSpaceMouseSection(); // Preferences > Input > SpaceMouse+ SDL_Joystick* spaceMouse_ = nullptr;+ SDL_JoystickID spaceMouseId_ = 0;+ std::string spaceMouseName_;+ int spaceMouseButtonCount_ = 0;+ std::array<float, kSmAxes> spaceMouseAxes_{}; // the last values read, -1 .. 1 (Preferences shows them)+ bool spaceMouseMoving_ = false;+ int spaceMouseLastButton_ = -1; // for Preferences: "Button N pressed"+ // ---- end SpaceMouse ----};} // namespace sfdiff --git a/src/app/Config.cpp b/src/app/Config.cppindex 23c50a29..4071f781 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -50,6 +50,7 @@ Json toJson(const UiPrefs& p) {j.set("emulateNumpad", p.emulateNumpad);j.set("alphabeticalPalettes", p.alphabeticalPalettes);j.set("tablet", toJson(p.tablet));+ j.set("spaceMouse", toJson(p.spaceMouse));j.set("antialiasing", double(p.antialiasing));j.set("fastNavigation", p.fastNavigation);j.set("multithreading", p.multithreading);@@ -78,6 +79,7 @@ void fromJson(const Json& j, UiPrefs& p) {p.emulateNumpad = j["emulateNumpad"].asBool(p.emulateNumpad);p.alphabeticalPalettes = j["alphabeticalPalettes"].asBool(p.alphabeticalPalettes);fromJson(j["tablet"], p.tablet);+ fromJson(j["spaceMouse"], p.spaceMouse);const int aa = int(j["antialiasing"].asNumber(p.antialiasing));p.antialiasing = aa >= 8 ? 8 : aa >= 4 ? 4 : aa >= 2 ? 2 : 1;p.fastNavigation = j["fastNavigation"].asBool(p.fastNavigation);diff --git a/src/app/Config.h b/src/app/Config.hindex bc656321..636b4983 100644--- a/src/app/Config.h+++ b/src/app/Config.h@@ -9,6 +9,7 @@#pragma once#include "core/Json.h"+#include "core/SpaceMouse.h"#include "core/Tablet.h"#include <string>@@ -33,6 +34,7 @@ struct UiPrefs {// 2 Blender (middle-drag orbit, numpad views, Blender's sculpt keys; Input.cpp)bool emulateNumpad = false; // Blender style: the 1-9 and 0 keys above the letters act as the numpad (laptops)TabletSettings tablet; // Preferences > Tablet: pressure curve, eraser, pen buttons+ SpaceMouseSettings spaceMouse; // Preferences > Input > SpaceMouse// Preferences > Performance (PanelPerformance.cpp).int antialiasing = 4; // samples per pixel in the 3D view: 1 (off), 2, 4 or 8bool fastNavigation = true; // big scenes draw without antialiasing while the view movesdiff --git a/src/app/Demo.h b/src/app/Demo.hindex cb1571e8..b699fe92 100644--- a/src/app/Demo.h+++ b/src/app/Demo.h@@ -160,6 +160,11 @@ private:// `snapshot` saves the active mesh; moved* values compare against it. `remember` keeps values for $NAME.std::vector<glm::vec3> basePositions_, baseNormals_;std::map<std::string, double> remembered_;+ // Simulated SpaceMouse (spacemouse* steps): an SDL virtual joystick with a SpaceMouse Compact's ids.+ SDL_JoystickID virtualSpaceMouse_ = 0;+ SDL_Joystick* virtualSpaceMouseHandle_ = nullptr;+ bool attachVirtualSpaceMouse();+ void detachVirtualSpaceMouse();};} // namespace sfdiff --git a/src/app/Input.cpp b/src/app/Input.cppindex e6f8aff8..4e990d9a 100644--- a/src/app/Input.cpp+++ b/src/app/Input.cpp@@ -398,6 +398,7 @@ void App::drawInputSection() {"Free: the model turns about the screen's axes and can roll over the top, as in ZBrush. Turntable: it ""stays upright, as in Blender or Maya.","Preferences > Input");+ drawSpaceMouseSection(); // SpaceMouse.cpp}void App::drawZIntensitySlider(const char* id) {diff --git a/src/app/SpaceMouse.cpp b/src/app/SpaceMouse.cppnew file mode 100644index 00000000..498cf788--- /dev/null+++ b/src/app/SpaceMouse.cpp@@ -0,0 +1,281 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// 3Dconnexion SpaceMouse navigation (#6), experimental: the device is opened+// through SDL's joystick API, not the 3Dconnexion SDK, so it works where the+// operating system shows it as a HID joystick (Linux without spacenavd holding+// it, macOS, Windows without 3DxWare hiding it). The cap's six axes move the+// camera every frame about the same pivot the mouse orbits around; the buttons+// run actions (Frame and Front view by default). The math and the settings are+// in core/SpaceMouse.h; Preferences > Input > SpaceMouse edits them, Store+// Config keeps them. User guide: docs/guide/navigation.md.+#include "app/App.h"+#include "app/Ui.h"++#include <IconsLucide.h>++#include <algorithm>+#include <cfloat>+#include <cmath>+#include <cstdio>+#include <string>++namespace sf {++namespace {++ImVec4 col(ImU32 c) { return ImGui::ColorConvertU32ToFloat4(c); }++// What a button can run from Preferences (ui.json may name any action id).+struct ButtonChoice {+ const char* id;+ const char* label;+};+constexpr ButtonChoice kButtonChoices[] = {+ {"", "Nothing"},+ {"view.frame", "Frame"},+ {"view.frame_selected", "Frame SubTool"},+ {"view.front", "Front view"},+ {"view.back", "Back view"},+ {"view.right", "Right view"},+ {"view.left", "Left view"},+ {"view.top", "Top view"},+ {"view.bottom", "Bottom view"},+ {"view.opposite", "Opposite side"},+ {"view.ortho", "Orthographic"},+ {"edit.undo", "Undo"},+ {"edit.redo", "Redo"},+};++// Short enough for three to a row in the narrowest tray.+const char* const kAxisNames[kSmAxes] = {"Pan X", "Zoom", "Pan Y", "Tilt", "Roll", "Spin"};++} // namespace++void App::spaceMouseScan() {+ if (spaceMouse_) return;+ int count = 0;+ SDL_JoystickID* ids = SDL_GetJoysticks(&count);+ if (!ids) return;+ for (int i = 0; i < count && !spaceMouse_; ++i) {+ // UI tests take only their own virtual SpaceMouse, not one plugged into the machine running them.+ if (!options_.uiTest.empty() && !SDL_IsJoystickVirtual(ids[i])) continue;+ const char* name = SDL_GetJoystickNameForID(ids[i]);+ if (!isSpaceMouseDevice(SDL_GetJoystickVendorForID(ids[i]), SDL_GetJoystickProductForID(ids[i]), name ? name : ""))+ continue;+ SDL_Joystick* j = SDL_OpenJoystick(ids[i]);+ if (!j) {+ SDL_Log("SpaceMouse: cannot open %s: %s", name ? name : "?", SDL_GetError());+ continue;+ }+ if (SDL_GetNumJoystickAxes(j) < kSmAxes) { // a 3Dconnexion device without a 6-DoF cap+ SDL_CloseJoystick(j);+ continue;+ }+ spaceMouse_ = j;+ spaceMouseId_ = ids[i];+ spaceMouseName_ = name && *name ? name : "SpaceMouse";+ spaceMouseButtonCount_ = std::max(SDL_GetNumJoystickButtons(j), 0);+ spaceMouseAxes_ = {};+ SDL_Log("SpaceMouse: %s (%04x:%04x, %d buttons)", spaceMouseName_.c_str(), SDL_GetJoystickVendor(j),+ SDL_GetJoystickProduct(j), spaceMouseButtonCount_);+ }+ SDL_free(ids);+}++void App::spaceMouseClose() {+ if (spaceMouse_) SDL_CloseJoystick(spaceMouse_);+ spaceMouse_ = nullptr;+ spaceMouseId_ = 0;+ spaceMouseName_.clear();+ spaceMouseButtonCount_ = 0;+ spaceMouseAxes_ = {};+ spaceMouseMoving_ = false;+}++void App::spaceMouseEvent(const SDL_Event& e) {+ switch (e.type) {+ case SDL_EVENT_JOYSTICK_ADDED:+ spaceMouseScan();+ break;+ case SDL_EVENT_JOYSTICK_REMOVED:+ if (spaceMouse_ && e.jdevice.which == spaceMouseId_) {+ SDL_Log("SpaceMouse: %s unplugged", spaceMouseName_.c_str());+ spaceMouseClose();+ spaceMouseScan(); // another one may still be plugged in+ }+ break;+ case SDL_EVENT_JOYSTICK_BUTTON_DOWN: {+ if (!spaceMouse_ || e.jbutton.which != spaceMouseId_) break;+ spaceMouseLastButton_ = e.jbutton.button;+ const SpaceMouseSettings& s = uiPrefs_.spaceMouse;+ if (!s.enabled || e.jbutton.button >= s.buttons.size()) break;+ const std::string& id = s.buttons[e.jbutton.button];+ if (id.empty()) break;+ const Action* a = actions_.find(id);+ if (a && a->run && (!a->enabled || a->enabled())) a->run();+ break;+ }+ default:+ break; // axis motion is read once a frame (updateSpaceMouse); the event only wakes the loop+ }+}++void App::updateSpaceMouse(float dt) {+ // The first frame of a move counts as one frame, not the time since the last frame drawn (a loop that sleeps+ // while idle wakes on the axis event: the cap has only just left the centre).+ if (!spaceMouseMoving_) dt = std::min(dt, 1.0f / 60.0f);+ spaceMouseMoving_ = false;+ if (!spaceMouse_) return;+ for (int i = 0; i < kSmAxes; ++i)+ spaceMouseAxes_[size_t(i)] = std::clamp(float(SDL_GetJoystickAxis(spaceMouse_, i)) / 32767.0f, -1.0f, 1.0f);+ const SpaceMouseSettings& s = uiPrefs_.spaceMouse;+ const SpaceMouseMotion m = spaceMouseMotion(spaceMouseAxes_, dt, s);+ if (!m.any()) return;+ spaceMouseMoving_ = true;+ if (m.spin != 0.0f || m.tip != 0.0f || m.roll != 0.0f) {+ if (autoOrtho_) { // an axis view turned: back to perspective, as when orbiting with the mouse+ camera_.ortho = false;+ autoOrtho_ = false;+ }+ // About the camera's target, the pivot every orbit turns around.+ if (s.turntable) {+ camera_.orbit(m.spin / 0.008f, m.tip / 0.008f); // (Camera::orbit takes pixels at 0.008 rad each)+ } else {+ camera_.setOrientation(camera_.orientation() * glm::angleAxis(-m.spin, glm::vec3(0, 1, 0)) *+ glm::angleAxis(-m.tip, glm::vec3(1, 0, 0)) * glm::angleAxis(-m.roll, glm::vec3(0, 0, 1)));+ }+ orbitStarted_ = false; // a mouse orbit under way continues from here, not from where it started+ }+ const float h = canvasHeight();+ if (m.panX != 0.0f || m.panY != 0.0f) camera_.pan(m.panX * h, m.panY * h, h);+ if (m.zoom != 0.0f) camera_.zoom(m.zoom);+ // A stroke held by the pen carries on: its dabs follow the pen on screen, so the next sample sculpts where the+ // pen now points on the turned model; nothing else about the stroke changes.+}++// ---------------------------------------------------------------------------+// Preferences > Input > SpaceMouse+// ---------------------------------------------------------------------------++void App::drawSpaceMouseSection() {+ SpaceMouseSettings& s = uiPrefs_.spaceMouse;+ const char* path = "Preferences > Input > SpaceMouse";+ const float width = ImGui::GetContentRegionAvail().x;+ ImGui::Spacing();+ ImGui::SeparatorText("SpaceMouse (experimental)");+ if (spaceMouse_) {+ ImGui::TextColored(col(ui::color::accent), ICON_LC_JOYSTICK);+ ImGui::SameLine();+ ImGui::TextUnformatted(spaceMouseName_.c_str());+ } else {+ ImGui::TextUnformatted(ICON_LC_JOYSTICK " No SpaceMouse found");+ ImGui::PushStyleColor(ImGuiCol_Text, col(ui::color::textDim));+ ImGui::PushTextWrapPos(0.0f);+#if defined(_WIN32) || defined(__APPLE__)+ ImGui::TextUnformatted("Plug it in. If 3DxWare is installed it may keep the device to itself: see the "+ "Navigation page of the guide.");+#else+ ImGui::TextUnformatted("Plug it in. SculptForge reads it as a joystick (/dev/input): you need read access to "+ "it, and spacenavd may hold it. See the Navigation page of the guide.");+#endif+ ImGui::PopTextWrapPos();+ ImGui::PopStyleColor();+ }+ ui::HelpText("SpaceMouse", nullptr,+ "Experimental. A 3Dconnexion SpaceMouse moves the view with one hand while the other holds the pen: "+ "push, pull and twist the cap to pan, zoom and turn the model about the pivot. Read directly as a USB "+ "device, without 3Dconnexion's driver; tested only with simulated input so far.",+ path);++ ui::Checkbox("Use SpaceMouse##spacemouse.enabled", &s.enabled);+ ui::HelpText("Use SpaceMouse", nullptr, "Experimental. Off: the SpaceMouse is ignored.", path);+ ImGui::SetNextItemWidth(-FLT_MIN);+ ui::SliderInside("##spacemouse.speed", &s.speed, 0.1f, 4.0f, "Speed %.2fx", ImGuiSliderFlags_Logarithmic);+ ui::HelpText("SpaceMouse speed", nullptr, "How fast the view moves for the same push on the cap.", path);+ float dead = s.deadZone * 100.0f;+ ImGui::SetNextItemWidth(-FLT_MIN);+ if (ui::SliderInside("##spacemouse.dead_zone", &dead, 0.0f, 50.0f, "Dead zone %.0f%%"))+ s.deadZone = std::clamp(dead / 100.0f, 0.0f, 0.5f);+ ui::HelpText("Dead zone", nullptr,+ "How far the cap must move before the view does, so a hand resting on it or a slightly off-centre cap "+ "doesn't drift the view.",+ path);+ ui::Checkbox("Lock rotation to turntable##spacemouse.turntable", &s.turntable);+ ui::HelpText("Lock rotation to turntable", nullptr,+ "The model stays upright: twisting turns it about the world's up axis, tilting looks over or under it, "+ "and rolling the cap does nothing.",+ path);+ ui::Checkbox("Dominant axis##spacemouse.dominant", &s.dominant);+ ui::HelpText("Dominant axis", nullptr,+ "Only the direction you push the most moves the view: a twist doesn't also pan a little.", path);++ // Invert, two rows of three: the moves, then the turns.+ ImGui::TextDisabled("Invert");+ const float cw = (width - 2.0f * ImGui::GetStyle().ItemSpacing.x) / 3.0f;+ for (int i = 0; i < kSmAxes; ++i) {+ if (i % 3) ImGui::SameLine(float(i % 3) * (cw + ImGui::GetStyle().ItemSpacing.x));+ bool inv = s.invert[size_t(i)];+ if (ui::Checkbox((std::string(kAxisNames[i]) + "##spacemouse.invert" + std::to_string(i)).c_str(), &inv))+ s.invert[size_t(i)] = inv;+ ui::HelpText((std::string("Invert ") + kAxisNames[i]).c_str(), nullptr,+ "Move the view the other way for this push or turn of the cap.", path);+ }++ // The live axes, so a cap that drifts or an axis going the wrong way is easy to see: one bar per axis, in the+ // order above, filled from the centre; grey while inside the dead zone.+ if (spaceMouse_) {+ ImGui::AlignTextToFramePadding();+ ImGui::TextDisabled("Live");+ ImGui::SameLine();+ const float x0 = ImGui::GetCursorScreenPos().x, avail = ImGui::GetContentRegionAvail().x;+ const float gap = 4.0f * ImGui::GetFontSize() / 15.0f, bw = (avail - 5.0f * gap) / 6.0f;+ const float bh = std::max(3.0f, ImGui::GetFontSize() * 0.3f);+ const float y = ImGui::GetCursorScreenPos().y + (ImGui::GetFrameHeight() - bh) * 0.5f;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ for (int i = 0; i < kSmAxes; ++i) {+ const float a = x0 + float(i) * (bw + gap), mid = a + bw * 0.5f, v = spaceMouseAxes_[size_t(i)];+ dl->AddRectFilled(ImVec2(a, y), ImVec2(a + bw, y + bh), IM_COL32(255, 255, 255, 28), bh * 0.5f);+ dl->AddRectFilled(ImVec2(std::min(mid, mid + v * bw * 0.5f), y), ImVec2(std::max(mid, mid + v * bw * 0.5f), y + bh),+ std::abs(v) <= s.deadZone ? ui::color::textDim : ui::color::accent, bh * 0.5f);+ dl->AddLine(ImVec2(mid, y - 1.0f), ImVec2(mid, y + bh + 1.0f), ui::color::textDim);+ }+ ImGui::Dummy(ImVec2(avail, ImGui::GetFrameHeight()));+ ui::HelpText("Live axes", nullptr,+ "What the SpaceMouse reports now: Pan X, Zoom, Pan Y, Tilt, Roll, Spin. Grey: inside the dead zone.",+ path);+ }++ // Buttons: as many rows as the device has (at least the two side buttons), up to kSpaceMouseButtonSlots.+ const int rows = std::clamp(spaceMouseButtonCount_, 2, kSpaceMouseButtonSlots);+ for (int b = 0; b < rows; ++b) {+ std::string& id = s.buttons[size_t(b)];+ const char* shown = id.empty() ? "Nothing" : id.c_str();+ for (const ButtonChoice& c : kButtonChoices)+ if (id == c.id) shown = c.label;+ const std::string label = b == 0 ? "Left button" : b == 1 ? "Right button" : "Button " + std::to_string(b + 1);+ ImGui::AlignTextToFramePadding();+ ImGui::TextUnformatted(label.c_str());+ ImGui::SameLine(width * 0.42f);+ ImGui::SetNextItemWidth(-FLT_MIN);+ if (ImGui::BeginCombo(("##spacemouse.button" + std::to_string(b)).c_str(), shown)) {+ for (const ButtonChoice& c : kButtonChoices)+ if (ImGui::Selectable((std::string(c.label) + "##spacemouse.button" + std::to_string(b)).c_str(), id == c.id))+ id = c.id;+ ImGui::EndCombo();+ }+ ui::HelpText(label.c_str(), nullptr,+ b < 2 ? "What this side button of the SpaceMouse does (the two side buttons: Frame and Front view)."+ : "What this button of the SpaceMouse does.",+ path);+ }+ if (spaceMouse_ && spaceMouseLastButton_ >= 0)+ ImGui::TextColored(col(ui::color::textDim), "Last button pressed: %d", spaceMouseLastButton_ + 1);+ if (ImGui::SmallButton(ICON_LC_ROTATE_CCW " SpaceMouse defaults##spacemouse.defaults")) s = SpaceMouseSettings();+ ui::HelpText("SpaceMouse defaults", nullptr,+ "On, speed 1, dead zone 8%, nothing inverted, free rotation, all axes at once; left button Frame, right "+ "button Front view.",+ path);+}++} // namespace sfdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 989f314b..35ea4974 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -135,6 +135,16 @@// pen_out the pen leaves proximity// mouse_move U V a plain mouse (not the pen) moves to a point on the model, e.g. the stray mouse// events Windows Ink sends beside the pen's+//+// Simulated 3Dconnexion SpaceMouse: an SDL virtual joystick with a SpaceMouse Compact's USB ids (256F:C635), six+// axes and two buttons, found and opened by the app as a real one would be (SpaceMouse.cpp, hot-plug included).+// spacemouse TX TY TZ RX RY RZ [S] plug it in if needed, hold the cap at these axis values (-1..1, the device's+// raw directions) for S seconds (default 0.5), then let go+// spacemouse_hold TX TY TZ RX RY RZ hold the cap there until the next spacemouse step (for steps in between,+// e.g. a pen stroke while the view turns); spacemouse_hold 0 0 0 0 0 0 lets go+// spacemouse_button N press and release button N (1 = left side button, 2 = right)+// spacemouse_unplug unplug it+// expect_value spacemouse_connected (1 when the app opened it), spacemouse_moving (1 while it moves the view)#include "app/App.h"#ifndef SDL_PEN_INPUT_IN_PROXIMITY@@ -261,6 +271,35 @@ void Demo::fail(int line, const std::string& message) {// The frame loop still renders one more frame, so the failure screenshot shows the state.}+bool Demo::attachVirtualSpaceMouse() {+ if (virtualSpaceMouse_) return true;+ SDL_VirtualJoystickDesc desc;+ SDL_INIT_INTERFACE(&desc);+ desc.type = SDL_JOYSTICK_TYPE_UNKNOWN; // (what SDL reports for a real one: it is no gamepad)+ desc.vendor_id = 0x256F; // 3Dconnexion+ desc.product_id = 0xC635; // SpaceMouse Compact: six axes, two side buttons+ desc.naxes = 6;+ desc.nbuttons = 2;+ desc.name = "SpaceMouse Compact (UI test)";+ virtualSpaceMouse_ = SDL_AttachVirtualJoystick(&desc);+ if (!virtualSpaceMouse_) return false;+ virtualSpaceMouseHandle_ = SDL_OpenJoystick(virtualSpaceMouse_); // (the same device the app opens; refcounted)+ if (!virtualSpaceMouseHandle_) {+ SDL_DetachVirtualJoystick(virtualSpaceMouse_);+ virtualSpaceMouse_ = 0;+ return false;+ }+ return true;+}++void Demo::detachVirtualSpaceMouse() {+ if (!virtualSpaceMouse_) return;+ SDL_CloseJoystick(virtualSpaceMouseHandle_);+ SDL_DetachVirtualJoystick(virtualSpaceMouse_);+ virtualSpaceMouse_ = 0;+ virtualSpaceMouseHandle_ = nullptr;+}+double Demo::query(const std::string& name, bool& known) const {const Mesh& m = app_.doc_.mesh;known = true;@@ -487,6 +526,8 @@ double Demo::query(const std::string& name, bool& known) const {const glm::vec3 f = glm::abs(app_.camera_.forward());return std::max({f.x, f.y, f.z}) > 0.99999f ? 1.0 : 0.0;}+ if (name == "spacemouse_connected") return app_.spaceMouse_ ? 1.0 : 0.0;+ if (name == "spacemouse_moving") return app_.spaceMouseMoving() ? 1.0 : 0.0;if (name == "camera_distance") return app_.camera_.distance;if (name == "camera_pan") return glm::length(app_.camera_.target);if (name == "groups") {@@ -1383,6 +1424,56 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& emouseMotion(p.x, p.y);});wait(0.05f);+ } else if (verb == "spacemouse" || verb == "spacemouse_hold") {+ if (!need(6)) return false;+ std::array<float, 6> v{};+ for (size_t i = 0; i < 6; ++i) v[i] = std::clamp(num(i + 1, 0), -1.0f, 1.0f);+ const bool hold = verb == "spacemouse_hold";+ const float seconds = num(7, 0.5f);+ steps_.push_back([this, line](float t) { // plug it in; the app opens it on the next frame's events+ if (t == 0.0f && !attachVirtualSpaceMouse()) {+ fail(line, std::string("cannot attach a virtual joystick: ") + SDL_GetError());+ return true;+ }+ if (app_.spaceMouse_) return true;+ if (t > 2.0f) fail(line, "the app didn't open the virtual SpaceMouse");+ return t > 2.0f;+ });+ auto setAxes = [this](const std::array<float, 6>& a) {+ for (int i = 0; i < 6; ++i)+ SDL_SetJoystickVirtualAxis(virtualSpaceMouseHandle_, i, Sint16(std::lround(a[size_t(i)] * 32767.0f)));+ };+ if (hold) {+ run([setAxes, v] { setAxes(v); });+ wait(0.05f);+ } else {+ steps_.push_back([setAxes, v, seconds](float t) {+ setAxes(t < seconds ? v : std::array<float, 6>{});+ return t >= seconds;+ });+ wait(0.1f); // the view settles (the axes read back as centred)+ }+ } else if (verb == "spacemouse_button") {+ if (!need(1)) return false;+ const int button = int(num(1, 1)) - 1;+ steps_.push_back([this, line, button](float t) {+ if (t == 0.0f && !attachVirtualSpaceMouse()) {+ fail(line, std::string("cannot attach a virtual joystick: ") + SDL_GetError());+ return true;+ }+ if (!app_.spaceMouse_) {+ if (t > 2.0f) fail(line, "the app didn't open the virtual SpaceMouse");+ return t > 2.0f;+ }+ SDL_SetJoystickVirtualButton(virtualSpaceMouseHandle_, button, true);+ return true;+ });+ wait(0.05f);+ run([this, button] { SDL_SetJoystickVirtualButton(virtualSpaceMouseHandle_, button, false); });+ wait(0.1f);+ } else if (verb == "spacemouse_unplug") {+ run([this] { detachVirtualSpaceMouse(); });+ wait(0.1f);} else if (verb == "pen_out") {run([this] { penProximity(false); });wait(0.05f);diff --git a/src/core/SpaceMouse.cpp b/src/core/SpaceMouse.cppnew file mode 100644index 00000000..725d696b--- /dev/null+++ b/src/core/SpaceMouse.cpp@@ -0,0 +1,131 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/SpaceMouse.h"++#include <algorithm>+#include <cctype>+#include <cmath>++namespace sf {++namespace {++constexpr uint16_t kVendor3Dconnexion = 0x256F;+constexpr uint16_t kVendorLogitech = 0x046D;++// 3Dconnexion devices sold under Logitech's vendor id (spacenavd's device list, Linux hid-ids.h).+constexpr uint16_t kLogitechSpaceMice[] = {+ 0xC603, // SpaceMouse Plus XT+ 0xC605, // CADman+ 0xC606, // SpaceMouse Classic+ 0xC621, // SpaceBall 5000+ 0xC623, // SpaceTraveler+ 0xC625, // SpacePilot+ 0xC626, // SpaceNavigator+ 0xC627, // SpaceExplorer+ 0xC628, // SpaceNavigator for Notebooks+ 0xC629, // SpacePilot Pro+ 0xC62B, // SpaceMouse Pro+};++// Under 3Dconnexion's own id every SpaceMouse counts (Wireless C62E / C62F, Pro Wireless C631 / C632, Enterprise+// C633, Compact C635, Module C636, the Universal Receiver C652, and models newer than this list) except these,+// which have no 6-DoF cap. The app also wants six axes before it takes a device.+constexpr uint16_t kNot6Dof[] = {+ 0xC650, // CadMouse+ 0xC651, // CadMouse Wireless+ 0xC654, // CadMouse Pro Wireless+ 0xC655, // CadMouse Compact+ 0xC664, // Keyboard Pro+ 0xC665, // Numpad Pro+};++std::string lower(std::string s) {+ for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));+ return s;+}++} // namespace++bool isSpaceMouseDevice(uint16_t vendor, uint16_t product, const std::string& name) {+ if (vendor == kVendor3Dconnexion) return std::find(std::begin(kNot6Dof), std::end(kNot6Dof), product) == std::end(kNot6Dof);+ if (vendor == kVendorLogitech) {+ if (std::find(std::begin(kLogitechSpaceMice), std::end(kLogitechSpaceMice), product) != std::end(kLogitechSpaceMice))+ return true;+ const std::string n = lower(name);+ for (const char* word : {"spacemouse", "space mouse", "spacenavigator", "space navigator", "spacepilot",+ "spaceexplorer", "spaceball", "spacetraveler"})+ if (n.find(word) != std::string::npos) return true;+ }+ return false;+}++Json toJson(const SpaceMouseSettings& s) {+ Json j = Json::object();+ j.set("enabled", s.enabled);+ j.set("speed", double(s.speed));+ j.set("deadZone", double(s.deadZone));+ Json invert = Json::array();+ for (bool b : s.invert) invert.push(b);+ j.set("invert", invert);+ j.set("turntable", s.turntable);+ j.set("dominant", s.dominant);+ Json buttons = Json::array();+ for (const std::string& b : s.buttons) buttons.push(b);+ j.set("buttons", buttons);+ return j;+}++void fromJson(const Json& j, SpaceMouseSettings& s) {+ if (!j.isObject()) return;+ s.enabled = j["enabled"].asBool(s.enabled);+ const float speed = float(j["speed"].asNumber(s.speed));+ if (std::isfinite(speed)) s.speed = std::clamp(speed, 0.1f, 4.0f);+ const float dead = float(j["deadZone"].asNumber(s.deadZone));+ if (std::isfinite(dead)) s.deadZone = std::clamp(dead, 0.0f, 0.5f);+ if (const Json& inv = j["invert"]; inv.isArray())+ for (size_t i = 0; i < s.invert.size() && i < inv.size(); ++i) s.invert[i] = inv[i].asBool(s.invert[i]);+ s.turntable = j["turntable"].asBool(s.turntable);+ s.dominant = j["dominant"].asBool(s.dominant);+ if (const Json& b = j["buttons"]; b.isArray())+ for (size_t i = 0; i < s.buttons.size() && i < b.size(); ++i)+ if (b[i].isString()) s.buttons[i] = b[i].asString();+}++float spaceMouseDeadZone(float value, float deadZone) {+ if (!std::isfinite(value)) return 0.0f;+ value = std::clamp(value, -1.0f, 1.0f);+ deadZone = std::clamp(deadZone, 0.0f, 0.95f);+ const float a = std::abs(value);+ if (a <= deadZone) return 0.0f;+ return std::copysign((a - deadZone) / (1.0f - deadZone), value);+}++SpaceMouseMotion spaceMouseMotion(const std::array<float, kSmAxes>& axes, float dt, const SpaceMouseSettings& s) {+ SpaceMouseMotion m;+ if (!s.enabled || !(dt > 0.0f)) return m;+ dt = std::min(dt, kSpaceMouseMaxStep);+ std::array<float, kSmAxes> v{};+ for (int i = 0; i < kSmAxes; ++i) v[i] = spaceMouseDeadZone(axes[i], s.deadZone) * (s.invert[i] ? -1.0f : 1.0f);+ if (s.turntable) v[kSmRy] = 0.0f; // (a roll can't win the dominant axis either)+ if (s.dominant) {+ int best = 0;+ for (int i = 1; i < kSmAxes; ++i)+ if (std::abs(v[i]) > std::abs(v[best])) best = i;+ for (int i = 0; i < kSmAxes; ++i)+ if (i != best) v[i] = 0.0f;+ }+ const float k = s.speed * dt;+ // "Object mode": the model moves the way the cap is pushed. X right -> right on screen; Z down -> down on screen;+ // Y towards you -> closer. Rx tilts the cap's top towards you, Rz twists clockwise from above (the model's front+ // goes left), Ry rolls the cap's top to the left (anticlockwise on screen).+ m.panX = v[kSmTx] * kSpaceMousePanRate * k;+ m.panY = v[kSmTz] * kSpaceMousePanRate * k;+ m.zoom = v[kSmTy] * kSpaceMouseZoomRate * k;+ m.tip = v[kSmRx] * kSpaceMouseTurnRate * k;+ m.spin = -v[kSmRz] * kSpaceMouseTurnRate * k;+ m.roll = -v[kSmRy] * kSpaceMouseTurnRate * k;+ return m;+}++} // namespace sfdiff --git a/src/core/SpaceMouse.h b/src/core/SpaceMouse.hnew file mode 100644index 00000000..63d63de1--- /dev/null+++ b/src/core/SpaceMouse.h@@ -0,0 +1,75 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// 3Dconnexion SpaceMouse navigation (#6), independent of SDL so it can be unit+// tested: which USB devices are SpaceMice, the settings (Preferences > Input >+// SpaceMouse) and the mapping from the six axes to a camera move for one frame.+// The device is read through SDL's joystick API (no 3Dconnexion SDK); the app+// side is src/app/SpaceMouse.cpp, the user guide docs/guide/navigation.md.+#pragma once++#include "core/Json.h"++#include <glm/glm.hpp>++#include <array>+#include <cstdint>+#include <string>+#include <vector>++namespace sf {++// The six axes in the order the device reports them (USB HID: X Y Z Rx Ry Rz). With the cable at the back:+// X is a push to the right, Y a pull towards you, Z a push down; Rx tilts the cap towards you, Ry rolls it to the+// left, Rz twists it clockwise (seen from above).+enum SpaceMouseAxis { kSmTx, kSmTy, kSmTz, kSmRx, kSmRy, kSmRz, kSmAxes };++// True for a 3Dconnexion 6-DoF device: vendor 0x256F (3Dconnexion) or one of the older ones sold under Logitech's+// vendor id 0x046D (SpaceNavigator, SpacePilot, SpaceExplorer...). SDL itself has no list of them (its+// controller_list.h only knows gamepads), so this is ours, from the ids spacenavd and Linux's hid-ids.h use.+// The CadMouse and the 3Dconnexion keyboards / numpads share the vendor id but are not SpaceMice.+// `name` is the device's name: a Logitech-id device with an unknown product counts when it calls itself one.+bool isSpaceMouseDevice(uint16_t vendor, uint16_t product, const std::string& name = {});++constexpr int kSpaceMouseButtonSlots = 8; // buttons whose action Preferences lists (an Enterprise has 31)++struct SpaceMouseSettings {+ bool enabled = true;+ float speed = 1.0f; // 0.1 .. 4+ float deadZone = 0.08f; // fraction of the full deflection ignored around the rest position (0 .. 0.5)+ std::array<bool, kSmAxes> invert{};+ bool turntable = false; // lock rotation to a turntable: no roll, the world's up stays up+ bool dominant = false; // only the axis pushed furthest moves the view (no accidental diagonal moves)+ // The action each button runs ("" = nothing): the two side buttons default to Frame and Front view.+ std::array<std::string, kSpaceMouseButtonSlots> buttons{"view.frame", "view.front"};+};++Json toJson(const SpaceMouseSettings& s);+void fromJson(const Json& j, SpaceMouseSettings& s);++// One frame's camera move.+struct SpaceMouseMotion {+ // Rotation in radians, in "the model follows the cap" terms: spin > 0 turns the model's front to the right+ // (like dragging right), tip > 0 brings its top towards you (like dragging down), roll > 0 turns it clockwise+ // on screen.+ float spin = 0.0f, tip = 0.0f, roll = 0.0f;+ // Pan in viewport heights: > 0 moves the model right / down on screen (like a pan drag).+ float panX = 0.0f, panY = 0.0f;+ float zoom = 0.0f; // Camera::zoom steps: > 0 moves closer+ bool any() const { return spin != 0.0f || tip != 0.0f || roll != 0.0f || panX != 0.0f || panY != 0.0f || zoom != 0.0f; }+};++// Full deflection, at speed 1, per second.+constexpr float kSpaceMouseTurnRate = 2.0f; // radians+constexpr float kSpaceMousePanRate = 1.0f; // viewport heights+constexpr float kSpaceMouseZoomRate = 6.0f; // Camera::zoom steps (x0.46 of the distance)+constexpr float kSpaceMouseMaxStep = 0.1f; // seconds: a stalled frame doesn't throw the view++// An axis value (-1 .. 1) after the dead zone: 0 inside it, rescaled so the rest of the travel still reaches 1.+float spaceMouseDeadZone(float value, float deadZone);++// The move for `dt` seconds with the axes held at `axes` (-1 .. 1, the device's raw directions). Rates are per+// second, so the same deflection turns the view as far at 30 fps as at 144 fps. With turntable on, roll is 0.+SpaceMouseMotion spaceMouseMotion(const std::array<float, kSmAxes>& axes, float dt, const SpaceMouseSettings& s);++} // namespace sfdiff --git a/tests/test_spacemouse.cpp b/tests/test_spacemouse.cppnew file mode 100644index 00000000..36ce02db--- /dev/null+++ b/tests/test_spacemouse.cpp@@ -0,0 +1,180 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// SpaceMouse navigation (#6): which devices count, the dead zone, speed,+// per-axis inversion, dominant axis, turntable lock, frame-rate independence+// and the settings' JSON round trip.+#include "TestHarness.h"++#include "core/SpaceMouse.h"+#include "render/Camera.h"++#include <cmath>++using namespace sf;++namespace {+bool near(float a, float b, float eps = 1e-5f) { return std::abs(a - b) < eps; }+std::array<float, kSmAxes> axes(float tx, float ty, float tz, float rx, float ry, float rz) { return {tx, ty, tz, rx, ry, rz}; }+} // namespace++TEST(spacemouse_device_ids) {+ CHECK(isSpaceMouseDevice(0x256F, 0xC635)); // SpaceMouse Compact+ CHECK(isSpaceMouseDevice(0x256F, 0xC633)); // Enterprise+ CHECK(isSpaceMouseDevice(0x256F, 0xC652)); // Universal Receiver+ CHECK(isSpaceMouseDevice(0x256F, 0xC6FF)); // a newer model+ CHECK(!isSpaceMouseDevice(0x256F, 0xC650)); // CadMouse+ CHECK(!isSpaceMouseDevice(0x256F, 0xC665)); // Numpad Pro+ CHECK(isSpaceMouseDevice(0x046D, 0xC626)); // SpaceNavigator+ CHECK(isSpaceMouseDevice(0x046D, 0xC62B)); // SpaceMouse Pro+ CHECK(!isSpaceMouseDevice(0x046D, 0xC52B)); // a Logitech Unifying receiver+ CHECK(!isSpaceMouseDevice(0x046D, 0xC215, "Logitech Extreme 3D")); // a flight stick+ CHECK(isSpaceMouseDevice(0x046D, 0xC6AA, "3Dconnexion SpaceNavigator")); // by name+ CHECK(!isSpaceMouseDevice(0x045E, 0x028E, "SpaceMouse")); // another vendor never+}++TEST(spacemouse_dead_zone) {+ CHECK(near(spaceMouseDeadZone(0.0f, 0.1f), 0.0f));+ CHECK(near(spaceMouseDeadZone(0.09f, 0.1f), 0.0f));+ CHECK(near(spaceMouseDeadZone(-0.1f, 0.1f), 0.0f));+ CHECK(near(spaceMouseDeadZone(1.0f, 0.1f), 1.0f)); // the full travel is still reachable+ CHECK(near(spaceMouseDeadZone(-1.0f, 0.1f), -1.0f));+ CHECK(near(spaceMouseDeadZone(0.55f, 0.1f), 0.5f)); // rescaled, no jump at the edge+ CHECK(spaceMouseDeadZone(0.1001f, 0.1f) < 0.001f);+ CHECK(near(spaceMouseDeadZone(2.0f, 0.1f), 1.0f)); // clamped+ CHECK(near(spaceMouseDeadZone(NAN, 0.1f), 0.0f));+ CHECK(near(spaceMouseDeadZone(0.3f, 0.0f), 0.3f));++ // A cap resting slightly off centre doesn't move the view.+ SpaceMouseSettings s;+ CHECK(!spaceMouseMotion(axes(0.05f, -0.06f, 0.04f, 0.07f, -0.02f, 0.05f), 1.0f / 60.0f, s).any());+}++TEST(spacemouse_directions_and_rates) {+ SpaceMouseSettings s;+ s.deadZone = 0.0f;+ const float dt = 0.05f;+ // Object mode: the model goes where the cap is pushed.+ SpaceMouseMotion m = spaceMouseMotion(axes(1, 0, 0, 0, 0, 0), dt, s);+ CHECK(near(m.panX, kSpaceMousePanRate * dt));+ CHECK(m.panY == 0.0f && m.zoom == 0.0f && m.spin == 0.0f);+ CHECK(spaceMouseMotion(axes(0, 0, 1, 0, 0, 0), dt, s).panY > 0.0f); // pushed down: the model goes down+ CHECK(near(spaceMouseMotion(axes(0, 1, 0, 0, 0, 0), dt, s).zoom, kSpaceMouseZoomRate * dt)); // pulled: closer+ CHECK(near(spaceMouseMotion(axes(0, 0, 0, 1, 0, 0), dt, s).tip, kSpaceMouseTurnRate * dt));+ CHECK(near(spaceMouseMotion(axes(0, 0, 0, 0, 0, 1), dt, s).spin, -kSpaceMouseTurnRate * dt)); // clockwise twist+ CHECK(near(spaceMouseMotion(axes(0, 0, 0, 0, 1, 0), dt, s).roll, -kSpaceMouseTurnRate * dt));++ // Speed scales every axis.+ s.speed = 2.5f;+ m = spaceMouseMotion(axes(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f), dt, s);+ CHECK(near(m.panX, 0.5f * kSpaceMousePanRate * dt * 2.5f));+ CHECK(near(m.zoom, 0.5f * kSpaceMouseZoomRate * dt * 2.5f));+ CHECK(near(m.spin, -0.5f * kSpaceMouseTurnRate * dt * 2.5f));++ // Off: nothing, whatever the cap does. No time: nothing.+ s.enabled = false;+ CHECK(!spaceMouseMotion(axes(1, 1, 1, 1, 1, 1), dt, s).any());+ s.enabled = true;+ CHECK(!spaceMouseMotion(axes(1, 1, 1, 1, 1, 1), 0.0f, s).any());+}++TEST(spacemouse_invert_each_axis) {+ SpaceMouseSettings s;+ s.deadZone = 0.0f;+ const auto all = axes(0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f);+ const SpaceMouseMotion plain = spaceMouseMotion(all, 0.02f, s);+ for (int i = 0; i < kSmAxes; ++i) {+ SpaceMouseSettings inv = s;+ inv.invert[size_t(i)] = true;+ const SpaceMouseMotion m = spaceMouseMotion(all, 0.02f, inv);+ const float got[] = {m.panX, m.zoom, m.panY, m.tip, m.roll, m.spin};+ const float want[] = {plain.panX, plain.zoom, plain.panY, plain.tip, plain.roll, plain.spin};+ for (int k = 0; k < kSmAxes; ++k) CHECK(near(got[k], k == i ? -want[k] : want[k]));+ }+}++TEST(spacemouse_dominant_axis_and_turntable) {+ SpaceMouseSettings s;+ s.dominant = true;+ // Twisting hard while also nudging sideways: only the twist moves the view.+ SpaceMouseMotion m = spaceMouseMotion(axes(0.5f, 0.2f, 0.0f, 0.3f, 0.1f, -0.9f), 0.02f, s);+ CHECK(m.spin > 0.0f);+ CHECK(m.panX == 0.0f && m.zoom == 0.0f && m.tip == 0.0f && m.roll == 0.0f);+ // Inversion counts before the choice, the magnitude decides.+ m = spaceMouseMotion(axes(-0.95f, 0.2f, 0.0f, 0.3f, 0.1f, -0.9f), 0.02f, s);+ CHECK(m.panX < 0.0f && m.spin == 0.0f);++ // Turntable: rolling the cap does nothing, and a roll can't win the dominant choice.+ s.turntable = true;+ m = spaceMouseMotion(axes(0.0f, 0.0f, 0.0f, 0.3f, 0.95f, 0.0f), 0.02f, s);+ CHECK(m.roll == 0.0f && m.tip > 0.0f);+ s.dominant = false;+ CHECK(!spaceMouseMotion(axes(0, 0, 0, 0, 1, 0), 0.02f, s).any());+}++TEST(spacemouse_frame_rate_independent) {+ SpaceMouseSettings s;+ const auto held = axes(0.6f, -0.4f, 0.3f, 0.5f, 0.0f, -0.7f);+ // One second held at 30, 60 and 144 fps moves the view the same distance.+ auto oneSecond = [&](int fps) {+ Camera cam;+ cam.distance = 5.0f;+ SpaceMouseMotion total;+ for (int f = 0; f < fps; ++f) {+ const SpaceMouseMotion m = spaceMouseMotion(held, 1.0f / float(fps), s);+ total.spin += m.spin, total.tip += m.tip, total.panX += m.panX, total.panY += m.panY, total.zoom += m.zoom;+ cam.zoom(m.zoom);+ cam.orbit(m.spin / 0.008f, m.tip / 0.008f);+ }+ return std::make_pair(total, cam);+ };+ const auto [a, camA] = oneSecond(30);+ const auto [b, camB] = oneSecond(60);+ const auto [c, camC] = oneSecond(144);+ for (const SpaceMouseMotion* m : {&b, &c}) {+ CHECK(near(m->spin, a.spin, 1e-4f));+ CHECK(near(m->tip, a.tip, 1e-4f));+ CHECK(near(m->panX, a.panX, 1e-4f));+ CHECK(near(m->panY, a.panY, 1e-4f));+ CHECK(near(m->zoom, a.zoom, 1e-3f));+ }+ CHECK(near(camB.distance, camA.distance, 1e-3f) && near(camC.distance, camA.distance, 1e-3f));+ CHECK(near(camB.yaw, camA.yaw, 1e-4f) && near(camC.yaw, camA.yaw, 1e-4f));+ CHECK(near(camC.pitch, camA.pitch, 1e-4f));+ CHECK(camA.distance > 5.0f); // pushed away from you: further+ // A stalled frame (a second-long hitch) moves no further than kSpaceMouseMaxStep would.+ const SpaceMouseMotion hitch = spaceMouseMotion(held, 1.0f, s), capped = spaceMouseMotion(held, kSpaceMouseMaxStep, s);+ CHECK(near(hitch.spin, capped.spin) && near(hitch.zoom, capped.zoom));+}++TEST(spacemouse_settings_json) {+ SpaceMouseSettings s;+ CHECK(s.enabled && s.buttons[0] == "view.frame" && s.buttons[1] == "view.front");+ s.enabled = false;+ s.speed = 2.25f;+ s.deadZone = 0.2f;+ s.invert[2] = s.invert[5] = true;+ s.turntable = true;+ s.dominant = true;+ s.buttons[0] = "view.top";+ s.buttons[1] = "";+ s.buttons[3] = "edit.undo";+ SpaceMouseSettings r;+ Json parsed;+ std::string err;+ CHECK(Json::parse(toJson(s).dump(), parsed, err));+ fromJson(parsed, r);+ CHECK(!r.enabled && near(r.speed, 2.25f) && near(r.deadZone, 0.2f) && r.turntable && r.dominant);+ for (int i = 0; i < kSmAxes; ++i) CHECK(r.invert[size_t(i)] == (i == 2 || i == 5));+ CHECK(r.buttons[0] == "view.top" && r.buttons[1].empty() && r.buttons[3] == "edit.undo");++ // Out-of-range values are clamped, missing ones keep their defaults.+ Json j = Json::object();+ j.set("speed", 100.0);+ j.set("deadZone", -1.0);+ SpaceMouseSettings d;+ fromJson(j, d);+ CHECK(near(d.speed, 4.0f) && near(d.deadZone, 0.0f) && d.enabled && d.buttons[0] == "view.frame");+ fromJson(Json(), d); // not an object: untouched+ CHECK(near(d.speed, 4.0f));+}diff --git a/tests/ui/spacemouse.sfui b/tests/ui/spacemouse.sfuinew file mode 100644index 00000000..a4e6c3c1--- /dev/null+++ b/tests/ui/spacemouse.sfui@@ -0,0 +1,147 @@+# SpaceMouse navigation (#6), with a virtual joystick that has a SpaceMouse Compact's USB ids (the app finds and+# opens it as it would the real device): twisting, tilting, pushing and pulling the cap turn, pan and zoom the view;+# a resting cap inside the dead zone does nothing; Preferences > Input > SpaceMouse inverts axes, locks the+# rotation to a turntable and turns it off; the side buttons frame and show the front; a pen stroke held while the+# view turns stays one stroke; unplugging and plugging back in works; every input style.+run new_sphere subdivisions=4+snapshot+expect_value spacemouse_connected == 0++# Twist the cap clockwise for half a second: the model turns (about 45 degrees at speed 1).+camera 0 0+spacemouse 0 0 0 0 0 0.8 0.5+expect_value spacemouse_connected == 1+expect_value camera_yaw > 25+expect_value camera_yaw < 65+expect_value spacemouse_moving == 0+expect_value moved == 0++# Tilt it towards you: the model's top comes towards you.+camera 0 0+spacemouse 0 0 0 0.8 0 0 0.3+expect_value camera_pitch < -10++# Roll the cap's top to the left: free rotation rolls the model anticlockwise (the camera the other way).+camera 0 0+spacemouse 0 0 0 0 0.8 0 0.3+expect_value camera_roll > 10++# Push it right: the view pans. Pull it towards you: closer. Push it away: further.+key f+camera 0 0+remember camera_pan p0+spacemouse 0.8 0 0 0 0 0 0.3+expect_value camera_pan > $p0+key f+remember camera_distance d0+spacemouse 0 0.8 0 0 0 0 0.3+expect_value camera_distance < $d0+remember camera_distance d1+spacemouse 0 -0.8 0 0 0 0 0.3+expect_value camera_distance > $d1++# A hand resting on the cap (inside the 8% dead zone) doesn't drift the view.+key f+camera 0 0+remember camera_distance d2+remember camera_pan p2+spacemouse 0.05 -0.06 0.04 0.07 -0.05 0.06 0.5+expect_value camera_yaw == 0+expect_value camera_pitch == 0+expect_value camera_distance == $d2+expect_value camera_pan == $p2++# Side buttons: the right one shows the front (an orthographic axis view), the left one frames the model.+camera 30 20+expect_value camera_aligned == 0+spacemouse_button 2+expect_value camera_aligned == 1+expect_value camera_ortho == 1+spacemouse 0 0 0 0 0 0.5 0.2+expect_value camera_ortho == 0+key f+remember camera_distance framed+zoom 3+spacemouse_button 1+expect_value camera_distance >= $framed-0.001+expect_value camera_distance <= $framed+0.001++# Preferences > Input > SpaceMouse: invert the twist.+click "Preferences##palette.preferences"+click "Input##preferences.input"+expect_text "SpaceMouse (experimental)"+expect_text "SpaceMouse Compact (UI test)"+shot spacemouse_prefs+click "Spin##spacemouse.invert5"+key escape+camera 0 0+spacemouse 0 0 0 0 0 0.8 0.5+expect_value camera_yaw < -25++# Lock rotation to turntable: rolling the cap does nothing, a twist turns about the world's up axis.+click "Preferences##palette.preferences"+click "Lock rotation to turntable##spacemouse.turntable"+key escape+camera 0 0+spacemouse 0 0 0 0 0.9 0 0.3+expect_value camera_roll == 0+expect_value camera_yaw == 0+spacemouse 0 0 0 0.6 0 0.8 0.4+expect_value camera_roll == 0+expect_value camera_up > 0++# Off: the SpaceMouse is ignored, buttons too.+click "Preferences##palette.preferences"+click "Use SpaceMouse##spacemouse.enabled"+key escape+camera 10 0+spacemouse 0 0 0 0 0 0.8 0.3+expect_value camera_yaw == 10+spacemouse_button 2+expect_value camera_yaw == 10+click "Preferences##palette.preferences"+click "Use SpaceMouse##spacemouse.enabled"+click "SpaceMouse defaults##spacemouse.defaults"+key escape++# A pen stroke held while the cap turns the view stays one stroke, and one undo takes it back.+key f+camera 0 0+snapshot+spacemouse_hold 0 0 0 0 0 0.5+pen_stroke 0.3 0.45 0.7 0.55 0.6 0.6+expect_value camera_yaw > 5+spacemouse_hold 0 0 0 0 0 0+expect_value stroking == 0+expect_value moved_out > 0+key ctrl+z+expect_value moved == 0+# The pen still navigates and sculpts afterwards.+pen_stroke 0.3 0.45 0.7 0.55 0.6 0.6+expect_value moved_out > 0+key ctrl+z++# Unplugged and plugged back in (hot-plug).+spacemouse_unplug+expect_value spacemouse_connected == 0+camera 0 0+spacemouse 0 0 0 0 0 0.8 0.5+expect_value spacemouse_connected == 1+expect_value camera_yaw > 25++# Every input style: SculptForge and Blender navigate the same way.+click "Preferences##palette.preferences"+click "SculptForge##input.style_sculptforge"+key escape+camera 0 0+spacemouse 0 0 0 0 0 0.8 0.5+expect_value camera_yaw > 25+click "Preferences##palette.preferences"+click "Blender##input.style_blender"+key escape+camera 0 0+spacemouse 0 0 0 0 0 0.8 0.5+expect_value camera_yaw > 25+remember camera_distance d3+spacemouse 0 0.8 0 0 0 0 0.3+expect_value camera_distance < $d3