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
Radial menus core: menus, slot geometry and strict JSON (#45)
islandmed0b1ebdd5c002
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 85467228..562d08b1 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -111,6 +111,7 @@ add_library(sculptforge_core STATICsrc/core/Guide.cppsrc/core/UpdateCheck.cppsrc/core/Tablet.cpp+ src/core/RadialMenu.cppsrc/core/SpaceMouse.cppsrc/io/ObjIO.cppsrc/io/FbxIO.cppdiff --git a/src/core/RadialMenu.cpp b/src/core/RadialMenu.cppnew file mode 100644index 00000000..e5f3bc5f--- /dev/null+++ b/src/core/RadialMenu.cpp@@ -0,0 +1,216 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/RadialMenu.h"++#include <algorithm>+#include <cmath>+#include <cstdint>++namespace sf {++namespace {++constexpr const char* kFormat = "sculptforge-radial-menu";+constexpr float kTwoPi = 6.28318530717958647692f;++struct ButtonName {+ const char* id;+ const char* label;+};+constexpr ButtonName kButtons[int(RadialButton::Count)] = {+ {"none", "None"},+ {"mouse_middle", "Middle mouse button"},+ {"mouse_back", "Mouse back button"},+ {"mouse_forward", "Mouse forward button"},+ {"pen_lower", "Pen lower button"},+ {"pen_upper", "Pen upper button"},+ {"pen_third", "Pen third button"},+};++// An id from a file: a string of sensible length the vocabulary knows, or "".+std::string knownId(const Json& j, const std::function<bool(std::string_view)>& known) {+ if (!j.isString()) return {};+ const std::string& s = j.asString();+ if (s.empty() || s.size() > kRadialIdMax || !known || !known(s)) return {};+ return s;+}++} // namespace++const char* radialButtonId(RadialButton b) {+ const int i = int(b);+ return i >= 0 && i < int(RadialButton::Count) ? kButtons[i].id : "none";+}++const char* radialButtonLabel(RadialButton b) {+ const int i = int(b);+ return i >= 0 && i < int(RadialButton::Count) ? kButtons[i].label : "None";+}++RadialButton radialButtonFromId(std::string_view id) {+ for (int i = 0; i < int(RadialButton::Count); ++i)+ if (id == kButtons[i].id) return RadialButton(i);+ return RadialButton::None;+}++int radialSlotAt(float dx, float dy, int count, float deadZone) {+ if (count <= 0 || !std::isfinite(dx) || !std::isfinite(dy)) return -1;+ if (dx * dx + dy * dy <= deadZone * deadZone) return -1;+ // Clockwise from straight up (screen y points down).+ float a = std::atan2(dx, -dy);+ if (a < 0.0f) a += kTwoPi;+ const float wedge = kTwoPi / float(count);+ const int slot = int(std::floor((a + wedge * 0.5f) / wedge));+ return ((slot % count) + count) % count;+}++void radialSlotDirection(int slot, int count, float& x, float& y) {+ const float a = count > 0 ? kTwoPi * float(slot) / float(count) : 0.0f;+ x = std::sin(a);+ y = -std::cos(a);+}++std::string radialCleanText(std::string_view text, size_t maxBytes) {+ std::string out;+ size_t i = 0;+ while (i < text.size()) {+ const auto c = uint8_t(text[i]);+ size_t len = 0;+ if (c < 0x80) len = 1;+ else if (c >= 0xC2 && c <= 0xDF) len = 2;+ else if (c >= 0xE0 && c <= 0xEF) len = 3;+ else if (c >= 0xF0 && c <= 0xF4) len = 4;+ if (len == 0 || i + len > text.size()) { // a stray continuation byte, a bad lead byte, a cut-off sequence+ ++i;+ continue;+ }+ bool valid = true;+ for (size_t k = 1; k < len; ++k) valid = valid && (uint8_t(text[i + k]) & 0xC0) == 0x80;+ if (valid && len == 3) { // no overlong forms, no UTF-16 surrogates+ const auto c1 = uint8_t(text[i + 1]);+ valid = !(c == 0xE0 && c1 < 0xA0) && !(c == 0xED && c1 >= 0xA0);+ } else if (valid && len == 4) {+ const auto c1 = uint8_t(text[i + 1]);+ valid = !(c == 0xF0 && c1 < 0x90) && !(c == 0xF4 && c1 >= 0x90);+ }+ if (!valid) {+ ++i;+ continue;+ }+ if (len == 1 && (c < 0x20 || c == 0x7F)) { // control characters (newlines, tabs, escapes)+ ++i;+ continue;+ }+ if (out.size() + len > maxBytes) break;+ out.append(text.substr(i, len));+ i += len;+ }+ return out;+}++Json toJson(const RadialMenu& menu) {+ Json j = Json::object();+ j.set("name", menu.name);+ j.set("button", std::string(radialButtonId(menu.button)));+ Json slots = Json::array();+ for (const RadialSlot& s : menu.slots) {+ Json slot = Json::object();+ slot.set("action", s.action);+ if (!s.label.empty()) slot.set("label", s.label);+ if (!s.icon.empty()) slot.set("icon", s.icon);+ slots.push(std::move(slot));+ }+ j.set("slots", std::move(slots));+ return j;+}++Json toJson(const std::vector<RadialMenu>& menus) {+ Json j = Json::array();+ for (const RadialMenu& m : menus) j.push(toJson(m));+ return j;+}++bool radialMenuFromJson(const Json& j, const RadialVocabulary& vocab, RadialMenu& menu, int* dropped) {+ if (!j.isObject()) return false;+ int lost = 0;+ menu = RadialMenu();+ if (j["name"].isString()) menu.name = radialCleanText(j["name"].asString(), kRadialNameMax);+ if (j["button"].isString() && j["button"].asString().size() <= kRadialIdMax)+ menu.button = radialButtonFromId(j["button"].asString());+ const Json& slots = j["slots"];+ if (slots.isArray()) {+ const std::vector<Json>& items = slots.items();+ for (size_t i = 0; i < items.size(); ++i) {+ if (menu.slots.size() == size_t(kRadialSlots)) { // the rest don't fit+ lost += int(std::min<size_t>(items.size() - i, 1u << 20));+ break;+ }+ const Json& item = items[i];+ if (!item.isObject()) {+ ++lost;+ continue;+ }+ RadialSlot slot;+ slot.action = knownId(item["action"], vocab.action);+ if (slot.action.empty()) {+ ++lost;+ continue;+ }+ if (item["label"].isString()) slot.label = radialCleanText(item["label"].asString(), kRadialLabelMax);+ slot.icon = knownId(item["icon"], vocab.icon);+ if (slot.icon.empty() && item["icon"].isString() && !item["icon"].asString().empty()) ++lost;+ menu.slots.push_back(std::move(slot));+ }+ } else if (!slots.isNull()) {+ ++lost;+ }+ if (dropped) *dropped += lost;+ return true;+}++std::vector<RadialMenu> radialMenusFromJson(const Json& j, const RadialVocabulary& vocab, int* dropped) {+ std::vector<RadialMenu> menus;+ if (!j.isArray()) return menus;+ int lost = 0;+ const std::vector<Json>& items = j.items();+ for (size_t i = 0; i < items.size(); ++i) {+ if (menus.size() == size_t(kRadialMenus)) {+ lost += int(std::min<size_t>(items.size() - i, 1u << 20));+ break;+ }+ RadialMenu m;+ if (radialMenuFromJson(items[i], vocab, m, &lost)) menus.push_back(std::move(m));+ else ++lost;+ }+ if (dropped) *dropped += lost;+ return menus;+}++std::string radialMenuFileText(const RadialMenu& menu) {+ Json j = Json::object();+ j.set("format", kFormat);+ j.set("version", 1);+ j.set("menu", toJson(menu));+ return j.dump(true) + "\n";+}++bool parseRadialMenuFile(const std::string& text, const RadialVocabulary& vocab, RadialMenu& menu, std::string& error,+ int* dropped) {+ if (text.size() > kRadialFileMax) {+ error = "That file is too big for a radial menu";+ return false;+ }+ Json j;+ if (!Json::parse(text, j, error)) return false;+ if (!j.isObject() || !j["format"].isString() || j["format"].asString() != kFormat) {+ error = "Not a SculptForge radial menu file";+ return false;+ }+ if (!radialMenuFromJson(j["menu"], vocab, menu, dropped)) {+ error = "The file has no menu in it";+ return false;+ }+ return true;+}++} // namespace sfdiff --git a/src/core/RadialMenu.h b/src/core/RadialMenu.hnew file mode 100644index 00000000..3fa9c7ef--- /dev/null+++ b/src/core/RadialMenu.h@@ -0,0 +1,77 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Radial (pie) menus (#45), independent of SDL and ImGui so they can be unit tested: the menus a user defines+// (up to kRadialMenus, each with up to kRadialSlots), which slot a flick points at, and their JSON in ui.json+// and in an exported menu file. A slot only names an action id from the action registry; nothing in a menu+// is ever run as code. Reading is strict: unknown actions and icons are dropped, counts and string lengths are+// capped, wrong types fall back to defaults. The app side (opening, drawing, Preferences > Input > Radial Menus)+// is src/app/RadialMenu.cpp.+#pragma once++#include "core/Json.h"++#include <functional>+#include <string>+#include <string_view>+#include <vector>++namespace sf {++constexpr int kRadialMenus = 8; // menus a user can define+constexpr int kRadialSlots = 8; // slots in one menu+constexpr size_t kRadialNameMax = 32; // bytes in a menu's name+constexpr size_t kRadialLabelMax = 32; // bytes in a slot's label+constexpr size_t kRadialIdMax = 96; // bytes in an action or icon id (longer ones are never real ids)+constexpr size_t kRadialFileMax = 64 * 1024; // an imported menu file larger than this is refused unread++// What opens a menu besides its key: a mouse button or a pen side button, held like the key.+enum class RadialButton { None, MouseMiddle, MouseBack, MouseForward, PenLower, PenUpper, PenThird, Count };+const char* radialButtonId(RadialButton b); // "mouse_middle" ... (stored in ui.json)+const char* radialButtonLabel(RadialButton b); // "Middle mouse button" ... (Preferences > Input > Radial Menus)+RadialButton radialButtonFromId(std::string_view id); // unknown: None++struct RadialSlot {+ std::string action; // ActionRegistry id: "brush.clay", "mask.invert"+ std::string label; // "" = the action's own label+ std::string icon; // a name from the app's icon list; "" = the action's own icon+};++struct RadialMenu {+ std::string name;+ std::vector<RadialSlot> slots; // at most kRadialSlots; slot 0 points up, the rest go clockwise+ RadialButton button = RadialButton::None;+};++// Which slot the pointer at (dx, dy) from the menu's centre points at (screen coordinates, y down), for a menu of+// COUNT slots: slot 0 is centred straight up and the others follow clockwise, each owning an equal wedge. -1 when+// the pointer is within DEADZONE pixels of the centre (or there are no slots).+int radialSlotAt(float dx, float dy, int count, float deadZone);+// The unit direction (screen coordinates, y down) of slot SLOT's centre in a menu of COUNT slots.+void radialSlotDirection(int slot, int count, float& x, float& y);++// What a reader may accept (the app checks against its action registry and icon list).+struct RadialVocabulary {+ std::function<bool(std::string_view)> action; // a known action that a slot may run+ std::function<bool(std::string_view)> icon; // a known icon name+};++// A string from a file, made safe to show: control characters dropped, cut to MAXBYTES without splitting a UTF-8+// sequence (invalid UTF-8 bytes are dropped too).+std::string radialCleanText(std::string_view text, size_t maxBytes);++Json toJson(const RadialMenu& menu);+Json toJson(const std::vector<RadialMenu>& menus);+// One menu. False when J isn't a menu object at all; otherwise MENU holds what was valid and DROPPED counts the+// slots (and the icons) that were not.+bool radialMenuFromJson(const Json& j, const RadialVocabulary& vocab, RadialMenu& menu, int* dropped = nullptr);+// The menus array of ui.json: at most kRadialMenus menus; anything else in J is ignored.+std::vector<RadialMenu> radialMenusFromJson(const Json& j, const RadialVocabulary& vocab, int* dropped = nullptr);++// An exported menu file: {"format": "sculptforge-radial-menu", "version": 1, "menu": {...}}.+std::string radialMenuFileText(const RadialMenu& menu);+// Reads TEXT (the whole file) as an exported menu; false with ERROR when it isn't one.+bool parseRadialMenuFile(const std::string& text, const RadialVocabulary& vocab, RadialMenu& menu, std::string& error,+ int* dropped = nullptr);++} // namespace sfdiff --git a/tests/test_radial_menu.cpp b/tests/test_radial_menu.cppnew file mode 100644index 00000000..86b43da7--- /dev/null+++ b/tests/test_radial_menu.cpp@@ -0,0 +1,204 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Radial menus (#45): the slot a flick points at (wedges, the dead zone) and the strict JSON reading of ui.json+// and exported menu files, including hostile input (huge arrays, unknown ids, long strings, wrong types).+#include "TestHarness.h"++#include "core/RadialMenu.h"++#include <cmath>+#include <string>++using namespace sf;++namespace {++RadialVocabulary vocab() {+ RadialVocabulary v;+ v.action = [](std::string_view id) { return id == "brush.clay" || id == "brush.move" || id == "mask.invert"; };+ v.icon = [](std::string_view id) { return id == "brush" || id == "eraser"; };+ return v;+}++bool validUtf8(const std::string& s) { return radialCleanText(s, s.size() + 1) == s; }++} // namespace++TEST(radial_slot_dead_zone) {+ CHECK(radialSlotAt(0.0f, 0.0f, 8, 20.0f) == -1);+ CHECK(radialSlotAt(10.0f, -10.0f, 8, 20.0f) == -1); // 14 px out: still inside+ CHECK(radialSlotAt(0.0f, -21.0f, 8, 20.0f) == 0);+ CHECK(radialSlotAt(0.0f, -100.0f, 0, 20.0f) == -1); // no slots+ CHECK(radialSlotAt(NAN, 50.0f, 8, 20.0f) == -1);+ CHECK(radialSlotAt(INFINITY, 0.0f, 8, 20.0f) == -1);+}++TEST(radial_slot_from_angle) {+ // Eight slots: 0 up, then clockwise (screen y points down).+ CHECK(radialSlotAt(0.0f, -100.0f, 8, 10.0f) == 0);+ CHECK(radialSlotAt(70.0f, -70.0f, 8, 10.0f) == 1);+ CHECK(radialSlotAt(100.0f, 0.0f, 8, 10.0f) == 2);+ CHECK(radialSlotAt(70.0f, 70.0f, 8, 10.0f) == 3);+ CHECK(radialSlotAt(0.0f, 100.0f, 8, 10.0f) == 4);+ CHECK(radialSlotAt(-70.0f, 70.0f, 8, 10.0f) == 5);+ CHECK(radialSlotAt(-100.0f, 0.0f, 8, 10.0f) == 6);+ CHECK(radialSlotAt(-70.0f, -70.0f, 8, 10.0f) == 7);+ // Wedges are centred on their slot: just either side of straight up is still slot 0 (not 7 or 1).+ CHECK(radialSlotAt(-15.0f, -100.0f, 8, 10.0f) == 0);+ CHECK(radialSlotAt(15.0f, -100.0f, 8, 10.0f) == 0);+ // Fewer slots: wider wedges. Two slots split top and bottom; four make a cross.+ CHECK(radialSlotAt(90.0f, -10.0f, 2, 10.0f) == 0);+ CHECK(radialSlotAt(90.0f, 10.0f, 2, 10.0f) == 1);+ CHECK(radialSlotAt(100.0f, 20.0f, 4, 10.0f) == 1);+ CHECK(radialSlotAt(-20.0f, 100.0f, 4, 10.0f) == 2);+ CHECK(radialSlotAt(5.0f, 100.0f, 1, 10.0f) == 0); // one slot owns every direction+ // Every slot's own direction picks that slot, for every menu size.+ for (int count = 1; count <= kRadialSlots; ++count)+ for (int slot = 0; slot < count; ++slot) {+ float x = 0.0f, y = 0.0f;+ radialSlotDirection(slot, count, x, y);+ CHECK(std::abs(x * x + y * y - 1.0f) < 1e-4f);+ CHECK(radialSlotAt(x * 80.0f, y * 80.0f, count, 20.0f) == slot);+ }+}++TEST(radial_json_round_trip) {+ RadialMenu m;+ m.name = "Brushes";+ m.button = RadialButton::PenUpper;+ m.slots = {{"brush.clay", "Clay", "brush"}, {"mask.invert", "", ""}};+ RadialMenu back;+ int dropped = 0;+ CHECK(radialMenuFromJson(toJson(m), vocab(), back, &dropped));+ CHECK(dropped == 0);+ CHECK(back.name == "Brushes");+ CHECK(back.button == RadialButton::PenUpper);+ CHECK(back.slots.size() == 2);+ CHECK(back.slots[0].action == "brush.clay" && back.slots[0].label == "Clay" && back.slots[0].icon == "brush");+ CHECK(back.slots[1].action == "mask.invert" && back.slots[1].label.empty() && back.slots[1].icon.empty());++ // A whole file, and the menus array of ui.json.+ RadialMenu fromFile;+ std::string err;+ CHECK(parseRadialMenuFile(radialMenuFileText(m), vocab(), fromFile, err));+ CHECK(fromFile.slots.size() == 2 && fromFile.name == "Brushes");+ const std::vector<RadialMenu> menus = radialMenusFromJson(toJson(std::vector<RadialMenu>{m, m}), vocab());+ CHECK(menus.size() == 2);+ for (int b = 0; b < int(RadialButton::Count); ++b)+ CHECK(radialButtonFromId(radialButtonId(RadialButton(b))) == RadialButton(b));+}++TEST(radial_json_drops_unknown_and_wrong_types) {+ Json j;+ std::string err;+ CHECK(Json::parse(R"({"name": 42, "button": "launch_missiles", "slots": [+ {"action": "brush.clay"},+ {"action": "cmd.run_script", "label": "evil"},+ {"action": "brush.move", "icon": "../../etc/passwd"},+ {"action": ["brush.clay"]},+ "brush.clay",+ 17, null, true,+ {"label": "no action"},+ {"action": "mask.invert", "label": {"x": 1}, "icon": 5}+ ]})", j, err));+ RadialMenu m;+ int dropped = 0;+ CHECK(radialMenuFromJson(j, vocab(), m, &dropped));+ CHECK(m.name.empty()); // not a string: no name+ CHECK(m.button == RadialButton::None); // unknown button+ CHECK(m.slots.size() == 3);+ CHECK(m.slots[0].action == "brush.clay");+ CHECK(m.slots[1].action == "brush.move" && m.slots[1].icon.empty()); // unknown icon dropped, slot kept+ CHECK(m.slots[2].action == "mask.invert" && m.slots[2].label.empty() && m.slots[2].icon.empty());+ CHECK(dropped == 8); // 7 slots and 1 icon++ // Not a menu at all.+ CHECK(!radialMenuFromJson(Json(3.0), vocab(), m));+ CHECK(!radialMenuFromJson(Json::array(), vocab(), m));+ CHECK(radialMenusFromJson(Json("menus"), vocab()).empty());+ Json slotsObject;+ CHECK(Json::parse(R"({"name": "x", "slots": {"action": "brush.clay"}})", slotsObject, err));+ dropped = 0;+ CHECK(radialMenuFromJson(slotsObject, vocab(), m, &dropped));+ CHECK(m.slots.empty() && dropped == 1);+}++TEST(radial_json_caps_counts) {+ // A huge array of slots and of menus: only the caps are kept, the rest counted as dropped.+ std::string text = R"({"name": "big", "slots": [)";+ for (int i = 0; i < 100000; ++i) text += std::string(i ? "," : "") + R"({"action": "brush.clay"})";+ text += "]}";+ Json j;+ std::string err;+ CHECK(Json::parse(text, j, err));+ RadialMenu m;+ int dropped = 0;+ CHECK(radialMenuFromJson(j, vocab(), m, &dropped));+ CHECK(m.slots.size() == size_t(kRadialSlots));+ CHECK(dropped == 100000 - kRadialSlots);++ Json menus = Json::array();+ for (int i = 0; i < 50; ++i) menus.push(j);+ dropped = 0;+ const std::vector<RadialMenu> all = radialMenusFromJson(menus, vocab(), &dropped);+ CHECK(all.size() == size_t(kRadialMenus));+ for (const RadialMenu& menu : all) CHECK(menu.slots.size() == size_t(kRadialSlots));+ CHECK(dropped > 0);++ // A file over the size cap is refused before parsing.+ RadialMenu fromFile;+ CHECK(!parseRadialMenuFile(std::string(kRadialFileMax + 1, ' '), vocab(), fromFile, err));+ CHECK(!err.empty());+}++TEST(radial_json_long_and_odd_strings) {+ RadialMenu m;+ m.name = std::string(10000, 'N');+ m.slots = {{"brush.clay", std::string(5000, 'L'), ""}};+ RadialMenu back;+ CHECK(radialMenuFromJson(toJson(m), vocab(), back));+ CHECK(back.name.size() == kRadialNameMax);+ CHECK(back.slots.size() == 1 && back.slots[0].label.size() == kRadialLabelMax);++ // A very long action id is never looked up (and isn't one).+ Json j = Json::object();+ Json slots = Json::array();+ Json slot = Json::object();+ slot.set("action", "brush.clay" + std::string(kRadialIdMax, 'x'));+ slots.push(slot);+ j.set("slots", slots);+ int dropped = 0;+ CHECK(radialMenuFromJson(j, vocab(), back, &dropped));+ CHECK(back.slots.empty() && dropped == 1);++ // Control characters go; UTF-8 is cut on a character boundary; broken UTF-8 is dropped.+ CHECK(radialCleanText("a\nb\tc\x1b[31md\x7f", 32) == "abc[31md");+ const std::string accents = "\xC3\xA9\xC3\xA9\xC3\xA9"; // three e-acute, 2 bytes each+ CHECK(radialCleanText(accents, 5) == "\xC3\xA9\xC3\xA9");+ CHECK(radialCleanText("\xF0\x9F\x8E\xA8 art", 3).empty()); // a 4-byte emoji doesn't fit in 3+ CHECK(radialCleanText("ok\xC3", 32) == "ok"); // cut-off sequence+ CHECK(radialCleanText("\x80\xBFok\xFF", 32) == "ok"); // stray continuation and invalid bytes+ CHECK(radialCleanText("\xED\xA0\x80x", 32) == "x"); // a UTF-16 surrogate+ CHECK(radialCleanText("\xC0\xAFx", 32) == "x"); // an overlong '/'+ std::string junk;+ for (int i = 0; i < 4096; ++i) junk += char((i * 37) & 0xFF);+ const std::string cleaned = radialCleanText(junk, kRadialLabelMax);+ CHECK(cleaned.size() <= kRadialLabelMax);+ CHECK(validUtf8(cleaned));+}++TEST(radial_menu_file_rejects_other_json) {+ RadialMenu m;+ std::string err;+ CHECK(!parseRadialMenuFile("not json", vocab(), m, err));+ CHECK(!parseRadialMenuFile("[1, 2, 3]", vocab(), m, err));+ CHECK(!parseRadialMenuFile(R"({"layout": {}, "prefs": {}})", vocab(), m, err)); // a UI layout, not a menu+ CHECK(!parseRadialMenuFile(R"({"format": "sculptforge-radial-menu", "menu": "x"})", vocab(), m, err));+ std::string deep;+ for (int i = 0; i < 100000; ++i) deep += '[';+ CHECK(!parseRadialMenuFile(deep, vocab(), m, err)); // over the size cap (and too deep anyway)+ std::string nested = R"({"format": "sculptforge-radial-menu", "menu": {"name": "n", "slots": )";+ for (int i = 0; i < 1000; ++i) nested += '[';+ CHECK(!parseRadialMenuFile(nested, vocab(), m, err)); // nesting refused by the parser+}