Skip to content

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.

Brushes: DamStandard, ClayBuildup, SnakeHook, Trim, Layer, Nudge; stroke types; alphas

islandmedb0a54ee7d382
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4e439795..97e8ddbe 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -41,6 +41,8 @@ add_library(sculptforge_core STATIC
src/core/Splats.cpp
src/core/Voxel.cpp
src/core/EnginePresets.cpp
+ src/core/BrushAlpha.cpp
+ src/core/Stroke.cpp
src/io/ObjIO.cpp
src/io/FbxIO.cpp
third_party/ufbx/ufbx.c
@@ -103,6 +105,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/main.cpp
src/app/App.cpp
src/app/Demo.cpp
+ src/app/PanelBrushes.cpp
src/render/GL.cpp
src/render/Camera.cpp
src/render/Renderer.cpp
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 2125f4ba..84420ec3 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -521,7 +521,9 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
case SDLK_F: camera_.frame(sceneBounds()); break;
case SDLK_F1: showHelp_ = !showHelp_; break;
default:
- if (key >= SDLK_1 && key < SDLK_1 + int(BrushType::Count)) brush_ = BrushType(key - SDLK_1);
+ // 1-9 pick the first nine brushes, 0 the tenth.
+ if (key >= SDLK_1 && key <= SDLK_9) brush_ = BrushType(key - SDLK_1);
+ else if (key == SDLK_0) brush_ = BrushType(9);
break;
}
}
@@ -560,6 +562,16 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
grabPlanePoint_ = grabLast_ = hit.position;
return;
}
+ lazyMouse_.reset(glm::vec2(x, y));
+ if (strokeBrush_ == BrushType::SnakeHook && !recipe) {
+ grabPlanePoint_ = grabLast_ = hit.position; // the pulled tip (see snakeHookTo)
+ return;
+ }
+ if (strokeType_ == StrokeType::DragRect) {
+ dragAnchor_ = glm::vec2(x, y);
+ dragAnchorHit_ = hit.position;
+ return; // the stamp appears once the drag gives it a size
+ }
dabAt(x, y);
}
@@ -579,6 +591,19 @@ void App::strokeTo(float x, float y) {
grabLast_ = p;
return;
}
+ if (strokeBrush_ == BrushType::SnakeHook && !recipe) {
+ snakeHookTo(x, y);
+ return;
+ }
+ if (strokeType_ == StrokeType::DragRect) {
+ dragRectTo(x, y);
+ return;
+ }
+ if (strokeType_ == StrokeType::LazyMouse) {
+ const glm::vec2 lazy = lazyMouse_.follow(glm::vec2(x, y));
+ x = lazy.x;
+ y = lazy.y;
+ }
// Place dabs at even screen-space spacing along the cursor path.
const float spacing = std::max(1.0f, radiusPx_ * (recipe ? recipe->spacing : 0.15f));
@@ -608,6 +633,16 @@ void App::dabAt(float x, float y) {
x += rnd() * recipe->jitter * radiusPx_;
y += rnd() * recipe->jitter * radiusPx_;
}
+ dabRadiusScale_ = dabStrengthScale_ = 1.0f;
+ dabAngle_ = 0.0f;
+ if (strokeType_ == StrokeType::Spray) {
+ const SprayDab s = spray_.next(radiusPx_, sprayScatter_);
+ x += s.offset.x;
+ y += s.offset.y;
+ dabRadiusScale_ = s.scale;
+ dabStrengthScale_ = s.strength;
+ dabAngle_ = s.angle;
+ }
RayHit hit;
if (!pick(x, y, hit)) return;
int w = 0, h = 0;
@@ -618,15 +653,17 @@ void App::dabAt(float x, float y) {
p.center = hit.position;
p.viewDir = camera_.forward();
p.radius = radiusPx_ * (pressureSize_ ? std::max(pressure, 0.05f) : 1.0f) *
- camera_.worldPerPixel(hit.position, float(h));
- p.strength = strength_;
+ camera_.worldPerPixel(hit.position, float(h)) * dabRadiusScale_;
+ p.strength = strength_ * dabStrengthScale_;
p.pressure = pressureStrength_ ? pressure : 1.0f;
p.invert = strokeInvert_;
p.frontFacesOnly = frontFacesOnly_;
+ p.alpha = &doc_.brushAlpha;
+ p.alphaUp = screenUpVector(dabAngle_);
+ p.strokeDelta = haveLastDab_ ? hit.position - lastDabHit_ : glm::vec3(0.0f);
+ lastDabHit_ = hit.position;
+ haveLastDab_ = true;
if (recipe) {
- p.strokeDelta = haveLastDab_ ? hit.position - lastDabHit_ : glm::vec3(0.0f);
- lastDabHit_ = hit.position;
- haveLastDab_ = true;
doc_.sculptor.dabRecipe(doc_.mesh, doc_.bvh, *recipe, p, symmetry_);
return;
}
@@ -1585,7 +1622,9 @@ void App::drawToolPanel() {
const auto type = BrushType(i);
const bool selected = brush_ == type && doc_.activeBrush < 0;
if (selected) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive));
- std::string label = std::to_string(i + 1) + " " + brushName(type);
+ // Hotkeys 1-9 and 0 cover the first ten brushes.
+ std::string label = (i < 9 ? std::to_string(i + 1) : i == 9 ? std::string("0") : std::string(" ")) + " " +
+ brushName(type);
if (ImGui::Button(label.c_str(), ImVec2(bw, 0))) {
brush_ = type;
doc_.activeBrush = -1;
@@ -1614,6 +1653,7 @@ void App::drawToolPanel() {
ImGui::PopItemWidth();
ImGui::Checkbox("Invert (Alt)", &invertToggle_);
ImGui::Checkbox("Front faces only", &frontFacesOnly_);
+ drawBrushOptions();
ImGui::SeparatorText("Symmetry");
ImGui::Checkbox("X", &symmetry_.x);
@@ -1709,6 +1749,12 @@ void App::drawBrushCursor() {
: IM_COL32(255, 190, 120, 200);
dl->AddCircle(c, r, col, 64, 1.5f);
dl->AddCircle(c, r * (0.25f + 0.75f * (1.0f - strength_)), IM_COL32(255, 255, 255, 60), 48, 1.0f);
+ if (strokeType_ == StrokeType::LazyMouse && drag_ == Drag::Stroke) {
+ // The string from the cursor to the lagging brush point.
+ const ImVec2 lp(lazyMouse_.point.x, lazyMouse_.point.y);
+ dl->AddLine(c, lp, IM_COL32(255, 255, 255, 120), 1.0f);
+ dl->AddCircleFilled(lp, 3.0f, col);
+ }
}
} // namespace sf
diff --git a/src/app/App.h b/src/app/App.h
index e6de675a..8246b201 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -7,6 +7,7 @@
#include "core/Commands.h"
#include "core/Image.h"
#include "core/Document.h"
+#include "core/Stroke.h"
#include "render/Camera.h"
#include "render/Renderer.h"
@@ -229,6 +230,23 @@ private:
const Mesh* lastDisplayed_ = nullptr;
std::mutex pendingMutex_;
std::vector<PendingFile> pendingFiles_;
+
+ // Stroke types, alphas and the extra brushes (PanelBrushes.cpp).
+ void drawBrushOptions();
+ void snakeHookTo(float x, float y);
+ void dragRectTo(float x, float y);
+ glm::vec3 screenUpVector(float angle) const; // camera up rotated by `angle` around the view axis
+ static void SDLCALL onAlphaChosen(void* userdata, const char* const* files, int filter);
+ StrokeType strokeType_ = StrokeType::Dots;
+ LazyMouse lazyMouse_;
+ Spray spray_;
+ float sprayScatter_ = 1.0f; // jitter radius as a fraction of brush size
+ glm::vec2 dragAnchor_{0.0f}; // DragRect: where the click landed (window pixels)
+ glm::vec3 dragAnchorHit_{0.0f};
+ float dabRadiusScale_ = 1.0f, dabStrengthScale_ = 1.0f, dabAngle_ = 0.0f; // per-dab overrides
+ bool alphaInvert_ = false;
+ std::mutex alphaMutex_;
+ std::string pendingAlphaPath_; // set by the file dialog thread
};
} // namespace sf
diff --git a/src/app/PanelBrushes.cpp b/src/app/PanelBrushes.cpp
new file mode 100644
index 00000000..c35c7f41
--- /dev/null
+++ b/src/app/PanelBrushes.cpp
@@ -0,0 +1,149 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Brush options panel (stroke type, lazy mouse, spray, alpha) and the
+// stroke handling of the SnakeHook brush and the DragRect stroke.
+#include "app/App.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+namespace {
+
+const SDL_DialogFileFilter kAlphaFilters[] = {{"Images", "png;jpg;jpeg;bmp;tga;psd;gif"}, {"All files", "*"}};
+
+} // namespace
+
+void SDLCALL App::onAlphaChosen(void* userdata, const char* const* files, int) {
+ if (!files || !files[0]) return;
+ auto* app = static_cast<App*>(userdata);
+ std::lock_guard lock(app->alphaMutex_);
+ app->pendingAlphaPath_ = files[0];
+}
+
+glm::vec3 App::screenUpVector(float angle) const {
+ const glm::quat q = camera_.orientation();
+ return q * glm::vec3(-std::sin(angle), std::cos(angle), 0.0f);
+}
+
+void App::drawBrushOptions() {
+ std::string alphaPath;
+ {
+ std::lock_guard lock(alphaMutex_);
+ alphaPath.swap(pendingAlphaPath_);
+ }
+ if (!alphaPath.empty()) runCommand("brush_set_alpha", {{"path", alphaPath}, {"invert", alphaInvert_}});
+
+ ImGui::SeparatorText("Stroke");
+ ImGui::SetNextItemWidth(-1);
+ if (ImGui::BeginCombo("##stroke", strokeTypeName(strokeType_))) {
+ for (int i = 0; i < int(StrokeType::Count); ++i)
+ if (ImGui::Selectable(strokeTypeName(StrokeType(i)), strokeType_ == StrokeType(i))) strokeType_ = StrokeType(i);
+ ImGui::EndCombo();
+ }
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("Dots: even dabs along the path\nDragRect: click-drag one stamp (length = size, direction = "
+ "rotation)\nSpray: scattered dabs of random size and strength\nLazyMouse: the brush trails the "
+ "cursor for smooth lines");
+ if (strokeType_ == StrokeType::Spray) {
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderFloat("##scatter", &sprayScatter_, 0.0f, 2.0f, "scatter %.2f");
+ } else if (strokeType_ == StrokeType::LazyMouse) {
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderFloat("##lazy", &lazyMouse_.radius, 1.0f, 300.0f, "lazy radius %.0f px");
+ }
+
+ ImGui::SeparatorText("Alpha");
+ const BrushAlpha& alpha = doc_.brushAlpha;
+ const float preview = ImGui::GetFrameHeight() * 2.0f;
+ {
+ // Thumbnail of the stamp.
+ const ImVec2 p0 = ImGui::GetCursorScreenPos();
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ constexpr int kCells = 20;
+ const float cell = preview / kCells;
+ for (int y = 0; y < kCells; ++y)
+ for (int x = 0; x < kCells; ++x) {
+ const float u = (float(x) + 0.5f) / kCells * 2.0f - 1.0f, v = 1.0f - (float(y) + 0.5f) / kCells * 2.0f;
+ const int g = int(std::clamp(alpha.sample(u, v), 0.0f, 1.0f) * 255.0f);
+ dl->AddRectFilled(ImVec2(p0.x + x * cell, p0.y + y * cell), ImVec2(p0.x + (x + 1) * cell, p0.y + (y + 1) * cell),
+ IM_COL32(g, g, g, 255));
+ }
+ ImGui::Dummy(ImVec2(preview, preview));
+ }
+ ImGui::SameLine();
+ ImGui::BeginGroup();
+ ImGui::SetNextItemWidth(-1);
+ if (ImGui::BeginCombo("##alpha", alpha.name.c_str())) {
+ for (const char* name : {"Round", "Square", "Noise"})
+ if (ImGui::Selectable(name, alpha.name == name)) runCommand("brush_set_alpha", {{"name", std::string(name)}});
+ ImGui::EndCombo();
+ }
+ if (ImGui::Button("Load image...", ImVec2(-1, 0)))
+ SDL_ShowOpenFileDialog(onAlphaChosen, this, window_, kAlphaFilters, 2, nullptr, false);
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Grayscale image: white = full effect, black = none");
+ ImGui::EndGroup();
+ ImGui::Checkbox("Invert loaded image", &alphaInvert_);
+}
+
+// SnakeHook: pull the region under the click along with the cursor, like Move,
+// but re-centred on the pulled tip every step so it can be dragged out into horns.
+void App::snakeHookTo(float x, float y) {
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ glm::vec3 origin, dir;
+ camera_.screenRay(x, y, float(w), float(h), origin, dir);
+ const glm::vec3 n = camera_.forward();
+ const float denom = glm::dot(dir, n);
+ if (std::abs(denom) < 1e-6f) return;
+ const glm::vec3 target = origin + dir * (glm::dot(grabLast_ - origin, n) / denom);
+
+ const float pressure = lastInputPen_ ? std::clamp(penPressure_, 0.0f, 1.0f) : 1.0f;
+ DabParams p;
+ p.viewDir = n;
+ p.radius = radiusPx_ * (pressureSize_ ? std::max(pressure, 0.05f) : 1.0f) * camera_.worldPerPixel(grabLast_, float(h));
+ p.strength = strength_;
+ p.pressure = pressureStrength_ ? pressure : 1.0f;
+ p.invert = strokeInvert_;
+ p.alpha = &doc_.brushAlpha;
+ p.alphaUp = screenUpVector(0.0f);
+ // Small steps keep the tip under the cursor and the pulled surface even.
+ const glm::vec3 delta = target - grabLast_;
+ const int steps = std::clamp(int(std::ceil(glm::length(delta) / (p.radius * 0.15f))), 1, 64);
+ p.strokeDelta = delta / float(steps);
+ for (int i = 0; i < steps; ++i) {
+ p.center = grabLast_;
+ doc_.sculptor.dab(doc_.mesh, doc_.bvh, BrushType::SnakeHook, p, symmetry_);
+ grabLast_ += p.strokeDelta;
+ }
+}
+
+// DragRect: undo the previous stamp and press a new one sized and rotated by the drag.
+void App::dragRectTo(float x, float y) {
+ doc_.sculptor.restoreStroke(doc_.mesh, doc_.bvh);
+ const glm::vec2 drag = glm::vec2(x, y) - dragAnchor_;
+ const float len = glm::length(drag);
+ if (len < 2.0f) return;
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ const glm::quat q = camera_.orientation();
+ const float pressure = lastInputPen_ ? std::clamp(penPressure_, 0.0f, 1.0f) : 1.0f;
+
+ DabParams p;
+ p.center = dragAnchorHit_;
+ p.viewDir = camera_.forward();
+ p.radius = len * camera_.worldPerPixel(dragAnchorHit_, float(h));
+ p.strength = strength_;
+ p.pressure = pressureStrength_ ? pressure : 1.0f;
+ p.invert = strokeInvert_;
+ p.frontFacesOnly = frontFacesOnly_;
+ p.alpha = &doc_.brushAlpha;
+ p.alphaUp = glm::normalize(q * glm::vec3(drag.x, -drag.y, 0.0f)); // the alpha's top follows the drag
+ const BrushRecipe* recipe = strokeBrush_ == BrushType::Smooth ? nullptr : activeRecipe();
+ if (recipe) doc_.sculptor.dabRecipe(doc_.mesh, doc_.bvh, *recipe, p, symmetry_);
+ else doc_.sculptor.dab(doc_.mesh, doc_.bvh, strokeBrush_, p, symmetry_);
+}
+
+} // namespace sf
diff --git a/src/core/BrushAlpha.cpp b/src/core/BrushAlpha.cpp
new file mode 100644
index 00000000..9542545f
--- /dev/null
+++ b/src/core/BrushAlpha.cpp
@@ -0,0 +1,154 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/BrushAlpha.h"
+
+#include "core/Commands.h"
+#include "core/Sculpt.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <filesystem>
+
+namespace sf {
+
+namespace {
+
+constexpr int kBuiltinSize = 128;
+
+float smooth01(float t) {
+ t = std::clamp(t, 0.0f, 1.0f);
+ return t * t * (3.0f - 2.0f * t);
+}
+
+uint32_t hash2(int x, int y, uint32_t seed) {
+ uint32_t h = uint32_t(x) * 0x8da6b343u ^ uint32_t(y) * 0xd8163841u ^ seed * 0xcb1ab31fu;
+ h ^= h >> 13;
+ h *= 0x5bd1e995u;
+ h ^= h >> 15;
+ return h;
+}
+
+float valueNoise2(float x, float y, uint32_t seed) {
+ const float fx = std::floor(x), fy = std::floor(y);
+ const int ix = int(fx), iy = int(fy);
+ const float tx = smooth01(x - fx), ty = smooth01(y - fy);
+ auto at = [&](int dx, int dy) { return float(hash2(ix + dx, iy + dy, seed) & 0xffffu) / 65535.0f; };
+ const float a = at(0, 0) + (at(1, 0) - at(0, 0)) * tx;
+ const float b = at(0, 1) + (at(1, 1) - at(0, 1)) * tx;
+ return a + (b - a) * ty;
+}
+
+// Fills a square alpha from f(u, v) with u, v in -1..1.
+template <class F>
+BrushAlpha generate(std::string name, F&& f) {
+ BrushAlpha a;
+ a.name = std::move(name);
+ a.width = a.height = kBuiltinSize;
+ a.values.resize(size_t(kBuiltinSize) * kBuiltinSize);
+ for (int y = 0; y < kBuiltinSize; ++y)
+ for (int x = 0; x < kBuiltinSize; ++x) {
+ const float u = (float(x) + 0.5f) / kBuiltinSize * 2.0f - 1.0f;
+ const float v = 1.0f - (float(y) + 0.5f) / kBuiltinSize * 2.0f;
+ a.values[size_t(y) * kBuiltinSize + size_t(x)] = std::clamp(f(u, v), 0.0f, 1.0f);
+ }
+ return a;
+}
+
+std::string lower(std::string s) {
+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return s;
+}
+
+} // namespace
+
+float BrushAlpha::sample(float u, float v) const {
+ if (u < -1.0f || u > 1.0f || v < -1.0f || v > 1.0f) return 0.0f;
+ if (empty()) return brushFalloff(std::sqrt(u * u + v * v), 1.0f);
+ // Bilinear lookup; pixel centres span the -1..1 square.
+ const float px = std::clamp((u * 0.5f + 0.5f) * float(width) - 0.5f, 0.0f, float(width - 1));
+ const float py = std::clamp((0.5f - v * 0.5f) * float(height) - 0.5f, 0.0f, float(height - 1));
+ const int x0 = int(px), y0 = int(py);
+ const int x1 = std::min(x0 + 1, width - 1), y1 = std::min(y0 + 1, height - 1);
+ const float tx = px - float(x0), ty = py - float(y0);
+ auto at = [&](int x, int y) { return values[size_t(y) * size_t(width) + size_t(x)]; };
+ const float a = at(x0, y0) + (at(x1, y0) - at(x0, y0)) * tx;
+ const float b = at(x0, y1) + (at(x1, y1) - at(x0, y1)) * tx;
+ return a + (b - a) * ty;
+}
+
+BrushAlpha BrushAlpha::round() { return BrushAlpha{}; }
+
+BrushAlpha BrushAlpha::square() {
+ // Flat plateau with soft edges over the outer fifth.
+ return generate("Square", [](float u, float v) {
+ return smooth01((1.0f - std::max(std::abs(u), std::abs(v))) / 0.2f);
+ });
+}
+
+BrushAlpha BrushAlpha::noise(uint32_t seed) {
+ // Three octaves of value noise inside the round falloff.
+ return generate("Noise", [seed](float u, float v) {
+ const float x = u * 4.0f + 8.0f, y = v * 4.0f + 8.0f;
+ float n = valueNoise2(x, y, seed) * 0.57f + valueNoise2(x * 2.03f, y * 2.03f, seed + 1) * 0.29f +
+ valueNoise2(x * 4.01f, y * 4.01f, seed + 2) * 0.14f;
+ n = std::clamp(n * 1.6f - 0.3f, 0.0f, 1.0f);
+ return n * brushFalloff(std::sqrt(u * u + v * v), 1.0f);
+ });
+}
+
+bool BrushAlpha::builtin(const std::string& name, BrushAlpha& out) {
+ const std::string n = lower(name);
+ if (n == "round" || n == "none" || n.empty()) out = round();
+ else if (n == "square") out = square();
+ else if (n == "noise") out = noise();
+ else return false;
+ return true;
+}
+
+BrushAlpha BrushAlpha::fromImage(const Image& image, std::string name, bool invert) {
+ BrushAlpha a;
+ a.name = std::move(name);
+ if (image.empty()) return a;
+ const Image img = image.downscaled(512);
+ a.width = img.width;
+ a.height = img.height;
+ a.values.resize(size_t(img.width) * size_t(img.height));
+ for (size_t i = 0; i < a.values.size(); ++i) {
+ const uint8_t* p = &img.rgba[i * 4];
+ float l = (0.2126f * p[0] + 0.7152f * p[1] + 0.0722f * p[2]) / 255.0f;
+ if (invert) l = 1.0f - l;
+ a.values[i] = l * (float(p[3]) / 255.0f);
+ }
+ return a;
+}
+
+void registerBrushCommands(CommandRegistry& registry) {
+ using T = ParamSpec::Type;
+ registry.add({"brush_set_alpha",
+ "Set the brush alpha (grayscale stamp shaping the falloff of every brush): a built-in "
+ "(round = none, square, noise) or a grayscale image file.",
+ {{"name", T::String, "Built-in alpha: round, square or noise.", false},
+ {"path", T::String, "Image file (png, jpg, ...) used as the alpha; overrides name.", false},
+ {"invert", T::Bool, "Use the image's negative (white = no effect).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string path = argString(a, "path");
+ if (!path.empty()) {
+ Image img;
+ std::string err;
+ if (!Image::load(path, img, err)) return {false, err};
+ auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();
+ doc.brushAlpha = BrushAlpha::fromImage(img, std::string(stem.begin(), stem.end()),
+ argBool(a, "invert", false));
+ return {true, "Alpha '" + doc.brushAlpha.name + "' (" + std::to_string(doc.brushAlpha.width) +
+ "x" + std::to_string(doc.brushAlpha.height) + ")"};
+ }
+ const std::string name = argString(a, "name", "round");
+ BrushAlpha alpha;
+ if (!BrushAlpha::builtin(name, alpha)) return {false, "Unknown alpha: " + name + " (round, square, noise)"};
+ doc.brushAlpha = std::move(alpha);
+ return {true, "Alpha '" + doc.brushAlpha.name + "'"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/BrushAlpha.h b/src/core/BrushAlpha.h
new file mode 100644
index 00000000..92ce805a
--- /dev/null
+++ b/src/core/BrushAlpha.h
@@ -0,0 +1,40 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Image.h"
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class CommandRegistry;
+
+// Grayscale stamp that shapes a brush's falloff (ZBrush "alpha"). An empty
+// alpha is the plain round smoothstep falloff, so brushes behave exactly as
+// without one. Built-ins: Round (empty), Square, Noise; anything else comes
+// from an image's luminance (transparent pixels count as black).
+struct BrushAlpha {
+ std::string name = "Round";
+ int width = 0, height = 0;
+ std::vector<float> values; // 0..1, row-major, row 0 at the top
+
+ bool empty() const { return values.empty(); }
+ // u, v in brush-local -1..1 (v points up); 0 outside the stamp.
+ float sample(float u, float v) const;
+
+ static BrushAlpha round();
+ static BrushAlpha square();
+ static BrushAlpha noise(uint32_t seed = 1);
+ // Case-insensitive "round"/"none", "square" or "noise"; false for unknown names.
+ static bool builtin(const std::string& name, BrushAlpha& out);
+ // Luminance x alpha, downscaled to at most 512 px; `invert` swaps black and white.
+ static BrushAlpha fromImage(const Image& image, std::string name, bool invert = false);
+};
+
+// Registers brush_set_alpha (and future brush-option commands) with the registry.
+void registerBrushCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 22da76d6..5fb9edfc 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/Commands.h"
+#include "core/BrushAlpha.h"
#include "core/Decimate.h"
#include "core/EnginePresets.h"
#include "core/ImageTo3D.h"
@@ -467,6 +468,7 @@ CommandRegistry::CommandRegistry() {
doc.activeBrush = doc.addBrush(std::move(r));
return {true, "Loaded brush '" + doc.brushes[doc.activeBrush].name + "'"};
}});
+ registerBrushCommands(*this); // brush_set_alpha (BrushAlpha.cpp)
add({"splat_info", "Report the loaded Gaussian splats.", {},
[](Document& doc, const Args&) -> CommandResult {
diff --git a/src/core/Document.h b/src/core/Document.h
index 1920f1a7..1e84f717 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -3,6 +3,7 @@
#pragma once
#include "core/BVH.h"
+#include "core/BrushAlpha.h"
#include "core/BrushRecipe.h"
#include "core/Mesh.h"
#include "core/Sculpt.h"
@@ -27,6 +28,7 @@ struct Document {
// Recipe brush library (built-ins, loaded .sfbrush files, AI-made brushes).
std::vector<BrushRecipe> brushes = builtinBrushRecipes();
int activeBrush = -1; // index into `brushes`, -1 = use a built-in brush type
+ BrushAlpha brushAlpha; // stamp shaping every brush's falloff (empty = round); brush_set_alpha
// Adds or replaces (by name) a recipe and returns its index.
int addBrush(BrushRecipe recipe);
// Gaussian splats shown alongside the mesh (a capture used as reference or
diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cpp
index 760390da..2e4662de 100644
--- a/src/core/Sculpt.cpp
+++ b/src/core/Sculpt.cpp
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/Sculpt.h"
+#include "core/BrushAlpha.h"
+
#include <algorithm>
#include <cmath>
@@ -17,6 +19,12 @@ const char* brushName(BrushType type) {
case BrushType::Crease: return "Crease";
case BrushType::Flatten: return "Flatten";
case BrushType::Pinch: return "Pinch";
+ case BrushType::DamStandard: return "DamStandard";
+ case BrushType::ClayBuildup: return "ClayBuildup";
+ case BrushType::SnakeHook: return "SnakeHook";
+ case BrushType::Trim: return "Trim";
+ case BrushType::Layer: return "Layer";
+ case BrushType::Nudge: return "Nudge";
default: return "?";
}
}
@@ -187,12 +195,17 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Sym
DabParams mp = p;
mp.center *= m;
mp.viewDir *= m;
+ mp.strokeDelta *= m;
+ mp.alphaUp *= m;
dabSingle(mesh, bvh, type, mp);
}
}
void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p) {
- brushVertices(mesh, bvh, p.center, p.radius, verts_);
+ // Alphas and the square ClayBuildup tip reach into the corners of their square.
+ const bool useAlpha = p.alpha && !p.alpha->empty();
+ const float reach = useAlpha ? 1.4143f : type == BrushType::ClayBuildup ? 1.3f : 1.0f;
+ brushVertices(mesh, bvh, p.center, p.radius * reach, verts_);
if (verts_.empty()) return;
auto& pos = mesh.positions;
@@ -221,11 +234,23 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
const float sign = p.invert ? -1.0f : 1.0f;
const float r = p.radius;
+ // Brush-local frame on the area plane (alpha orientation, square tips).
+ glm::vec3 up = projectOnPlane(p.alphaUp, areaNormal);
+ if (glm::length(up) < 1e-6f)
+ up = projectOnPlane(std::abs(areaNormal.x) < 0.9f ? glm::vec3(1, 0, 0) : glm::vec3(0, 1, 0), areaNormal);
+ up = glm::normalize(up);
+ const glm::vec3 right = glm::cross(up, areaNormal);
+ const float strokeLen = glm::length(p.strokeDelta);
+ const glm::vec3 strokeDir = strokeLen > 1e-12f ? p.strokeDelta / strokeLen : glm::vec3(0.0f);
+ if (type == BrushType::Layer) prepareLayer(mesh, r * 0.08f * std::clamp(p.strength, 0.0f, 1.0f));
+
scratch_.resize(verts_.size());
for (size_t i = 0; i < verts_.size(); ++i) {
const uint32_t v = verts_[i];
const glm::vec3& x = pos[v];
- const float f = brushFalloff(glm::distance(x, p.center), r);
+ const glm::vec3 o = x - p.center;
+ const float f = useAlpha ? p.alpha->sample(glm::dot(o, right) / r, glm::dot(o, up) / r)
+ : brushFalloff(glm::length(o), r);
glm::vec3 d(0.0f);
switch (type) {
@@ -266,6 +291,66 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
case BrushType::Pinch:
d = projectOnPlane(p.center - x, areaNormal) * (sign * 0.2f * s * f);
break;
+ case BrushType::DamStandard: {
+ // Narrow, deep V-groove (a ridge when inverted); the sides are always
+ // pinched in toward the stroke line, so the crease stays sharp.
+ const float core = f * f * f * f;
+ d = areaNormal * (-sign * s * r * 0.08f * core);
+ glm::vec3 pull = projectOnPlane(p.center - x, areaNormal);
+ pull -= strokeDir * glm::dot(pull, strokeDir);
+ d += pull * (0.3f * s * f);
+ break;
+ }
+ case BrushType::ClayBuildup: {
+ // Square tip (rounded corners) with a flat top: a raised plane that
+ // everything below is pulled up to, so strokes build up in slabs.
+ float w = f;
+ if (!useAlpha) {
+ const float cheb = std::max(std::abs(glm::dot(o, right)), std::abs(glm::dot(o, up))) / r;
+ const float corner = std::clamp((1.3f - glm::length(o) / r) / 0.3f, 0.0f, 1.0f);
+ const float edge = std::clamp((1.0f - cheb) / 0.35f, 0.0f, 1.0f);
+ w = edge * edge * (3.0f - 2.0f * edge) * corner;
+ }
+ glm::vec3 planePoint = areaCenter + areaNormal * (sign * r * 0.08f * s);
+ float h = glm::dot(x - planePoint, areaNormal);
+ if (sign * h < 0.0f) d = -areaNormal * (h * w);
+ break;
+ }
+ case BrushType::SnakeHook: {
+ // Drag the region along with the stroke; the sides pinch in, so pulled shapes taper.
+ d = p.strokeDelta * f;
+ glm::vec3 side = p.center - x;
+ side -= strokeDir * glm::dot(side, strokeDir);
+ d += side * (0.1f * s * f * std::min(1.0f, strokeLen / (0.1f * r)));
+ break;
+ }
+ case BrushType::Trim: {
+ // Trim Dynamic: a plane just below the area cuts off whatever sticks out
+ // above it (fills up to it when inverted). sqrt falloff for a crisp edge.
+ glm::vec3 planePoint = areaCenter - areaNormal * (sign * r * 0.02f * s);
+ float h = glm::dot(x - planePoint, areaNormal);
+ if (sign * h > 0.0f) d = -areaNormal * (h * std::min(1.0f, std::sqrt(f) * (0.5f + s)));
+ break;
+ }
+ case BrushType::Layer: {
+ // Each vertex rises to the stroke's height x falloff once; later dabs
+ // only add what is missing, so overlaps within a stroke never stack.
+ if (layerStamp_[v] != layerEpoch_) {
+ layerStamp_[v] = layerEpoch_;
+ layerDone_[v] = 0.0f;
+ layerDir_[v] = areaNormal;
+ }
+ const float target = sign * layerHeight_ * std::clamp(p.pressure, 0.0f, 1.0f) * f;
+ if (std::abs(target) > std::abs(layerDone_[v])) {
+ d = layerDir_[v] * (target - layerDone_[v]);
+ layerDone_[v] = target;
+ }
+ break;
+ }
+ case BrushType::Nudge:
+ // Slide the surface sideways along the stroke without lifting it.
+ d = projectOnPlane(p.strokeDelta, nrm[v]) * (f * std::min(1.0f, 0.4f + s));
+ break;
default:
break;
}
@@ -287,6 +372,7 @@ void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const
mp.center *= m;
mp.viewDir *= m;
mp.strokeDelta *= m;
+ mp.alphaUp *= m;
dabRecipeSingle(mesh, bvh, recipe, mp);
}
}
@@ -296,6 +382,15 @@ void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const
if (verts_.empty()) return;
const auto& pos = mesh.positions;
const auto& nrm = mesh.normals;
+ // An alpha (if any) modulates the recipe's tip, oriented on the view-facing plane.
+ const bool useAlpha = p.alpha && !p.alpha->empty();
+ glm::vec3 aUp = projectOnPlane(p.alphaUp, p.viewDir);
+ aUp = glm::length(aUp) > 1e-6f ? glm::normalize(aUp) : glm::vec3(0, 1, 0);
+ const glm::vec3 aRight = glm::cross(aUp, -p.viewDir);
+ auto alphaWeight = [&](const glm::vec3& x) {
+ const glm::vec3 o = x - p.center;
+ return p.alpha->sample(glm::dot(o, aRight) / p.radius, glm::dot(o, aUp) / p.radius);
+ };
if (p.frontFacesOnly) {
std::erase_if(verts_, [&](uint32_t v) { return glm::dot(nrm[v], p.viewDir) > 0.0f; });
if (verts_.empty()) return;
@@ -338,6 +433,7 @@ void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const
}
if (r.pattern != BrushRecipe::Pattern::None && r.patternAmount > 0.0f)
w *= glm::mix(1.0f, samplePattern(r.pattern, pos[v] * patternFreq), r.patternAmount);
+ if (useAlpha) w *= alphaWeight(pos[v]);
weights_[i] = w;
}
if (wsum <= 0.0f) return;
@@ -431,4 +527,37 @@ void Sculptor::grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta) {
bvh.refit(mesh, grabVerts_);
}
+// Puts every vertex the current stroke moved back to its stroke-start position.
+void Sculptor::restoreStroke(Mesh& mesh, BVH& bvh) {
+ if (!active_ || record_.positions.empty()) return;
+ auto& target = mesh.layerTarget(layer_);
+ const auto& idx = record_.positions.indices;
+ for (size_t i = 0; i < idx.size(); ++i) target[idx[i]] = record_.positions.values[i];
+ mesh.evaluate(idx);
+ mesh.updateNormals(idx);
+ bvh.refit(mesh, idx);
+ // The Layer brush starts over too.
+ if (layerEpoch_ != 0 && ++layerEpoch_ == 0) {
+ std::fill(layerStamp_.begin(), layerStamp_.end(), 0);
+ layerEpoch_ = 1;
+ }
+}
+
+// Sizes the Layer brush state and starts a fresh height map for each new stroke.
+void Sculptor::prepareLayer(const Mesh& mesh, float height) {
+ if (layerStamp_.size() != mesh.vertexCount()) {
+ layerStamp_.assign(mesh.vertexCount(), 0);
+ layerDone_.assign(mesh.vertexCount(), 0.0f);
+ layerDir_.assign(mesh.vertexCount(), glm::vec3(0.0f));
+ layerEpoch_ = 0;
+ }
+ if (layerEpoch_ != 0 && layerSeenStamp_ == stamp_) return;
+ layerSeenStamp_ = stamp_;
+ layerHeight_ = height;
+ if (++layerEpoch_ == 0) {
+ std::fill(layerStamp_.begin(), layerStamp_.end(), 0);
+ layerEpoch_ = 1;
+ }
+}
+
} // namespace sf
diff --git a/src/core/Sculpt.h b/src/core/Sculpt.h
index 2aa1f97c..020d8bbd 100644
--- a/src/core/Sculpt.h
+++ b/src/core/Sculpt.h
@@ -12,7 +12,18 @@
namespace sf {
-enum class BrushType { Standard, Clay, Smooth, Move, Inflate, Crease, Flatten, Pinch, Count };
+struct BrushAlpha;
+
+enum class BrushType {
+ Standard, Clay, Smooth, Move, Inflate, Crease, Flatten, Pinch,
+ DamStandard, // sharp V-crease with the sides pinched toward the stroke
+ ClayBuildup, // square-ish, flat-topped clay
+ SnakeHook, // pulls the region along the stroke (strokeDelta), tapering
+ Trim, // Trim Dynamic: a plane cuts away everything above it
+ Layer, // raises to one fixed height per stroke (overlaps never stack)
+ Nudge, // slides the surface sideways along the stroke
+ Count
+};
const char* brushName(BrushType type);
@@ -24,7 +35,9 @@ struct DabParams {
float pressure = 1.0f; // tablet pressure, 0..1
bool invert = false;
bool frontFacesOnly = false;
- glm::vec3 strokeDelta{0.0f}; // world-space movement since the previous dab (recipe brushes)
+ glm::vec3 strokeDelta{0.0f}; // world-space movement since the previous dab (recipe, SnakeHook, Nudge, DamStandard)
+ const BrushAlpha* alpha = nullptr; // stamp shaping the falloff (null/empty = round)
+ glm::vec3 alphaUp{0.0f, 1.0f, 0.0f}; // world direction of the alpha's top edge (screen up, or rotated)
};
struct Symmetry {
@@ -73,6 +86,10 @@ public:
// Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).
static std::vector<glm::vec3> mirrors(Symmetry sym);
+ // Puts every vertex the current stroke moved back where it started (the
+ // stroke stays open). DragRect re-stamps from scratch while dragging.
+ void restoreStroke(Mesh& mesh, BVH& bvh);
+
private:
struct GrabEntry {
uint32_t vertex;
@@ -97,6 +114,14 @@ private:
std::vector<float> weights_;
std::vector<GrabEntry> grab_;
std::vector<uint32_t> grabVerts_;
+
+ // Layer brush: per-stroke height already applied to each vertex.
+ void prepareLayer(const Mesh& mesh, float height);
+ std::vector<uint32_t> layerStamp_;
+ std::vector<float> layerDone_;
+ std::vector<glm::vec3> layerDir_;
+ uint32_t layerEpoch_ = 0, layerSeenStamp_ = 0;
+ float layerHeight_ = 0.0f;
};
} // namespace sf
diff --git a/src/core/Stroke.cpp b/src/core/Stroke.cpp
new file mode 100644
index 00000000..b3d0e22f
--- /dev/null
+++ b/src/core/Stroke.cpp
@@ -0,0 +1,63 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Stroke.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+const char* strokeTypeName(StrokeType type) {
+ switch (type) {
+ case StrokeType::Dots: return "Dots";
+ case StrokeType::DragRect: return "DragRect";
+ case StrokeType::Spray: return "Spray";
+ case StrokeType::LazyMouse: return "LazyMouse";
+ default: return "?";
+ }
+}
+
+void StrokeSpacer::reset(glm::vec2 start) {
+ last_ = start;
+ residual_ = 0.0f;
+}
+
+void StrokeSpacer::moveTo(glm::vec2 to, float spacing, std::vector<glm::vec2>& out) {
+ spacing = std::max(spacing, 1e-3f);
+ const glm::vec2 from = last_;
+ const float len = glm::length(to - from);
+ float travelled = spacing - residual_;
+ while (travelled <= len) {
+ out.push_back(from + (to - from) * (travelled / len));
+ travelled += spacing;
+ }
+ residual_ = len - (travelled - spacing);
+ last_ = to;
+}
+
+glm::vec2 LazyMouse::follow(glm::vec2 cursor) {
+ const glm::vec2 d = cursor - point;
+ const float len = glm::length(d);
+ if (len > radius) point += d * ((len - radius) / len);
+ return point;
+}
+
+float Spray::uniform() {
+ state_ ^= state_ << 13;
+ state_ ^= state_ >> 17;
+ state_ ^= state_ << 5;
+ return float(state_ & 0xffffffu) / float(0xffffff);
+}
+
+SprayDab Spray::next(float radiusPx, float scatter) {
+ SprayDab d;
+ const float a = uniform() * 6.2831853f;
+ const float r = std::sqrt(uniform()) * scatter * radiusPx;
+ d.offset = glm::vec2(std::cos(a), std::sin(a)) * r;
+ d.scale = 0.5f + 0.5f * uniform();
+ d.strength = 0.5f + 0.5f * uniform();
+ d.angle = uniform() * 6.2831853f;
+ return d;
+}
+
+} // namespace sf
diff --git a/src/core/Stroke.h b/src/core/Stroke.h
new file mode 100644
index 00000000..c2aa377b
--- /dev/null
+++ b/src/core/Stroke.h
@@ -0,0 +1,70 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Stroke types: how cursor motion turns into brush dabs. Screen-space and
+// UI-independent so they can be tested without a window.
+#pragma once
+
+#include <glm/glm.hpp>
+
+#include <cstdint>
+#include <vector>
+
+namespace sf {
+
+enum class StrokeType {
+ Dots, // evenly spaced dabs along the cursor path
+ DragRect, // click-drag stamps one dab: drag length = size, drag direction = alpha rotation
+ Spray, // scattered dabs with random size, strength and rotation
+ LazyMouse, // dabs follow a point dragged behind the cursor on a string (smooth lines)
+ Count
+};
+
+const char* strokeTypeName(StrokeType type);
+
+// Points at even `spacing` along a polyline, carrying the leftover distance between calls.
+class StrokeSpacer {
+public:
+ void reset(glm::vec2 start);
+ // Appends the dab positions between the last point and `to`.
+ void moveTo(glm::vec2 to, float spacing, std::vector<glm::vec2>& out);
+ glm::vec2 last() const { return last_; }
+
+private:
+ glm::vec2 last_{0.0f};
+ float residual_ = 0.0f;
+};
+
+// ZBrush-style lazy mouse: the brush point trails the cursor by `radius`
+// pixels and only moves once the string is taut, filtering out hand jitter.
+struct LazyMouse {
+ float radius = 40.0f;
+ glm::vec2 point{0.0f};
+
+ void reset(glm::vec2 p) { point = p; }
+ // Pulls the brush point toward `cursor`; returns its new position.
+ glm::vec2 follow(glm::vec2 cursor);
+};
+
+// One sprayed dab, relative to the path point.
+struct SprayDab {
+ glm::vec2 offset{0.0f}; // pixels
+ float scale = 1.0f; // brush radius multiplier
+ float strength = 1.0f; // strength multiplier
+ float angle = 0.0f; // alpha rotation, radians
+};
+
+// Deterministic random scatter (xorshift), so a seed always gives the same spray.
+class Spray {
+public:
+ explicit Spray(uint32_t seed = 1) { reseed(seed); }
+ void reseed(uint32_t seed) { state_ = seed ? seed : 1u; }
+ float uniform(); // 0..1
+ // Offset within `scatter` x radius (uniform over the disc), scale and strength in 0.5..1.
+ SprayDab next(float radiusPx, float scatter);
+
+private:
+ uint32_t state_ = 1;
+};
+
+} // namespace sf
diff --git a/tests/test_brushes.cpp b/tests/test_brushes.cpp
new file mode 100644
index 00000000..e2c2540c
--- /dev/null
+++ b/tests/test_brushes.cpp
@@ -0,0 +1,443 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// v0.2 brushes (DamStandard, ClayBuildup, SnakeHook, Trim, Layer, Nudge),
+// alphas, stroke helpers (lazy mouse, spray, spacing) and brush_set_alpha.
+#include "TestHarness.h"
+
+#include "core/BrushAlpha.h"
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "core/Sculpt.h"
+#include "core/Stroke.h"
+
+#include <algorithm>
+#include <cmath>
+#include <filesystem>
+
+using namespace sf;
+
+namespace {
+
+constexpr Symmetry kNoSymmetry{false, false, false};
+
+// 64 x 64 quads over [-1, 1]^2 in XZ, normal +Y; there is a vertex at the origin.
+Document planeDoc() { return makeDoc(makePlane(64, 2.0f)); }
+
+uint32_t nearest(const Mesh& m, const glm::vec3& p) {
+ uint32_t best = 0;
+ for (uint32_t v = 1; v < m.vertexCount(); ++v)
+ if (glm::distance(m.positions[v], p) < glm::distance(m.positions[best], p)) best = v;
+ return best;
+}
+
+DabParams dabAt(glm::vec3 center, float radius = 0.3f, float strength = 0.5f) {
+ DabParams p;
+ p.center = center;
+ p.viewDir = glm::vec3(0, -1, 0);
+ p.radius = radius;
+ p.strength = strength;
+ return p;
+}
+
+// One stroke of `count` identical dabs.
+void stroke(Document& d, BrushType type, const DabParams& p, Symmetry sym = kNoSymmetry, int count = 1) {
+ d.sculptor.beginStroke(d.mesh, brushName(type));
+ for (int i = 0; i < count; ++i) d.sculptor.dab(d.mesh, d.bvh, type, p, sym);
+ d.undo.push(d.sculptor.endStroke());
+}
+
+glm::vec3 moved(const Document& d, const std::vector<glm::vec3>& before, uint32_t v) {
+ return d.mesh.positions[v] - before[v];
+}
+
+} // namespace
+
+TEST(brush_names_cover_new_types) {
+ CHECK(std::string(brushName(BrushType::DamStandard)) == "DamStandard");
+ CHECK(std::string(brushName(BrushType::ClayBuildup)) == "ClayBuildup");
+ CHECK(std::string(brushName(BrushType::SnakeHook)) == "SnakeHook");
+ CHECK(std::string(brushName(BrushType::Trim)) == "Trim");
+ CHECK(std::string(brushName(BrushType::Layer)) == "Layer");
+ CHECK(std::string(brushName(BrushType::Nudge)) == "Nudge");
+ for (int i = 0; i < int(BrushType::Count); ++i) CHECK(std::string(brushName(BrushType(i))) != "?");
+ // Original brushes keep their slots (hotkeys 1-8, saved settings).
+ CHECK(int(BrushType::Standard) == 0 && int(BrushType::Pinch) == 7 && int(BrushType::DamStandard) == 8);
+}
+
+TEST(round_alpha_leaves_existing_brushes_unchanged) {
+ for (BrushType type : {BrushType::Standard, BrushType::Clay, BrushType::Crease, BrushType::Pinch}) {
+ Document a = planeDoc(), b = planeDoc();
+ DabParams p = dabAt(glm::vec3(0.1f, 0.0f, 0.0f));
+ stroke(a, type, p);
+ BrushAlpha round = BrushAlpha::round();
+ p.alpha = &round;
+ p.strokeDelta = glm::vec3(0.02f, 0, 0);
+ p.alphaUp = glm::vec3(0.3f, 0.2f, 0.9f);
+ stroke(b, type, p);
+ CHECK(a.mesh.positions == b.mesh.positions);
+ }
+ // Standard: centre raised by r * 0.06 * strength.
+ Document d = planeDoc();
+ stroke(d, BrushType::Standard, dabAt(glm::vec3(0.0f)));
+ CHECK(std::abs(d.mesh.positions[nearest(d.mesh, glm::vec3(0))].y - 0.3f * 0.06f * 0.5f) < 1e-5f);
+}
+
+TEST(dam_standard_carves_sharp_pinched_groove) {
+ Document d = planeDoc();
+ const auto before = d.mesh.positions;
+ DabParams p = dabAt(glm::vec3(0.0f));
+ p.strokeDelta = glm::vec3(0, 0, 0.05f); // stroke runs along +z
+ stroke(d, BrushType::DamStandard, p);
+ const uint32_t c = nearest(d.mesh, glm::vec3(0)), side = nearest(d.mesh, glm::vec3(0.15f, 0, 0));
+ const uint32_t along = nearest(d.mesh, glm::vec3(0, 0, 0.15f));
+ CHECK(moved(d, before, c).y < -0.005f); // carves inward
+ const float sideDepth = -moved(d, before, side).y, centreDepth = -moved(d, before, c).y;
+ CHECK(sideDepth >= 0.0f && sideDepth < 0.2f * centreDepth); // sharp V (Standard would be ~0.5)
+ CHECK(moved(d, before, side).x < -0.005f); // sides pinch toward the line
+ CHECK(std::abs(moved(d, before, along).z) < 1e-5f); // ...but not along it
+ CHECK(std::abs(moved(d, before, along).x) < 1e-5f);
+
+ Document r = planeDoc();
+ p.invert = true;
+ stroke(r, BrushType::DamStandard, p);
+ CHECK(r.mesh.positions[c].y > 0.005f); // Alt raises a sharp ridge
+}
+
+TEST(clay_buildup_is_square_and_flat_topped) {
+ Document d = planeDoc(), clay = planeDoc();
+ const DabParams p = dabAt(glm::vec3(0.0f));
+ stroke(d, BrushType::ClayBuildup, p);
+ stroke(clay, BrushType::Clay, p);
+ const uint32_t c = nearest(d.mesh, glm::vec3(0)), diag = nearest(d.mesh, glm::vec3(0.2f, 0, 0.2f));
+ const uint32_t mid = nearest(d.mesh, glm::vec3(0.1f, 0, 0));
+ const float hc = d.mesh.positions[c].y;
+ CHECK(hc > 0.005f);
+ CHECK(std::abs(d.mesh.positions[mid].y - hc) < 0.05f * hc); // flat top
+ CHECK(d.mesh.positions[diag].y > 0.6f * hc); // square: corners filled
+ CHECK(clay.mesh.positions[diag].y < 0.3f * clay.mesh.positions[c].y); // round Clay is not
+ // Builds up over strokes.
+ stroke(d, BrushType::ClayBuildup, p);
+ CHECK(d.mesh.positions[c].y > 1.5f * hc);
+ // Nothing outside the rounded square moves.
+ CHECK(d.mesh.positions[nearest(d.mesh, glm::vec3(0.45f, 0, 0))].y == 0.0f);
+}
+
+TEST(snake_hook_pulls_and_tapers) {
+ Document d = planeDoc();
+ const auto before = d.mesh.positions;
+ DabParams p = dabAt(glm::vec3(0.0f));
+ p.strokeDelta = glm::vec3(0, 0.05f, 0);
+ stroke(d, BrushType::SnakeHook, p);
+ const uint32_t c = nearest(d.mesh, glm::vec3(0)), side = nearest(d.mesh, glm::vec3(0.15f, 0, 0));
+ CHECK(std::abs(moved(d, before, c).y - 0.05f) < 1e-4f); // the tip follows the stroke
+ CHECK(moved(d, before, side).y > 0.0f && moved(d, before, side).y < 0.05f);
+ CHECK(moved(d, before, side).x < 0.0f); // sides taper inward
+ CHECK(d.mesh.positions[nearest(d.mesh, glm::vec3(0.5f, 0, 0))] == before[nearest(d.mesh, glm::vec3(0.5f, 0, 0))]);
+
+ // Re-centred on the tip every step (as the app does), it pulls out a horn.
+ Document h = planeDoc();
+ h.sculptor.beginStroke(h.mesh, "SnakeHook");
+ glm::vec3 tip(0.0f);
+ for (int i = 0; i < 40; ++i) {
+ DabParams s = dabAt(tip);
+ s.strokeDelta = glm::vec3(0, 0.025f, 0);
+ h.sculptor.dab(h.mesh, h.bvh, BrushType::SnakeHook, s, kNoSymmetry);
+ tip += s.strokeDelta;
+ }
+ h.undo.push(h.sculptor.endStroke());
+ float top = 0.0f, widthHigh = 0.0f, widthLow = 0.0f;
+ for (const glm::vec3& v : h.mesh.positions) {
+ top = std::max(top, v.y);
+ const float r = std::sqrt(v.x * v.x + v.z * v.z);
+ if (v.y > 0.6f) widthHigh = std::max(widthHigh, r);
+ if (v.y > 0.1f && v.y < 0.3f) widthLow = std::max(widthLow, r);
+ }
+ CHECK(top > 0.8f);
+ CHECK(widthHigh < widthLow); // tapers toward the tip
+ CHECK(widthLow < 0.3f);
+}
+
+TEST(trim_cuts_flat_and_never_raises) {
+ Document d = makeDoc(makeIcosphere(4));
+ const auto before = d.mesh.positions;
+ auto spreadNearAxis = [](const std::vector<glm::vec3>& pos) {
+ float lo = 1e9f, hi = -1e9f;
+ for (const glm::vec3& v : pos)
+ if (v.y > 0 && v.x * v.x + v.z * v.z < 0.15f * 0.15f) {
+ lo = std::min(lo, v.y);
+ hi = std::max(hi, v.y);
+ }
+ return hi - lo;
+ };
+ stroke(d, BrushType::Trim, dabAt(glm::vec3(0, 1, 0), 0.4f, 1.0f), kNoSymmetry, 5);
+ const uint32_t top = nearest(d.mesh, glm::vec3(0, 2, 0));
+ CHECK(d.mesh.positions[top].y < before[top].y - 0.005f); // cut down
+ CHECK(spreadNearAxis(d.mesh.positions) < 0.3f * spreadNearAxis(before)); // to a flat plane
+ bool raised = false;
+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) raised |= glm::length(d.mesh.positions[v]) > glm::length(before[v]) + 1e-6f;
+ CHECK(!raised);
+}
+
+TEST(layer_brush_raises_constant_height_without_stacking) {
+ Document d = planeDoc();
+ const DabParams p = dabAt(glm::vec3(0.0f));
+ const float height = 0.3f * 0.08f * 0.5f;
+ stroke(d, BrushType::Layer, p, kNoSymmetry, 10);
+ const uint32_t c = nearest(d.mesh, glm::vec3(0));
+ CHECK(std::abs(d.mesh.positions[c].y - height) < 1e-5f); // ten dabs, one height
+
+ // Overlapping dabs along a line: the result is the max, not the sum.
+ Document l = planeDoc();
+ l.sculptor.beginStroke(l.mesh, "Layer");
+ for (float x = -0.2f; x <= 0.2001f; x += 0.05f)
+ l.sculptor.dab(l.mesh, l.bvh, BrushType::Layer, dabAt(glm::vec3(x, 0, 0)), kNoSymmetry);
+ l.undo.push(l.sculptor.endStroke());
+ float maxY = 0.0f;
+ for (const glm::vec3& v : l.mesh.positions) maxY = std::max(maxY, v.y);
+ CHECK(maxY <= height + 1e-5f && maxY > 0.99f * height);
+
+ // A new stroke adds another layer.
+ stroke(d, BrushType::Layer, p);
+ CHECK(std::abs(d.mesh.positions[c].y - 2.0f * height) < 0.02f * height); // along the (bumped) area normal
+ // Undo restores the stroke exactly.
+ d.undo.undo(d.mesh, d.bvh);
+ CHECK(std::abs(d.mesh.positions[c].y - height) < 1e-5f);
+}
+
+TEST(nudge_slides_along_the_surface) {
+ Document d = planeDoc();
+ const auto before = d.mesh.positions;
+ DabParams p = dabAt(glm::vec3(0.0f));
+ p.strokeDelta = glm::vec3(0.05f, 0.04f, 0.0f); // the normal component is dropped
+ stroke(d, BrushType::Nudge, p);
+ const uint32_t c = nearest(d.mesh, glm::vec3(0));
+ CHECK(moved(d, before, c).x > 0.02f);
+ float maxDy = 0.0f;
+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) maxDy = std::max(maxDy, std::abs(moved(d, before, v).y));
+ CHECK(maxDy < 1e-6f);
+ const uint32_t far = nearest(d.mesh, glm::vec3(0.5f, 0, 0));
+ CHECK(d.mesh.positions[far] == before[far]);
+}
+
+TEST(new_brushes_respect_mask_and_symmetry) {
+ const BrushType types[] = {BrushType::DamStandard, BrushType::ClayBuildup, BrushType::SnakeHook,
+ BrushType::Trim, BrushType::Layer, BrushType::Nudge};
+ for (BrushType type : types) {
+ DabParams p = dabAt(glm::vec3(0.5f, 0, 0), 0.3f, 1.0f);
+ p.strokeDelta = glm::vec3(0.03f, 0.03f, 0.03f);
+ if (type == BrushType::Trim) p.invert = true; // fill: a flat plane has nothing to cut
+
+ // Symmetry X: the mirrored dab mirrors the displacement.
+ Document s = planeDoc();
+ const auto before = s.mesh.positions;
+ stroke(s, type, p, Symmetry{true, false, false});
+ const uint32_t right = nearest(s.mesh, glm::vec3(0.55f, 0, 0.05f));
+ const uint32_t left = nearest(s.mesh, glm::vec3(-0.55f, 0, 0.05f));
+ const glm::vec3 dr = moved(s, before, right), dl = moved(s, before, left);
+ CHECK(glm::length(dr) > 1e-4f);
+ CHECK(glm::length(dr - dl * glm::vec3(-1, 1, 1)) < 1e-5f);
+
+ // Mask the left half: the mirrored dab leaves it alone.
+ Document m = planeDoc();
+ m.mesh.ensureMask();
+ for (uint32_t v = 0; v < m.mesh.vertexCount(); ++v) m.mesh.mask[v] = m.mesh.positions[v].x < 0 ? 1.0f : 0.0f;
+ stroke(m, type, p, Symmetry{true, false, false});
+ bool leftMoved = false;
+ for (uint32_t v = 0; v < m.mesh.vertexCount(); ++v)
+ if (before[v].x < 0) leftMoved |= m.mesh.positions[v] != before[v];
+ CHECK(!leftMoved);
+ CHECK(glm::length(moved(m, before, right)) > 1e-4f);
+ }
+}
+
+TEST(alpha_sampling) {
+ const BrushAlpha round = BrushAlpha::round();
+ CHECK(round.empty() && round.name == "Round");
+ CHECK(std::abs(round.sample(0, 0) - 1.0f) < 1e-6f && round.sample(1.0f, 0) == 0.0f);
+ CHECK(std::abs(round.sample(0.5f, 0) - 0.5f) < 1e-6f && round.sample(0, 1.5f) == 0.0f);
+
+ const BrushAlpha square = BrushAlpha::square();
+ CHECK(square.width == 128 && square.values.size() == 128u * 128u);
+ CHECK(square.sample(0.7f, 0.7f) > 0.99f && square.sample(0.0f, 0.0f) > 0.99f);
+ CHECK(square.sample(0.96f, 0.0f) < 0.5f && square.sample(1.2f, 0.0f) == 0.0f);
+
+ const BrushAlpha noise = BrushAlpha::noise(), noise2 = BrushAlpha::noise();
+ CHECK(noise.values == noise2.values); // deterministic
+ float lo = 1.0f, hi = 0.0f;
+ for (float v : noise.values) {
+ lo = std::min(lo, v);
+ hi = std::max(hi, v);
+ }
+ CHECK(lo >= 0.0f && hi <= 1.0f && hi - lo > 0.5f);
+
+ // Image alphas: luminance x alpha, bilinear, row 0 at the top.
+ Image img;
+ img.width = 2;
+ img.height = 2;
+ img.rgba = {255, 255, 255, 255, 0, 0, 0, 255, // top: white, black
+ 255, 255, 255, 0, 0, 0, 0, 255}; // bottom: transparent white, black
+ const BrushAlpha a = BrushAlpha::fromImage(img, "test");
+ CHECK(a.name == "test" && a.width == 2 && a.height == 2);
+ CHECK(std::abs(a.sample(-0.9f, 0.9f) - 1.0f) < 1e-5f); // top-left
+ CHECK(a.sample(0.9f, 0.9f) < 1e-5f); // top-right
+ CHECK(a.sample(-0.9f, -0.9f) < 1e-5f); // transparent counts as black
+ CHECK(std::abs(a.sample(0.0f, 0.9f) - 0.5f) < 1e-5f); // bilinear between pixel centres
+ const BrushAlpha inv = BrushAlpha::fromImage(img, "inv", true);
+ CHECK(inv.sample(-0.9f, 0.9f) < 1e-5f && std::abs(inv.sample(0.9f, 0.9f) - 1.0f) < 1e-5f);
+ CHECK(BrushAlpha::fromImage(Image{}, "x").empty());
+
+ BrushAlpha out;
+ CHECK(BrushAlpha::builtin("SQUARE", out) && out.name == "Square");
+ CHECK(BrushAlpha::builtin("none", out) && out.empty());
+ CHECK(!BrushAlpha::builtin("star", out));
+}
+
+TEST(alpha_shapes_and_orients_dabs) {
+ // Square alpha fills the corners a round dab leaves untouched.
+ Document round = planeDoc(), sq = planeDoc();
+ stroke(round, BrushType::Standard, dabAt(glm::vec3(0)));
+ BrushAlpha square = BrushAlpha::square();
+ DabParams p = dabAt(glm::vec3(0));
+ p.alpha = &square;
+ stroke(sq, BrushType::Standard, p);
+ const uint32_t c = nearest(sq.mesh, glm::vec3(0)), diag = nearest(sq.mesh, glm::vec3(0.25f, 0, 0.25f));
+ CHECK(sq.mesh.positions[diag].y > 0.9f * sq.mesh.positions[c].y);
+ CHECK(round.mesh.positions[diag].y == 0.0f);
+
+ // Half-white image: only the white side moves; alphaUp sets the orientation.
+ Image img;
+ img.width = 8;
+ img.height = 8;
+ img.rgba.resize(8 * 8 * 4, 255);
+ for (int y = 0; y < 8; ++y)
+ for (int x = 4; x < 8; ++x)
+ for (int k = 0; k < 3; ++k) img.rgba[size_t((y * 8 + x) * 4 + k)] = 0;
+ BrushAlpha half = BrushAlpha::fromImage(img, "half");
+ Document h = planeDoc();
+ p.alpha = &half;
+ p.alphaUp = glm::vec3(0, 0, -1); // seen from above (+Y), image right = +x
+ stroke(h, BrushType::Standard, p);
+ CHECK(h.mesh.positions[nearest(h.mesh, glm::vec3(-0.12f, 0, 0))].y > 0.005f);
+ CHECK(h.mesh.positions[nearest(h.mesh, glm::vec3(0.12f, 0, 0))].y == 0.0f);
+ // Rotated 180 degrees, the other side moves.
+ Document h2 = planeDoc();
+ p.alphaUp = glm::vec3(0, 0, 1);
+ stroke(h2, BrushType::Standard, p);
+ CHECK(h2.mesh.positions[nearest(h2.mesh, glm::vec3(-0.12f, 0, 0))].y == 0.0f);
+ CHECK(h2.mesh.positions[nearest(h2.mesh, glm::vec3(0.12f, 0, 0))].y > 0.005f);
+
+ // Recipe brushes are modulated too.
+ Document r = planeDoc();
+ BrushRecipe recipe;
+ recipe.name = "test";
+ p.alphaUp = glm::vec3(0, 0, -1);
+ r.sculptor.beginStroke(r.mesh, "test");
+ r.sculptor.dabRecipe(r.mesh, r.bvh, recipe, p, kNoSymmetry);
+ r.undo.push(r.sculptor.endStroke());
+ CHECK(r.mesh.positions[nearest(r.mesh, glm::vec3(-0.12f, 0, 0))].y > 0.001f);
+ CHECK(r.mesh.positions[nearest(r.mesh, glm::vec3(0.12f, 0, 0))].y == 0.0f);
+}
+
+TEST(brush_set_alpha_command) {
+ CommandRegistry reg;
+ Document d = planeDoc();
+ CHECK(reg.find("brush_set_alpha") != nullptr);
+ CHECK(d.brushAlpha.empty());
+ CHECK(reg.execute(d, "brush_set_alpha", {{"name", std::string("square")}}).ok);
+ CHECK(d.brushAlpha.name == "Square" && !d.brushAlpha.empty());
+ CHECK(!reg.execute(d, "brush_set_alpha", {{"name", std::string("star")}}).ok);
+ CHECK(d.brushAlpha.name == "Square");
+
+ Image img;
+ img.width = 16;
+ img.height = 8;
+ img.rgba.assign(16 * 8 * 4, 200);
+ const std::string path = tempPath("sf_test_alpha.png");
+ std::string err;
+ CHECK(img.savePng(path, err));
+ CHECK(reg.execute(d, "brush_set_alpha", {{"path", path}}).ok);
+ CHECK(d.brushAlpha.name == "sf_test_alpha" && d.brushAlpha.width == 16 && d.brushAlpha.height == 8);
+ CHECK(!reg.execute(d, "brush_set_alpha", {{"path", tempPath("sf_no_such_alpha.png")}}).ok);
+ CHECK(reg.execute(d, "brush_set_alpha", {}).ok && d.brushAlpha.empty()); // back to round
+ std::filesystem::remove(path);
+}
+
+TEST(restore_stroke_reverts_for_drag_rect) {
+ Document d = planeDoc();
+ const auto before = d.mesh.positions;
+ d.sculptor.beginStroke(d.mesh, "DragRect");
+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, dabAt(glm::vec3(0), 0.2f), kNoSymmetry);
+ d.sculptor.restoreStroke(d.mesh, d.bvh);
+ CHECK(d.mesh.positions == before);
+ // Re-stamp bigger: only the final stamp remains, and undo goes back to the start.
+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Layer, dabAt(glm::vec3(0), 0.4f), kNoSymmetry);
+ d.sculptor.restoreStroke(d.mesh, d.bvh);
+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Layer, dabAt(glm::vec3(0), 0.4f), kNoSymmetry);
+ const uint32_t c = nearest(d.mesh, glm::vec3(0));
+ CHECK(std::abs(d.mesh.positions[c].y - 0.4f * 0.08f * 0.5f) < 1e-5f); // Layer restarts after a restore
+ d.undo.push(d.sculptor.endStroke());
+ d.undo.undo(d.mesh, d.bvh);
+ CHECK(d.mesh.positions == before);
+
+ // With sculpt layers the restore goes through the layer offsets.
+ Document l = planeDoc();
+ l.mesh.addLayer("L");
+ l.sculptor.beginStroke(l.mesh, "DragRect", 0);
+ l.sculptor.dab(l.mesh, l.bvh, BrushType::Standard, dabAt(glm::vec3(0)), kNoSymmetry);
+ CHECK(l.mesh.positions != before);
+ l.sculptor.restoreStroke(l.mesh, l.bvh);
+ l.sculptor.endStroke();
+ bool same = true;
+ for (uint32_t v = 0; v < l.mesh.vertexCount(); ++v) same &= glm::distance(l.mesh.positions[v], before[v]) < 1e-6f;
+ CHECK(same);
+}
+
+TEST(lazy_mouse_smooths_jitter) {
+ LazyMouse lazy;
+ lazy.radius = 20.0f;
+ lazy.reset(glm::vec2(0.0f));
+ CHECK(lazy.follow(glm::vec2(10, 5)) == glm::vec2(0.0f)); // inside the string: no movement
+ // A jittery horizontal line: +-6 px of vertical noise.
+ float inLo = 1e9f, inHi = -1e9f, outLo = 1e9f, outHi = -1e9f;
+ glm::vec2 cursor(0.0f), point(0.0f);
+ for (int i = 0; i < 300; ++i) {
+ cursor = glm::vec2(float(i) * 2.0f, (i % 2 ? 6.0f : -6.0f));
+ point = lazy.follow(cursor);
+ if (i < 100) continue;
+ inLo = std::min(inLo, cursor.y);
+ inHi = std::max(inHi, cursor.y);
+ outLo = std::min(outLo, point.y);
+ outHi = std::max(outHi, point.y);
+ }
+ CHECK(outHi - outLo < 0.25f * (inHi - inLo));
+ CHECK(std::abs(glm::distance(point, cursor) - 20.0f) < 1e-3f); // trails by the radius
+ CHECK(point.x < cursor.x);
+}
+
+TEST(spray_and_spacing_are_deterministic) {
+ Spray a(7), b(7), c(8);
+ bool same = true, differs = false, bounded = true;
+ for (int i = 0; i < 200; ++i) {
+ const SprayDab x = a.next(50.0f, 0.5f), y = b.next(50.0f, 0.5f), z = c.next(50.0f, 0.5f);
+ same &= x.offset == y.offset && x.scale == y.scale && x.strength == y.strength && x.angle == y.angle;
+ differs |= x.offset != z.offset;
+ bounded &= glm::length(x.offset) <= 25.0f + 1e-4f && x.scale >= 0.5f && x.scale <= 1.0f &&
+ x.strength >= 0.5f && x.strength <= 1.0f;
+ }
+ CHECK(same && differs && bounded);
+ Spray zero(0); // a zero seed still produces numbers
+ CHECK(zero.uniform() > 0.0f);
+
+ StrokeSpacer spacer;
+ std::vector<glm::vec2> pts;
+ spacer.reset(glm::vec2(0.0f));
+ spacer.moveTo(glm::vec2(100, 0), 10.0f, pts);
+ CHECK(pts.size() == 10 && std::abs(pts[0].x - 10.0f) < 1e-4f && std::abs(pts.back().x - 100.0f) < 1e-3f);
+ pts.clear();
+ spacer.moveTo(glm::vec2(105, 0), 10.0f, pts);
+ CHECK(pts.empty());
+ spacer.moveTo(glm::vec2(115, 0), 10.0f, pts);
+ CHECK(pts.size() == 1 && std::abs(pts[0].x - 110.0f) < 1e-3f);
+ CHECK(std::string(strokeTypeName(StrokeType::LazyMouse)) == "LazyMouse");
+}