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
Blender input style (#12): middle-drag navigation, numpad views, Blender's sculpt keys, keymap import
islandmed46bfeb621c64
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ce4f6d43..b58260de 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -202,6 +202,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/Demo.cppsrc/app/UiTest.cppsrc/app/Actions.cpp+ src/app/BlenderKeymap.cppsrc/app/Ui.cppsrc/app/UiLayout.cppsrc/app/Shell.cpp@@ -428,7 +429,7 @@ if(SCULPTFORGE_BUILD_TESTS)target_compile_definitions(sculptforge_tests PRIVATE SF_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/data")target_link_libraries(sculptforge_tests PRIVATE sculptforge_core sculptforge_ai sculptforge_phone)if(SCULPTFORGE_BUILD_APP) # the action registry (key chords, shortcut overrides) needs SDL's key names- target_sources(sculptforge_tests PRIVATE src/app/Actions.cpp)+ target_sources(sculptforge_tests PRIVATE src/app/Actions.cpp src/app/BlenderKeymap.cpp)target_link_libraries(sculptforge_tests PRIVATE SDL3::SDL3)target_compile_definitions(sculptforge_tests PRIVATE SF_TEST_ACTIONS)endif()diff --git a/src/app/Actions.cpp b/src/app/Actions.cppindex 1d939810..4b283efa 100644--- a/src/app/Actions.cpp+++ b/src/app/Actions.cpp@@ -45,6 +45,30 @@ bool isModifierKey(SDL_Keycode key) {}}+namespace {++// "Numpad 1", "Numpad .", "Numpad Plus" (also "Numpad1", "Keypad 1") -> the keypad's key.+SDL_Keycode keypadKey(const std::string& lowerName) {+ std::string rest;+ for (const char* prefix : {"numpad", "keypad", "kp"})+ if (lowerName.rfind(prefix, 0) == 0) {+ rest = trim(lowerName.substr(std::string_view(prefix).size()));+ break;+ }+ if (rest.empty()) return SDLK_UNKNOWN;+ if (rest.size() == 1 && rest[0] >= '1' && rest[0] <= '9') return SDL_Keycode(SDLK_KP_1 + (rest[0] - '1'));+ if (rest == "0") return SDLK_KP_0;+ if (rest == "." || rest == "period" || rest == "del") return SDLK_KP_PERIOD;+ if (rest == "plus") return SDLK_KP_PLUS;+ if (rest == "minus" || rest == "-") return SDLK_KP_MINUS;+ if (rest == "/" || rest == "slash") return SDLK_KP_DIVIDE;+ if (rest == "*" || rest == "asterisk") return SDLK_KP_MULTIPLY;+ if (rest == "enter") return SDLK_KP_ENTER;+ return SDLK_UNKNOWN;+}++} // namespace+bool parseChord(std::string_view text, Chord& out) {out = Chord{};std::string t = trim(text);@@ -81,6 +105,10 @@ bool parseChord(std::string_view text, Chord& out) {return true;}const std::string k = lower(key);+ if (const SDL_Keycode kp = keypadKey(k); kp != SDLK_UNKNOWN) {+ out.key = kp;+ return true;+ }if (k == "enter") key = "Return";else if (k == "esc") key = "Escape";else if (k == "comma") key = ",";@@ -110,6 +138,17 @@ std::string keyName(SDL_Keycode key) {if (key > 32 && key < 127) return std::string(1, char(std::toupper(int(key))));if (key == SDLK_RETURN) return "Enter";if (key == SDLK_ESCAPE) return "Esc";+ if (key >= SDLK_KP_1 && key <= SDLK_KP_9) return "Numpad " + std::to_string(int(key - SDLK_KP_1) + 1);+ switch (key) { // spelled so that parseChord reads them back (a '+' would split the chord)+ case SDLK_KP_0: return "Numpad 0";+ case SDLK_KP_PERIOD: return "Numpad .";+ case SDLK_KP_PLUS: return "Numpad Plus";+ case SDLK_KP_MINUS: return "Numpad Minus";+ case SDLK_KP_DIVIDE: return "Numpad /";+ case SDLK_KP_MULTIPLY: return "Numpad *";+ case SDLK_KP_ENTER: return "Numpad Enter";+ default: break;+ }const char* name = SDL_GetKeyName(key);return name && *name ? name : "?";}@@ -227,10 +266,10 @@ void ActionRegistry::setShortcut(std::string_view id, std::string chord) {if (!isDefault) overrides_.emplace_back(std::string(id), std::move(chord));}-std::string ActionRegistry::assignShortcut(std::string_view id, const std::string& chordString) {+std::string ActionRegistry::assignShortcut(std::string_view id, const std::string& chordString, bool keepOthers) {Chord chord;if (!parseChord(chordString, chord)) {- setShortcut(id, "");+ if (!keepOthers) setShortcut(id, "");return {};}std::string lost;@@ -244,7 +283,11 @@ std::string ActionRegistry::assignShortcut(std::string_view id, const std::strinlost = other.label;setShortcut(other.id, keep);}- setShortcut(id, chordText(chord));+ std::string mine = chordText(chord);+ if (keepOthers)+ for (const Chord& c : parseChords(shortcutText(id)))+ if (!(c == chord)) mine += " / " + chordText(c);+ setShortcut(id, mine);return lost;}diff --git a/src/app/Actions.h b/src/app/Actions.hindex f096559f..a3bfd69a 100644--- a/src/app/Actions.h+++ b/src/app/Actions.h@@ -68,7 +68,8 @@ public:// Like setShortcut, but takes CHORD away from any other action that has it (ZBrush reassigns// on conflict). Returns the label of the action that lost it, or "".- std::string assignShortcut(std::string_view id, const std::string& chord);+ // keepOthers: add CHORD to the action's chords instead of replacing them (an imported keymap's second key).+ std::string assignShortcut(std::string_view id, const std::string& chord, bool keepOthers = false);bool hasOverride(std::string_view id) const;void clearOverrides();// The action that CHORD runs (enabled or not), or nullptr.diff --git a/src/app/App.cpp b/src/app/App.cppindex 7b72d0ba..0f0017e1 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -693,6 +693,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {if (eraserAction() == PenAction::EraseMask && previewLod_ < 0 && pick(x, y, hit)) beginMaskStroke(x, y);return;}+ if (blenderStyle() && blenderNavigationDown(button)) return; // middle / Alt+left / right drags navigateif (button == SDL_BUTTON_LEFT) {if (polygroupMouseDown(x, y, mod)) return;if (maskSelectMouseDown(x, y, mod)) return;@@ -703,7 +704,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {// Alt+click on another SubTool selects it (ZBrush); Alt+drag stays an inverted stroke or a pan.// Shift+Alt+click selects and frames it (ZBrush), the active one too.const bool frameClick = (mod & SDL_KMOD_ALT) && (mod & SDL_KMOD_SHIFT) && !ctrlDown(mod);- if ((mod & SDL_KMOD_ALT) && !ctrlDown(mod) && (frameClick || !(mod & SDL_KMOD_SHIFT)) &&+ if (!blenderStyle() && (mod & SDL_KMOD_ALT) && !ctrlDown(mod) && (frameClick || !(mod & SDL_KMOD_SHIFT)) &&(doc_.subtoolCount() > 1 || frameClick)) {const int target = pickSubtool(x, y);subtoolClickFrame_ = frameClick;@@ -720,6 +721,10 @@ void App::onMouseDown(float x, float y, Uint8 button) {if (previewLod_ < 0 && pick(x, y, hit)) {if (maskMod) beginMaskStroke(x, y);else beginStroke(x, y, hit);+ } else if (blenderStyle()) {+ // Blender: a drag beside the model navigates as the middle button would (Shift pans, Ctrl zooms).+ const SDL_Keymod keys = SDL_GetModState();+ drag_ = (keys & SDL_KMOD_SHIFT) ? Drag::Pan : ctrlDown(keys) ? Drag::Zoom : Drag::Orbit;} else if (maskMod && !(mod & SDL_KMOD_ALT) && previewLod_ < 0) {drag_ = Drag::MaskCanvas; // click inverts, drag clears (or zooms without a mask)maskCanvasX_ = x;@@ -743,6 +748,16 @@ void App::onMouseDown(float x, float y, Uint8 button) {}}+// Blender: middle-drag orbits, Shift+middle pans, Ctrl+middle zooms; Alt+left-drag is the emulated middle button+// (pens, trackpads); the right button drags the same way. True when the press started navigating.+bool App::blenderNavigationDown(Uint8 button) {+ const SDL_Keymod keys = SDL_GetModState(); // the keyboard itself: blenderMods turns Ctrl into the invert+ const bool emulated = button == SDL_BUTTON_LEFT && (keys & SDL_KMOD_ALT);+ if (button != SDL_BUTTON_MIDDLE && button != SDL_BUTTON_RIGHT && !emulated) return false;+ drag_ = (keys & SDL_KMOD_SHIFT) ? Drag::Pan : ctrlDown(keys) ? Drag::Zoom : Drag::Orbit;+ return true;+}+void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {if (!fromPen) {// Windows Ink and some tablet drivers send mouse events of their own beside the pen's, often at an old@@ -776,7 +791,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {case Drag::Orbit: orbitBy(dx, dy); break;case Drag::Roll: rollBy(x, y, dx, dy); break;case Drag::Pan: camera_.pan(dx, dy, canvasHeight()); break;- // ZBrush: dragging up (forward) zooms out, every zoom drag; the SculptForge style zooms in.+ // ZBrush: dragging up (forward) zooms out, every zoom drag; the SculptForge and Blender styles zoom in.case Drag::Zoom: camera_.zoom((zbrushStyle() ? dy : -dy) * 0.05f); break;case Drag::MaskCanvas: maskCanvasMove(x, y); break;case Drag::SubToolClick: subtoolClickMove(x, y); break;@@ -789,6 +804,10 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {}void App::orbitBy(float dx, float dy) {+ if (autoOrtho_) { // an axis view turned: back to perspective (Blender's Auto Perspective)+ camera_.ortho = false;+ autoOrtho_ = false;+ }if (!orbitStarted_) {orbitRaw_ = camera_;orbitStarted_ = true;@@ -836,6 +855,10 @@ void App::onMouseUp() {void App::onKey(SDL_Keycode key, SDL_Keymod mod) {if (captureShortcutKey(key, mod)) return; // Ctrl+Alt+click a button, then press its new keyif (lightBoxKey(key, mod)) return; // , LightBox, B / M pickers, S / I pop-ups (LightBox.cpp)+ // Blender's Emulate Numpad: the number row works as the numpad, unless the key itself has an action.+ if (blenderStyle() && uiPrefs_.emulateNumpad && key >= SDLK_0 && key <= SDLK_9 &&+ !actions_.actionForChord(chordFromEvent(key, mod)))+ key = key == SDLK_0 ? SDLK_KP_0 : SDL_Keycode(SDLK_KP_1 + (key - SDLK_1));actions_.handleKey(key, mod); // the shortcut map: Config.cpp initActions()}diff --git a/src/app/App.h b/src/app/App.hindex fec5058a..d17411e3 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -109,6 +109,7 @@ private:void onMouseDown(float x, float y, Uint8 button);void onMouseMove(float x, float y, float dx, float dy, bool fromPen);void onMouseUp();+ bool blenderNavigationDown(Uint8 button); // Blender style: a press that navigates (Input.cpp's style)void orbitBy(float dx, float dy); // a rotation drag: free or turntable (Preferences), Shift snapsvoid rollBy(float x, float y, float dx, float dy); // Shift+click, release Shift, drag: turn about the view axisvoid onKey(SDL_Keycode key, SDL_Keymod mod);@@ -1011,6 +1012,30 @@ private:void registerInputActions();void applyInputStyle(); // the style's default shortcuts (1-0 brushes or 9 QuickSave; I = RGB or Z Intensity)bool zbrushStyle() const { return uiPrefs_.inputStyle == 0; }+ bool blenderStyle() const { return uiPrefs_.inputStyle == 2; }+ void setInputStyle(int style);+ // ---- Blender style (Input.cpp) ----+ // Middle-drag orbits (Shift pans, Ctrl zooms), Alt+left-drag emulates the middle button (pens), Ctrl inverts+ // a stroke, M toggles the mask brush, and Blender's sculpt-mode letters pick brushes. The numpad views work in+ // every style. Import Blender keymap reads a keymap exported from Blender (BlenderKeymap.h).+ void registerViewActions();+ void viewAxis(float yawDegrees, float pitchDegrees); // Numpad 1 / 3 / 7: orthographic until turned+ void viewOrbitStep(float yawDegrees, float pitchDegrees);+ void frameActiveSubtool();+ SDL_Keymod blenderMods(SDL_Keymod keyboard) const; // Ctrl -> Alt (invert), the mask brush -> Ctrl (mask)+ bool maskBrushActive() const;+ void toggleMaskBrush();+ void hideGroupUnderCursor(bool isolate);+ void importBlenderKeymapDialog();+ bool importBlenderKeymap(const std::string& path);+ void drawInputStyleRow(float width = -1.0f); // the three styles (Preferences > Input, Controls)+ struct MaskBrush {+ bool on = false;+ BrushType brush = BrushType::Standard; // what was picked when M was pressed: picking another brush ends it+ int custom = -1;+ bool paint = false;+ } maskBrush_;+ bool autoOrtho_ = false; // an axis view switched to orthographic; orbiting goes back to perspective (Blender)// ZBrush: while Ctrl is held the brush is the mask brush, with Ctrl+Shift the selection (hide) brush. The shelf// tiles show it, and the Brush / Stroke pickers opened then pick among those brushes (PanelMasking.cpp).enum class HeldBrush { None, Mask, Select };diff --git a/src/app/BlenderKeymap.cpp b/src/app/BlenderKeymap.cppnew file mode 100644index 00000000..30e26efb--- /dev/null+++ b/src/app/BlenderKeymap.cpp@@ -0,0 +1,331 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "app/BlenderKeymap.h"++#include <algorithm>+#include <cctype>+#include <cmath>+#include <cstdlib>++namespace sf {++namespace {++constexpr size_t kMaxName = 128; // keymap and operator names+constexpr size_t kMaxDict = 512; // an event dict: {"type": 'A', "value": 'PRESS', "shift": True}+constexpr size_t kMaxProps = 8192; // an item's {"properties": [...]} block++bool isSpace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\\'; } // '\' continues a line++size_t skipSpace(std::string_view t, size_t i) {+ while (i < t.size() && isSpace(t[i])) ++i;+ return i;+}++// "name" at i (no escapes, no line breaks); npos if there isn't one.+size_t readQuoted(std::string_view t, size_t i, std::string& out) {+ if (i >= t.size() || t[i] != '"') return std::string_view::npos;+ const size_t end = t.find('"', i + 1);+ if (end == std::string_view::npos || end - i - 1 > kMaxName) return std::string_view::npos;+ out.assign(t.substr(i + 1, end - i - 1));+ if (out.find('\n') != std::string::npos || out.find('\\') != std::string::npos) return std::string_view::npos;+ return end + 1;+}++// A {...} block at i: braces may nest (sets in property values), quoted text is skipped over. Returns the index+// after the closing brace, or npos when it is unbalanced or longer than `limit`.+size_t readBraces(std::string_view t, size_t i, size_t limit, std::string_view& out) {+ if (i >= t.size() || t[i] != '{') return std::string_view::npos;+ int depth = 0;+ for (size_t j = i; j < t.size() && j - i <= limit; ++j) {+ const char c = t[j];+ if (c == '\'' || c == '"') {+ const size_t end = t.find(c, j + 1);+ if (end == std::string_view::npos) return std::string_view::npos;+ j = end;+ } else if (c == '{') {+ ++depth;+ } else if (c == '}' && --depth == 0) {+ out = t.substr(i, j + 1 - i);+ return j + 1;+ }+ }+ return std::string_view::npos;+}++// The value after `"key":` in a dict ('PRESS' -> PRESS, True, -1, 0.9), or "" when the key isn't there.+std::string dictValue(std::string_view dict, std::string_view key) {+ const std::string needle = "\"" + std::string(key) + "\":";+ const size_t at = dict.find(needle);+ if (at == std::string_view::npos) return {};+ size_t i = skipSpace(dict, at + needle.size());+ if (i < dict.size() && dict[i] == '\'') {+ const size_t end = dict.find('\'', i + 1);+ return end == std::string_view::npos ? std::string() : std::string(dict.substr(i + 1, end - i - 1));+ }+ size_t end = i;+ while (end < dict.size() && dict[end] != ',' && dict[end] != '}' && !isSpace(dict[end])) ++end;+ return std::string(dict.substr(i, end - i));+}++// An operator property, ("name", value), from the item's properties block: 'FRONT' -> FRONT, True, -1, 0.9.+std::string propValue(std::string_view props, std::string_view name) {+ const std::string needle = "(\"" + std::string(name) + "\",";+ const size_t at = props.find(needle);+ if (at == std::string_view::npos) return {};+ size_t i = skipSpace(props, at + needle.size());+ if (i < props.size() && (props[i] == '\'' || props[i] == '"')) {+ const size_t end = props.find(props[i], i + 1);+ return end == std::string_view::npos ? std::string() : std::string(props.substr(i + 1, end - i - 1));+ }+ size_t end = i;+ while (end < props.size() && props[end] != ')' && props[end] != ',' && !isSpace(props[end])) ++end;+ return std::string(props.substr(i, end - i));+}++double number(const std::string& s, double fallback) {+ if (s.empty()) return fallback;+ char* end = nullptr;+ const double v = std::strtod(s.c_str(), &end);+ return end && *end == '\0' ? v : fallback;+}++// Blender's event type -> SDL key; SDLK_UNKNOWN for mouse buttons, the wheel, the trackpad and NDOF.+SDL_Keycode keyFromType(const std::string& type) {+ if (type.size() == 1 && type[0] >= 'A' && type[0] <= 'Z') return SDL_Keycode(type[0] - 'A' + 'a');+ static const char* kDigits[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};+ for (int d = 0; d < 10; ++d)+ if (type == kDigits[d]) return SDL_Keycode('0' + d);+ if (type.rfind("NUMPAD_", 0) == 0) {+ const std::string k = type.substr(7);+ if (k.size() == 1 && k[0] >= '1' && k[0] <= '9') return SDL_Keycode(SDLK_KP_1 + (k[0] - '1'));+ if (k == "0") return SDLK_KP_0;+ if (k == "PERIOD") return SDLK_KP_PERIOD;+ if (k == "PLUS") return SDLK_KP_PLUS;+ if (k == "MINUS") return SDLK_KP_MINUS;+ if (k == "SLASH") return SDLK_KP_DIVIDE;+ if (k == "ASTERIX") return SDLK_KP_MULTIPLY;+ if (k == "ENTER") return SDLK_KP_ENTER;+ return SDLK_UNKNOWN;+ }+ if (type.size() >= 2 && type.size() <= 3 && type[0] == 'F' && std::isdigit(static_cast<unsigned char>(type[1]))) {+ const int n = std::atoi(type.c_str() + 1);+ if (n >= 1 && n <= 12) return SDL_Keycode(SDLK_F1 + (n - 1));+ return SDLK_UNKNOWN;+ }+ static const std::pair<const char*, SDL_Keycode> kKeys[] = {+ {"HOME", SDLK_HOME}, {"END", SDLK_END}, {"PAGE_UP", SDLK_PAGEUP},+ {"PAGE_DOWN", SDLK_PAGEDOWN}, {"INSERT", SDLK_INSERT}, {"DEL", SDLK_DELETE},+ {"BACK_SPACE", SDLK_BACKSPACE}, {"RET", SDLK_RETURN}, {"TAB", SDLK_TAB},+ {"SPACE", SDLK_SPACE}, {"LEFT_BRACKET", SDLK_LEFTBRACKET}, {"RIGHT_BRACKET", SDLK_RIGHTBRACKET},+ {"COMMA", SDLK_COMMA}, {"PERIOD", SDLK_PERIOD}, {"MINUS", SDLK_MINUS},+ {"EQUAL", SDLK_EQUALS}, {"SEMI_COLON", SDLK_SEMICOLON}, {"QUOTE", SDLK_APOSTROPHE},+ {"SLASH", SDLK_SLASH}, {"BACK_SLASH", SDLK_BACKSLASH}, {"ACCENT_GRAVE", SDLK_GRAVE},+ {"LEFT_ARROW", SDLK_LEFT}, {"RIGHT_ARROW", SDLK_RIGHT}, {"UP_ARROW", SDLK_UP},+ {"DOWN_ARROW", SDLK_DOWN},+ };+ for (const auto& [name, key] : kKeys)+ if (type == name) return key;+ return SDLK_UNKNOWN;+}++// Blender's sculpt tools (paint.brush_select, up to 4.2) and essentials brush assets (brush.asset_activate,+// 4.3 on) -> SculptForge's nearest brush. Scrape / Fill flatten, as SculptForge has no separate scrape.+std::string brushAction(std::string tool) {+ for (auto& c : tool) c = char(std::toupper(static_cast<unsigned char>(c)));+ for (auto& c : tool)+ if (c == ' ') c = '_';+ static const std::pair<const char*, const char*> kBrushes[] = {+ {"DRAW", "brush.standard"}, {"DRAW_SHARP", "brush.damstandard"}, {"CLAY", "brush.clay"},+ {"CLAY_STRIPS", "brush.claybuildup"}, {"LAYER", "brush.layer"}, {"INFLATE", "brush.inflate"},+ {"INFLATE/DEFLATE", "brush.inflate"}, {"CREASE", "brush.crease"}, {"CREASE_POLISH", "brush.crease"},+ {"CREASE_SHARP", "brush.crease"}, {"SMOOTH", "brush.smooth"}, {"FLATTEN", "brush.flatten"},+ {"FLATTEN/CONTRAST", "brush.flatten"}, {"SCRAPE", "brush.flatten"}, {"SCRAPE/FILL", "brush.flatten"},+ {"PINCH", "brush.pinch"}, {"PINCH/MAGNIFY", "brush.pinch"}, {"GRAB", "brush.move"},+ {"SNAKE_HOOK", "brush.snakehook"}, {"NUDGE", "brush.nudge"}, {"MASK", "mask.brush"},+ };+ for (const auto& [name, id] : kBrushes)+ if (tool == name) return id;+ return {};+}++// The SculptForge action for one keymap item, or "".+std::string actionFor(const std::string& op, std::string_view props) {+ auto prop = [&](const char* name) { return propValue(props, name); };+ if (op == "view3d.view_axis") {+ if (prop("align_active") == "True" || prop("relative") == "True") return {};+ const std::string t = prop("type");+ if (t == "FRONT") return "view.front";+ if (t == "BACK") return "view.back";+ if (t == "LEFT") return "view.left";+ if (t == "RIGHT") return "view.right";+ if (t == "TOP") return "view.top";+ if (t == "BOTTOM") return "view.bottom";+ return {};+ }+ if (op == "view3d.view_persportho") return "view.ortho";+ if (op == "view3d.view_selected") return prop("use_all_regions") == "True" ? "" : "view.frame_selected";+ if (op == "view3d.view_all") return prop("use_all_regions") == "True" ? "" : "view.frame";+ if (op == "view3d.view_orbit") {+ const std::string t = prop("type");+ if (std::abs(number(prop("angle"), 0.0) - 3.14159265) < 0.01) return "view.opposite";+ if (t == "ORBITLEFT") return "view.orbit_left";+ if (t == "ORBITRIGHT") return "view.orbit_right";+ if (t == "ORBITUP") return "view.orbit_up";+ if (t == "ORBITDOWN") return "view.orbit_down";+ return {};+ }+ if (op == "view3d.zoom") {+ const double d = number(prop("delta"), 0.0);+ return d > 0 ? "view.zoom_in" : d < 0 ? "view.zoom_out" : "";+ }+ if (op == "view3d.toggle_shading") return prop("type") == "WIREFRAME" ? "view.wireframe" : "";+ if (op == "paint.brush_select") return brushAction(prop("sculpt_tool"));+ if (op == "brush.asset_activate") {+ const std::string id = prop("relative_asset_identifier");+ const size_t at = id.find("/Brush/");+ return at == std::string::npos ? std::string() : brushAction(id.substr(at + 7));+ }+ if (op == "wm.radial_control") {+ const std::string path = prop("data_path_primary");+ if (path.find("sculpt") == std::string::npos) return {};+ if (path.size() >= 5 && path.compare(path.size() - 5, 5, ".size") == 0) return "ui.size_popup";+ if (path.size() >= 9 && path.compare(path.size() - 9, 9, ".strength") == 0) return "ui.strength_popup";+ return {};+ }+ if (op == "paint.mask_flood_fill") {+ const std::string mode = prop("mode");+ if (mode == "INVERT") return "mask.invert";+ if (mode == "VALUE") return number(prop("value"), 0.0) > 0.5 ? "mask.all" : "mask.clear";+ return {};+ }+ if (op == "paint.hide_show_all") return prop("action") == "SHOW" ? "visibility.show_all" : "";+ if (op == "sculpt.face_set_change_visibility" || op == "sculpt.face_sets_change_visibility") {+ const std::string mode = prop("mode");+ return mode == "HIDE_ACTIVE" ? "visibility.hide_group" : mode == "TOGGLE" ? "visibility.isolate_group" : "";+ }+ if (op == "object.subdivision_set") {+ if (prop("relative") != "True") return {};+ const double level = number(prop("level"), 0.0);+ return level < 0 ? "geometry.lower_res" : level > 0 ? "geometry.higher_res" : "";+ }+ if (op == "brush.scale_size") {+ const double s = number(prop("scalar"), 1.0);+ return s < 1.0 ? "brush.size_down" : s > 1.0 ? "brush.size_up" : "";+ }+ if (op == "paint.brush_colors_flip") return "color.switch";+ if (op == "sculpt.sample_color") return "color.pick";+ if (op == "wm.context_toggle") {+ const std::string path = prop("data_path");+ const std::string_view tail = "use_smooth_stroke";+ return path.size() >= tail.size() && path.compare(path.size() - tail.size(), tail.size(), tail) == 0 ? "stroke.lazy"+ : "";+ }+ if (op == "ed.undo") return "edit.undo";+ if (op == "ed.redo") return "edit.redo";+ return {};+}++int keymapPriority(const std::string& keymap) {+ if (keymap == "Sculpt") return 2;+ if (keymap == "3D View") return 1;+ if (keymap == "Screen") return 0;+ return -1; // not read+}++} // namespace++bool parseBlenderKeymap(std::string_view t, BlenderKeymap& out, std::string& error) {+ out = BlenderKeymap{};+ if (t.find("keyconfig_data") == std::string_view::npos) {+ error = "Not a Blender keymap: export one in Blender with Preferences > Keymap > Export";+ return false;+ }+ struct Found {+ BlenderKeyBinding b;+ size_t order;+ };+ std::vector<Found> found;+ std::string keymap;+ bool modal = false;+ size_t i = 0;+ while ((i = t.find("(\"", i)) != std::string_view::npos) {+ std::string name;+ size_t j = readQuoted(t, i + 1, name);+ ++i;+ if (j == std::string_view::npos) continue;+ j = skipSpace(t, j);+ if (j >= t.size() || t[j] != ',') continue;+ j = skipSpace(t, j + 1);+ std::string_view dict;+ const size_t afterDict = readBraces(t, j, kMaxDict, dict);+ if (afterDict == std::string_view::npos) continue;+ const std::string_view inner = dict.substr(1);+ const size_t firstKey = skipSpace(inner, 0);+ if (inner.compare(firstKey, 12, "\"space_type\"") == 0) { // a keymap: ("Sculpt", {"space_type": ...+ keymap = name;+ modal = dictValue(dict, "modal") == "True";+ i = afterDict;+ continue;+ }+ if (inner.compare(firstKey, 6, "\"type\"") != 0) continue;+ // An item: ("operator.name", {event}, None or {"properties": [...]})+ size_t k = skipSpace(t, afterDict);+ if (k >= t.size() || t[k] != ',') continue;+ k = skipSpace(t, k + 1);+ std::string_view props;+ if (t.compare(k, 4, "None") == 0) {+ k += 4;+ } else if (readBraces(t, k, kMaxProps, props) == std::string_view::npos) {+ continue;+ } else {+ k += props.size();+ }+ i = k;+ if (modal || keymapPriority(keymap) < 0) continue;+ const std::string value = dictValue(dict, "value");+ if (value != "PRESS" && value != "CLICK") continue;+ Chord chord;+ chord.key = keyFromType(dictValue(dict, "type"));+ if (chord.key == SDLK_UNKNOWN) continue; // mouse, wheel, trackpad, NDOF: not keys+ if (!dictValue(dict, "key_modifier").empty()) continue; // two-key chords: SculptForge has none+ if (props.find("\"active\":False") != std::string_view::npos ||+ props.find("\"active\": False") != std::string_view::npos)+ continue;+ if (dictValue(dict, "any") != "True") {+ chord.shift = dictValue(dict, "shift") == "True";+ chord.ctrl = dictValue(dict, "ctrl") == "True" || dictValue(dict, "oskey") == "True"; // Cmd on a Mac+ chord.alt = dictValue(dict, "alt") == "True";+ }+ ++out.items;+ const std::string action = actionFor(name, props);+ if (action.empty()) {+ ++out.skipped;+ continue;+ }+ found.push_back({{action, chord, keymapPriority(keymap)}, found.size()});+ }+ if (out.items == 0) {+ error = "The keymap has no keys for the 3D View or Sculpt mode (export it with \"All Keymaps\" on, or edit a "+ "sculpt key first)";+ return false;+ }+ // Blender looks in Sculpt mode's keymap before the 3D View's: one action per key, the higher keymap's.+ std::stable_sort(found.begin(), found.end(), [](const Found& a, const Found& b) {+ return a.b.priority != b.b.priority ? a.b.priority > b.b.priority : a.order < b.order;+ });+ for (const Found& f : found) {+ const bool taken = std::any_of(out.bindings.begin(), out.bindings.end(),+ [&](const BlenderKeyBinding& b) { return b.chord == f.b.chord; });+ if (taken) {+ if (std::none_of(out.bindings.begin(), out.bindings.end(),+ [&](const BlenderKeyBinding& b) { return b.chord == f.b.chord && b.action == f.b.action; }))+ ++out.skipped; // shadowed by Sculpt mode's own use of the key+ continue;+ }+ out.bindings.push_back(f.b);+ }+ return true;+}++} // namespace sfdiff --git a/src/app/BlenderKeymap.h b/src/app/BlenderKeymap.hnew file mode 100644index 00000000..fed74085--- /dev/null+++ b/src/app/BlenderKeymap.h@@ -0,0 +1,34 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Reads the keys out of a keymap exported from Blender (Preferences > Keymap > Export: a .py file of+// keyconfig_data tuples). The file is never run: a strict scanner reads the item tuples as text and keeps only+// the navigation and sculpt entries SculptForge has an action for (view3d.view_axis, paint.brush_select,+// wm.radial_control...). Everything else, and anything that doesn't look exactly like Blender's export, is+// skipped. Used by Preferences > Input / Controls > Import Blender keymap (Input.cpp).+#pragma once++#include "app/Actions.h"++#include <string>+#include <string_view>+#include <vector>++namespace sf {++struct BlenderKeyBinding {+ std::string action; // SculptForge action id: "view.front", "brush.standard", "ui.size_popup"+ Chord chord;+ int priority = 0; // the keymap it came from: Sculpt 2 > 3D View 1 > Screen / Window 0 (Blender's order)+};++struct BlenderKeymap {+ std::vector<BlenderKeyBinding> bindings; // one chord per action and per key, highest priority first+ int items = 0; // key map items read (keyboard presses in the keymaps SculptForge looks at)+ int skipped = 0; // of those, the ones with no SculptForge equivalent+};++// False (with `error`) when the text isn't a Blender keymap export at all.+bool parseBlenderKeymap(std::string_view text, BlenderKeymap& out, std::string& error);++} // namespace sfdiff --git a/src/app/Config.cpp b/src/app/Config.cppindex 6ee38d3d..f2584493 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -22,6 +22,7 @@#include <filesystem>#include <fstream>#include <map>+#include <span>namespace sf {@@ -45,7 +46,8 @@ Json toJson(const UiPrefs& p) {j.set("libraryFolder", p.libraryFolder);j.set("cameraNotch", double(p.cameraNotch));j.set("turntable", p.turntable);- j.set("inputStyle", std::string(p.inputStyle == 1 ? "sculptforge" : "zbrush"));+ j.set("inputStyle", std::string(p.inputStyle == 2 ? "blender" : p.inputStyle == 1 ? "sculptforge" : "zbrush"));+ j.set("emulateNumpad", p.emulateNumpad);j.set("alphabeticalPalettes", p.alphabeticalPalettes);j.set("tablet", toJson(p.tablet));j.set("antialiasing", double(p.antialiasing));@@ -68,7 +70,11 @@ void fromJson(const Json& j, UiPrefs& p) {if (j["libraryFolder"].isString()) p.libraryFolder = j["libraryFolder"].asString();p.cameraNotch = std::clamp(int(j["cameraNotch"].asNumber(p.cameraNotch)), 0, 2);p.turntable = j["turntable"].asBool(p.turntable);- if (j["inputStyle"].isString()) p.inputStyle = j["inputStyle"].asString() == "sculptforge" ? 1 : 0;+ if (j["inputStyle"].isString()) {+ const std::string style = j["inputStyle"].asString();+ p.inputStyle = style == "blender" ? 2 : style == "sculptforge" ? 1 : 0;+ }+ p.emulateNumpad = j["emulateNumpad"].asBool(p.emulateNumpad);p.alphabeticalPalettes = j["alphabeticalPalettes"].asBool(p.alphabeticalPalettes);fromJson(j["tablet"], p.tablet);const int aa = int(j["antialiasing"].asNumber(p.antialiasing));@@ -80,7 +86,7 @@ void fromJson(const Json& j, UiPrefs& p) {namespace {-enum UiFileKind { kSaveUi, kLoadUi, kRunScript, kLibraryFolder, kUiFileKinds };+enum UiFileKind { kSaveUi, kLoadUi, kRunScript, kLibraryFolder, kBlenderKeymap, kUiFileKinds };struct UiFileRequest {App* app = nullptr;@@ -95,6 +101,7 @@ void SDLCALL onUiFileChosen(void* userdata, const char* const* files, int) {}const SDL_DialogFileFilter kUiFilters[] = {{"SculptForge UI layout", "json"}};+const SDL_DialogFileFilter kBlenderKeymapFilters[] = {{"Blender keymap", "py"}, {"All files", "*"}};const SDL_DialogFileFilter kScriptFilters[] = {{"SculptForge script", "sfscript;txt"}, {"All files", "*"}};std::filesystem::path fsPath(const std::string& utf8) { return std::filesystem::path(std::u8string(utf8.begin(), utf8.end())); }@@ -140,6 +147,27 @@ constexpr Gesture kGestures[] = {{"Open files", "Drop a model (.obj, .glb ...), brush (.sfbrush) or image onto the window"},};+// The same in the Blender style (Preferences > Input).+constexpr Gesture kBlenderGestures[] = {+ {"Sculpt", "Left drag on the model"},+ {"Invert (subtract)", "Hold Ctrl while sculpting"},+ {"Smooth", "Hold Shift while sculpting"},+ {"Rotate", "Middle drag, Alt + left drag (pen, trackpad), or left drag beside the model"},+ {"Pan", "Shift + middle drag, or Alt+Shift + left drag"},+ {"Zoom", "Mouse wheel, Ctrl + middle drag, or Alt+Ctrl + left drag"},+ {"Views", "Numpad 1 front, 3 right, 7 top (Ctrl: the opposite side), 5 orthographic, . frame the SubTool, Home "+ "frame everything; Emulate Numpad (Preferences > Input) for the number row"},+ {"Paint mask", "M for the Mask brush, then drag (Ctrl+drag unmasks); M again goes back"},+ {"Invert / clear mask", "Ctrl+I / Alt+M"},+ {"Hide polygroup", "H over it (Shift+H: show only it, again: everything; Alt+H shows all)"},+ {"Brush radius / strength", "F / Shift+F, then drag or type a number"},+ {"Help on any control", "Hold Ctrl and point at it (Ctrl+Alt: scripting parameters)"},+ {"Assign a shortcut", "Ctrl+Alt + click any button, then press the key"},+ {"Tablet pressure", "Used automatically when a pen is detected (Preferences > Tablet: curve, test area)"},+ {"Pen side buttons", "Lower: right-click (drag to rotate), upper: invert; Preferences > Tablet"},+ {"Open files", "Drop a model (.obj, .glb ...), brush (.sfbrush) or image onto the window"},+};+} // namespace// ---------------------------------------------------------------------------@@ -288,6 +316,7 @@ void App::initActions() {doc_.activeBrush = -1;paintMode_ = false;guidesMode_ = false; // leaves the QRemesh Guides brush+ maskBrush_.on = false;},ICON_LC_BRUSH, nullptr, [this, type] { return brush_ == type && doc_.activeBrush < 0 && !paintMode_ && !guidesMode_; }, nullptr,(std::string("Sculpt with the ") + brushName(type) + " brush.").c_str());@@ -485,6 +514,10 @@ void App::saveUiDialog() {SDL_ShowSaveFileDialog(onUiFileChosen, &g_requests[kSaveUi], window_, kUiFilters, 1, nullptr);}+void App::importBlenderKeymapDialog() {+ SDL_ShowOpenFileDialog(onUiFileChosen, &g_requests[kBlenderKeymap], window_, kBlenderKeymapFilters, 2, nullptr, false);+}+void App::loadUiDialog() {SDL_ShowOpenFileDialog(onUiFileChosen, &g_requests[kLoadUi], window_, kUiFilters, 1, nullptr, false);}@@ -593,6 +626,8 @@ void App::drawHelpConsoleUi() {} else {status_ = err;}+ } else if (kind == kBlenderKeymap) {+ importBlenderKeymap(path);} else if (kind == kRunScript) {setConsoleOpen(true);console_.queueScriptFile(path);@@ -652,6 +687,12 @@ void App::drawControlsWindow() {ImGui::End();return;}+ // The key style (Preferences > Input), and a keymap exported from Blender (#12).+ ImGui::TextDisabled("Style");+ ImGui::SameLine();+ drawInputStyleRow(ImGui::GetContentRegionAvail().x * 0.6f);+ ImGui::SameLine();+ ui::ActionButton(*this, "input.import_blender", ImVec2(-FLT_MIN, 0), ui::Look::IconLabel);static char filter[96] = "";ImGui::SetNextItemWidth(-FLT_MIN);ImGui::InputTextWithHint("##controls_filter", ICON_LC_SEARCH " Filter shortcuts and gestures", filter, sizeof filter);@@ -704,7 +745,8 @@ void App::drawControlsWindow() {if (ImGui::BeginTable("##gestures", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_PadOuterX)) {ImGui::TableSetupColumn("what", ImGuiTableColumnFlags_WidthFixed, 180.0f * s);ImGui::TableSetupColumn("how", ImGuiTableColumnFlags_WidthStretch);- for (const auto& g : kGestures) {+ const bool blender = blenderStyle();+ for (const auto& g : blender ? std::span<const Gesture>(kBlenderGestures) : std::span<const Gesture>(kGestures)) {if (!matches(g.what, g.how, "")) continue;ImGui::TableNextRow();ImGui::TableNextColumn();diff --git a/src/app/Config.h b/src/app/Config.hindex 9b072909..a026e8ca 100644--- a/src/app/Config.h+++ b/src/app/Config.h@@ -29,7 +29,9 @@ struct UiPrefs {bool alphabeticalPalettes = false; // strict A-Z palette bar like ZBrush (default: File, Edit first)int cameraNotch = 0; // keep the UI out of a laptop's camera notch: 0 automatic, 1 always, 2 neverbool turntable = false; // rotation: false = free, about the screen axes (ZBrush); true = turntable (Y up)- int inputStyle = 0; // Preferences > Input: 0 ZBrush, 1 SculptForge (1-0 brushes, I = Z Intensity...)+ int inputStyle = 0; // Preferences > Input: 0 ZBrush, 1 SculptForge (1-0 brushes, I = Z Intensity...),+ // 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// Preferences > Performance (PanelPerformance.cpp).int antialiasing = 4; // samples per pixel in the 3D view: 1 (off), 2, 4 or 8diff --git a/src/app/Input.cpp b/src/app/Input.cppindex 787d252a..e6f8aff8 100644--- a/src/app/Input.cpp+++ b/src/app/Input.cpp@@ -6,9 +6,15 @@// Ctrl+H for the mask, Ctrl+W group masked), Preferences > Input with the ZBrush and SculptForge key styles,// the QuickMenu itself and Shift-constrained straight strokes. The mouse gestures live with the rest of the// input in App.cpp (roll, Ctrl+click blur / sharpen in PanelMasking.cpp).+//+// The Blender style (#12): its default keys come from Blender 4.2 - 5.x's own keymap (blender_default.py, Sculpt+// and 3D View), with the brush letters on SculptForge's nearest brush. The mouse side is in App.cpp+// (onMouseDown: middle-drag orbit, Alt+left-drag as the middle button) and blenderMods (Ctrl inverts).#include "app/App.h"+#include "app/BlenderKeymap.h"#include "app/Pickers.h"#include "app/Ui.h"+#include "core/Polygroups.h"#include <IconsLucide.h>@@ -17,6 +23,9 @@#include <algorithm>#include <cctype>#include <cmath>+#include <filesystem>+#include <fstream>+#include <iterator>#include <string>namespace sf {@@ -107,35 +116,279 @@ void App::registerInputActions() {add("input.style_zbrush", "ZBrush", nullptr, "Preferences > Input", "","ZBrush's keys and gestures: I is RGB Intensity, 9 is QuickSave, the number keys don't pick brushes, and ""Ctrl+drag on the background only clears the mask.",- [this] {- uiPrefs_.inputStyle = 0;- applyInputStyle();- },- [this] { return uiPrefs_.inputStyle == 0; });+ [this] { setInputStyle(0); }, [this] { return uiPrefs_.inputStyle == 0; });add("input.style_sculptforge", "SculptForge", nullptr, "Preferences > Input", "","SculptForge's own keys from before 0.7: 1-9 and 0 pick the first ten brushes, I is Z Intensity (as is U), ""and Ctrl+drag on the background zooms when nothing is masked.",+ [this] { setInputStyle(1); }, [this] { return uiPrefs_.inputStyle == 1; });+ add("input.style_blender", "Blender", nullptr, "Preferences > Input", "",+ "Blender's navigation and sculpt-mode keys: middle-drag orbits (Shift pans, Ctrl zooms), Alt+left-drag does "+ "the same for pens and trackpads, Ctrl inverts a stroke, Shift smooths, F / Shift+F set radius and strength, "+ "V S P I G C K pick brushes and M the mask brush, Home frames everything. Rotation switches to Turntable.",+ [this] { setInputStyle(2); }, [this] { return uiPrefs_.inputStyle == 2; });+ add("input.emulate_numpad", "Emulate Numpad", nullptr, "Preferences > Input", "",+ "Blender style: the number keys above the letters work as the numpad (1 front, 3 right, 7 top, 5 "+ "orthographic...), for keyboards without one.",+ [this] { uiPrefs_.emulateNumpad = !uiPrefs_.emulateNumpad; }, [this] { return uiPrefs_.emulateNumpad; },+ [this] { return blenderStyle(); });+ add("input.import_blender", "Import Blender keymap...", ICON_LC_FILE_INPUT, "Preferences > Input", "",+ "Use the keys from a keymap you exported in Blender (Preferences > Keymap > Export, a .py file). Switches "+ "to the Blender style, then takes the navigation and sculpt keys SculptForge has an equivalent for. The "+ "file is only read, never run. Store Config keeps the result.",+ [this] { importBlenderKeymapDialog(); });++ // Blender style: the mask brush and Sculpt mode's visibility keys.+ add("mask.brush", "Mask brush", ICON_LC_PAINTBRUSH, "Tool > Masking", "",+ "Paint the mask with a plain left drag, Ctrl+drag to unmask (Blender's Mask brush). Press it again, or pick "+ "another brush, to go back.",+ [this] { toggleMaskBrush(); }, [this] { return maskBrushActive(); });+ add("visibility.hide_group", "Hide polygroup under cursor", ICON_LC_EYE_OFF, "Tool > Visibility", "",+ "Hide the polygroup under the cursor (Blender: hide the face set).", [this] { hideGroupUnderCursor(false); });+ add("visibility.isolate_group", "Isolate polygroup under cursor", ICON_LC_EYE, "Tool > Visibility", "",+ "Show only the polygroup under the cursor; again, with it isolated, shows everything (Blender: toggle "+ "visibility).",+ [this] { hideGroupUnderCursor(true); });+ add("visibility.show_all", "Show all", ICON_LC_EYE, "Tool > Visibility", "", "Show every hidden part of the mesh.",+ [this] { runCommand("show_all"); });++ commands_.add({"blender_keymap_import",+ "Use the keys of a keymap exported from Blender (Preferences > Keymap > Export, a .py file): "+ "switches to the Blender input style and takes the navigation and sculpt keys SculptForge has an "+ "equivalent for. The file is read as text, never run.",+ {{"path", ParamSpec::Type::String, "The exported .py file.", true}},+ [this](Document&, const Args& a) -> CommandResult {+ const bool ok = importBlenderKeymap(argString(a, "path"));+ return {ok, status_};+ }});+ registerViewActions();+ applyInputStyle();+}++void App::registerViewActions() {+ auto add = [this](const char* id, const char* label, const char* shortcut, const char* description,+ std::function<void()> run, std::function<bool()> checked = nullptr) {+ Action a;+ a.id = id;+ a.label = label;+ a.palette = "Transform";+ a.shortcut = shortcut;+ a.description = description;+ a.run = std::move(run);+ a.checked = std::move(checked);+ actions_.add(std::move(a));+ };+ // The numpad, as in Blender (every style: the keys are free otherwise). Axis views are orthographic until the+ // view is turned again (Blender's Auto Perspective).+ add("view.front", "Front view", "Numpad 1", "Look at the model from the front (orthographic).",+ [this] { viewAxis(0.0f, 0.0f); });+ add("view.back", "Back view", "Ctrl+Numpad 1", "Look at the model from behind (orthographic).",+ [this] { viewAxis(180.0f, 0.0f); });+ add("view.right", "Right view", "Numpad 3", "Look at the model's right side (orthographic).",+ [this] { viewAxis(90.0f, 0.0f); });+ add("view.left", "Left view", "Ctrl+Numpad 3", "Look at the model's left side (orthographic).",+ [this] { viewAxis(-90.0f, 0.0f); });+ add("view.top", "Top view", "Numpad 7", "Look down on the model (orthographic).", [this] { viewAxis(0.0f, -90.0f); });+ add("view.bottom", "Bottom view", "Ctrl+Numpad 7", "Look up at the model from below (orthographic).",+ [this] { viewAxis(0.0f, 90.0f); });+ add("view.ortho", "Orthographic", "Numpad 5",+ "Switch between a perspective and an orthographic view (no foreshortening: sizes don't shrink with depth).",[this] {- uiPrefs_.inputStyle = 1;- applyInputStyle();+ camera_.ortho = !camera_.ortho;+ autoOrtho_ = false;},- [this] { return uiPrefs_.inputStyle == 1; });+ [this] { return camera_.ortho; });+ add("view.orbit_left", "Orbit left", "Numpad 4", "Turn the view 15 degrees to the left around the model.",+ [this] { viewOrbitStep(-15.0f, 0.0f); });+ add("view.orbit_right", "Orbit right", "Numpad 6", "Turn the view 15 degrees to the right around the model.",+ [this] { viewOrbitStep(15.0f, 0.0f); });+ add("view.orbit_up", "Orbit up", "Numpad 8", "Turn the view 15 degrees up over the model.",+ [this] { viewOrbitStep(0.0f, -15.0f); });+ add("view.orbit_down", "Orbit down", "Numpad 2", "Turn the view 15 degrees down under the model.",+ [this] { viewOrbitStep(0.0f, 15.0f); });+ add("view.opposite", "Opposite side", "Numpad 9", "Look at the model from the other side.", [this] {+ camera_.setOrientation(camera_.orientation() * glm::angleAxis(glm::pi<float>(), glm::vec3(0, 1, 0)));+ });+ add("view.zoom_in", "Zoom in", "Numpad Plus", "Move the view closer.", [this] { camera_.zoom(1.0f); });+ add("view.zoom_out", "Zoom out", "Numpad Minus", "Move the view back.", [this] { camera_.zoom(-1.0f); });+ add("view.frame_selected", "Frame SubTool", "Numpad .", "Fit the active SubTool in the view (Blender: View Selected).",+ [this] { frameActiveSubtool(); });+}++void App::setInputStyle(int style) {+ uiPrefs_.inputStyle = std::clamp(style, 0, 2);+ if (blenderStyle()) uiPrefs_.turntable = true; // Blender orbits as a turntable; Preferences > Input changes it+ maskBrush_.on = false;applyInputStyle();}void App::applyInputStyle() {- const bool sf = !zbrushStyle();- for (int i = 0; i < int(BrushType::Count) && i < 10; ++i)- actions_.setDefaultShortcut(brushId(BrushType(i)), sf ? (i < 9 ? std::to_string(i + 1) : "0") : "");- actions_.setDefaultShortcut("file.quicksave", sf ? "" : "9");- actions_.setDefaultShortcut("ui.strength_popup", sf ? "U / I" : "U");- actions_.setDefaultShortcut("ui.rgb_popup", sf ? "" : "I");+ const int style = std::clamp(uiPrefs_.inputStyle, 0, 2);+ const bool sf = style == 1;+ // One row per action whose key depends on the style: ZBrush, SculptForge, Blender (Blender 4.2 - 5.x defaults).+ struct Keys {+ const char* id;+ const char* keys[3];+ };+ static const Keys kKeys[] = {+ {"file.quicksave", {"9", "", ""}},+ {"ui.strength_popup", {"U", "U / I", "Shift+F / U"}},+ {"ui.rgb_popup", {"I", "", ""}},+ {"ui.size_popup", {"S", "S", "F"}},+ {"view.frame", {"F", "F", "Home"}},+ {"view.wireframe", {"Shift+F", "Shift+F", "Shift+Z"}},+ {"color.switch", {"V", "V", "X"}},+ {"color.pick", {"C", "C", "Shift+X"}},+ {"transform.symmetry_x", {"X", "X", ""}},+ {"draw.paint", {"P", "P", ""}},+ {"ui.picker.material", {"M", "M", ""}},+ {"stroke.lazy", {"L", "L", "L / Shift+S"}},+ {"mask.clear", {"Ctrl+Shift+A", "Ctrl+Shift+A", "Alt+M / Ctrl+Shift+A"}},+ {"geometry.lower_res", {"Shift+D", "Shift+D", "Alt+1 / Shift+D"}},+ {"geometry.higher_res", {"D", "D", "Alt+2 / D"}},+ {"mask.brush", {"", "", "M"}},+ {"visibility.hide_group", {"", "", "H"}},+ {"visibility.isolate_group", {"", "", "Shift+H"}},+ {"visibility.show_all", {"", "", "Alt+H"}},+ };+ for (const Keys& k : kKeys) actions_.setDefaultShortcut(k.id, k.keys[style]);+ // Brushes: 1-9 and 0 in the SculptForge style; Blender's sculpt-mode letters in the Blender style.+ static const std::pair<BrushType, const char*> kBlenderBrushes[] = {+ {BrushType::Standard, "V"}, {BrushType::Smooth, "S"}, {BrushType::Pinch, "P"},+ {BrushType::Inflate, "I"}, {BrushType::Move, "G"}, {BrushType::Flatten, "Shift+T"},+ {BrushType::ClayBuildup, "C"}, {BrushType::Crease, "Shift+C"}, {BrushType::SnakeHook, "K"},+ };+ for (int i = 0; i < int(BrushType::Count); ++i) {+ std::string key = sf && i < 10 ? (i < 9 ? std::to_string(i + 1) : "0") : "";+ if (style == 2)+ for (const auto& [type, letter] : kBlenderBrushes)+ if (int(type) == i) key = letter;+ actions_.setDefaultShortcut(brushId(BrushType(i)), key);+ }+}++// ---------------------------------------------------------------------------+// Blender style+// ---------------------------------------------------------------------------++void App::viewAxis(float yawDegrees, float pitchDegrees) {+ camera_.yaw = glm::radians(yawDegrees);+ camera_.pitch = glm::radians(pitchDegrees);+ camera_.roll = 0.0f;+ if (!camera_.ortho) {+ camera_.ortho = true;+ autoOrtho_ = true;+ }+}++void App::viewOrbitStep(float yawDegrees, float pitchDegrees) {+ // Yaw about the world's up axis, pitch about the view's own right axis (Blender's numpad orbit).+ camera_.setOrientation(glm::angleAxis(glm::radians(yawDegrees), glm::vec3(0, 1, 0)) * camera_.orientation() *+ glm::angleAxis(glm::radians(pitchDegrees), glm::vec3(1, 0, 0)));+ if (autoOrtho_) {+ camera_.ortho = false;+ autoOrtho_ = false;+ }+}++void App::frameActiveSubtool() {+ const AABB b = doc_.mesh.bounds();+ if (b.valid()) camera_.frame(b);+ else camera_.frame(sceneBounds());+}++SDL_Keymod App::blenderMods(SDL_Keymod keyboard) const {+ // What the sculpting code reads: Alt inverts, Ctrl masks, Shift smooths (the ZBrush meanings). Blender inverts+ // with Ctrl and masks with the Mask brush; its Alt is the emulated middle button, so it means nothing here.+ SDL_Keymod out = keyboard & SDL_KMOD_SHIFT;+ const bool ctrl = (keyboard & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0;+ if (maskBrushActive()) {+ if (!(keyboard & SDL_KMOD_SHIFT)) out |= SDL_KMOD_LCTRL; // Shift still smooths the surface+ if (ctrl) out |= SDL_KMOD_LALT; // Ctrl unmasks+ } else if (ctrl) {+ out |= SDL_KMOD_LALT;+ }+ return out;+}++bool App::maskBrushActive() const {+ return maskBrush_.on && blenderStyle() && brush_ == maskBrush_.brush && doc_.activeBrush == maskBrush_.custom &&+ paintMode_ == maskBrush_.paint && !guidesMode_;+}++void App::toggleMaskBrush() {+ if (maskBrushActive()) {+ maskBrush_.on = false;+ status_ = "Mask brush off";+ return;+ }+ maskBrush_ = {true, brush_, doc_.activeBrush, paintMode_};+ status_ = blenderStyle() ? "Mask brush: drag to mask, Ctrl+drag to unmask (M again: back to your brush)"+ : "The Mask brush is for the Blender style; here, hold Ctrl to mask";+}++void App::hideGroupUnderCursor(bool isolate) {+ doc_.syncBvh();+ RayHit hit;+ if (!pick(mouseX_, mouseY_, hit)) {+ if (isolate && doc_.mesh.hasHidden()) runCommand("show_all");+ return;+ }+ const uint32_t group = doc_.mesh.polygroupAt(hit.triangle);+ if (!isolate) runCommand("hide_polygroup", {{"group", double(group)}});+ else if (polygroupIsolated(doc_.mesh, group)) runCommand("show_all");+ else runCommand("isolate_polygroup", {{"group", double(group)}});+}++bool App::importBlenderKeymap(const std::string& path) {+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);+ std::string text;+ if (f) text.assign(std::istreambuf_iterator<char>(f), {});+ if (!f && text.empty()) {+ status_ = "Could not read " + path;+ lastCommandOk_ = false;+ return false;+ }+ if (text.size() > 8u * 1024u * 1024u) {+ status_ = "That file is too big for a Blender keymap";+ lastCommandOk_ = false;+ return false;+ }+ BlenderKeymap keymap;+ std::string err;+ if (!parseBlenderKeymap(text, keymap, err)) {+ status_ = err;+ lastCommandOk_ = false;+ return false;+ }+ setInputStyle(2);+ std::vector<std::string> assigned;+ for (const BlenderKeyBinding& b : keymap.bindings) {+ if (!actions_.find(b.action)) continue;+ const bool first = std::find(assigned.begin(), assigned.end(), b.action) == assigned.end();+ actions_.assignShortcut(b.action, chordText(b.chord), !first);+ if (first) assigned.push_back(b.action);+ }+ status_ = "Blender keymap: " + std::to_string(keymap.bindings.size()) + " keys for " ++ std::to_string(assigned.size()) + " actions (" + std::to_string(keymap.skipped) ++ " Blender keys have no SculptForge equivalent). Store Config keeps them.";+ lastCommandOk_ = true;+ return true;+}++void App::drawInputStyleRow(float width) {+ ui::Segmented(*this, {"input.style_zbrush", "input.style_sculptforge", "input.style_blender"}, width);}void App::drawInputSection() {ImGui::TextDisabled("Style");ImGui::SameLine();- ui::Segmented(*this, {"input.style_zbrush", "input.style_sculptforge"});+ drawInputStyleRow();+ if (blenderStyle()) {+ bool emulate = uiPrefs_.emulateNumpad;+ if (ImGui::Checkbox("Emulate Numpad", &emulate)) uiPrefs_.emulateNumpad = emulate;+ ui::HelpAction(*this, "input.emulate_numpad");+ }+ ui::ActionButton(*this, "input.import_blender", ImVec2(-FLT_MIN, 0), ui::Look::IconLabel);ImGui::TextDisabled("Rotation");ImGui::SameLine();int rotation = uiPrefs_.turntable ? 1 : 0;diff --git a/src/app/LightBox.cpp b/src/app/LightBox.cppindex e3e95d4c..d778d423 100644--- a/src/app/LightBox.cpp+++ b/src/app/LightBox.cpp@@ -1043,6 +1043,10 @@ bool App::lightBoxKey(SDL_Keycode key, SDL_Keymod mod) {: nullptr;const Action* a = id ? actions_.find(id) : nullptr;if (!a || !a->run) return false;+ if (!heldPicker) { // only while the key is still the action's (the Blender style gives S and M to brushes)+ const std::vector<Chord> chords = parseChords(actions_.shortcutText(a->id));+ if (std::find(chords.begin(), chords.end(), chordFromEvent(key, mod)) == chords.end()) return false;+ }actions_.touch(a->id);a->run();return true;diff --git a/src/app/PanelMasking.cpp b/src/app/PanelMasking.cppindex 5f785537..f8f1b98f 100644--- a/src/app/PanelMasking.cpp+++ b/src/app/PanelMasking.cpp@@ -48,7 +48,7 @@ void App::beginMaskStroke(float x, float y) {lazyMouse_.reset(glm::vec2(x, y));// ZBrush: a Ctrl+click on the model blurs the mask (Ctrl+Alt+click sharpens it); only a drag paints. The// pen's eraser end set to Erase mask paints straight away.- maskClickPending_ = ctrlDown(inputMods());+ maskClickPending_ = ctrlDown(inputMods()) && !blenderStyle(); // (Blender's Mask brush dabs on a click)maskClickX_ = x;maskClickY_ = y;if (!maskClickPending_) firstDab(x, y);@@ -68,7 +68,7 @@ void App::maskCanvasMove(float x, float y) {if (std::hypot(x - maskCanvasX_, y - maskCanvasY_) < kMaskDragThresholdPx) return;maskCanvasMoved_ = true;if (anyMasked(doc_.mesh)) runCommand("mask_clear");- else if (!zbrushStyle()) drag_ = Drag::Zoom;+ else if (uiPrefs_.inputStyle == 1) drag_ = Drag::Zoom;}void App::maskCanvasRelease() {diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 671ba3ad..31febf9f 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -302,6 +302,7 @@ void App::registerShellActions() {doc_.activeBrush = -1;paintMode_ = false;guidesMode_ = false; // leaves the QRemesh Guides brush+ maskBrush_.on = false;};a.checked = [this, type] { return brush_ == type && doc_.activeBrush < 0 && !paintMode_ && !guidesMode_; };add(std::move(a));diff --git a/src/app/Tablet.cpp b/src/app/Tablet.cppindex b1785fa5..04bfc4d8 100644--- a/src/app/Tablet.cpp+++ b/src/app/Tablet.cpp@@ -142,6 +142,7 @@ float App::strokePressure() const {SDL_Keymod App::inputMods() const {SDL_Keymod mods = SDL_GetModState();+ if (blenderStyle()) mods = blenderMods(mods); // Blender's Ctrl inverts, its Mask brush masks (Input.cpp)for (int b = 1; b <= kPenButtons; ++b) {if (!(penButtons_ & (1u << b))) continue;const PenAction a = uiPrefs_.tablet.buttons[size_t(b - 1)];diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 680fd391..e840bc60 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -8,7 +8,8 @@//// click LABEL / double_click LABEL / right_click LABEL / hover LABEL// type LABEL TEXT click a text field and type into it-// key COMBO e.g. enter, escape, ctrl+z, ctrl+shift+z, 3, comma, backtick, tab, f3, space, minus+// key COMBO e.g. enter, escape, ctrl+z, ctrl+shift+z, 3, comma, backtick, tab, f3, space, minus,+// home, numpad1, ctrl+numpad7, numpad., numpadplus// hold MODS ctrl / shift / alt / ctrl+shift ... or none (for strokes and drags)// stroke U0 V0 U1 V1 [S] brush stroke across the model (fractions of its on-screen bounds)// drag X0 Y0 X1 Y1 [S] [release] left-drag in window fractions (rectangle hide, sliders...); release:@@ -26,6 +27,8 @@// gizmo_hover HANDLE move the mouse onto a Gizmo 3D handle (it lights up, for screenshots)// drag_landmark N DX DY [S] left-drag Make sculptable's face landmark N (0-7, FaceLandmarks order) by DX DY pixels// orbit DX DY right-drag on the background, in pixels (with the held modifiers)+// button_drag middle|right X0 Y0 X1 Y1 [S] drag with that button in window fractions (with the held modifiers)+// expect_shortcut ACTION KEYS the action's effective keys, e.g. expect_shortcut view.front Numpad 1// camera YAW PITCH set the view's angles in degrees (0 0 = the front view), e.g. for guide screenshots// zoom FACTOR / look X Y Z move the camera FACTOR times closer / turn it about (and look at) the point X Y Z// run COMMANDS sculptforge-cli commands, e.g. run new_sphere subdivisions=4 ($SCRIPT_DIR: the script's folder)@@ -80,7 +83,9 @@// last_stroke_dabs (dabs of the last finished stroke), stroke_type (0 Dots, 1 DragRect,// 2 DragDot, 3 Spray, 4 LazyMouse), vdms (VDM brush maps), vdm_files (.sfvdm in the library)// z_intensity, smooth_intensity, rgb_intensity (0-100), focal_shift (-100..100), draw_size,-// quickmenu_open, lazy_mouse, input_style (0 ZBrush, 1 SculptForge), brush_type (BrushType+// quickmenu_open, lazy_mouse, input_style (0 ZBrush, 1 SculptForge, 2 Blender), turntable,+// camera_ortho, mask_brush (Blender's Mask brush on), shortcut_conflicts (keys two actions+// claim), brush_type (BrushType// index, -1 for a custom brush or Paint), last_dab_x / last_dab_y (window pixels), paint_r// 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,@@ -323,6 +328,19 @@ double Demo::query(const std::string& name, bool& known) const {return -1.0; // no such layer}if (name == "input_style") return double(app_.uiPrefs_.inputStyle);+ if (name == "turntable") return app_.uiPrefs_.turntable ? 1.0 : 0.0;+ if (name == "camera_ortho") return app_.camera_.ortho ? 1.0 : 0.0;+ if (name == "mask_brush") return app_.maskBrushActive() ? 1.0 : 0.0;+ if (name == "shortcut_conflicts") { // keys that two actions claim (only the first would ever run)+ int conflicts = 0;+ std::vector<Chord> seen;+ for (const Action& a : app_.actions_.all())+ for (const Chord& c : parseChords(app_.actions_.shortcutText(a.id))) {+ if (std::find(seen.begin(), seen.end(), c) != seen.end()) ++conflicts;+ else seen.push_back(c);+ }+ return conflicts;+ }if (name == "mask_shape") return double(int(app_.maskShape_)); // 0 MaskPen, 1 MaskLasso, 2 MaskRectif (name == "hide_shape") return double(int(app_.hideShape_)); // 1 SelectLasso, 2 SelectRectif (name.rfind("phone_", 0) == 0) {@@ -525,6 +543,10 @@ void Demo::testKey(int line, const std::string& combo) {else if (lower == "f3") keyName = "F3";else if (lower == "space") keyName = "Space";else if (lower == "minus") keyName = "-";+ else if (lower.rfind("numpad", 0) == 0) { // numpad1 .. numpad0, numpad., numpadplus, numpadminus+ const std::string k = lower.substr(6);+ keyName = "Keypad " + (k == "plus" ? std::string("+") : k == "minus" ? std::string("-") : k);+ }const SDL_Keycode key = SDL_GetKeyFromName(keyName.c_str());if (key == SDLK_UNKNOWN) {run([this, line, keyName] { fail(line, "unknown key \"" + keyName + "\""); });@@ -704,6 +726,43 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& ereturn false;});wait(0.1f);+ } else if (verb == "button_drag") { // button_drag middle|right X0 Y0 X1 Y1 [S]: navigation drags+ if (!need(5)) return false;+ const int button = w[1] == "middle" ? SDL_BUTTON_MIDDLE : w[1] == "right" ? SDL_BUTTON_RIGHT : 0;+ if (!button) {+ error = "button_drag needs middle or right";+ return false;+ }+ const float x0 = num(2, 0), y0 = num(3, 0), x1 = num(4, 0), y1 = num(5, 0), seconds = num(6, 0.4f);+ auto down = std::make_shared<bool>(false);+ steps_.push_back([this, button, down, x0, y0, x1, y1, seconds](float t) {+ int ww = 0, wh = 0;+ SDL_GetWindowSize(app_.window_, &ww, &wh);+ const ImVec2 a(x0 * float(ww), y0 * float(wh)), b(x1 * float(ww), y1 * float(wh));+ if (t == 0.0f) {+ mouseMotion(a.x, a.y);+ return false;+ }+ if (!*down) {+ SDL_SetModState(held_);+ mouseButton(true, button);+ *down = true;+ }+ const float u = std::min(t / seconds, 1.0f);+ mouseMotion(a.x + (b.x - a.x) * u, a.y + (b.y - a.y) * u);+ if (t < seconds) return false;+ mouseButton(false, button);+ return true;+ });+ wait(0.1f);+ } else if (verb == "expect_shortcut") { // expect_shortcut ACTION KEYS: the action's keys (none: no key)+ if (!need(1)) return false;+ const std::string id = w[1], want = restOf(lineText_, 2);+ run([this, line, id, want] {+ std::string got = app_.actions_.shortcutText(id);+ if (!app_.actions_.find(id)) fail(line, "no action " + id);+ else if (got != want) fail(line, id + " has \"" + got + "\", expected \"" + want + "\"");+ });} else if (verb == "drag_landmark") {if (!need(3)) return false;const int index = int(num(1, 0));diff --git a/src/render/Camera.cpp b/src/render/Camera.cppindex f455e71f..5bfb0bfc 100644--- a/src/render/Camera.cpp+++ b/src/render/Camera.cpp@@ -25,7 +25,13 @@ glm::mat4 Camera::view() const {return glm::inverse(world);}-glm::mat4 Camera::projection() const { return glm::perspective(fovY, aspect, nearPlane(), farPlane()); }+glm::mat4 Camera::projection() const {+ if (!ortho) return glm::perspective(fovY, aspect, nearPlane(), farPlane());+ // As tall as the perspective view at the target; the depth range reaches behind the eye, as in Blender, so+ // zooming in never clips the model.+ const float h = distance * std::tan(fovY * 0.5f);+ return glm::ortho(-h * aspect, h * aspect, -h, h, -farPlane(), farPlane());+}void Camera::orbit(float dx, float dy) {if (roll != 0.0f) { // coming from free orbiting: stand the view upright again@@ -93,6 +99,7 @@ void Camera::screenRay(float x, float y, float width, float height, glm::vec3& o}float Camera::worldPerPixel(const glm::vec3& point, float viewportHeight) const {+ if (ortho) return 2.0f * distance * std::tan(fovY * 0.5f) / std::max(viewportHeight, 1.0f);float depth = std::max(glm::dot(point - position(), forward()), nearPlane());return 2.0f * depth * std::tan(fovY * 0.5f) / std::max(viewportHeight, 1.0f);}diff --git a/src/render/Camera.h b/src/render/Camera.hindex e0b99ee6..74520527 100644--- a/src/render/Camera.h+++ b/src/render/Camera.h@@ -20,6 +20,7 @@ public:float roll = 0.0f; // radians around the view direction; only free orbiting makes it non-zerofloat fovY = glm::radians(35.0f);float aspect = 1.0f;+ bool ortho = false; // orthographic: shows what a perspective view would at the target's depth (Numpad 5)glm::quat orientation() const;glm::vec3 position() const;diff --git a/src/render/Clusters.cpp b/src/render/Clusters.cppindex 08043ae0..4947f10b 100644--- a/src/render/Clusters.cpp+++ b/src/render/Clusters.cpp@@ -402,6 +402,7 @@ CullView CullView::from(const glm::mat4& view, const glm::mat4& proj) {const glm::mat4 inv = glm::inverse(view);v.eye = glm::vec3(inv[3]);v.forward = glm::normalize(glm::vec3(inv * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f)));+ v.ortho = proj[3][3] == 1.0f && proj[2][3] == 0.0f;v.nearDistance = std::abs(proj[2][2] - 1.0f) > 1e-12f ? proj[3][2] / (proj[2][2] - 1.0f) : 0.0f;return v;}diff --git a/src/render/Clusters.h b/src/render/Clusters.hindex c07fcd1f..54ccf242 100644--- a/src/render/Clusters.h+++ b/src/render/Clusters.h@@ -86,6 +86,7 @@ struct CullView {float nearDistance = 0.0f;glm::vec3 forward{0.0f, 0.0f, -1.0f};bool backfaces = false; // cull clusters facing away+ bool ortho = false; // an orthographic projection: no eye point, so facing away isn't judged from `eye`static CullView from(const glm::mat4& view, const glm::mat4& proj);};bool insideFrustum(const CullView& v, const ClusterBounds& b);diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex 5d882185..6aa4a642 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -2081,7 +2081,7 @@ void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy) {proxy = proxy && s.proxyCount.size() == s.drawCount.size() && s.proxyBounds.size() == s.drawCount.size();CullView v = frame;const glm::vec3 e = v.eye;- v.backfaces = s.closed && s.volume > 0.0 && !s.anyHidden && s.box.valid() &&+ v.backfaces = !v.ortho && s.closed && s.volume > 0.0 && !s.anyHidden && s.box.valid() &&(e.x < s.box.min.x || e.y < s.box.min.y || e.z < s.box.min.z || e.x > s.box.max.x || e.y > s.box.max.y ||e.z > s.box.max.z);auto reachesNear = [&](const ClusterBounds& b) {diff --git a/tests/data/blender_keymap_export.py b/tests/data/blender_keymap_export.pynew file mode 100644index 00000000..a5d55625--- /dev/null+++ b/tests/data/blender_keymap_export.py@@ -0,0 +1,185 @@+keyconfig_version = (4, 2, 61)+keyconfig_data = \+[("3D View",+ {"space_type": 'VIEW_3D', "region_type": 'WINDOW'},+ {"items":+ [("view3d.rotate", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None),+ ("view3d.view_axis",+ {"type": 'NUMPAD_1', "value": 'PRESS'},+ {"properties":+ [("type", 'FRONT'),+ ],+ },+ ),+ ("view3d.view_axis",+ {"type": 'ONE', "value": 'PRESS', "alt": True},+ {"properties":+ [("type", 'FRONT'),+ ],+ },+ ),+ ("view3d.view_axis",+ {"type": 'NUMPAD_1', "value": 'PRESS', "shift": True},+ {"properties":+ [("type", 'FRONT'),+ ("align_active", True),+ ],+ },+ ),+ ("view3d.view_axis",+ {"type": 'NUMPAD_7', "value": 'PRESS', "ctrl": True},+ {"properties":+ [("type", 'BOTTOM'),+ ],+ },+ ),+ ("view3d.view_persportho", {"type": 'BACK_SLASH', "value": 'PRESS'}, None),+ ("view3d.view_all",+ {"type": 'HOME', "value": 'PRESS'},+ {"properties":+ [("center", False),+ ],+ },+ ),+ ("view3d.view_all",+ {"type": 'C', "value": 'PRESS', "shift": True},+ {"properties":+ [("center", True),+ ],+ },+ ),+ ("view3d.view_orbit",+ {"type": 'NUMPAD_9', "value": 'PRESS'},+ {"properties":+ [("angle", 3.1416),+ ("type", 'ORBITRIGHT'),+ ],+ },+ ),+ ("view3d.localview", {"type": 'NUMPAD_SLASH', "value": 'PRESS'}, None),+ ],+ },+ ),+ ("Knife Tool Modal Map",+ {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True},+ {"items":+ [("CANCEL", {"type": 'ESC', "value": 'ANY', "any": True}, None),+ ],+ },+ ),+ ("Object Mode",+ {"space_type": 'EMPTY', "region_type": 'WINDOW'},+ {"items":+ [("object.delete", {"type": 'X', "value": 'PRESS'}, None),+ ],+ },+ ),+ ("Sculpt",+ {"space_type": 'EMPTY', "region_type": 'WINDOW'},+ {"items":+ [("sculpt.brush_stroke", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None),+ ("paint.brush_select",+ {"type": 'D', "value": 'PRESS'},+ {"properties":+ [("sculpt_tool", 'DRAW'),+ ],+ },+ ),+ ("brush.asset_activate",+ {"type": 'Q', "value": 'PRESS', "shift": True},+ {"properties":+ [("asset_library_type", 'ESSENTIALS'),+ ("relative_asset_identifier", "brushes/essentials_brushes-mesh_sculpt.blend/Brush/Clay Strips"),+ ],+ },+ ),+ ("paint.brush_select",+ {"type": 'C', "value": 'PRESS', "shift": True},+ {"properties":+ [("sculpt_tool", 'CREASE'),+ ],+ },+ ),+ ("paint.brush_select",+ {"type": 'K', "value": 'PRESS'},+ {"properties":+ [("sculpt_tool", 'SNAKE_HOOK'),+ ],+ "active":False,+ },+ ),+ ("wm.radial_control",+ {"type": 'F', "value": 'PRESS'},+ {"properties":+ [("data_path_primary", 'tool_settings.sculpt.brush.size'),+ ("data_path_secondary", 'tool_settings.unified_paint_settings.size'),+ ("use_secondary", 'tool_settings.unified_paint_settings.use_unified_size'),+ ("rotation_path", 'tool_settings.sculpt.brush.mask_texture_slot.angle'),+ ("color_path", 'tool_settings.sculpt.brush.cursor_color_add'),+ ("fill_color_path", ''),+ ("fill_color_override_path", ''),+ ("fill_color_override_test_path", ''),+ ("zoom_path", ''),+ ("image_id", 'tool_settings.sculpt.brush'),+ ("secondary_tex", False),+ ],+ },+ ),+ ("wm.radial_control",+ {"type": 'R', "value": 'PRESS', "shift": True},+ {"properties":+ [("data_path_primary", 'tool_settings.sculpt.brush.strength'),+ ("use_secondary", 'tool_settings.unified_paint_settings.use_unified_strength'),+ ],+ },+ ),+ ("object.subdivision_set",+ {"type": 'ONE', "value": 'PRESS', "alt": True, "repeat": True},+ {"properties":+ [("level", -1),+ ("relative", True),+ ],+ },+ ),+ ("paint.mask_flood_fill",+ {"type": 'M', "value": 'PRESS', "alt": True},+ {"properties":+ [("mode", 'VALUE'),+ ("value", 0.0),+ ],+ },+ ),+ ("paint.mask_flood_fill",+ {"type": 'I', "value": 'PRESS', "oskey": True},+ {"properties":+ [("mode", 'INVERT'),+ ],+ },+ ),+ ("sculpt.dyntopo_detail_size_edit", {"type": 'R', "value": 'PRESS'}, None),+ ("wm.context_menu_enum",+ {"type": 'E', "value": 'PRESS', "alt": True},+ {"properties":+ [("data_path", 'tool_settings.sculpt.brush.stroke_method'),+ ],+ },+ ),+ ],+ },+ ),+ ]+++if __name__ == "__main__":+ # Only add keywords that are supported.+ from bpy.app import version as blender_version+ keywords = {}+ if blender_version >= (2, 92, 0):+ keywords["keyconfig_version"] = keyconfig_version+ import os+ from bl_keymap_utils.io import keyconfig_import_from_data+ keyconfig_import_from_data(+ os.path.splitext(os.path.basename(__file__))[0],+ keyconfig_data,+ **keywords,+ )diff --git a/tests/test_blender_keymap.cpp b/tests/test_blender_keymap.cppnew file mode 100644index 00000000..ac761bcf--- /dev/null+++ b/tests/test_blender_keymap.cpp@@ -0,0 +1,94 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Reading a keymap exported from Blender (src/app/BlenderKeymap.cpp) and the numpad chords it needs.+#include "TestHarness.h"++#ifdef SF_TEST_ACTIONS+#include "app/BlenderKeymap.h"++#include <fstream>+#include <iterator>++using namespace sf;++namespace {++std::string readFile(const std::string& path) {+ std::ifstream f(path, std::ios::binary);+ return std::string(std::istreambuf_iterator<char>(f), {});+}++std::string keysOf(const BlenderKeymap& k, const std::string& action) {+ std::string out;+ for (const auto& b : k.bindings)+ if (b.action == action) out += (out.empty() ? "" : " / ") + chordText(b.chord);+ return out;+}++} // namespace++TEST(numpad_chords_round_trip) {+ Chord c;+ CHECK(parseChord("Numpad 1", c) && c.key == SDLK_KP_1 && chordText(c) == "Numpad 1");+ CHECK(parseChord("Ctrl+Numpad 7", c) && c.key == SDLK_KP_7 && c.ctrl && chordText(c) == "Ctrl+Numpad 7");+ CHECK(parseChord("numpad0", c) && c.key == SDLK_KP_0);+ CHECK(parseChord("Numpad .", c) && c.key == SDLK_KP_PERIOD && chordText(c) == "Numpad .");+ CHECK(parseChord("Numpad Plus", c) && c.key == SDLK_KP_PLUS && chordText(c) == "Numpad Plus");+ CHECK(parseChord("Shift+Numpad Minus", c) && c.key == SDLK_KP_MINUS && c.shift);+ CHECK(parseChord("Home", c) && c.key == SDLK_HOME && chordText(c) == "Home");+ CHECK((chordKeys("Ctrl+Numpad 3") == std::vector<std::string>{"Ctrl", "Numpad 3"}));+ // The number row and the numpad are different keys.+ Chord row;+ CHECK(parseChord("1", row) && parseChord("Numpad 1", c) && !(row == c));+ // An import adds a second key without dropping the first.+ ActionRegistry reg;+ reg.add({"view.front", "Front", nullptr, "", "Transform", "Numpad 1", "", [] {}, nullptr, nullptr});+ reg.assignShortcut("view.front", "Alt+F", true);+ CHECK(reg.shortcutText("view.front") == "Alt+F / Numpad 1");+}++TEST(blender_keymap_export_is_read_as_text) {+ BlenderKeymap k;+ std::string err;+ CHECK(parseBlenderKeymap(readFile(SF_TEST_DATA_DIR "/blender_keymap_export.py"), k, err));+ CHECK(err.empty());+ CHECK(keysOf(k, "brush.standard") == "D");+ CHECK(keysOf(k, "brush.claybuildup") == "Shift+Q"); // a 4.3+ brush asset+ CHECK(keysOf(k, "brush.crease") == "Shift+C");+ CHECK(keysOf(k, "brush.snakehook").empty()); // switched off in Blender ("active": False)+ CHECK(keysOf(k, "ui.size_popup") == "F");+ CHECK(keysOf(k, "ui.strength_popup") == "Shift+R");+ CHECK(keysOf(k, "mask.clear") == "Alt+M");+ CHECK(keysOf(k, "mask.invert") == "Ctrl+I"); // Cmd+I on a Mac+ CHECK(keysOf(k, "geometry.lower_res") == "Alt+1");+ // Sculpt mode's keys win over the 3D View's: Alt+1 and Shift+C stay with Sculpt mode.+ CHECK(keysOf(k, "view.front") == "Numpad 1"); // not the Shift (align to active) one either+ CHECK(keysOf(k, "view.frame") == "Home");+ CHECK(keysOf(k, "view.bottom") == "Ctrl+Numpad 7");+ CHECK(keysOf(k, "view.ortho") == "\\");+ CHECK(keysOf(k, "view.opposite") == "Numpad 9");+ // Read: the keyboard items of the 3D View and Sculpt keymaps (not the mouse, the modal map or Object Mode).+ CHECK(k.items == 19); // 9 in the 3D View (Numpad 1, Alt+1, Shift+Numpad 1, Ctrl+Numpad 7, \\, Home, Shift+C, 9, /), 10 in Sculpt+ // Skipped: Alt+1 front and Shift+C view all (shadowed), Shift+Numpad 1, local view, detail size, Alt+E menu.+ CHECK(k.skipped == 6);+ CHECK(k.bindings.size() == 13);+}++TEST(blender_keymap_rejects_other_text) {+ BlenderKeymap k;+ std::string err;+ CHECK(!parseBlenderKeymap("import os\nos.system('echo hi')\n", k, err) && !err.empty());+ err.clear();+ CHECK(!parseBlenderKeymap("keyconfig_data = []\n", k, err) && !err.empty()); // nothing SculptForge reads+ // Malformed tuples are skipped, not guessed at: an unterminated dict, a nested call, a missing comma.+ const char* odd = "keyconfig_data = [(\"Sculpt\", {\"space_type\": 'EMPTY', \"region_type\": 'WINDOW'}, {\"items\": [\n"+ "(\"paint.brush_select\", {\"type\": 'X', \"value\": 'PRESS', {\"properties\": [(\"sculpt_tool\", 'DRAW')]}),\n"+ "(\"paint.brush_select\" {\"type\": 'Y', \"value\": 'PRESS'}, None),\n"+ "(\"paint.brush_select\", {\"type\": 'G', \"value\": 'PRESS'}, {\"properties\": [(\"sculpt_tool\", 'GRAB')]}),\n"+ "]})]\n";+ CHECK(parseBlenderKeymap(odd, k, err));+ CHECK(k.bindings.size() == 1 && k.bindings[0].action == "brush.move" && chordText(k.bindings[0].chord) == "G");+}++#endifdiff --git a/tests/test_camera.cpp b/tests/test_camera.cppindex 3ea404e5..e3d9e1ae 100644--- a/tests/test_camera.cpp+++ b/tests/test_camera.cpp@@ -78,3 +78,31 @@ TEST(camera_turntable_after_free_rotation_stands_upright) {// The view direction is kept (clamped short of straight up / down).if (std::abs(f.y) < 0.99f) CHECK(near(c.forward(), f, 1e-3f));}++TEST(camera_orthographic_matches_perspective_at_the_target) {+ // Numpad 5: the orthographic view is as tall as the perspective one at the target, rays are parallel, and a+ // pixel covers the same width at any depth.+ Camera c;+ c.distance = 5.0f;+ c.aspect = 1.5f;+ const float w = 900.0f, h = 600.0f;+ const float persp = c.worldPerPixel(c.target, h);+ c.ortho = true;+ CHECK(std::abs(c.worldPerPixel(c.target, h) - persp) < 1e-5f);+ CHECK(std::abs(c.worldPerPixel(c.target + glm::vec3(0, 0, -3), h) - persp) < 1e-5f);+ glm::vec3 o1, d1, o2, d2;+ c.screenRay(10.0f, 20.0f, w, h, o1, d1);+ c.screenRay(800.0f, 500.0f, w, h, o2, d2);+ CHECK(near(d1, d2) && near(d1, c.forward()));+ // The centre ray goes through the target; one pixel to the right lands one pixel's width to the right.+ glm::vec3 oc, dc, or_, dr;+ c.screenRay(w * 0.5f, h * 0.5f, w, h, oc, dc);+ c.screenRay(w * 0.5f + 1.0f, h * 0.5f, w, h, or_, dr);+ const glm::vec3 toTarget = c.target - oc;+ CHECK(glm::length(toTarget - dc * glm::dot(toTarget, dc)) < 1e-4f);+ CHECK(std::abs(glm::length(or_ - oc) - persp) < 1e-4f);+ // Zooming in never clips the model: the depth range reaches behind the eye.+ c.distance = 0.01f;+ const glm::vec4 p = c.projection() * c.view() * glm::vec4(0.0f, 0.0f, 1.0f, 1.0f); // in front of the target...+ CHECK(std::abs(p.z / p.w) <= 1.0f); // ...and behind the eye, still drawn+}diff --git a/tests/ui/blender_keys.sfui b/tests/ui/blender_keys.sfuinew file mode 100644index 00000000..f5e6b36b--- /dev/null+++ b/tests/ui/blender_keys.sfui@@ -0,0 +1,268 @@+# The Blender input style (#12): Preferences > Input > Blender, middle-drag navigation and Alt+left-drag for pens,+# the numpad views (orthographic until turned), Blender's sculpt-mode brush letters, F / Shift+F, Ctrl to invert,+# M for the Mask brush, H / Shift+H / Alt+H, Alt+1 / Alt+2, Emulate Numpad, the Controls window, a keymap+# exported from Blender, and back to the ZBrush style with its keys intact.+run new_sphere subdivisions=4+expect_value input_style == 0+expect_value shortcut_conflicts == 0+# The numpad views work in every style.+key numpad3+expect_value camera_yaw == 90+expect_value camera_ortho == 1+key f++# --- Preferences > Input: three styles ---+click "Preferences##palette.preferences"+click "Input##preferences.input"+hold ctrl+hover "Blender##input.style_blender"+expect_help "middle-drag orbits"+hold none+click "Blender##input.style_blender"+expect_value input_style == 2+expect_value turntable == 1+expect "Emulate Numpad"+shot preferences-input-blender+expect_value shortcut_conflicts == 0+expect_shortcut view.frame Home+expect_shortcut ui.size_popup F+expect_shortcut ui.strength_popup Shift+F / U+expect_shortcut view.wireframe Shift+Z+expect_shortcut ui.picker.material+key home++# --- Blender 4.2+ sculpt-mode brush letters (SculptForge's nearest brush) ---+key s+expect_value brush_type == 2+key p+expect_value brush_type == 7+key i+expect_value brush_type == 4+key g+expect_value brush_type == 3+key shift+t+expect_value brush_type == 6+key c+expect_value brush_type == 9+key shift+c+expect_value brush_type == 5+key k+expect_value brush_type == 10+key v+expect_value brush_type == 0+# S is Smooth now, not the Draw Size pop-up; F is the radius, Shift+F the strength.+mouse_move 0.5 0.5+key f+expect_text Draw Size+key escape+key shift+f+expect_text Z Intensity+key escape++# --- Sculpting: a plain drag adds, Ctrl+drag subtracts, Alt+drag navigates instead of sculpting ---+snapshot+stroke 0.3 0.5 0.7 0.5+expect_value moved_out > 0+key ctrl+z+snapshot+hold ctrl+stroke 0.3 0.5 0.7 0.5+hold none+expect_value moved_out < 0+key ctrl+z+snapshot+remember camera_yaw y0+hold alt+stroke 0.3 0.5 0.7 0.5+hold none+expect_value moved == 0+expect_value camera_yaw != $y0+remember camera_pan p0+hold alt+shift+stroke 0.3 0.5 0.7 0.5+hold none+expect_value moved == 0+expect_value camera_pan != $p0+key home++# --- The middle button: orbit, Shift pans, Ctrl zooms (up: in) ---+remember camera_yaw y1+button_drag middle 0.4 0.5 0.6 0.5+expect_value camera_yaw != $y1+expect_value camera_roll == 0+remember camera_pan p1+hold shift+button_drag middle 0.4 0.5 0.6 0.5+hold none+expect_value camera_pan != $p1+remember camera_distance d1+hold ctrl+button_drag middle 0.5 0.6 0.5 0.4+hold none+expect_value camera_distance < $d1+remember camera_distance d2+key numpadminus+expect_value camera_distance > $d2+key home++# --- The numpad: axis views (orthographic until turned), 5, 9, . ---+key numpad1+expect_value camera_yaw == 0+expect_value camera_pitch == 0+expect_value camera_ortho == 1+shot front-ortho+key ctrl+numpad1+expect_value camera_yaw == 180+key ctrl+numpad3+expect_value camera_yaw == -90+key numpad7+expect_value camera_pitch == -90+expect_value camera_aligned == 1+key ctrl+numpad7+expect_value camera_pitch == 90+key numpad1+key numpad6+expect_value camera_yaw > 14.99+expect_value camera_yaw < 15.01+expect_value camera_ortho == 0+key numpad5+expect_value camera_ortho == 1+button_drag middle 0.4 0.5 0.45 0.5+# Numpad 5 chose orthographic: turning keeps it.+expect_value camera_ortho == 1+key numpad5+expect_value camera_ortho == 0+key numpad1+key numpad9+expect_value camera_aligned == 1+expect_value camera_ortho == 1+key numpad.+key home++# --- M: the Mask brush (a drag masks, Ctrl+drag unmasks; M again goes back), Alt+M clears, Ctrl+I inverts ---+key m+expect_value mask_brush == 1+stroke 0.2 0.5 0.8 0.5+expect_value masked > 100+remember masked m1+shot mask-brush+hold ctrl+stroke 0.4 0.5 0.6 0.5+hold none+expect_value masked < $m1+key m+expect_value mask_brush == 0+expect_value brush_type == 0+key alt+m+expect_value masked == 0+key ctrl+i+expect_value masked > 1000+key alt+m+# Picking another brush ends the Mask brush too.+key m+key s+expect_value mask_brush == 0++# --- H hides the polygroup under the cursor, Shift+H shows only it, Alt+H shows everything ---+key v+key m+stroke 0.0 0.3 1.0 0.3+key m+key ctrl+w+expect_value groups == 2+mouse_move 0.5 0.3+key h+expect_value hidden > 0+key alt+h+expect_value hidden == 0+mouse_move 0.5 0.3+key shift+h+expect_value hidden > 0+mouse_move 0.5 0.3+key shift+h+expect_value hidden == 0++# --- Alt+1 / Alt+2 step the subdivision levels; X swaps the colours; Shift+Z wireframe ---+run subdiv_divide+expect_value sdiv == 2+key alt+1+expect_value sdiv == 1+key alt+2+expect_value sdiv == 2+remember paint_r r0+key x+expect_value paint_r != $r0+key x+expect_value wireframe == 0+key shift+z+expect_value wireframe == 1+key shift+z++# --- Emulate Numpad: the number row works as the numpad ---+click "Preferences##palette.preferences"+click "Emulate Numpad"+key 3+expect_value camera_yaw == 90+key 7+expect_value camera_pitch == -90+click "Emulate Numpad"+key 1+expect_value camera_pitch == -90+key home++# --- Controls (F1): the style row, the import button and Blender's gestures ---+key f1+expect "Blender##input.style_blender"+expect "Import Blender keymap...##input.import_blender"+expect_text Front view+click "Mouse & pen"+expect_text Middle drag+shot controls-blender+# The style row in Controls switches too.+click "ZBrush##input.style_zbrush"+expect_value input_style == 0+expect_text Alt + click it+key f1++# --- A keymap exported from Blender: read as text, its sculpt keys win over the 3D View's ---+run blender_keymap_import path=$SCRIPT_DIR/../data/blender_keymap_export.py+expect_status Blender keymap: 13 keys+expect_value input_style == 2+expect_shortcut brush.standard D+expect_shortcut geometry.higher_res Alt+2+expect_shortcut brush.claybuildup Shift+Q+expect_shortcut ui.strength_popup Shift+R+expect_shortcut view.ortho \+expect_shortcut view.front Numpad 1+expect_value shortcut_conflicts == 0+key d+expect_value brush_type == 0+key shift+q+expect_value brush_type == 9++# --- Back to ZBrush: its keys and gestures are as they were (the imported keys stay until Restore Standard UI) ---+click "Preferences##palette.preferences"+click "Config##preferences.config"+click "Restore Standard UI##config.restore_standard"+expect_value shortcut_conflicts == 0+expect_shortcut brush.standard V+key f1+click "ZBrush##input.style_zbrush"+key f1+expect_value input_style == 0+expect_value shortcut_conflicts == 0+expect_shortcut ui.size_popup S+expect_shortcut view.frame F+expect_shortcut brush.standard+mouse_move 0.5 0.5+key s+expect_text Draw Size+key escape+key b+key s+key t+snapshot+hold alt+stroke 0.3 0.5 0.7 0.5+hold none+expect_value moved_out < 0diff --git a/tests/ui/whats_new.sfui b/tests/ui/whats_new.sfuiindex 5684911a..5e066a75 100644--- a/tests/ui/whats_new.sfui+++ b/tests/ui/whats_new.sfui@@ -4,6 +4,8 @@ click "Help##palette.help"click "What's New##help.whats_new"expect_value guide_open == 1expect_guide whats-new.md+expect_text "Next version"+expect_text "Blender keys"expect_text "Version 0.9.4"expect_text "Version 0.9.3"expect_text "Version 0.9.2"