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
Persistent brush library, brush codes and brush sharing
islandmed8527e6ff2f59
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ec5e44f..f90c1246 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,20 @@ All notable changes to SculptForge are listed here. The format follows- OBJ import: `g` groups now become polygroups (as ZBrush writes them) and `o` objects become SubTools.- New cube primitive.+### Brush library and sharing+- Custom brushes persist: Brush Lab saves every brush made or refined there to your brush library (a moment+ after the last change), and it loads at every start in the app, `sculptforge-cli` and Python.+- Brush codes: right-click a brush > Copy brush code gives one line of text (`sfbrush1:...`) to share in chat+ or a forum. Ctrl+V in the viewport, or Paste brush in Brush Lab, installs a pasted code or `.sfbrush` text.+ Dropping or opening a `.sfbrush` file installs it too.+- The Custom brushes list shows where each brush comes from (studio, gallery, project, unsaved, or `yours` when+ your version replaces a built-in or studio brush) and has a right-click menu: copy code, save, rename,+ delete (with confirmation), reveal in folder.+- Studio brush folders: list read-only shared folders in `SCULPTFORGE_BRUSH_PATH`; the Rez package adds+ `SCULPTFORGE_STUDIO_BRUSHES` when set. Precedence: yours > studio > built-in.+- New commands `brush_install`, `brush_code`, `brush_delete`, `brush_rename` and `brush_library`;+ `brush_list` shows each brush's source.+### Fixed- Side panels (Brush Lab, Tools, Generate 3D...) never grow past the bottom of the window. They move upand scroll instead, so expanded sections such as AI provider are always reachable.diff --git a/CMakeLists.txt b/CMakeLists.txtindex 4e157fb6..8c6bfc21 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -38,6 +38,7 @@ add_library(sculptforge_core STATICsrc/core/Script.cppsrc/core/Json.cppsrc/core/BrushRecipe.cpp+ src/core/BrushLibrary.cppsrc/core/Image.cppsrc/core/ImageTo3D.cppsrc/core/Splats.cpp@@ -120,6 +121,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/PanelMasking.cppsrc/app/PanelPolygroups.cppsrc/app/PanelBrushes.cpp+ src/app/PanelBrushLibrary.cppsrc/app/PanelPolypaint.cppsrc/app/PanelGoz.cppsrc/app/PanelProject.cppdiff --git a/README.md b/README.mdindex 6d4cd8d3..fe7a4b19 100644--- a/README.md+++ b/README.md@@ -83,7 +83,8 @@ keep polygroups, mask and polypaint) or as OBJ, FBX or GLB.**Free built-in AI: Brush Lab (describe a brush, AI builds it)**- "Dry cracked mud", "overlapping dragon scales", then "make it sharper". Brushes are recipes (data, never- code), with every value exposed as a slider. Share them as `.sfbrush` files.+ code), with every value exposed as a slider. They're kept in your brush library; share them as+ `.sfbrush` files or one-line brush codes (right-click > Copy brush code, Ctrl+V to paste one).- **Free out of the box**: no account or key. It uses an open model (GPT-OSS 20B) hosted by Pollinations.ai,and falls back to a local Ollama when you're offline.- Or bring your own: Claude (Anthropic API) or any OpenAI-compatible endpoint, including **private localdiff --git a/docs/studios.md b/docs/studios.mdindex 05024894..0bbefc9f 100644--- a/docs/studios.md+++ b/docs/studios.md@@ -38,6 +38,46 @@ rez-env sculptforge python-3.13 -- python -c "import sculptforge"```The package puts `bin/` on `PATH`, puts the Python module on `PYTHONPATH`, and sets `SCULPTFORGE_ROOT`.+If `SCULPTFORGE_STUDIO_BRUSHES` is set when the package resolves (in a site package, your rezconfig or the+launcher), it is appended to `SCULPTFORGE_BRUSH_PATH` (see below).++## Studio brush libraries++Artists' own brushes live in their user library, one `.sfbrush` file per brush: Brush Lab saves every brush+made or refined there automatically, and brushes installed from a file, a pasted brush code+(`sfbrush1:...`) or the community gallery go there too.++| OS | User library |+|---|---|+| Linux | `$XDG_DATA_HOME/SculptForge/SculptForge/brushes` (`~/.local/share/...` by default) |+| macOS | `~/Library/Application Support/SculptForge/SculptForge/brushes` |+| Windows | `%APPDATA%\SculptForge\SculptForge\brushes` |++To share a set of brushes across a team, put them on a share and list it in `SCULPTFORGE_BRUSH_PATH`+(`:`-separated, `;` on Windows). The app, `sculptforge-cli` and the Python module load these folders at start-up,+read-only: SculptForge never writes into them, so the share can be mounted read-only. Each brush shows where it+comes from (a `studio` tag in the Custom brushes list, `brush_library` from scripts).++```sh+export SCULPTFORGE_BRUSH_PATH=/studio/brushes:/show/troll/brushes+sculptforge-cli -c 'brush_library' # every brush, its source and file, plus the library folders+```++When brushes share a name, the artist's own wins over a studio one, which wins over a built-in; among studio+folders, the first one listed wins. Refining a studio brush in Brush Lab saves the artist's version (tagged+`yours`) without touching the share; deleting it brings the studio version back. Files that aren't valid+brushes are skipped with a message in the log.++Publishing to the share is copying `.sfbrush` files into it: save one from the app (right-click a brush >+Save .sfbrush...), take it from the user library, or turn a brush code into a file with+`sculptforge-cli -c 'brush_install code=sfbrush1:...'` on a machine whose user library you then copy from.++With Rez, set the share once for everyone:++```sh+export SCULPTFORGE_STUDIO_BRUSHES=/studio/brushes # e.g. in the studio's launcher environment+rez-env sculptforge -- sculptforge # SCULPTFORGE_BRUSH_PATH now includes /studio/brushes+```## Python APIdiff --git a/packaging/rez/package.py b/packaging/rez/package.pyindex 7104c152..71728dda 100644--- a/packaging/rez/package.py+++ b/packaging/rez/package.py@@ -24,3 +24,7 @@ def commands():env.PATH.prepend("{root}/bin")env.PYTHONPATH.prepend("{root}/python")env.SCULPTFORGE_ROOT = "{root}"+ # Optional studio brush library (read-only, see docs/studios.md): set SCULPTFORGE_STUDIO_BRUSHES to a shared+ # folder of .sfbrush files and every artist gets those brushes.+ if defined("SCULPTFORGE_STUDIO_BRUSHES"):+ env.SCULPTFORGE_BRUSH_PATH.append(getenv("SCULPTFORGE_STUDIO_BRUSHES"))diff --git a/src/ai/BrushAssistant.cpp b/src/ai/BrushAssistant.cppindex e4c4fd17..417e0b00 100644--- a/src/ai/BrushAssistant.cpp+++ b/src/ai/BrushAssistant.cpp@@ -3,6 +3,7 @@#include "ai/BrushAssistant.h"#include "ai/Http.h"+#include "core/BrushLibrary.h"#include <cstdlib>#include <filesystem>@@ -208,18 +209,11 @@ AiSettings AiSettings::load(const std::string& path) {}std::string defaultAiSettingsPath() {- auto env = [](const char* name) -> std::string {- const char* v = std::getenv(name);- return v ? v : "";- };+ const std::string dir = appDataDir(); // shared with the brush library (core/BrushLibrary.h)#if defined(_WIN32)- const std::string base = env("APPDATA");- return base.empty() ? "ai.json" : base + "\\SculptForge\\SculptForge\\ai.json";-#elif defined(__APPLE__)- return env("HOME") + "/Library/Application Support/SculptForge/SculptForge/ai.json";+ return dir.empty() ? "ai.json" : dir + "\\ai.json";#else- const std::string xdg = env("XDG_DATA_HOME");- return (xdg.empty() ? env("HOME") + "/.local/share" : xdg) + "/SculptForge/SculptForge/ai.json";+ return dir + "/ai.json";#endif}diff --git a/src/app/App.cpp b/src/app/App.cppindex 3b1f65ee..ddf2f7d6 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -9,6 +9,7 @@#include "ai/Generator3D.h"#include "core/EnginePresets.h"#include "link/UnrealLink.h"+#include "core/BrushLibrary.h"#include "core/Decimate.h"#include "core/ImageTo3D.h"#include "core/Project.h"@@ -197,6 +198,7 @@ bool App::init(const AppOptions& options) {ImGui_ImplOpenGL3_Init("#version 330 core");for (int i = 0; i < int(FileAction::Count); ++i) dialogRequests_[i] = {this, FileAction(i)};+ initBrushLibrary(); // before a project can bring its own brushesinitProject(); // before opening anything, so it lands in the recent filesrunCommand("new_sphere");if (!options.openPath.empty()) openPath(options.openPath);@@ -230,6 +232,7 @@ bool App::init(const AppOptions& options) {}void App::shutdown() {+ flushBrushEdits();if (refTexture_) gl::DeleteTextures(1, &refTexture_);ImGui_ImplOpenGL3_Shutdown();ImGui_ImplSDL3_Shutdown();@@ -595,6 +598,7 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {case SDLK_N: confirmDiscard([this] { runCommand("new_sphere"); }); break;case SDLK_E: saveFileDialog(FileAction::ExportGlb); break;case SDLK_U: sendToUnreal(); break;+ case SDLK_V: pasteBrush(); break; // a brush code or .sfbrush textdefault: break;}return;@@ -797,6 +801,7 @@ void App::endStroke() {void App::runCommand(const std::string& name, const Args& args) {if (doc_.sculptor.strokeActive()) endStroke();if (name == "save_project") storeProjectSettings();+ flushBrushEdits(); // commands may replace brushes: save edits first, then watch what's there afterwardsCommandResult r = commands_.execute(doc_, name, args);status_ = r.message;lastCommandOk_ = r.ok;@@ -818,6 +823,7 @@ void App::runCommand(const std::string& name, const Args& args) {if (r.ok && (name == "subtool_append" || name == "subtool_duplicate") && !onScreen(doc_.mesh.bounds()))camera_.frame(sceneBounds());afterCommand(name, args, r);+ watchActiveBrush();updateTitle();}@@ -860,7 +866,7 @@ void App::openPath(const std::string& path) {if (Image::isImagePath(path)) {if (loadReferenceImage(path)) showImageTo3D_ = true;} else if (ext == ".sfbrush") {- runCommand("brush_load", {{"path", path}});+ installBrushFile(path);} else {runCommand("open", {{"path", path}});}@@ -921,7 +927,7 @@ void App::processPendingFiles() {runCommand("export_lods", {{"path", f.path}, {"levels", double(lodLevels_)}, {"ratio", double(lodRatio_)}});break;case FileAction::SaveBrush: runCommand("brush_save", {{"path", f.path}}); break;- case FileAction::LoadBrush: runCommand("brush_load", {{"path", f.path}}); break;+ case FileAction::LoadBrush: installBrushFile(f.path); break;case FileAction::ExportUsd: runCommand("export_usd", {{"path", f.path}}); break;case FileAction::SaveSplats: runCommand("splat_save", {{"path", f.path}}); break;case FileAction::ExportUnreal: {@@ -1038,6 +1044,8 @@ void App::drawUi() {}if (!ImGui::GetIO().WantCaptureMouse || drag_ == Drag::Stroke) drawBrushCursor();drawPolygroupOverlay();+ drawBrushLibraryPopups();+ autosaveBrush();if (showAbout_) {ImGui::SetNextWindowSize(ImVec2(460 * uiScale_, 0), ImGuiCond_Always);@@ -1369,17 +1377,20 @@ void App::pollBrushRequest() {return;}chat_.push_back({ai::ChatMessage::Role::Assistant, reply.raw, reply.suggestion.reply});+ flushBrushEdits();doc_.activeBrush = doc_.addBrush(reply.suggestion.recipe);chatLog_.push_back({ChatLine::Kind::Assistant, "[" + reply.suggestion.recipe.name + "] " + reply.suggestion.reply});status_ = "Brush '" + reply.suggestion.recipe.name + "' is ready - try it on the model";+ saveBrushEdits(doc_.activeBrush); // Brush Lab brushes go straight into the library (status says if that fails)+ watchActiveBrush();}void App::drawRecipeEditor(BrushRecipe& recipe) {char name[64];std::snprintf(name, sizeof name, "%s", recipe.name.c_str());ImGui::SetNextItemWidth(-1);- if (ImGui::InputText("##name", name, sizeof name, ImGuiInputTextFlags_EnterReturnsTrue) && name[0])- recipe.name = name;+ if (ImGui::InputText("##name", name, sizeof name, ImGuiInputTextFlags_EnterReturnsTrue) && name[0] && recipe.name != name)+ pendingRename_ = name; // brush_rename after the panel: it renames the file and may add a brushImGui::PushItemWidth(-ImGui::CalcTextSize("Pressure curve").x - ImGui::GetStyle().ItemInnerSpacing.x);for (const auto& p : recipeParams()) {switch (p.kind) {@@ -1399,7 +1410,7 @@ void App::drawRecipeEditor(BrushRecipe& recipe) {const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;if (ImGui::Button("Save .sfbrush...", ImVec2(half, 0))) saveFileDialog(FileAction::SaveBrush);ImGui::SameLine();- if (ImGui::Button("Load .sfbrush...", ImVec2(half, 0)))+ if (ImGui::Button("Install .sfbrush...", ImVec2(half, 0)))SDL_ShowOpenFileDialog(onFileChosen, &dialogRequests_[int(FileAction::LoadBrush)], window_, kBrushFilters, 2,nullptr, false);}@@ -1622,12 +1633,21 @@ void App::drawBrushLab() {chat_.clear();chatLog_.clear();}+ ImGui::SameLine();+ if (ImGui::SmallButton("Paste brush")) pasteBrush();+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))+ ImGui::SetTooltip("Install a brush someone shared: a brush code (sfbrush1:...) or .sfbrush text on the "+ "clipboard (Ctrl+V in the viewport)");if (BrushRecipe* recipe = doc_.activeBrush >= 0 ? &doc_.brushes[doc_.activeBrush] : nullptr) {if (ImGui::CollapsingHeader(("Recipe: " + recipe->name + "###recipe").c_str())) drawRecipeEditor(*recipe);}if (ImGui::CollapsingHeader("AI provider")) drawAiSettings();ImGui::End();+ if (!pendingRename_.empty()) {+ runCommand("brush_rename", {{"to", pendingRename_}});+ pendingRename_.clear();+ }}// ---------------------------------------------------------------------------@@ -1920,18 +1940,7 @@ void App::drawToolPanel() {if (i % 2 == 0) ImGui::SameLine();}- ImGui::SeparatorText("Custom brushes");- if (ImGui::BeginListBox("##custom", ImVec2(-1, ImGui::GetTextLineHeightWithSpacing() * 5.5f))) {- for (int i = 0; i < int(doc_.brushes.size()); ++i) {- if (ImGui::Selectable(doc_.brushes[i].name.c_str(), doc_.activeBrush == i)) {- doc_.activeBrush = i;- paintMode_ = false;- }- if (ImGui::IsItemHovered() && !doc_.brushes[i].description.empty())- ImGui::SetTooltip("%s", doc_.brushes[i].description.c_str());- }- ImGui::EndListBox();- }+ drawCustomBrushes(); // PanelBrushLibrary.cppif (ImGui::Button(showBrushLab_ ? "Hide Brush Lab" : "Brush Lab (AI)...", ImVec2(-1, 0)))showBrushLab_ = !showBrushLab_;if (ImGui::Button(showImageTo3D_ ? "Hide Generate 3D" : "Generate 3D...", ImVec2(-1, 0)))diff --git a/src/app/App.h b/src/app/App.hindex 3eefa891..6c6d5beb 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -289,6 +289,31 @@ private:bool alphaInvert_ = false;std::mutex alphaMutex_;std::string pendingAlphaPath_; // set by the file dialog thread+ // Persistent brush library (PanelBrushLibrary.cpp, core/BrushLibrary.h): the Custom brushes list+ // with its right-click menu, paste (Ctrl+V), and saving Brush Lab edits a moment after the last change.+ void initBrushLibrary();+ void drawCustomBrushes();+ void drawBrushLibraryPopups();+ void pasteBrush();+ void installBrushFile(const std::string& path); // opened, dropped or chosen .sfbrush files+ void copyBrushCode(int index);+ void revealBrushFile(int index);+ void watchActiveBrush(); // the active brush as it is now counts as saved+ void flushBrushEdits(); // save recipe edits that are still waiting+ void autosaveBrush(); // per frame: saves recipe edits once they settle+ void saveBrushEdits(int index);+ struct BrushWatch {+ int index = -1;+ std::string name, json;+ bool pending = false;+ double changedAt = 0.0;+ } brushWatch_;+ enum class BrushPopup { None, Rename, Delete } brushPopup_ = BrushPopup::None;+ std::string brushPopupName_; // the brush the popup is about+ char brushRenameBuf_[64] = "";+ std::string brushPopupError_; // why the last rename failed+ int listedBrush_ = -1; // active brush when the list was last drawn (to scroll to a new one)+ std::string pendingRename_; // new name typed in the recipe editor, applied after the panel is drawn// Polypaint and MatCap materials (PanelPolypaint.cpp)bool paintMode_ = false; // Paint brush: colour only, no sculpting (ZBrush Rgb on, Zadd off)bool paintRgb_ = false; // also paint the colour while sculpting (ZBrush Rgb + Zadd)diff --git a/src/app/PanelBrushLibrary.cpp b/src/app/PanelBrushLibrary.cppnew file mode 100644index 00000000..69c1d439--- /dev/null+++ b/src/app/PanelBrushLibrary.cpp@@ -0,0 +1,343 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The persistent brush library in the app (core/BrushLibrary.h): the Custom+// brushes list with where each brush comes from and its right-click menu+// (copy code, save, rename, delete, reveal), pasting brushes from the+// clipboard, and saving Brush Lab edits to the user library automatically.+#include "app/App.h"++#include "core/BrushLibrary.h"++#include <imgui.h>++#include <cctype>+#include <cstring>+#include <filesystem>++namespace sf {++namespace {++namespace fs = std::filesystem;++constexpr double kAutosaveDelay = 0.75; // seconds after the last edit (sliders save once released)+constexpr const char* kRenamePopup = "Rename brush";+constexpr const char* kDeletePopup = "Delete brush?";++fs::path fsPath(const std::string& p) { return fs::path(std::u8string(p.begin(), p.end())); }+std::string utf8(const fs::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}++// The subtle tag after a brush's name: where it comes from, when that isn't the artist's own or a built-in.+const char* brushTag(const BrushRecipe& b) {+ switch (b.origin.source) {+ case BrushSource::Studio: return "studio";+ case BrushSource::Gallery: return "gallery";+ case BrushSource::Project: return "project";+ case BrushSource::Session: return "unsaved";+ case BrushSource::User: return b.origin.overrides != BrushSource::Session ? "yours" : nullptr;+ case BrushSource::Builtin: return nullptr;+ }+ return nullptr;+}++std::string brushOriginText(const BrushRecipe& b) {+ switch (b.origin.source) {+ case BrushSource::Builtin: return "Built-in brush";+ case BrushSource::User:+ return b.origin.overrides != BrushSource::Session+ ? std::string("Your version - replaces the ") + brushSourceName(b.origin.overrides) ++ " brush of the same name (delete it to go back)"+ : "In your brush library";+ case BrushSource::Gallery: return "From the community gallery, in your brush library";+ case BrushSource::Studio: return "Studio brush (shared folder, read-only)";+ case BrushSource::Project: return "From the open project, not in your brush library";+ case BrushSource::Session: return "Not saved - refine it in Brush Lab to keep it";+ }+ return "";+}++// `text` shortened with "..." to fit `width` pixels.+std::string fitText(const std::string& text, float width) {+ if (ImGui::CalcTextSize(text.c_str()).x <= width) return text;+ std::string s = text;+ while (!s.empty() && ImGui::CalcTextSize((s + "...").c_str()).x > width) {+ s.pop_back();+ while (!s.empty() && (static_cast<unsigned char>(s.back()) & 0xC0) == 0x80) s.pop_back(); // whole UTF-8 characters+ }+ return s + "...";+}++std::string fileUrl(const std::string& path) {+ std::string p = path;+ for (char& c : p)+ if (c == '\\') c = '/';+ std::string url = p.rfind('/', 0) == 0 ? "file://" : "file:///";+ const char* hex = "0123456789ABCDEF";+ for (unsigned char c : p) {+ if (std::isalnum(c) || std::strchr("/:-_.~", c)) url += char(c);+ else url += std::string("%") + hex[c >> 4] + hex[c & 15];+ }+ return url;+}++} // namespace++void App::initBrushLibrary() {+ BrushLibraryPaths& paths = brushLibraryPaths();+ if (!options_.uiTest.empty()) {+ // UI tests get an empty library of their own, never the artist's.+ const fs::path base = options_.uiOutDir.empty() ? fs::temp_directory_path() / "sculptforge-ui-test" : fsPath(options_.uiOutDir);+ paths = {utf8(base / "brush-library"), {}};+ std::error_code ec;+ fs::remove_all(fsPath(paths.userDir), ec);+ } else if (!options_.recordPath.empty() || !options_.renderPath.empty()) {+ paths = {}; // demo videos and renders: built-in brushes only, nothing saved+ }+ const auto messages = loadBrushLibrary(doc_, paths);+ for (const auto& m : messages) SDL_Log("Brush library: %s", m.c_str());+ if (!messages.empty())+ status_ = std::to_string(messages.size()) + (messages.size() == 1 ? " brush file" : " brush files") ++ " couldn't be loaded (details in the log)";+ watchActiveBrush();+}++void App::watchActiveBrush() {+ const BrushRecipe* r = activeRecipe();+ brushWatch_ = {r ? doc_.activeBrush : -1, r ? r->name : "", r ? r->toJson().dump() : "", false, ImGui::GetTime()};+}++void App::saveBrushEdits(int index) {+ if (brushLibraryPaths().userDir.empty() || index < 0 || index >= int(doc_.brushes.size())) return;+ const bool wasSaved = isUserLibraryBrush(doc_.brushes[size_t(index)]);+ std::string err;+ if (!saveBrushToLibrary(doc_, index, err)) {+ status_ = "Couldn't save brush '" + doc_.brushes[size_t(index)].name + "': " + err;+ SDL_Log("%s", status_.c_str());+ return;+ }+ const BrushRecipe& b = doc_.brushes[size_t(index)];+ if (!wasSaved)+ status_ = b.origin.overrides != BrushSource::Session+ ? "Saved your version of '" + b.name + "' (the " + brushSourceName(b.origin.overrides) + " one stays available)"+ : "Saved '" + b.name + "' to your brush library";+}++void App::flushBrushEdits() {+ if (!brushWatch_.pending) return;+ brushWatch_.pending = false;+ // By name: the list may have changed since the edit.+ for (int i = 0; i < int(doc_.brushes.size()); ++i)+ if (doc_.brushes[size_t(i)].name == brushWatch_.name) saveBrushEdits(i);+}++void App::autosaveBrush() {+ const BrushRecipe* r = activeRecipe();+ if (!r || doc_.activeBrush != brushWatch_.index || r->name != brushWatch_.name) {+ flushBrushEdits(); // another brush was picked: the last one's edits first+ watchActiveBrush();+ return;+ }+ const double now = ImGui::GetTime();+ std::string json = r->toJson().dump();+ if (json != brushWatch_.json) {+ brushWatch_.json = std::move(json);+ brushWatch_.pending = true;+ brushWatch_.changedAt = now;+ }+ if (brushWatch_.pending && now - brushWatch_.changedAt >= kAutosaveDelay && !ImGui::IsAnyItemActive()) {+ brushWatch_.pending = false;+ saveBrushEdits(doc_.activeBrush);+ }+}++void App::copyBrushCode(int index) {+ if (index < 0 || index >= int(doc_.brushes.size())) return;+ const BrushRecipe& b = doc_.brushes[size_t(index)];+ if (!SDL_SetClipboardText(encodeBrushCode(b).c_str())) {+ status_ = std::string("Couldn't copy to the clipboard: ") + SDL_GetError();+ return;+ }+ status_ = "Copied the brush code for '" + b.name + "' - share it anywhere; Ctrl+V in SculptForge installs it";+}++void App::pasteBrush() {+ char* clip = SDL_GetClipboardText();+ const std::string text = clip ? clip : "";+ SDL_free(clip);+ BrushRecipe r;+ std::string err;+ if (!parseBrushText(text, r, err)) {+ status_ = "Paste brush: " + err;+ return;+ }+ runCommand("brush_install", {{"json", r.toJson().dump()}});+ if (!lastCommandOk_ || !activeRecipe()) return; // status says why+ paintMode_ = false;+ const BrushRecipe& b = *activeRecipe();+ status_ = "Pasted brush '" + b.name + "'" + (isUserLibraryBrush(b) ? " - it's in your brush library" : "");+}++void App::installBrushFile(const std::string& path) {+ runCommand("brush_install", {{"path", path}});+ if (!lastCommandOk_ || !activeRecipe()) return; // status says why+ paintMode_ = false;+ const BrushRecipe& b = *activeRecipe();+ status_ = "Installed brush '" + b.name + "'" + (isUserLibraryBrush(b) ? " in your brush library" : "");+}++void App::revealBrushFile(int index) {+ if (index < 0 || index >= int(doc_.brushes.size()) || doc_.brushes[size_t(index)].origin.path.empty()) return;+ const std::string dir = utf8(fsPath(doc_.brushes[size_t(index)].origin.path).parent_path());+ if (!SDL_OpenURL(fileUrl(dir).c_str())) status_ = "Couldn't open " + dir + ": " + SDL_GetError();+}++void App::drawCustomBrushes() {+ ImGui::SeparatorText("Custom brushes");+ enum class Action { None, Copy, Save, Rename, Delete, Reveal } action = Action::None;+ int actionIndex = -1;+ if (ImGui::BeginListBox("##custom", ImVec2(-1, ImGui::GetTextLineHeightWithSpacing() * 5.5f))) {+ const ImGuiStyle& style = ImGui::GetStyle();+ for (int i = 0; i < int(doc_.brushes.size()); ++i) {+ const BrushRecipe& b = doc_.brushes[size_t(i)];+ const char* tag = brushTag(b);+ const float tagWidth = tag ? ImGui::CalcTextSize(tag).x + style.ItemSpacing.x : 0.0f;+ const std::string label = fitText(b.name, ImGui::GetContentRegionAvail().x - tagWidth) + "##brush" + std::to_string(i);+ if (ImGui::Selectable(label.c_str(), doc_.activeBrush == i, ImGuiSelectableFlags_AllowOverlap)) {+ doc_.activeBrush = i;+ paintMode_ = false;+ }+ // A brush picked elsewhere (pasted, installed, made in Brush Lab) is scrolled into view.+ if (i == doc_.activeBrush && i != listedBrush_) {+ const float top = ImGui::GetWindowPos().y, bottom = top + ImGui::GetWindowHeight();+ if (ImGui::GetItemRectMin().y < top || ImGui::GetItemRectMax().y > bottom) ImGui::SetScrollHereY(0.5f);+ }+ if (tag) {+ const ImVec2 min = ImGui::GetItemRectMin(), max = ImGui::GetItemRectMax(), size = ImGui::CalcTextSize(tag);+ ImGui::GetWindowDrawList()->AddText(ImVec2(max.x - size.x - style.FramePadding.x * 0.5f, min.y + (max.y - min.y - size.y) * 0.5f),+ ImGui::GetColorU32(doc_.activeBrush == i ? ImGuiCol_Text : ImGuiCol_TextDisabled,+ doc_.activeBrush == i ? 0.7f : 1.0f),+ tag);+ ImGui::LogText(" [%s]", tag); // drawn directly: tell the log (UI tests read it) too+ }+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort) && !ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) {+ ImGui::BeginTooltip();+ ImGui::PushTextWrapPos(ImGui::GetFontSize() * 22.0f);+ if (!b.description.empty()) ImGui::TextUnformatted(b.description.c_str());+ ImGui::TextDisabled("%s", brushOriginText(b).c_str());+ if (!b.origin.path.empty()) ImGui::TextDisabled("%s", b.origin.path.c_str());+ ImGui::TextDisabled("Right-click to share, rename or delete");+ ImGui::PopTextWrapPos();+ ImGui::EndTooltip();+ }+ if (ImGui::BeginPopupContextItem()) {+ if (ImGui::IsWindowAppearing()) { // right-clicking picks the brush too+ doc_.activeBrush = i;+ paintMode_ = false;+ }+ ImGui::TextDisabled("%s", b.name.c_str());+ ImGui::Separator();+ if (ImGui::MenuItem("Copy brush code")) action = Action::Copy;+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("One line of text to share in chat, email or a forum");+ if (ImGui::MenuItem("Save .sfbrush...")) action = Action::Save;+ if (ImGui::MenuItem("Rename...##brush")) action = Action::Rename;+ if (ImGui::MenuItem("Delete...##brush", nullptr, false, isUserLibraryBrush(b))) action = Action::Delete;+ if (!isUserLibraryBrush(b) && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))+ ImGui::SetTooltip("Only brushes in your own library can be deleted");+ if (ImGui::MenuItem("Reveal in folder", nullptr, false, !b.origin.path.empty())) action = Action::Reveal;+ if (action != Action::None) actionIndex = i;+ ImGui::EndPopup();+ }+ }+ ImGui::EndListBox();+ listedBrush_ = doc_.activeBrush;+ }+ // After the list: these may change it.+ if (actionIndex < 0) return;+ const std::string name = doc_.brushes[size_t(actionIndex)].name;+ switch (action) {+ case Action::Copy: copyBrushCode(actionIndex); break;+ case Action::Save:+ doc_.activeBrush = actionIndex;+ saveFileDialog(FileAction::SaveBrush);+ break;+ case Action::Rename:+ brushPopup_ = BrushPopup::Rename;+ brushPopupName_ = name;+ std::snprintf(brushRenameBuf_, sizeof brushRenameBuf_, "%s", name.c_str());+ break;+ case Action::Delete:+ brushPopup_ = BrushPopup::Delete;+ brushPopupName_ = name;+ break;+ case Action::Reveal: revealBrushFile(actionIndex); break;+ case Action::None: break;+ }+}++void App::drawBrushLibraryPopups() {+ if (brushPopup_ == BrushPopup::Rename) ImGui::OpenPopup(kRenamePopup);+ if (brushPopup_ == BrushPopup::Delete) ImGui::OpenPopup(kDeletePopup);+ brushPopup_ = BrushPopup::None;+ int index = -1;+ for (int i = 0; i < int(doc_.brushes.size()); ++i)+ if (doc_.brushes[size_t(i)].name == brushPopupName_) index = i;+ const float scale = uiScale_;+ const ImVec2 center = ImGui::GetMainViewport()->GetCenter();+ const ImVec2 buttonSize(110 * scale, 0);++ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ if (ImGui::BeginPopupModal(kRenamePopup, nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {+ std::string& error = brushPopupError_;+ if (ImGui::IsWindowAppearing()) {+ error.clear();+ ImGui::SetKeyboardFocusHere();+ }+ ImGui::SetNextItemWidth(300 * scale);+ bool ok = ImGui::InputText("##newname", brushRenameBuf_, sizeof brushRenameBuf_, ImGuiInputTextFlags_EnterReturnsTrue);+ if (index >= 0 && !isUserLibraryBrush(doc_.brushes[size_t(index)]) &&+ doc_.brushes[size_t(index)].origin.source != BrushSource::Session &&+ doc_.brushes[size_t(index)].origin.source != BrushSource::Project) {+ ImGui::PushTextWrapPos(300 * scale);+ ImGui::TextDisabled("The %s brush stays as it is; the renamed copy goes into your library.",+ brushSourceName(doc_.brushes[size_t(index)].origin.source));+ ImGui::PopTextWrapPos();+ }+ if (!error.empty()) ImGui::TextColored(ImVec4(1.0f, 0.45f, 0.45f, 1.0f), "%s", error.c_str());+ ok |= ImGui::Button("Rename", buttonSize);+ ImGui::SameLine();+ if (ImGui::Button("Cancel", buttonSize) || ImGui::IsKeyPressed(ImGuiKey_Escape) || index < 0) ImGui::CloseCurrentPopup();+ else if (ok) {+ runCommand("brush_rename", {{"name", brushPopupName_}, {"to", std::string(brushRenameBuf_)}});+ if (lastCommandOk_) ImGui::CloseCurrentPopup();+ else error = status_;+ }+ ImGui::EndPopup();+ }++ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ if (ImGui::BeginPopupModal(kDeletePopup, nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {+ if (index >= 0) {+ const BrushRecipe& b = doc_.brushes[size_t(index)];+ ImGui::Text("Delete '%s' from your brush library?", b.name.c_str());+ ImGui::PushTextWrapPos(340 * scale);+ if (b.origin.overrides != BrushSource::Session)+ ImGui::TextDisabled("The %s brush of the same name is used again.", brushSourceName(b.origin.overrides));+ else+ ImGui::TextDisabled("Its .sfbrush file is removed. Copy its brush code first if you might want it back.");+ ImGui::PopTextWrapPos();+ }+ if (ImGui::Button("Delete", buttonSize) && index >= 0) {+ runCommand("brush_delete", {{"name", brushPopupName_}});+ ImGui::CloseCurrentPopup();+ }+ ImGui::SameLine();+ if (ImGui::Button("Cancel", buttonSize) || ImGui::IsKeyPressed(ImGuiKey_Escape) || index < 0) ImGui::CloseCurrentPopup();+ ImGui::EndPopup();+ }+}++} // namespace sfdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 4d4e9c29..0cf05227 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -18,17 +18,22 @@// expect LABEL / expect_not LABEL// expect_text TEXT / expect_no_text TEXT any text drawn this frame contains TEXT// expect_status TEXT the status bar message contains TEXT+// clipboard TEXT put TEXT on the clipboard (to test pasting, e.g. a brush code)+// expect_clipboard TEXT the clipboard contains TEXT (after a copy)// click_subtool NAME [U V] left-click SubTool NAME in the viewport (with the held modifiers, e.g.// hold alt to select it); U V: fractions of its on-screen bounds// expect_value NAME OP N triangles, vertices, layers, brushes, masked, hidden, groups, colored,// can_undo, dirty, splats, show_polygroups, show_mask, wireframe,// subtools (count), active_subtool (index, 0 = top), visible_subtools,-// edited_subtools (SubTools with undo history); OP is == != < <= > >=+// edited_subtools (SubTools with undo history), user_brushes (brushes in the+// user library), library_files (.sfbrush files in it; UI tests get an empty+// one in --ui-out/brush-library); OP is == != < <= > >=// (mesh values are the active SubTool's)// shot NAME save a screenshot NAME.png (to --ui-out)#include "app/App.h"#include "app/Demo.h"+#include "core/BrushLibrary.h"#include "core/Script.h"#include <imgui_internal.h>@@ -166,6 +171,18 @@ double Demo::query(const std::string& name, bool& known) const {n += (i == doc.activeSubtool ? doc.undo.canUndo() : doc.subtools[size_t(i)].undo.canUndo()) ? 1 : 0;return double(n);}+ if (name == "user_brushes")+ return double(std::count_if(doc.brushes.begin(), doc.brushes.end(), [](const BrushRecipe& b) { return isUserLibraryBrush(b); }));+ if (name == "library_files") {+ const std::string& dir = brushLibraryPaths().userDir;+ std::error_code ec;+ size_t n = 0;+ if (!dir.empty())+ for (std::filesystem::directory_iterator it(std::filesystem::path(std::u8string(dir.begin(), dir.end())), ec), end;+ !ec && it != end; it.increment(ec))+ n += it->path().extension() == ".sfbrush";+ return double(n);+ }if (name == "masked") {size_t n = 0;for (float v : m.mask) n += v > 0.5f;@@ -476,6 +493,22 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& eif (app_.status_.find(text) == std::string::npos)fail(line, "status is \"" + app_.status_ + "\", expected it to contain \"" + text + "\"");});+ } else if (verb == "clipboard") {+ if (!need(1)) return false;+ const std::string text = restOf(lineText_, 1);+ run([this, line, text] {+ if (!SDL_SetClipboardText(text.c_str())) fail(line, std::string("can't set the clipboard: ") + SDL_GetError());+ });+ } else if (verb == "expect_clipboard") {+ if (!need(1)) return false;+ const std::string text = restOf(lineText_, 1);+ run([this, line, text] {+ char* clip = SDL_GetClipboardText();+ const std::string have = clip ? clip : "";+ SDL_free(clip);+ if (have.find(text) == std::string::npos)+ fail(line, "clipboard is \"" + have.substr(0, 80) + "\", expected it to contain \"" + text + "\"");+ });} else if (verb == "expect_value") {if (!need(3)) return false;bool known = false;diff --git a/src/cli/McpServer.cpp b/src/cli/McpServer.cppindex b4da1956..b51fb96b 100644--- a/src/cli/McpServer.cpp+++ b/src/cli/McpServer.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "cli/McpServer.h"+#include "core/BrushLibrary.h"#include "core/Json.h"#include <iostream>@@ -120,6 +121,8 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, conint runMcpServer(const CommandRegistry& registry, std::istream& in, std::ostream& out) {Document doc;+ // stdout is the protocol: library messages go to stderr.+ for (const auto& message : loadBrushLibrary(doc)) std::cerr << "sculptforge: " << message << "\n";std::string line;while (std::getline(in, line)) {if (line.find_first_not_of(" \t\r") == std::string::npos) continue;diff --git a/src/cli/main.cpp b/src/cli/main.cppindex ff464735..e7bb4805 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -5,6 +5,7 @@// pipelines and AI agents.#include "ai/AiCommands.h"#include "cli/McpServer.h"+#include "core/BrushLibrary.h"#include "core/Commands.h"#include "core/Script.h"@@ -125,6 +126,7 @@ int main(int argc, char** argv) {}sf::Document doc;+ for (const auto& message : sf::loadBrushLibrary(doc)) std::fprintf(stderr, "warning: %s\n", message.c_str());for (const auto& st : statements) {sf::CommandResult r = registry.execute(doc, st.command, st.args);if (!r.ok) {diff --git a/src/core/BrushLibrary.cpp b/src/core/BrushLibrary.cppnew file mode 100644index 00000000..8be26142--- /dev/null+++ b/src/core/BrushLibrary.cpp@@ -0,0 +1,661 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/BrushLibrary.h"++#include "core/Commands.h"+#include "core/Document.h"++#include <algorithm>+#include <cctype>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <iterator>++namespace sf {++namespace fs = std::filesystem;++namespace {++constexpr const char* kCodePrefix = "sfbrush1:";++fs::path utf8Path(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }+std::string pathString(const fs::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}+std::string fileNameOf(const std::string& path) { return pathString(utf8Path(path).filename()); }++std::string env(const char* name) {+ const char* v = std::getenv(name);+ return v ? v : "";+}++std::string trim(const std::string& s) {+ size_t a = 0, b = s.size();+ while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;+ while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;+ return s.substr(a, b - a);+}++// --- base64url (RFC 4648 section 5), no padding ---++const char kBase64Url[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";++std::string base64UrlEncode(const std::string& in) {+ std::string out;+ out.reserve((in.size() * 4 + 2) / 3);+ size_t i = 0;+ for (; i + 2 < in.size(); i += 3) {+ const uint32_t n = uint32_t(uint8_t(in[i])) << 16 | uint32_t(uint8_t(in[i + 1])) << 8 | uint8_t(in[i + 2]);+ out += kBase64Url[n >> 18 & 63];+ out += kBase64Url[n >> 12 & 63];+ out += kBase64Url[n >> 6 & 63];+ out += kBase64Url[n & 63];+ }+ if (i + 1 == in.size()) {+ const uint32_t n = uint32_t(uint8_t(in[i])) << 16;+ out += kBase64Url[n >> 18 & 63];+ out += kBase64Url[n >> 12 & 63];+ } else if (i + 2 == in.size()) {+ const uint32_t n = uint32_t(uint8_t(in[i])) << 16 | uint32_t(uint8_t(in[i + 1])) << 8;+ out += kBase64Url[n >> 18 & 63];+ out += kBase64Url[n >> 12 & 63];+ out += kBase64Url[n >> 6 & 63];+ }+ return out;+}++bool base64UrlDecode(const std::string& in, std::string& out) {+ out.clear();+ uint32_t acc = 0;+ int bits = 0;+ for (char c : in) {+ int v;+ if (c >= 'A' && c <= 'Z') v = c - 'A';+ else if (c >= 'a' && c <= 'z') v = c - 'a' + 26;+ else if (c >= '0' && c <= '9') v = c - '0' + 52;+ else if (c == '-') v = 62;+ else if (c == '_') v = 63;+ else return false;+ acc = (acc << 6) | uint32_t(v);+ bits += 6;+ if (bits >= 8) {+ bits -= 8;+ out += char((acc >> bits) & 0xFF);+ }+ }+ return bits < 6; // one leftover character can't encode a byte+}++// The JSON of a pasted brush or a .sfbrush file: an object that names a brush or says it's one.+bool brushFromJsonText(const std::string& text, BrushRecipe& out, std::string& error) {+ Json j;+ std::string parseError;+ if (!Json::parse(text, j, parseError)) {+ error = "Not a brush (" + parseError + ")";+ return false;+ }+ const bool isBrush = j.isObject() && (j["format"].isNull() ? j["name"].isString() : j["format"].asString() == "sfbrush");+ if (!isBrush) {+ error = "Not a SculptForge brush";+ return false;+ }+ out = BrushRecipe::fromJson(j);+ out.origin = {};+ if (j["source"].asString() == "gallery") out.origin.source = BrushSource::Gallery;+ return true;+}++bool sameFile(const std::string& a, const std::string& b) {+ std::error_code ec;+ return fs::weakly_canonical(utf8Path(a), ec) == fs::weakly_canonical(utf8Path(b), ec);+}++// True when `path` is inside folder `dir` (the user library): studio folders are never written.+bool insideDir(const std::string& path, const std::string& dir) {+ if (path.empty() || dir.empty()) return false;+ std::error_code ec;+ const fs::path p = fs::weakly_canonical(utf8Path(path), ec);+ const fs::path d = fs::weakly_canonical(utf8Path(dir), ec);+ if (ec) return false;+ const fs::path rel = p.lexically_relative(d);+ return !rel.empty() && *rel.begin() != ".." && rel != ".";+}++// The .sfbrush files directly in `dir`, by file name (so load order doesn't depend on the file system).+std::vector<std::string> brushFiles(const std::string& dir) {+ std::vector<std::string> out;+ std::error_code ec;+ for (fs::directory_iterator it(utf8Path(dir), ec), end; !ec && it != end; it.increment(ec)) {+ std::string ext = pathString(it->path().extension());+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ std::error_code fileEc;+ if (ext == ".sfbrush" && it->is_regular_file(fileEc)) out.push_back(pathString(it->path()));+ }+ std::sort(out.begin(), out.end());+ return out;+}++bool writeBrushFile(const std::string& path, const BrushRecipe& recipe, bool gallery, std::string& error) {+ Json j = recipe.toJson();+ j.set("format", "sfbrush");+ j.set("version", 1);+ if (gallery) j.set("source", "gallery");+ // Write next to it and rename over it, so a crash never leaves half a brush behind.+ const fs::path target = utf8Path(path);+ fs::path tmp = target;+ tmp += ".tmp";+ {+ std::ofstream f(tmp, std::ios::binary | std::ios::trunc);+ f << j.dump(true) << "\n";+ if (!f) {+ error = "Cannot write " + path;+ std::error_code ec;+ fs::remove(tmp, ec);+ return false;+ }+ }+ std::error_code ec;+ fs::rename(tmp, target, ec);+ if (ec) {+ error = "Cannot write " + path + ": " + ec.message();+ fs::remove(tmp, ec);+ return false;+ }+ return true;+}++// Where a new brush called `name` goes in the user library: its safe file name,+// numbered if that file already holds a different brush.+std::string libraryPathFor(const std::string& dir, const std::string& name) {+ const std::string file = brushFileName(name);+ const std::string stem = file.substr(0, file.size() - std::strlen(".sfbrush"));+ fs::path p;+ for (int n = 1; n <= 10000; ++n) {+ p = utf8Path(dir) / utf8Path(n == 1 ? file : stem + " " + std::to_string(n) + ".sfbrush");+ std::error_code ec;+ if (!fs::exists(p, ec)) break;+ BrushRecipe existing;+ std::string err;+ if (readBrushFile(pathString(p), existing, err) && existing.name == name) break;+ }+ return pathString(p);+}++// The studio or built-in brush called `name` that a user brush of that name hides.+bool findShadowed(const std::string& name, const BrushLibraryPaths& paths, BrushRecipe& out) {+ for (const auto& dir : paths.studioDirs) {+ for (const auto& file : brushFiles(dir)) {+ std::string err;+ if (readBrushFile(file, out, err) && out.name == name) {+ out.origin = {BrushSource::Studio, file, BrushSource::Session};+ return true;+ }+ }+ }+ for (auto& b : builtinBrushRecipes()) {+ if (b.name == name) {+ out = std::move(b);+ return true;+ }+ }+ return false;+}++int findBrush(const Document& doc, const std::string& name) {+ for (size_t i = 0; i < doc.brushes.size(); ++i)+ if (doc.brushes[i].name == name) return int(i);+ return -1;+}++} // namespace++BrushLibraryPaths BrushLibraryPaths::fromEnvironment() {+ BrushLibraryPaths p;+ p.userDir = pathString(utf8Path(appDataDir()) / "brushes");+ p.studioDirs = splitSearchPath(env("SCULPTFORGE_BRUSH_PATH"));+ return p;+}++BrushLibraryPaths& brushLibraryPaths() {+ static BrushLibraryPaths paths = BrushLibraryPaths::fromEnvironment();+ return paths;+}++std::string appDataDir() {+ // Matches SDL_GetPrefPath("SculptForge", "SculptForge"), which the app uses for its settings.+#if defined(_WIN32)+ const std::string base = env("APPDATA");+ return base.empty() ? "" : base + "\\SculptForge\\SculptForge";+#elif defined(__APPLE__)+ return env("HOME") + "/Library/Application Support/SculptForge/SculptForge";+#else+ const std::string xdg = env("XDG_DATA_HOME");+ return (xdg.empty() ? env("HOME") + "/.local/share" : xdg) + "/SculptForge/SculptForge";+#endif+}++std::vector<std::string> splitSearchPath(const std::string& value) {+#if defined(_WIN32)+ const char sep = ';';+#else+ const char sep = ':';+#endif+ std::vector<std::string> out;+ size_t start = 0;+ while (start <= value.size()) {+ size_t end = value.find(sep, start);+ if (end == std::string::npos) end = value.size();+ std::string part = trim(value.substr(start, end - start));+ if (!part.empty()) out.push_back(std::move(part));+ start = end + 1;+ }+ return out;+}++std::string encodeBrushCode(const BrushRecipe& recipe) { return kCodePrefix + base64UrlEncode(recipe.toJson().dump()); }++bool decodeBrushCode(const std::string& code, BrushRecipe& out, std::string& error) {+ const std::string text = trim(code);+ if (text.size() > kMaxBrushCodeSize) {+ error = "Brush code is too long (at most 8 KB)";+ return false;+ }+ if (text.rfind(kCodePrefix, 0) != 0) {+ const bool newer = text.rfind("sfbrush", 0) == 0 && text.size() > 8 && std::isdigit(static_cast<unsigned char>(text[7]));+ error = newer ? "This brush code needs a newer version of SculptForge" : "Not a brush code (they start with sfbrush1:)";+ return false;+ }+ // Codes can get wrapped or padded on their way through chat and email.+ std::string payload;+ for (size_t i = std::strlen(kCodePrefix); i < text.size(); ++i)+ if (!std::isspace(static_cast<unsigned char>(text[i]))) payload += text[i];+ while (!payload.empty() && payload.back() == '=') payload.pop_back();+ std::string json;+ if (payload.empty() || !base64UrlDecode(payload, json)) {+ error = "Damaged brush code (incomplete or changed while copying)";+ return false;+ }+ std::string err;+ if (!brushFromJsonText(json, out, err)) {+ error = "Damaged brush code (incomplete or changed while copying)";+ return false;+ }+ out.origin = {}; // a code says nothing about where the brush lives+ return true;+}++bool parseBrushText(const std::string& text, BrushRecipe& out, std::string& error) {+ const std::string t = trim(text);+ if (t.empty()) {+ error = "Nothing to paste: copy a brush code or a .sfbrush file first";+ return false;+ }+ if (t.front() == '{') {+ if (t.size() > kMaxBrushFileSize) {+ error = "Too large to be a brush";+ return false;+ }+ if (!brushFromJsonText(t, out, error)) return false;+ out.origin = {};+ return true;+ }+ // A code on its own, or inside a message ("try my brush: sfbrush1:...").+ size_t at = t.find("sfbrush");+ if (at == std::string::npos) {+ error = "No brush found: copy a brush code (sfbrush1:...) or the contents of a .sfbrush file";+ return false;+ }+ size_t end = at;+ while (end < t.size() && !std::isspace(static_cast<unsigned char>(t[end]))) ++end;+ return decodeBrushCode(t.substr(at, end - at), out, error);+}++bool readBrushFile(const std::string& path, BrushRecipe& out, std::string& error) {+ std::error_code ec;+ const auto size = fs::file_size(utf8Path(path), ec);+ if (ec) {+ error = "Cannot open " + path;+ return false;+ }+ if (size > kMaxBrushFileSize) {+ error = "Too large to be a brush (" + std::to_string(size / 1024) + " KB)";+ return false;+ }+ std::ifstream f(utf8Path(path), std::ios::binary);+ if (!f) {+ error = "Cannot open " + path;+ return false;+ }+ const std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ return brushFromJsonText(text, out, error);+}++std::string brushFileName(const std::string& name) {+ std::string out;+ for (unsigned char c : name) out += c < 0x20 || std::strchr("<>:\"/\\|?*", c) ? '_' : char(c);+ // No leading dots (hidden files, "..") or trailing dots and spaces (Windows drops them).+ const size_t a = out.find_first_not_of(". ");+ out = a == std::string::npos ? "" : out.substr(a);+ while (!out.empty() && (out.back() == '.' || out.back() == ' ')) out.pop_back();+ if (out.empty()) out = "Brush";+ // Reserved device names on Windows, with or without an extension.+ std::string base = out.substr(0, out.find('.'));+ std::transform(base.begin(), base.end(), base.begin(), [](unsigned char c) { return char(std::toupper(c)); });+ static const char* kReserved[] = {"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",+ "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"};+ for (const char* r : kReserved)+ if (base == r) out = "_" + out;+ return out + ".sfbrush";+}++bool isUserLibraryBrush(const BrushRecipe& recipe) {+ return recipe.origin.source == BrushSource::User || recipe.origin.source == BrushSource::Gallery;+}++std::vector<std::string> loadBrushLibrary(Document& doc, const BrushLibraryPaths& paths) {+ std::vector<std::string> messages;+ const std::string active =+ doc.activeBrush >= 0 && doc.activeBrush < int(doc.brushes.size()) ? doc.brushes[size_t(doc.activeBrush)].name : "";+ doc.brushes = builtinBrushRecipes();++ for (const auto& dir : paths.studioDirs) {+ std::error_code ec;+ if (!fs::is_directory(utf8Path(dir), ec)) {+ messages.push_back("Studio brush folder not found: " + dir);+ continue;+ }+ for (const auto& file : brushFiles(dir)) {+ BrushRecipe r;+ std::string err;+ if (!readBrushFile(file, r, err)) {+ messages.push_back("Skipped studio brush " + file + ": " + err);+ continue;+ }+ r.origin = {BrushSource::Studio, file, BrushSource::Session};+ const int i = findBrush(doc, r.name);+ if (i < 0) doc.brushes.push_back(std::move(r));+ else if (doc.brushes[size_t(i)].origin.source == BrushSource::Builtin) {+ r.origin.overrides = BrushSource::Builtin;+ doc.brushes[size_t(i)] = std::move(r);+ } // else an earlier studio folder has it, and wins+ }+ }++ if (!paths.userDir.empty()) {+ for (const auto& file : brushFiles(paths.userDir)) {+ BrushRecipe r;+ std::string err;+ if (!readBrushFile(file, r, err)) {+ messages.push_back("Skipped " + file + ": " + err);+ continue;+ }+ r.origin.source = r.origin.source == BrushSource::Gallery ? BrushSource::Gallery : BrushSource::User;+ r.origin.path = file;+ const int i = findBrush(doc, r.name);+ if (i < 0) {+ doc.brushes.push_back(std::move(r));+ } else if (isUserLibraryBrush(doc.brushes[size_t(i)])) {+ messages.push_back("Skipped " + file + ": " + fileNameOf(doc.brushes[size_t(i)].origin.path) ++ " already has a brush called '" + r.name + "'");+ } else {+ r.origin.overrides = doc.brushes[size_t(i)].origin.source;+ doc.brushes[size_t(i)] = std::move(r);+ }+ }+ }+ doc.activeBrush = active.empty() ? -1 : findBrush(doc, active);+ return messages;+}++bool saveBrushToLibrary(Document& doc, int index, std::string& error, bool gallery, const BrushLibraryPaths& paths) {+ if (index < 0 || index >= int(doc.brushes.size())) {+ error = "No such brush";+ return false;+ }+ if (paths.userDir.empty()) {+ error = "Brushes aren't saved in this session";+ return false;+ }+ std::error_code ec;+ fs::create_directories(utf8Path(paths.userDir), ec);+ if (ec) {+ error = "Cannot create the brush library " + paths.userDir + ": " + ec.message();+ return false;+ }+ BrushRecipe& r = doc.brushes[size_t(index)];+ const bool inLibrary = isUserLibraryBrush(r) && insideDir(r.origin.path, paths.userDir);+ const std::string target = inLibrary ? r.origin.path : libraryPathFor(paths.userDir, r.name);+ gallery = gallery || r.origin.source == BrushSource::Gallery;+ if (!writeBrushFile(target, r, gallery, error)) return false;+ if (!inLibrary) {+ BrushRecipe hidden;+ r.origin.overrides = findShadowed(r.name, paths, hidden) ? hidden.origin.source : BrushSource::Session;+ }+ r.origin.source = gallery ? BrushSource::Gallery : BrushSource::User;+ r.origin.path = target;+ return true;+}++int installBrush(Document& doc, BrushRecipe recipe, std::string& error, bool gallery, const BrushLibraryPaths& paths) {+ recipe.origin = {}; // an install of a brush already in the library updates it (see Document::addBrush)+ const int index = doc.addBrush(std::move(recipe));+ doc.activeBrush = index;+ error.clear();+ saveBrushToLibrary(doc, index, error, gallery, paths);+ return index;+}++bool deleteBrush(Document& doc, int index, std::string& error, const BrushLibraryPaths& paths) {+ if (index < 0 || index >= int(doc.brushes.size())) {+ error = "No such brush";+ return false;+ }+ const BrushRecipe& r = doc.brushes[size_t(index)];+ if (!isUserLibraryBrush(r)) {+ error = "'" + r.name + "' is a " + brushSourceName(r.origin.source) ++ " brush: only brushes in your own library can be deleted";+ return false;+ }+ if (!r.origin.path.empty()) {+ if (!insideDir(r.origin.path, paths.userDir)) {+ error = "'" + r.name + "' is not in your brush library (" + r.origin.path + ")";+ return false;+ }+ std::error_code ec;+ fs::remove(utf8Path(r.origin.path), ec);+ if (ec) {+ error = "Cannot delete " + r.origin.path + ": " + ec.message();+ return false;+ }+ }+ BrushRecipe hidden;+ if (findShadowed(r.name, paths, hidden)) {+ doc.brushes[size_t(index)] = std::move(hidden); // the studio or built-in version is back+ return true;+ }+ doc.brushes.erase(doc.brushes.begin() + index);+ if (doc.activeBrush == index) doc.activeBrush = -1;+ else if (doc.activeBrush > index) --doc.activeBrush;+ return true;+}++int renameBrush(Document& doc, int index, const std::string& newName, std::string& error, const BrushLibraryPaths& paths) {+ if (index < 0 || index >= int(doc.brushes.size())) {+ error = "No such brush";+ return -1;+ }+ BrushRecipe probe;+ probe.name = trim(newName);+ if (probe.name.empty()) {+ error = "A brush needs a name";+ return -1;+ }+ probe.clamp(); // same length limit as every recipe+ const std::string name = probe.name, oldName = doc.brushes[size_t(index)].name;+ if (name == oldName) return index;+ if (findBrush(doc, name) >= 0) {+ error = "There is already a brush called '" + name + "'";+ return -1;+ }+ auto insertAt = [&](int at, BrushRecipe r) {+ doc.brushes.insert(doc.brushes.begin() + at, std::move(r));+ if (doc.activeBrush >= at) ++doc.activeBrush;+ };++ BrushRecipe& r = doc.brushes[size_t(index)];+ const BrushSource source = r.origin.source;+ if (source == BrushSource::Builtin || source == BrushSource::Studio) {+ // Shared brushes stay as they are; the renamed one is the artist's copy.+ BrushRecipe copy = r;+ copy.name = name;+ copy.origin = {};+ insertAt(index + 1, std::move(copy));+ doc.activeBrush = index + 1;+ if (!paths.userDir.empty()) saveBrushToLibrary(doc, index + 1, error, false, paths);+ return index + 1;+ }+ if (!isUserLibraryBrush(r) || paths.userDir.empty()) {+ r.name = name; // session and project brushes aren't in the library+ doc.activeBrush = index;+ return index;+ }+ const std::string oldPath = r.origin.path;+ r.name = name;+ const std::string target = libraryPathFor(paths.userDir, name);+ std::string err;+ if (!writeBrushFile(target, r, r.origin.source == BrushSource::Gallery, err)) {+ r.name = oldName;+ error = err;+ return -1;+ }+ if (!oldPath.empty() && !sameFile(oldPath, target) && insideDir(oldPath, paths.userDir)) {+ std::error_code ec;+ fs::remove(utf8Path(oldPath), ec);+ }+ r.origin.path = target;+ BrushRecipe hidden;+ r.origin.overrides = findShadowed(name, paths, hidden) ? hidden.origin.source : BrushSource::Session;+ doc.activeBrush = index;+ if (findShadowed(oldName, paths, hidden)) { // the brush the old name overrode is back+ insertAt(index, std::move(hidden));+ doc.activeBrush = index + 1;+ return index + 1;+ }+ return index;+}++void registerBrushLibraryCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ // Brush by name, or the active brush when no name is given.+ auto pick = [](const Document& doc, const Args& a, std::string& error) {+ const std::string name = argString(a, "name");+ const int i = name.empty() ? doc.activeBrush : findBrush(doc, name);+ if (i < 0 || i >= int(doc.brushes.size())) error = name.empty() ? "No custom brush is active" : "No such brush: " + name;+ return i < 0 || i >= int(doc.brushes.size()) ? -1 : i;+ };++ registry.add(+ {"brush_install",+ "Install a brush into your brush library (saved, loaded at every start) and make it active: from a .sfbrush "+ "file, a brush code (sfbrush1:...) or recipe JSON. Installing a brush with the same name again updates it.",+ {{"path", T::String, ".sfbrush file to install.", false},+ {"code", T::String, "Brush code (sfbrush1:...).", false},+ {"json", T::String, "Brush recipe JSON (the contents of a .sfbrush file).", false},+ {"source", T::String, "'gallery' marks a brush installed from the community gallery.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ const int given = int(a.contains("path")) + int(a.contains("code")) + int(a.contains("json"));+ if (given != 1) return {false, "Give one of path, code or json"};+ BrushRecipe r;+ std::string err;+ const bool ok = a.contains("path") ? readBrushFile(argString(a, "path"), r, err)+ : a.contains("code") ? decodeBrushCode(argString(a, "code"), r, err)+ : parseBrushText(argString(a, "json"), r, err);+ if (!ok) return {false, err};+ const std::string source = argString(a, "source");+ if (!source.empty() && source != "gallery" && source != "user")+ return {false, "source must be 'gallery' or 'user'"};+ const bool gallery = source == "gallery" || (source.empty() && r.origin.source == BrushSource::Gallery);+ const int existing = findBrush(doc, r.name);+ const bool update = existing >= 0 && isUserLibraryBrush(doc.brushes[size_t(existing)]);+ const BrushLibraryPaths& paths = brushLibraryPaths();+ const int i = installBrush(doc, std::move(r), err, gallery, paths);+ const BrushRecipe& b = doc.brushes[size_t(i)];+ if (paths.userDir.empty()) return {true, "Brush '" + b.name + "' ready (not saved: no brush library this session)"};+ if (!err.empty()) return {false, "Brush '" + b.name + "' is ready this session but not saved: " + err};+ return {true, std::string(update ? "Updated" : "Installed") + " brush '" + b.name + "' in your library (" ++ b.origin.path + ")"};+ }});++ registry.add({"brush_code",+ "Print a brush as a brush code (sfbrush1:...): one line of text to share in chat, email or a forum. "+ "Paste it into SculptForge (Ctrl+V) or run brush_install code=... to add the brush.",+ {{"name", T::String, "Brush name (defaults to the active brush).", false}},+ [pick](Document& doc, const Args& a) -> CommandResult {+ std::string err;+ const int i = pick(doc, a, err);+ if (i < 0) return {false, err};+ return {true, encodeBrushCode(doc.brushes[size_t(i)])};+ }});++ registry.add({"brush_delete",+ "Delete a brush from your brush library (its file too). Built-in and studio brushes can't be "+ "deleted; if your brush replaced one of them, that one is used again.",+ {{"name", T::String, "Brush name.", true}},+ [pick](Document& doc, const Args& a) -> CommandResult {+ std::string err;+ const int i = pick(doc, a, err);+ if (i < 0) return {false, err};+ const std::string name = doc.brushes[size_t(i)].name;+ if (!deleteBrush(doc, i, err)) return {false, err};+ const int back = findBrush(doc, name);+ return {true, "Deleted brush '" + name + "'" ++ (back >= 0 ? std::string(" (the ") + brushSourceName(doc.brushes[size_t(back)].origin.source) ++ " brush of that name is back)"+ : "")};+ }});++ registry.add({"brush_rename",+ "Rename a brush. Your own brushes are renamed in the library; renaming a built-in or studio brush "+ "saves a renamed copy and keeps the original.",+ {{"name", T::String, "Current name (defaults to the active brush).", false},+ {"to", T::String, "New name.", true}},+ [pick](Document& doc, const Args& a) -> CommandResult {+ std::string err;+ const int i = pick(doc, a, err);+ if (i < 0) return {false, err};+ const std::string from = doc.brushes[size_t(i)].name;+ const BrushSource source = doc.brushes[size_t(i)].origin.source;+ const int j = renameBrush(doc, i, argString(a, "to"), err);+ if (j < 0) return {false, err};+ const std::string to = doc.brushes[size_t(j)].name;+ const std::string note = err.empty() ? "" : " (not saved: " + err + ")";+ if (source == BrushSource::Builtin || source == BrushSource::Studio)+ return {true, "Saved a copy of the " + std::string(brushSourceName(source)) + " brush '" + from ++ "' as '" + to + "'" + note};+ return {true, "Renamed '" + from + "' to '" + to + "'" + note};+ }});++ registry.add({"brush_library",+ "List every custom brush with where it comes from (built-in, user, studio, gallery, project, "+ "session) and its file, plus the library folders.",+ {},+ [](Document& doc, const Args&) -> CommandResult {+ const BrushLibraryPaths& paths = brushLibraryPaths();+ std::string out = "User library: " + (paths.userDir.empty() ? std::string("(none)") : paths.userDir);+ for (const auto& dir : paths.studioDirs) out += "\nStudio folder: " + dir;+ for (size_t i = 0; i < doc.brushes.size(); ++i) {+ const BrushRecipe& b = doc.brushes[i];+ out += "\n" + std::to_string(i) + ": " + b.name + " [" + brushSourceName(b.origin.source) + "]";+ if (b.origin.overrides != BrushSource::Session)+ out += std::string(" overrides ") + brushSourceName(b.origin.overrides);+ if (!b.origin.path.empty()) out += " " + b.origin.path;+ }+ return {true, out};+ }});+}++} // namespace sfdiff --git a/src/core/BrushLibrary.h b/src/core/BrushLibrary.hnew file mode 100644index 00000000..b7382479--- /dev/null+++ b/src/core/BrushLibrary.h@@ -0,0 +1,93 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The persistent brush library. Brushes live as one .sfbrush file each in:+// - the user library, <app data>/brushes: brushes the artist made, refined or+// installed (from a file, a pasted brush code or the community gallery);+// - studio folders listed in SCULPTFORGE_BRUSH_PATH (':' separated, ';' on+// Windows): shared, read-only - SculptForge never writes into them.+// The app, sculptforge-cli and the Python module load the library into+// Document::brushes at start-up. When several brushes share a name the user's+// wins over a studio one, which wins over a built-in (the first studio folder+// listed wins over later ones); each brush records its BrushOrigin.+//+// Brush codes share a brush as one line of text: "sfbrush1:" followed by the+// base64url (no padding) of the compact recipe JSON, at most 8 KB. Decoding+// validates and clamps like BrushRecipe::fromJson.+#pragma once++#include "core/BrushRecipe.h"++#include <string>+#include <vector>++namespace sf {++class CommandRegistry;+struct Document;++struct BrushLibraryPaths {+ std::string userDir; // empty = nothing is saved (tests, demo recordings)+ std::vector<std::string> studioDirs; // read-only, in precedence order+ // <app data>/brushes plus the folders in SCULPTFORGE_BRUSH_PATH.+ static BrushLibraryPaths fromEnvironment();+};++// The locations the brush commands use; starts as fromEnvironment(). The app+// points it elsewhere for UI tests and recordings, unit tests at temp folders.+BrushLibraryPaths& brushLibraryPaths();++// Per-user application data folder (where ai.json and brushes/ live), no trailing separator.+std::string appDataDir();+// Splits a search path (':' separated, ';' on Windows), dropping empty entries.+std::vector<std::string> splitSearchPath(const std::string& value);++constexpr size_t kMaxBrushCodeSize = 8 * 1024;+constexpr size_t kMaxBrushFileSize = 64 * 1024;++std::string encodeBrushCode(const BrushRecipe& recipe);+bool decodeBrushCode(const std::string& code, BrushRecipe& out, std::string& error);+// Text that holds a brush: a brush code or the contents of a .sfbrush file (as pasted from the clipboard).+bool parseBrushText(const std::string& text, BrushRecipe& out, std::string& error);+// Reads a .sfbrush file (size-limited, validated); `source` is set from its "source" key ("gallery").+bool readBrushFile(const std::string& path, BrushRecipe& out, std::string& error);++// File name (without folder) a brush is saved under: its name made safe on every OS.+std::string brushFileName(const std::string& name);++// Replaces doc.brushes with the built-ins, the studio folders and the user+// library (the active brush is kept by name). Files that can't be read are+// skipped; returns one message per skipped file or folder.+std::vector<std::string> loadBrushLibrary(Document& doc, const BrushLibraryPaths& paths = brushLibraryPaths());++// Saves doc.brushes[index] into the user library (updating its file if it has+// one) and makes it a user brush; a built-in or studio brush becomes the+// artist's own version that overrides it. `gallery` marks a gallery install.+// Returns false with `error` when there is no user library or it can't be written.+bool saveBrushToLibrary(Document& doc, int index, std::string& error, bool gallery = false,+ const BrushLibraryPaths& paths = brushLibraryPaths());++// Adds (or updates, by name) `recipe`, saves it to the user library and makes+// it the active brush. Returns its index; on a save error the brush is still+// usable this session and `error` says why it isn't saved.+int installBrush(Document& doc, BrushRecipe recipe, std::string& error, bool gallery = false,+ const BrushLibraryPaths& paths = brushLibraryPaths());++// Deletes a user or gallery brush and its file. A built-in or studio brush it+// overrode takes its place again. Other brushes can't be deleted.+bool deleteBrush(Document& doc, int index, std::string& error, const BrushLibraryPaths& paths = brushLibraryPaths());++// Renames a brush. A user brush's file is renamed with it; renaming a+// built-in or studio brush saves a renamed copy to the user library and keeps+// the original. Fails if another brush already has the name. Returns the+// renamed brush's index (or -1).+int renameBrush(Document& doc, int index, const std::string& newName, std::string& error,+ const BrushLibraryPaths& paths = brushLibraryPaths());++// True for brushes that live in the user library (user and gallery).+bool isUserLibraryBrush(const BrushRecipe& recipe);++// brush_install, brush_code, brush_delete, brush_rename, brush_library.+void registerBrushLibraryCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/BrushRecipe.cpp b/src/core/BrushRecipe.cppindex 36cdbf44..7bcef497 100644--- a/src/core/BrushRecipe.cpp+++ b/src/core/BrushRecipe.cpp@@ -97,6 +97,18 @@ const std::vector<RecipeParam>& recipeParams() {return params;}+const char* brushSourceName(BrushSource source) {+ switch (source) {+ case BrushSource::Session: return "session";+ case BrushSource::Builtin: return "built-in";+ case BrushSource::User: return "user";+ case BrushSource::Studio: return "studio";+ case BrushSource::Gallery: return "gallery";+ case BrushSource::Project: return "project";+ }+ return "session";+}+float* BrushRecipe::field(const std::string& key) { return floatField(*this, key); }int BrushRecipe::enumIndex(const std::string& key) const {@@ -242,6 +254,7 @@ std::vector<BrushRecipe> builtinBrushRecipes() {std::vector<BrushRecipe> out;auto add = [&](BrushRecipe r) {r.clamp();+ r.origin.source = BrushSource::Builtin;out.push_back(std::move(r));};{diff --git a/src/core/BrushRecipe.h b/src/core/BrushRecipe.hindex a87794f0..ddcfe37d 100644--- a/src/core/BrushRecipe.h+++ b/src/core/BrushRecipe.h@@ -14,6 +14,25 @@namespace sf {+// Where a brush in the library came from (see core/BrushLibrary.h). Precedence+// for brushes of the same name: user library > studio folders > built-in.+enum class BrushSource {+ Session, // made this session and not in the library (brush_create, brush_load, an AI reply not yet saved)+ Builtin, // ships with SculptForge+ User, // the artist's own library (<app data>/brushes), saved automatically+ Studio, // a read-only shared folder from SCULPTFORGE_BRUSH_PATH+ Gallery, // installed from the community gallery (lives in the user library)+ Project, // came with an opened .sfproj and differs from (or is not in) the library+};+const char* brushSourceName(BrushSource source); // "session", "built-in", "user", "studio", "gallery", "project"++struct BrushOrigin {+ BrushSource source = BrushSource::Session;+ std::string path; // the .sfbrush file it was loaded from or is saved to (user, gallery, studio)+ // A built-in or studio brush of the same name this user/gallery brush hides (Session = none).+ BrushSource overrides = BrushSource::Session;+};+struct BrushRecipe {enum class Direction { Normal, Inflate, View, Stroke };enum class Plane { None, Clay, Flatten, Fill, Scrape };@@ -49,6 +68,9 @@ struct BrushRecipe {bool frontFacesOnly = false;float cavityMask = 0.0f; // -1..1: >0 only affects cavities, <0 only ridges/peaks+ // Library bookkeeping, not part of the recipe: never written by toJson().+ BrushOrigin origin;+void clamp();// Numeric parameter by key (see recipeParams()), or nullptr.float* field(const std::string& key);diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex e6aa494e..6d951e1d 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -3,6 +3,7 @@#include "core/Commands.h"#include "core/BrushAlpha.h"+#include "core/BrushLibrary.h"#include "core/Decimate.h"#include "core/EnginePresets.h"#include "core/ImageTo3D.h"@@ -504,12 +505,12 @@ CommandRegistry::CommandRegistry() {}});}- add({"brush_list", "List the custom brushes in the library.", {},+ add({"brush_list", "List the custom brushes in the library (brush_library also shows their files).", {},[](Document& doc, const Args&) -> CommandResult {std::string out;for (size_t i = 0; i < doc.brushes.size(); ++i)- out += (i ? "\n" : "") + std::to_string(i) + ": " + doc.brushes[i].name + " - " +- doc.brushes[i].description;+ out += (i ? "\n" : "") + std::to_string(i) + ": " + doc.brushes[i].name + " [" ++ brushSourceName(doc.brushes[i].origin.source) + "] - " + doc.brushes[i].description;return {true, out};}});@@ -528,7 +529,7 @@ CommandRegistry::CommandRegistry() {return {true, "Saved brush '" + r->name + "'"};}});- add({"brush_load", "Load a .sfbrush file into the library and make it active.",+ add({"brush_load", "Load a .sfbrush file for this session and make it active (brush_install keeps it in your library).",{{"path", T::String, ".sfbrush path.", true}},[](Document& doc, const Args& a) -> CommandResult {BrushRecipe r;@@ -537,6 +538,7 @@ CommandRegistry::CommandRegistry() {doc.activeBrush = doc.addBrush(std::move(r));return {true, "Loaded brush '" + doc.brushes[doc.activeBrush].name + "'"};}});+ registerBrushLibraryCommands(*this); // brush_install, brush_code, brush_delete, ... (BrushLibrary.cpp)registerBrushCommands(*this); // brush_set_alpha (BrushAlpha.cpp)add({"splat_info", "Report the loaded Gaussian splats.", {},diff --git a/src/core/Document.cpp b/src/core/Document.cppindex 77c1bb1f..d35cd4e5 100644--- a/src/core/Document.cpp+++ b/src/core/Document.cpp@@ -131,6 +131,8 @@ int Document::addBrush(BrushRecipe recipe) {recipe.clamp();for (size_t i = 0; i < brushes.size(); ++i) {if (brushes[i].name == recipe.name) {+ // A session recipe with a library brush's name is an edit of that brush: it keeps its origin.+ if (recipe.origin.source == BrushSource::Session) recipe.origin = brushes[i].origin;brushes[i] = std::move(recipe);return int(i);}diff --git a/src/core/Document.h b/src/core/Document.hindex 01b2f969..0506751a 100644--- a/src/core/Document.h+++ b/src/core/Document.h@@ -46,12 +46,14 @@ struct Document {std::string path; // empty until saved/loadedbool modified = false; // set by edits the undo stack doesn't see (e.g. layer weights)int activeLayer = -1; // sculpt layer strokes write into (-1 = base)- // Recipe brush library (built-ins, loaded .sfbrush files, AI-made brushes).+ // Recipe brush library (built-ins, studio and user library brushes, loaded .sfbrush files,+ // AI-made brushes; see core/BrushLibrary.h). Each recipe records its origin.std::vector<BrushRecipe> brushes = builtinBrushRecipes();int activeBrush = -1; // index into `brushes`, -1 = use a built-in brush typeBrushAlpha brushAlpha; // stamp shaping every brush's falloff (empty = round); brush_set_alphaglm::vec3 paintColor{0.6f, 0.03f, 0.02f}; // current polypaint colour (linear RGB; see set_color)- // Adds or replaces (by name) a recipe and returns its index.+ // Adds or replaces (by name) a recipe and returns its index. Replacing with a+ // BrushSource::Session recipe keeps the existing brush's origin.int addBrush(BrushRecipe recipe);// Gaussian splats shown alongside the mesh (a capture used as reference or// source, or the sculpt converted for splat viewers). Not part of undo.diff --git a/src/core/Project.cpp b/src/core/Project.cppindex 8a4f06ce..3f677a04 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -410,8 +410,18 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {doc.selectSubtool(activeSubtool);doc.splats = std::move(splats);doc.splatsChanged();- for (const auto& b : manifest["brushes"].items())- if (b.isObject()) doc.addBrush(BrushRecipe::fromJson(b));+ for (const auto& b : manifest["brushes"].items()) {+ if (!b.isObject()) continue;+ // Brushes the library already has, unchanged, stay library brushes; the rest are the project's own.+ BrushRecipe recipe = BrushRecipe::fromJson(b);+ const std::string json = recipe.toJson().dump();+ const bool known = std::any_of(doc.brushes.begin(), doc.brushes.end(), [&](const BrushRecipe& have) {+ return have.name == recipe.name && have.toJson().dump() == json;+ });+ if (known) continue;+ recipe.origin.source = BrushSource::Project;+ doc.addBrush(std::move(recipe));+ }doc.activeBrush = -1;const std::string& activeBrush = manifest["active_brush"].asString();for (size_t i = 0; i < doc.brushes.size() && !activeBrush.empty(); ++i)diff --git a/src/python/module.cpp b/src/python/module.cppindex ff18491a..adfc87de 100644--- a/src/python/module.cpp+++ b/src/python/module.cpp@@ -11,6 +11,7 @@// verts, tris = doc.vertices, doc.triangles # (N, 3) float32, (M, 3) uint32// doc.mask, doc.colors, doc.polygroups # optional attributes, None when absent#include "ai/AiCommands.h"+#include "core/BrushLibrary.h"#include "core/Commands.h"#include "core/Script.h"@@ -19,6 +20,7 @@#include <pybind11/stl.h>#include <cstring>+#include <memory>namespace py = pybind11;using namespace sf;@@ -97,7 +99,13 @@ PYBIND11_MODULE(sculptforge, m) {py::register_exception<CommandError>(m, "CommandError", PyExc_RuntimeError);py::class_<Document>(m, "Document", "A scene: the sculpt mesh (with layers), Gaussian splats and edit history.")- .def(py::init<>())+ .def(py::init([] {+ // With the user's brush library and SCULPTFORGE_BRUSH_PATH studio brushes, like the app.+ auto doc = std::make_unique<Document>();+ for (const auto& message : loadBrushLibrary(*doc))+ if (PyErr_WarnEx(PyExc_RuntimeWarning, message.c_str(), 1) < 0) throw py::error_already_set();+ return doc;+ })).def_property_readonly("vertices", [](const Document& d) { return vec3Array(d.mesh.positions); },"Current vertex positions, (N, 3) float32 (a copy).").def_property_readonly("base_vertices", [](const Document& d) { return vec3Array(d.mesh.basePositions()); },diff --git a/tests/test_brush_library.cpp b/tests/test_brush_library.cppnew file mode 100644index 00000000..84954b60--- /dev/null+++ b/tests/test_brush_library.cpp@@ -0,0 +1,412 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The persistent brush library: load order and precedence, bad files, brush+// codes, install / update / rename / delete, read-only studio folders.+#include "TestHarness.h"++#include "core/BrushLibrary.h"+#include "core/Commands.h"+#include "core/Project.h"++#include <filesystem>+#include <fstream>+#include <map>++using namespace sf;+namespace fs = std::filesystem;++namespace {++// A fresh user library and two studio folders under the temp directory, used by+// the brush commands for the lifetime of the fixture.+struct LibraryFixture {+ fs::path root, user, studioA, studioB;+ BrushLibraryPaths saved = brushLibraryPaths();++ explicit LibraryFixture(const char* name) {+ root = fs::temp_directory_path() / (std::string("sculptforge_brushlib_") + name);+ fs::remove_all(root);+ user = root / "user";+ studioA = root / "studioA";+ studioB = root / "studioB";+ fs::create_directories(studioA);+ fs::create_directories(studioB);+ brushLibraryPaths() = paths();+ }+ ~LibraryFixture() {+ brushLibraryPaths() = saved;+ std::error_code ec;+ fs::remove_all(root, ec);+ }+ BrushLibraryPaths paths() const { return {user.string(), {studioA.string(), studioB.string()}}; }+};++void writeText(const fs::path& path, const std::string& text) {+ fs::create_directories(path.parent_path());+ std::ofstream(path, std::ios::binary) << text;+}++void writeBrush(const fs::path& path, const std::string& name, float depth) {+ BrushRecipe r;+ r.name = name;+ r.depth = depth;+ std::string err;+ fs::create_directories(path.parent_path());+ CHECK(r.save(path.string(), err));+}++const BrushRecipe* find(const Document& doc, const std::string& name) {+ for (const auto& b : doc.brushes)+ if (b.name == name) return &b;+ return nullptr;+}++int count(const Document& doc, const std::string& name) {+ int n = 0;+ for (const auto& b : doc.brushes) n += b.name == name;+ return n;+}++// Snapshot of every file under a folder (path -> contents), to prove nothing was written.+std::map<std::string, std::string> snapshot(const fs::path& dir) {+ std::map<std::string, std::string> out;+ for (const auto& e : fs::recursive_directory_iterator(dir)) {+ if (!e.is_regular_file()) continue;+ std::ifstream f(e.path(), std::ios::binary);+ out[e.path().string()] = std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());+ }+ return out;+}++} // namespace++TEST(brush_library_precedence_user_over_studio_over_builtin) {+ LibraryFixture lib("precedence");+ writeBrush(lib.studioA / "wrinkle.sfbrush", "Wrinkle", 0.11f); // overrides the built-in+ writeBrush(lib.studioA / "a.sfbrush", "Studio Only", 0.2f);+ writeBrush(lib.studioB / "a.sfbrush", "Studio Only", 0.9f); // later folder loses+ writeBrush(lib.studioB / "both.sfbrush", "Shared", 0.3f);+ writeBrush(lib.user / "Shared.sfbrush", "Shared", 0.44f); // the user's version wins+ writeBrush(lib.user / "Mine.sfbrush", "Mine", -0.5f);++ Document doc;+ const auto messages = loadBrushLibrary(doc, lib.paths());+ CHECK(messages.empty());+ const size_t builtins = builtinBrushRecipes().size();+ CHECK(doc.brushes.size() == builtins + 3);++ const BrushRecipe* wrinkle = find(doc, "Wrinkle");+ CHECK(wrinkle && wrinkle->origin.source == BrushSource::Studio && wrinkle->origin.overrides == BrushSource::Builtin);+ CHECK(wrinkle && std::abs(wrinkle->depth - 0.11f) < 1e-4f);+ const BrushRecipe* studio = find(doc, "Studio Only");+ CHECK(studio && std::abs(studio->depth - 0.2f) < 1e-4f && studio->origin.source == BrushSource::Studio);+ const BrushRecipe* shared = find(doc, "Shared");+ CHECK(shared && shared->origin.source == BrushSource::User && shared->origin.overrides == BrushSource::Studio);+ CHECK(shared && std::abs(shared->depth - 0.44f) < 1e-4f);+ CHECK(count(doc, "Shared") == 1);+ const BrushRecipe* mine = find(doc, "Mine");+ CHECK(mine && mine->origin.source == BrushSource::User && mine->origin.overrides == BrushSource::Session);+ CHECK(mine && fs::path(mine->origin.path).filename() == "Mine.sfbrush");+ const BrushRecipe* palette = find(doc, "Palette Knife");+ CHECK(palette && palette->origin.source == BrushSource::Builtin);++ // The active brush survives a reload by name.+ doc.activeBrush = int(mine - doc.brushes.data());+ loadBrushLibrary(doc, lib.paths());+ CHECK(doc.activeBrush >= 0 && doc.brushes[size_t(doc.activeBrush)].name == "Mine");+}++TEST(brush_library_skips_bad_files) {+ LibraryFixture lib("badfiles");+ writeText(lib.user / "garbage.sfbrush", "this is not json {{{");+ writeText(lib.user / "array.sfbrush", "[1, 2, 3]");+ writeText(lib.user / "other.sfbrush", R"({"format": "sfproj", "name": "Nope"})");+ writeText(lib.user / "empty.sfbrush", "");+ writeText(lib.user / "huge.sfbrush", std::string(kMaxBrushFileSize + 10, ' '));+ writeText(lib.user / "notes.txt", "ignored: not a brush file");+ // Out-of-range values are clamped, unknown keys and wrong types ignored.+ writeText(lib.user / "wild.sfbrush",+ R"({"format": "sfbrush", "name": "Wild", "depth": 99, "spacing": -5, "pattern": "lasers", "jitter": "lots", "extra": 1})");+ writeBrush(lib.user / "dup-a.sfbrush", "Twin", 0.1f);+ writeBrush(lib.user / "dup-b.sfbrush", "Twin", 0.9f);+ fs::create_directories(lib.user / "folder.sfbrush"); // a directory with a brush-like name++ Document doc;+ BrushLibraryPaths paths = lib.paths();+ paths.studioDirs.push_back((lib.root / "missing").string());+ const auto messages = loadBrushLibrary(doc, paths);+ CHECK(messages.size() == 7); // garbage, array, other, empty, huge, the second Twin, the missing folder+ const BrushRecipe* wild = find(doc, "Wild");+ CHECK(wild && wild->depth == 1.0f && wild->spacing == 0.02f && wild->pattern == BrushRecipe::Pattern::None);+ CHECK(count(doc, "Twin") == 1);+ const BrushRecipe* twin = find(doc, "Twin");+ CHECK(twin && std::abs(twin->depth - 0.1f) < 1e-4f); // first file by name wins+ CHECK(!find(doc, "Nope"));+}++TEST(brush_codes_round_trip) {+ BrushRecipe r = builtinBrushRecipes()[2];+ r.name = "Drachenschuppen – ñ"; // UTF-8 survives+ r.jitter = 0.37f;+ r.frontFacesOnly = true;+ const std::string code = encodeBrushCode(r);+ CHECK(code.rfind("sfbrush1:", 0) == 0);+ CHECK(code.find_first_of("+/= \n") == std::string::npos); // base64url, no padding, one line+ BrushRecipe back;+ std::string err;+ CHECK(decodeBrushCode(code, back, err));+ CHECK(back.toJson().dump() == r.toJson().dump());+ CHECK(back.origin.source == BrushSource::Session);++ // Surrounding text, wrapping and padding from chat or email are fine.+ CHECK(parseBrushText("Try my brush: " + code + "\nhave fun", back, err) && back.name == r.name);+ std::string wrapped = code;+ wrapped.insert(20, "\n ");+ CHECK(decodeBrushCode(" " + wrapped + "==\n", back, err) && back.name == r.name);+ // .sfbrush JSON pastes too.+ CHECK(parseBrushText(r.toJson().dump(true), back, err) && back.jitter == r.jitter);+}++TEST(brush_codes_reject_garbage) {+ BrushRecipe out;+ std::string err;+ CHECK(!decodeBrushCode("", out, err));+ CHECK(!decodeBrushCode("hello world", out, err));+ CHECK(!decodeBrushCode("sfbrush1:", out, err));+ CHECK(!decodeBrushCode("sfbrush1:!!!not*base64", out, err));+ CHECK(!decodeBrushCode("sfbrush1:QQ", out, err)); // decodes to "A": not JSON+ CHECK(!decodeBrushCode("sfbrush1:WzEsMl0", out, err)); // [1,2]: not a brush+ CHECK(!decodeBrushCode("sfbrush2:eyJuYW1lIjoiWCJ9", out, err));+ CHECK(err.find("newer") != std::string::npos);+ // Truncated code: base64 of half a JSON object.+ const std::string code = encodeBrushCode(builtinBrushRecipes()[0]);+ CHECK(!decodeBrushCode(code.substr(0, code.size() / 2), out, err));+ // Oversize: rejected before decoding.+ CHECK(!decodeBrushCode("sfbrush1:" + std::string(kMaxBrushCodeSize, 'A'), out, err));+ CHECK(err.find("too long") != std::string::npos);+ CHECK(!parseBrushText("just some text", out, err));+ CHECK(!parseBrushText("{\"not\": \"a brush\"}", out, err));+ CHECK(!parseBrushText("{" + std::string(kMaxBrushFileSize, ' ') + "}", out, err));+ // Values in a code are clamped like a file.+ const std::string wild = "sfbrush1:eyJuYW1lIjoiWCIsImRlcHRoIjo1MH0"; // {"name":"X","depth":50}+ CHECK(decodeBrushCode(wild, out, err) && out.name == "X" && out.depth == 1.0f);+}++TEST(brush_file_names_are_safe) {+ CHECK(brushFileName("Dragon Scales") == "Dragon Scales.sfbrush");+ CHECK(brushFileName("a/b\\c:d*e?f\"g<h>i|j") == "a_b_c_d_e_f_g_h_i_j.sfbrush");+ CHECK(brushFileName("../../etc/passwd") == "_.._etc_passwd.sfbrush");+ CHECK(brushFileName("...") == "Brush.sfbrush");+ CHECK(brushFileName("con") == "_con.sfbrush");+ CHECK(brushFileName("Trailing. ") == "Trailing.sfbrush");+}++TEST(brush_install_update_and_delete) {+ LibraryFixture lib("install");+ CommandRegistry reg;+ Document doc;+ loadBrushLibrary(doc, lib.paths());+ const size_t builtins = doc.brushes.size();++ BrushRecipe r;+ r.name = "Bark";+ r.depth = 0.25f;+ r.pattern = BrushRecipe::Pattern::Ridges;+ const std::string code = encodeBrushCode(r);+ auto res = reg.execute(doc, "brush_install", {{"code", code}});+ CHECK(res.ok && res.message.find("Installed") != std::string::npos);+ CHECK(doc.brushes.size() == builtins + 1);+ CHECK(doc.activeBrush >= 0 && doc.brushes[size_t(doc.activeBrush)].name == "Bark");+ CHECK(doc.brushes[size_t(doc.activeBrush)].origin.source == BrushSource::User);+ CHECK(fs::exists(lib.user / "Bark.sfbrush"));++ // Re-installing the same name updates the same file.+ r.depth = -0.6f;+ res = reg.execute(doc, "brush_install", {{"json", r.toJson().dump()}});+ CHECK(res.ok && res.message.find("Updated") != std::string::npos);+ CHECK(doc.brushes.size() == builtins + 1);+ CHECK(std::distance(fs::directory_iterator(lib.user), fs::directory_iterator()) == 1);+ Document fresh;+ loadBrushLibrary(fresh, lib.paths());+ CHECK(find(fresh, "Bark") && std::abs(find(fresh, "Bark")->depth + 0.6f) < 1e-4f);++ // From a file, marked as a gallery brush.+ BrushRecipe g;+ g.name = "Gallery Moss";+ std::string err;+ const fs::path download = lib.root / "download.sfbrush";+ CHECK(g.save(download.string(), err));+ CHECK(reg.execute(doc, "brush_install", {{"path", download.string()}, {"source", std::string("gallery")}}).ok);+ loadBrushLibrary(fresh, lib.paths());+ CHECK(find(fresh, "Gallery Moss") && find(fresh, "Gallery Moss")->origin.source == BrushSource::Gallery);++ // Argument checks.+ CHECK(!reg.execute(doc, "brush_install", {}).ok);+ CHECK(!reg.execute(doc, "brush_install", {{"code", code}, {"json", std::string("{}")}}).ok);+ CHECK(!reg.execute(doc, "brush_install", {{"code", std::string("sfbrush1:@@")}}).ok);+ CHECK(!reg.execute(doc, "brush_install", {{"path", (lib.root / "nope.sfbrush").string()}}).ok);++ // brush_code prints a code that installs the same brush.+ res = reg.execute(doc, "brush_code", {{"name", std::string("Bark")}});+ CHECK(res.ok && res.message.rfind("sfbrush1:", 0) == 0);+ BrushRecipe decoded;+ CHECK(decodeBrushCode(res.message, decoded, err) && std::abs(decoded.depth + 0.6f) < 1e-4f);+ CHECK(!reg.execute(doc, "brush_code", {{"name", std::string("Nobody")}}).ok);++ // brush_library lists source and path.+ res = reg.execute(doc, "brush_library", {});+ CHECK(res.ok && res.message.find("Bark [user]") != std::string::npos);+ CHECK(res.message.find("Gallery Moss [gallery]") != std::string::npos);+ CHECK(res.message.find("Wrinkle [built-in]") != std::string::npos);+ CHECK(reg.execute(doc, "brush_list", {}).message.find("Bark [user]") != std::string::npos);++ // Delete: user brushes only, file removed.+ doc.activeBrush = int(find(doc, "Bark") - doc.brushes.data());+ CHECK(reg.execute(doc, "brush_delete", {{"name", std::string("Bark")}}).ok);+ CHECK(!find(doc, "Bark") && !fs::exists(lib.user / "Bark.sfbrush"));+ CHECK(doc.activeBrush == -1);+ CHECK(!reg.execute(doc, "brush_delete", {{"name", std::string("Wrinkle")}}).ok);+ CHECK(find(doc, "Wrinkle"));+}++TEST(brush_library_overrides_and_restores) {+ LibraryFixture lib("override");+ writeBrush(lib.studioA / "chisel.sfbrush", "Stone Chisel", 0.05f);+ Document doc;+ loadBrushLibrary(doc, lib.paths());+ const size_t n = doc.brushes.size();++ // Refining a studio brush saves the artist's version; the studio file is untouched.+ const auto before = snapshot(lib.studioA);+ const int i = int(find(doc, "Stone Chisel") - doc.brushes.data());+ doc.brushes[size_t(i)].depth = -0.9f;+ std::string err;+ CHECK(saveBrushToLibrary(doc, i, err, false, lib.paths()));+ CHECK(doc.brushes[size_t(i)].origin.source == BrushSource::User);+ CHECK(doc.brushes[size_t(i)].origin.overrides == BrushSource::Studio);+ CHECK(fs::path(doc.brushes[size_t(i)].origin.path).parent_path() == lib.user);+ CHECK(snapshot(lib.studioA) == before);+ CHECK(doc.brushes.size() == n);++ // Deleting the user's version brings the studio one back.+ CHECK(deleteBrush(doc, i, err, lib.paths()));+ CHECK(doc.brushes.size() == n);+ CHECK(doc.brushes[size_t(i)].origin.source == BrushSource::Studio);+ CHECK(std::abs(doc.brushes[size_t(i)].depth - 0.05f) < 1e-4f);+ CHECK(snapshot(lib.studioA) == before);++ // Studio brushes can't be deleted.+ CHECK(!deleteBrush(doc, i, err, lib.paths()));+ CHECK(err.find("studio") != std::string::npos);++ // Same for a built-in: edit, save, delete -> the built-in is back.+ const int w = int(find(doc, "Wrinkle") - doc.brushes.data());+ doc.brushes[size_t(w)].pinch = -0.3f;+ CHECK(saveBrushToLibrary(doc, w, err, false, lib.paths()));+ CHECK(doc.brushes[size_t(w)].origin.overrides == BrushSource::Builtin);+ Document reloaded;+ loadBrushLibrary(reloaded, lib.paths());+ CHECK(find(reloaded, "Wrinkle")->origin.source == BrushSource::User);+ CHECK(deleteBrush(doc, w, err, lib.paths()));+ CHECK(doc.brushes[size_t(w)].origin.source == BrushSource::Builtin && doc.brushes[size_t(w)].pinch > 0.5f);+ CHECK(snapshot(lib.studioA) == before);+}++TEST(brush_rename) {+ LibraryFixture lib("rename");+ CommandRegistry reg;+ Document doc;+ loadBrushLibrary(doc, lib.paths());+ const size_t n = doc.brushes.size();+ BrushRecipe r;+ r.name = "Moss";+ std::string err;+ installBrush(doc, r, err, false, lib.paths());+ CHECK(err.empty() && fs::exists(lib.user / "Moss.sfbrush"));++ CHECK(reg.execute(doc, "brush_rename", {{"name", std::string("Moss")}, {"to", std::string("Lichen")}}).ok);+ CHECK(!find(doc, "Moss") && find(doc, "Lichen"));+ CHECK(!fs::exists(lib.user / "Moss.sfbrush") && fs::exists(lib.user / "Lichen.sfbrush"));+ CHECK(doc.brushes[size_t(doc.activeBrush)].name == "Lichen");+ // Clashes and empty names are refused.+ CHECK(!reg.execute(doc, "brush_rename", {{"name", std::string("Lichen")}, {"to", std::string("Wrinkle")}}).ok);+ CHECK(!reg.execute(doc, "brush_rename", {{"name", std::string("Lichen")}, {"to", std::string(" ")}}).ok);++ // Renaming a built-in keeps it and saves a renamed copy.+ CHECK(reg.execute(doc, "brush_rename", {{"name", std::string("Edge Wear")}, {"to", std::string("My Wear")}}).ok);+ CHECK(find(doc, "Edge Wear") && find(doc, "Edge Wear")->origin.source == BrushSource::Builtin);+ CHECK(find(doc, "My Wear") && find(doc, "My Wear")->origin.source == BrushSource::User);+ CHECK(doc.brushes.size() == n + 2);+ CHECK(fs::exists(lib.user / "My Wear.sfbrush"));++ // Renaming a user brush that overrode a built-in brings the built-in back.+ const int w = int(find(doc, "Wrinkle") - doc.brushes.data());+ CHECK(saveBrushToLibrary(doc, w, err, false, lib.paths()));+ CHECK(reg.execute(doc, "brush_rename", {{"name", std::string("Wrinkle")}, {"to", std::string("Deep Wrinkle")}}).ok);+ CHECK(find(doc, "Wrinkle") && find(doc, "Wrinkle")->origin.source == BrushSource::Builtin);+ CHECK(find(doc, "Deep Wrinkle") && find(doc, "Deep Wrinkle")->origin.source == BrushSource::User);+ CHECK(!fs::exists(lib.user / "Wrinkle.sfbrush"));+}++TEST(brush_library_file_name_clash) {+ LibraryFixture lib("clash");+ Document doc;+ loadBrushLibrary(doc, lib.paths());+ std::string err;+ BrushRecipe a, b;+ a.name = "Rock/Moss";+ b.name = "Rock_Moss"; // same safe file name, different brush+ installBrush(doc, a, err, false, lib.paths());+ installBrush(doc, b, err, false, lib.paths());+ CHECK(fs::exists(lib.user / "Rock_Moss.sfbrush") && fs::exists(lib.user / "Rock_Moss 2.sfbrush"));+ Document fresh;+ CHECK(loadBrushLibrary(fresh, lib.paths()).empty());+ CHECK(find(fresh, "Rock/Moss") && find(fresh, "Rock_Moss"));+}++TEST(brush_library_without_user_dir_saves_nothing) {+ LibraryFixture lib("nodir");+ brushLibraryPaths().userDir.clear();+ CommandRegistry reg;+ Document doc;+ BrushRecipe r;+ r.name = "Temp";+ auto res = reg.execute(doc, "brush_install", {{"code", encodeBrushCode(r)}});+ CHECK(res.ok && find(doc, "Temp"));+ CHECK(!fs::exists(lib.user));+}++TEST(brush_library_projects_keep_library_origins) {+ LibraryFixture lib("project");+ Document doc;+ loadBrushLibrary(doc, lib.paths());+ std::string err;+ BrushRecipe mine;+ mine.name = "Mine";+ installBrush(doc, mine, err, false, lib.paths());+ BrushRecipe extra;+ extra.name = "From Project";+ doc.addBrush(extra);+ const std::string path = tempPath("sculptforge_brushlib.sfproj");+ CHECK(saveProject(path, doc, err));++ Document opened;+ loadBrushLibrary(opened, lib.paths());+ CHECK(loadProject(path, opened, err));+ CHECK(find(opened, "Mine") && find(opened, "Mine")->origin.source == BrushSource::User);+ CHECK(find(opened, "Wrinkle")->origin.source == BrushSource::Builtin);+ CHECK(find(opened, "From Project") && find(opened, "From Project")->origin.source == BrushSource::Project);+ fs::remove(path);+}++TEST(brush_search_path_split) {+#if defined(_WIN32)+ const auto parts = splitSearchPath("C:\\a;; D:\\b ;");+ CHECK(parts.size() == 2 && parts[0] == "C:\\a" && parts[1] == "D:\\b");+#else+ const auto parts = splitSearchPath("/a:: /b c :");+ CHECK(parts.size() == 2 && parts[0] == "/a" && parts[1] == "/b c");+#endif+ CHECK(splitSearchPath("").empty());+}diff --git a/tests/ui/brush_sharing.sfui b/tests/ui/brush_sharing.sfuinew file mode 100644index 00000000..e5698901--- /dev/null+++ b/tests/ui/brush_sharing.sfui@@ -0,0 +1,89 @@+# Brush sharing: brushes refined in Brush Lab are saved to the library, shared as a brush code+# (right-click > Copy brush code), deleted, and pasted back with Ctrl+V or Brush Lab's Paste brush.+# UI tests get an empty library of their own in --ui-out/brush-library.+expect_value user_brushes == 0+expect_value library_files == 0++# A brush made this session is marked unsaved until it's refined in Brush Lab.+run brush_create name="Bark Ridges" depth=0.3 pattern=ridges patternAmount=0.6+expect "Bark Ridges"+expect_text Bark Ridges [unsaved]+click "Recipe: Bark Ridges"+click "Brush Lab/Front faces only"+wait 1.2+expect_value library_files == 1+expect_value user_brushes == 1+expect_status Saved 'Bark Ridges' to your brush library+expect_no_text Bark Ridges [unsaved]+shot saved++# Copy its code, then delete it (with a confirmation).+right_click "Bark Ridges"+expect "Copy brush code"+expect "Reveal in folder"+shot menu+click "Copy brush code"+expect_clipboard sfbrush1:+expect_status Copied the brush code for 'Bark Ridges'+right_click "Bark Ridges"+click "Delete...##brush"+expect_text Delete 'Bark Ridges' from your brush library?+shot confirm-delete+click "Delete brush?/Delete"+expect_not "Bark Ridges"+expect_value library_files == 0+expect_value user_brushes == 0++# Paste the code back with Ctrl+V in the viewport: installed into the library again.+key ctrl+v+expect_status Pasted brush 'Bark Ridges' - it's in your brush library+expect "Bark Ridges"+expect_value library_files == 1+run brush_library+expect_status Bark Ridges [user]++# Text that isn't a brush is refused with a message.+clipboard just some notes, not a brush+key ctrl+v+expect_status No brush found+expect_value library_files == 1++# A code someone shared in chat (with words around it), via Brush Lab's Paste brush.+clipboard "Try my moss: sfbrush1:eyJuYW1lIjoiU2hhcmVkIE1vc3MiLCJkZXNjcmlwdGlvbiI6IiIsImRpcmVjdGlvbiI6Im5vcm1hbCIsImRlcHRoIjowLjIsInBsYW5lIjoibm9uZSIsInBsYW5lQW1vdW50IjowLjUsInBpbmNoIjowLCJkcmFnIjowLCJzbW9vdGgiOjAsImhhcmRuZXNzIjowLCJ0aXBTaGFycG5lc3MiOjAsInBhdHRlcm4iOiJub2lzZSIsInBhdHRlcm5TY2FsZSI6MC4yLCJwYXR0ZXJuQW1vdW50IjowLjUsInNwYWNpbmciOjAuMTUsImppdHRlciI6MCwicHJlc3N1cmVDdXJ2ZSI6MSwiZnJvbnRGYWNlc09ubHkiOmZhbHNlLCJjYXZpdHlNYXNrIjowfQ enjoy"+click "Paste brush"+expect_status Pasted brush 'Shared Moss'+expect "Shared Moss"+expect_value library_files == 2++# Rename it from the menu: the library file follows.+right_click "Shared Moss"+click "Rename...##brush"+type "Rename brush/##newname" Wet Moss+click "Rename brush/Rename"+expect "Wet Moss"+expect_not "Shared Moss"+expect_value library_files == 2+expect_value user_brushes == 2++# Gallery installs are tagged; the tooltip says where a brush lives.+run brush_install source=gallery code=sfbrush1:eyJuYW1lIjoiU2hhcmVkIE1vc3MiLCJkZXNjcmlwdGlvbiI6IiIsImRpcmVjdGlvbiI6Im5vcm1hbCIsImRlcHRoIjowLjIsInBsYW5lIjoibm9uZSIsInBsYW5lQW1vdW50IjowLjUsInBpbmNoIjowLCJkcmFnIjowLCJzbW9vdGgiOjAsImhhcmRuZXNzIjowLCJ0aXBTaGFycG5lc3MiOjAsInBhdHRlcm4iOiJub2lzZSIsInBhdHRlcm5TY2FsZSI6MC4yLCJwYXR0ZXJuQW1vdW50IjowLjUsInNwYWNpbmciOjAuMTUsImppdHRlciI6MCwicHJlc3N1cmVDdXJ2ZSI6MSwiZnJvbnRGYWNlc09ubHkiOmZhbHNlLCJjYXZpdHlNYXNrIjowfQ+expect_text Shared Moss [gallery]+wait 0.2 # the list scrolls the new brush into view+hover "Shared Moss"+expect_text From the community gallery+shot gallery-tooltip++# Built-in brushes can't be deleted; refining one saves the artist's version, tagged "yours".+right_click "Wrinkle"+click "Rename...##brush"+expect_text The built-in brush stays as it is+shot rename-builtin+key escape+click "Wrinkle"+expect "Recipe: Wrinkle" # the recipe section stays open+click "Brush Lab/Front faces only"+wait 1.2+expect_status Saved your version of 'Wrinkle'+expect_text Wrinkle [yours]+expect_value library_files == 4+shot final