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.

Stencil: sculpt and paint through an image laid over the view (#155, @kenttumanda123-netizen)

islandmed9aa8f0738d4b
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 83b4c793..c060d2a1 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -93,6 +93,7 @@ add_library(sculptforge_core STATIC
src/core/Cut.cpp
src/core/CloseHoles.cpp
src/core/BrushAlpha.cpp
+ src/core/Stencil.cpp
src/core/Stroke.cpp
src/core/Precision.cpp
src/core/PathStroke.cpp
@@ -413,6 +414,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelBrushGallery.cpp
src/app/PanelVertexPaint.cpp
src/app/LineGradient.cpp
+ src/app/StencilOverlay.cpp
src/app/PanelPacks.cpp
src/app/MemoryConfirm.cpp
src/app/PanelPaintLayers.cpp
diff --git a/assets/fonts/NotoSansSC-UI.otf b/assets/fonts/NotoSansSC-UI.otf
index 8d053681..cb74e260 100644
Binary files a/assets/fonts/NotoSansSC-UI.otf and b/assets/fonts/NotoSansSC-UI.otf differ
diff --git a/assets/fonts/NotoSansTC-UI.otf b/assets/fonts/NotoSansTC-UI.otf
index 1bd2e461..1a99f770 100644
Binary files a/assets/fonts/NotoSansTC-UI.otf and b/assets/fonts/NotoSansTC-UI.otf differ
diff --git a/changes/feat-stencil.md b/changes/feat-stencil.md
new file mode 100644
index 00000000..eb224bc6
--- /dev/null
+++ b/changes/feat-stencil.md
@@ -0,0 +1,19 @@
+---
+whats_new: **Stencil**: lay an image over the view and sculpt or paint through it (**Sculpt > Alpha > Stencil**). Move,
+ scale and turn it on the canvas with **Adjust**, stroke over it, turn the model and repeat. Sculpt brushes take its
+ brightness, Vertex Paint its colours; Tile repeats it across the view.
+highlight: Stencil: sculpt and paint through an image (thanks @kenttumanda123-netizen, #155)
+added: **Stencil** (Sculpt > Alpha > Stencil, #155, thanks @kenttumanda123-netizen): an image over the view (loaded
+ like an alpha, or the brush's alpha) that the brushes work through. It stays put on screen while the model turns
+ under it; every brush that takes an alpha (built-in, custom and Community brushes, the Paint brush, micro levels)
+ takes its brightness (sculpt) or its colours (Vertex Paint, or its brightness masking the paint colour) at the place
+ each vertex shows, and nothing off the image. Adjust: drag to move, a corner to scale, the round handle to turn;
+ arrows, - =, , . on the keyboard. Invert, Tile, Opacity, Hide while navigating. Symmetry mirrors it. Commands
+ `stencil_load`, `stencil_set`, `stencil_clear`. Texture painting doesn't take it yet.
+testers:
+ - Any OS: Sculpt > Alpha > Stencil > Load image... (a photo or a pattern), Adjust, move / scale / turn it, Enter;
+ stroke Standard across its edge: the surface changes only under the image, in its pattern.
+ - Paint brush over a colour photo stencil: the model takes the photo's colours where it covers it, nothing elsewhere.
+ - Windows at 150% scaling: the handles sit on the stencil's corners and are easy to grab.
+---
+Design: docs/design/stencil.md. Core sampling tests: tests/test_stencil.cpp; UI: tests/ui/stencil.sfui.
diff --git a/docs/design/stencil.md b/docs/design/stencil.md
new file mode 100644
index 00000000..e8279859
--- /dev/null
+++ b/docs/design/stencil.md
@@ -0,0 +1,56 @@
+# Stencil (#155)
+
+Ask (@kenttumanda123-netizen): a reference image over the viewport that you move, turn, scale and fade, then sculpt
+or paint through it: its detail goes onto the model as displacement (sculpt brushes) or colour (Vertex Paint); move
+it and repeat. Roadmap item "stencils" (welcome.md). Our name: **Stencil**.
+
+## Model
+
+- **Screen space.** The stencil is an image placed on the canvas, not on the model: the model turns under it. Its
+ placement is kept in canvas fractions (centre 0..1 across and down, size = its height / the canvas height, angle
+ counter-clockwise as seen), so it stays put when the window changes size. `core/Stencil.h`, state on `Document`
+ (`doc.stencil`), not saved with the project (a session tool, like the brush cursor).
+- **Sampling.** Each dab carries a `StencilView` (the stencil, the dab's view-projection and canvas aspect). A vertex
+ is projected to the canvas, turned back by the stencil's placement into image coordinates and sampled bilinearly.
+ Sculpt brushes multiply their falloff (or alpha) by the image's brightness x its alpha; outside the image (unless
+ **Tile**) the weight is 0, so nothing moves. Behind the camera: 0.
+- **Vertex Paint** lays the image's own colours (alpha = coverage), or with **Paint its colours** off its brightness
+ masks the paint colour. Texture painting doesn't take it yet (follow-up: the same weight in `Texture.cpp`).
+- **Invert** uses the negative; **Opacity** only changes how strongly the overlay shows (the brushes always take the
+ whole image: a faint stencil shouldn't sculpt faintly without saying so; Intensity does that).
+- **Symmetry: yes, mirrored.** A symmetry copy's vertex takes the stencil at its mirror image's place on screen
+ (`SymCopy::inversePoint` before projecting), so the pattern mirrors across: a face stencilled on the right shows on
+ the left mirrored, as the stroke itself is. (Sampling the mirror's own screen position would put a different part
+ of the image there, or nothing.)
+- **Which brushes.** Every brush that takes an alpha: the built-in sculpt brushes (`Sculptor::dabSingle`), custom
+ brushes (`dabRecipeSingle`), Vertex Paint (`paintDab`). Not Move, the Kelvinlet brushes, Vector Displacement or the
+ mask brush (they don't take alphas either). A stencilled dab takes the exact path (no scale-adaptive dabs, no fused
+ batches, no micro base dabs), as an alpha does.
+- **Micro levels:** through the grid kernel's per-point pattern hook (`MicroStroke::dab`'s `texture`), as recipe
+ patterns are; big brushes evaluate it on the coarse points the way they do an alpha.
+
+## Image
+
+The same loader as alphas (`Image::load`; no new parser or dependency), kept up to 2048 px on its longer side (a
+stencil spans the view; an alpha's 512 is too coarse). **Use alpha** makes the brush's current alpha the stencil: a
+Library or image alpha is read again from its file at full size, a built-in pattern as generated.
+
+## UI
+
+Alpha palette > **Stencil**: Load image..., Use alpha, Remove; Show, Adjust, Invert, Tile, Paint its colours, Hide
+while navigating; Opacity, Size, Angle; Reset placement. Commands `stencil_load`, `stencil_set`, `stencil_clear`
+(scripts, tests, the AI). Actions in the command palette: Load Stencil..., Show Stencil, Adjust Stencil (no default
+keys: every input style keeps its own).
+
+- **Overlay** on the background draw list (under the panels, over the model), outline always, image at Opacity.
+- **Adjust** puts handles on it: drag inside = move, a corner = scale about the centre, the round knob above the top
+ edge = turn (Shift: 15 degree steps). Keys while adjusting: arrows move (Shift: 1 px), `-` / `=` scale, `,` / `.`
+ turn 15 degrees (Shift: 1). Enter or Esc goes back to sculpting. While adjusting the brush ring hides and clicks off
+ the stencil do nothing.
+- **Navigating** (orbit, pan, zoom, roll) fades it to 15% (Hide while navigating, on by default): it stays locked to
+ the view, which is what "reposition and repeat" needs: turn the model under it, stroke again.
+
+## Cost
+
+No stencil: one null check per dab. With one: a matrix multiply and four texel reads per vertex in the brush. The
+stroke lag bench (25/120/240 px) runs without a stencil and is unchanged.
diff --git a/docs/guide/sculpting.md b/docs/guide/sculpting.md
index 25e6f9b8..70ab2319 100644
--- a/docs/guide/sculpting.md
+++ b/docs/guide/sculpting.md
@@ -477,6 +477,37 @@ a .sfpack) turns its alpha the same way for everyone. Vector displacement stamps
[Stamp rotation](#stamp-rotation). From a script:
`brush_alpha_options follow_stroke=true angle=30 angle_jitter=10 tile_x=2 tile_y=2`.
+### Stencil
+
+A **Stencil** is an image laid over the view that you sculpt and paint *through*: wherever it covers the model, a
+stroke takes its detail (the sculpt brushes its brightness, white = full effect, as an alpha; Vertex Paint its
+colours). Off the image nothing happens. It stays put on the screen while the model turns under it, so you place it,
+stroke over it, turn the model or move the stencil, and stroke again.
+
+1. In **Sculpt > Alpha**, under **Stencil**, click **Load image...** (any PNG, JPG, BMP, TGA, PSD or GIF), or
+ **Use alpha** to make the brush's alpha (a built-in pattern or one from your Library) the stencil.
+2. Turn on **Adjust**: drag inside the stencil to move it, a corner to scale it, the round handle above it to turn it
+ (<kbd>Shift</kbd>: 15 degree steps). The arrow keys move it, <kbd>-</kbd> and <kbd>=</kbd> scale it,
+ <kbd>,</kbd> and <kbd>.</kbd> turn it (<kbd>Shift</kbd>: finely). <kbd>Enter</kbd> or <kbd>Esc</kbd> goes back to
+ sculpting.
+3. Stroke over it with any brush that takes an alpha: the built-in sculpt brushes, custom and Community brushes and
+ the Paint brush. The brush's own falloff, Intensity, mask and alpha still apply on top.
+
+| Option | What it does |
+|---|---|
+| **Show** | Hidden, the stencil is off and brushes work as if it weren't there. |
+| **Invert** | Uses the image's negative: black works, white leaves the surface alone. |
+| **Tile** | Repeats the image across the whole view, for skin, fabric and other patterns. |
+| **Paint its colours** | Vertex Paint lays the image's own colours; off, its brightness masks the paint colour. |
+| **Hide while navigating** | Fades the stencil while the view turns, moves or zooms, so you see the model under it. |
+| **Opacity** | How strongly the overlay shows. The brushes always take the whole image (use Intensity to go lighter). |
+| **Size** / **Angle** | Its height in percent of the view's, and its turn; **Reset placement** centres it again. |
+
+With symmetry on, the mirrored side gets the stencil mirrored, as the stroke is. Stencils work on
+[micro levels](micro-levels.md) too. Move, the Kelvinlet brushes, vector displacement stamps and the mask brush don't
+use it. Texture painting doesn't take it yet (Vertex Paint does). The stencil isn't saved with the project. From a
+script: `stencil_load path=skin.png`, `stencil_set x=0.5 y=0.5 size=0.8 angle=30 tile=true`, `stencil_clear`.
+
## Vector displacement brushes
A vector displacement brush stamps a whole 3D shape in one
diff --git a/docs/guide/vertex-paint.md b/docs/guide/vertex-paint.md
index 5ef3871b..92803a9b 100644
--- a/docs/guide/vertex-paint.md
+++ b/docs/guide/vertex-paint.md
@@ -80,6 +80,14 @@ edit), <kbd>Esc</kbd> takes it back. Each gradient is one undo step. It respects
hidden faces, and goes into the texture when the Part paints into one. With it on, <kbd>Ctrl</kbd> still masks and
<kbd>Shift</kbd> still smooths; turn it off with its button or <kbd>Esc</kbd>.
+## Paint through a Stencil
+
+A [Stencil](sculpting.md#stencil) (**Sculpt > Alpha > Stencil**) paints too: load a photo or a pattern, place it over
+the model, and paint over it with the Paint brush. Where it covers the model the brush lays the image's colours (with
+your Colour intensity, falloff and mask); everywhere else it paints nothing. Turn off **Paint its colours** to paint
+the paint colour through the image's brightness instead (a grayscale pattern as a mask). Turn the model or move the
+stencil and paint again to cover a whole model.
+
## Paint layers
Paint layers stack vertex paint the way Photoshop stacks image layers. Each layer has its own name, visibility,
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 10dae94c..ab42a092 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -1750,6 +1750,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {
if (button == SDL_BUTTON_LEFT) {
if (axisGizmoMouseDown(x, y)) return; // the axis gizmo's ends snap to a side view (#43)
if (forgesphereMouseDown(x, y, mod)) return; // a Forge Sphere Part takes clicks on it (PanelForge Spheres.cpp)
+ if (stencilMouseDown(x, y, nav)) return; // Adjust Stencil: move, scale, turn it (StencilOverlay.cpp)
if (gradientMouseDown(x, y, nav)) return; // Line Gradient: a new line or an end handle (LineGradient.cpp)
if (facegroupMouseDown(x, y, mod)) return;
if (maskSelectMouseDown(x, y, mod)) return;
@@ -1930,6 +1931,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
case Drag::Sculptable: sculptableMouseMove(x, y); break;
case Drag::Capture: captureMouseMove(x, y); break;
case Drag::Gradient: gradientMouseMove(x, y); break;
+ case Drag::Stencil: stencilMouseMove(x, y); break;
case Drag::ForgeSphere: forgesphereDragTo(x, y); break;
case Drag::AirStroke: airStrokeTo(x, y); break;
case Drag::QuickRemesh: break; // (remeshes when let go)
@@ -2070,6 +2072,7 @@ void App::onMouseUp() {
if (drag_ == Drag::Sculptable) sculptableMouseUp();
if (drag_ == Drag::Capture) captureMouseUp();
if (drag_ == Drag::Gradient) gradientMouseUp();
+ if (drag_ == Drag::Stencil) stencilMouseUp();
if (drag_ == Drag::ForgeSphere) forgesphereRelease();
if (drag_ == Drag::AirStroke) airStrokeRelease();
gizmoRelease();
@@ -2081,6 +2084,7 @@ void App::onMouseUp() {
void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
if (cutPolylineKey(key)) return; // Enter ends a Cut Polyline, Esc drops it (PanelCut.cpp)
if (gradientKey(key)) return; // Enter keeps a Line Gradient, Esc takes it back (LineGradient.cpp)
+ if (stencilKey(key, mod)) return; // Adjust Stencil's keys, Enter / Esc ends it (StencilOverlay.cpp)
if (key == SDLK_ESCAPE && radial_.menu >= 0) {
closeRadialMenu();
return;
@@ -2545,6 +2549,12 @@ void App::dabAt(float x, float y, float pressure) {
lastDabAngle_ = dabAngle_;
p.alphaUp = cam.orientation() * glm::vec3(-std::sin(dabAngle_), std::cos(dabAngle_), 0.0f); // screenUpVector
p.vdm = st.vdm;
+ if (st.stencil.active()) { // the Stencil (#155): each vertex takes the image where it shows in this view
+ const CanvasRect cr = dabView_ ? dabView_->canvas : canvasRect();
+ p.stencil.stencil = &st.stencil;
+ p.stencil.viewProj = cam.projection() * cam.view();
+ p.stencil.canvasAspect = cr.h > 0.0f ? cr.w / cr.h : 1.0f;
+ }
p.strokeDelta = haveLastDab_ ? hit.position - lastDabHit_ : glm::vec3(0.0f);
lastDabHit_ = hit.position;
haveLastDab_ = true;
@@ -2950,6 +2960,7 @@ void App::drawUi() {
drawUvEditor(); // Tool > Texture Map > UV Editor (PanelUvEditor.cpp)
drawTimelineUi(); // the Sculpt Timeline strip, timelapse, proof mode HUD (PanelTimeline.cpp, ProofMode.cpp)
pollAlphaFile();
+ pollStencilFile();
syncBrushSettings(); // a brush switch brings back that brush's own settings (#78); before pollVdm's stroke
syncWorldSize(); // World Size: the brush keeps its size on the surface as you zoom (Precision.cpp)
pollVdm();
@@ -2961,6 +2972,7 @@ void App::drawUi() {
c.y + c.h - ImGui::GetFrameHeight() - 20.0f * uiScale_);
}
const ImVec2 mouse(mouseX_, mouseY_);
+ drawStencilOverlay(); // the Stencil and, in Adjust, its handles (StencilOverlay.cpp)
drawGizmo(); // Transform gizmo handles and panel (Gizmo.cpp)
drawQRemeshGuides(); // QRemesh Guides curves (PanelRetopo.cpp)
drawUvEditorOverlay(); // UV seams on the model, the Seam tool's cursor (PanelUvEditor.cpp)
@@ -2980,7 +2992,7 @@ void App::drawUi() {
theme::u32(theme::accent), 48, 2.0f * uiScale_);
}
// In Gizmo mode (and with the QRemesh Guides brush) the brush ring shows only while Ctrl masks or Shift smooths.
- const bool ringOff = gizmoActive() || (guidesMode_ && !(inputMods() & SDL_KMOD_SHIFT)) || sculptableHot() || forgesphereActive() ||
+ const bool ringOff = gizmoActive() || stencil_.adjust || (guidesMode_ && !(inputMods() & SDL_KMOD_SHIFT)) || sculptableHot() || forgesphereActive() ||
uvToolActive();
// (The S / O pop-up holds the mouse, but its ring shows where it opened, #138.)
ImVec2 sliderOpened;
diff --git a/src/app/App.h b/src/app/App.h
index d75111b2..2808c671 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -170,7 +170,7 @@ public:
private:
enum class Drag { None, Stroke, Orbit, Pan, Zoom, Roll, MaskCanvas, PartClick, Select, Gizmo, Guide, Sculptable, ForgeSphere, Insert, Capture,
- AirStroke, UvTool, SizeScrub, QuickRemesh, Gradient }; // AirStroke: a stroke begun off the model, waiting to reach it (#62)
+ AirStroke, UvTool, SizeScrub, QuickRemesh, Gradient, Stencil }; // AirStroke: a stroke begun off the model, waiting to reach it (#62)
void handleEvent(const SDL_Event& e); // the pen's mouse events first (penMouseEvents), then dispatchEvent
void dispatchEvent(const SDL_Event& e);
@@ -367,6 +367,7 @@ private:
Symmetry symmetry;
const BrushRecipe* recipe = nullptr;
const BrushAlpha* alpha = nullptr;
+ Stencil stencil; // (a copy: its image is shared and never changes, so the solver thread can read it)
const VectorDisplacement* vdm = nullptr;
std::shared_ptr<const VectorDisplacement> vdmOwner; // (keeps the VDM alive for the batch)
};
@@ -937,6 +938,30 @@ private:
void endGradientEdit();
void drawGradientOverlay();
void drawLineGradientControls(); // Color palette
+ // Stencil (#155, StencilOverlay.cpp; core/Stencil.h): the image over the view the brushes work through. Adjust
+ // Stencil puts handles on it (move, scale, turn) and takes the drags and the arrow / - = / , . keys until Enter.
+ void registerStencilActions();
+ void drawStencilSection(); // Alpha palette
+ void drawStencilOverlay(); // under the panels, over the model
+ int stencilHandleAt(float x, float y) const; // 0 inside, 1 a corner, 2 the turn handle, -1 none
+ bool stencilMouseDown(float x, float y, SDL_Keymod mod); // true when Adjust takes the click
+ void stencilMouseMove(float x, float y);
+ void stencilMouseUp();
+ bool stencilKey(SDL_Keycode key, SDL_Keymod mod);
+ bool stencilUiValue(const std::string& name, double& out) const;
+ static void SDLCALL onStencilChosen(void* userdata, const char* const* files, int filter);
+ void pollStencilFile();
+ struct StencilUi {
+ bool adjust = false;
+ bool hideWhileNavigating = true;
+ int handle = -1; // being dragged (stencilHandleAt's)
+ Stencil start; // as it was when the drag began
+ glm::vec2 startMouse{0.0f};
+ unsigned tex = 0; // the overlay's texture, of texImage (inverted when texInvert)
+ const Image* texImage = nullptr;
+ bool texInvert = false;
+ std::string pendingPath; // set by the file dialog thread (under alphaMutex_)
+ } stencil_;
bool gradientUiValue(const std::string& name, double& out) const; // UI test values
struct GradientUi {
bool armed = false;
diff --git a/src/app/AsyncStroke.cpp b/src/app/AsyncStroke.cpp
index 3f2da961..dafccfe8 100644
--- a/src/app/AsyncStroke.cpp
+++ b/src/app/AsyncStroke.cpp
@@ -461,6 +461,7 @@ App::DabSettings App::dabSettings() const {
// A predictive stroke works from its own copies of the recipe and alpha (made when it began).
st.recipe = asyncStroke_ ? strokeRecipe_.get() : strokeRecipe();
st.alpha = asyncStroke_ ? strokeAlpha_.get() : &doc_.brushAlpha; // (null: round)
+ st.stencil = doc_.stencil;
st.vdmOwner = doc_.brushVdm;
st.vdm = st.vdmOwner.get();
return st;
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 759805c8..d4e60d59 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -771,6 +771,7 @@ void App::initActions() {
registerShellActions();
registerTextureUiActions(); // Tool > Texture Map, the Vertex / Texture paint target (PanelTexture.cpp)
registerLineGradientActions(); // Color > Line Gradient (LineGradient.cpp)
+ registerStencilActions(); // Alpha > Stencil (StencilOverlay.cpp)
registerPbrUiActions(); // material channels, solo view, map export (PanelPbr.cpp)
registerGizmoActions(); // Q W E R: Draw, and the Transform gizmo's Move, Scale, Rotate (Gizmo.cpp)
registerBakeUiActions(); // Tool > Bake (PanelBake.cpp)
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index c5bf7679..c5ee1f0d 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -4208,6 +4208,53 @@ constexpr Entry kSimplifiedChinese[] = {
"工作室模式"},
{"Studio build for %s",
"%s 专用的工作室版本"},
+ // --- Alpha > Stencil (#155, StencilOverlay.cpp) ---
+ {"Stencil",
+ "模板"},
+ {"Load Stencil...",
+ "加载模板..."},
+ {"Show Stencil",
+ "显示模板"},
+ {"Adjust Stencil",
+ "调整模板"},
+ {"Use alpha",
+ "使用 Alpha"},
+ {"Tile",
+ "平铺"},
+ {"Paint its colours",
+ "绘制其颜色"},
+ {"Hide while navigating",
+ "导航时隐藏"},
+ {"Reset placement",
+ "重置位置"},
+ {"Lay an image over the view and sculpt or paint through it: the sculpt brushes take its brightness (white = full effect), Vertex Paint its colours, only where it covers the model.",
+ "在视图上放一张图片,透过它雕刻或绘制:雕刻笔刷取其亮度(白色 = 完整效果),顶点绘制取其颜色,只在它覆盖模型的地方。"},
+ {"Hidden, the Stencil is off: the brushes work as if it weren't there.",
+ "隐藏时模板关闭:笔刷如同没有它一样工作。"},
+ {"Handles on the Stencil: drag inside it to move it, a corner to scale it, the round handle to turn it (Shift: 15 degree steps). Arrow keys move it, - and = scale it, comma and period turn it (Shift: finely). Enter or Esc goes back to sculpting.",
+ "模板上的控制点:在内部拖动以移动,拖动角落以缩放,拖动圆形控制点以旋转(Shift:15 度一格)。方向键移动,- 和 = 缩放,逗号和句号旋转(Shift:微调)。Enter 或 Esc 回到雕刻。"},
+ {"Make the brush's alpha (above, or one from the Library) the Stencil.",
+ "将笔刷的 Alpha(上方的,或资源库中的)设为模板。"},
+ {"Lay an image over the view, then sculpt or paint through it. Move it and repeat.",
+ "在视图上放一张图片,然后透过它雕刻或绘制。移动它并重复。"},
+ {"Take the Stencil off the view.",
+ "从视图中移除模板。"},
+ {"Use the image's negative: black works, white leaves the surface alone.",
+ "使用图片的负片:黑色起作用,白色不改变表面。"},
+ {"Repeat the image across the whole view, for skin, fabric and other patterns.",
+ "在整个视图中重复图片,适用于皮肤、布料和其他图案。"},
+ {"Vertex Paint lays the image's own colours. Off, its brightness masks the paint colour instead.",
+ "顶点绘制使用图片本身的颜色。关闭时,其亮度遮罩绘制颜色。"},
+ {"Fade the Stencil while the view turns, moves or zooms, so you can see the model under it.",
+ "在视图旋转、移动或缩放时淡化模板,以便看到下方的模型。"},
+ {"How strongly the Stencil shows. The brushes always take all of it.",
+ "模板显示的强度。笔刷总是取用全部。"},
+ {"The Stencil's height, in percent of the view's height.",
+ "模板的高度,以视图高度的百分比表示。"},
+ {"Turn the Stencil, in degrees counter-clockwise; Ctrl+click to type.",
+ "旋转模板,以逆时针度数表示;Ctrl+点击以输入。"},
+ {"Centre the Stencil again, upright, 80% of the view's height.",
+ "将模板重新居中、摆正,高度为视图的 80%。"},
};
} // namespace
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index 3a4da3d8..ec3f895c 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -4680,6 +4680,53 @@ constexpr Entry kSpanish[] = {
"Modo estudio"},
{"Studio build for %s",
"Versión de estudio para %s"},
+ // --- Alpha > Stencil (#155, StencilOverlay.cpp) ---
+ {"Stencil",
+ "Plantilla"},
+ {"Load Stencil...",
+ "Cargar plantilla..."},
+ {"Show Stencil",
+ "Mostrar plantilla"},
+ {"Adjust Stencil",
+ "Ajustar plantilla"},
+ {"Use alpha",
+ "Usar alpha"},
+ {"Tile",
+ "Repetir"},
+ {"Paint its colours",
+ "Pintar sus colores"},
+ {"Hide while navigating",
+ "Ocultar al navegar"},
+ {"Reset placement",
+ "Restablecer posición"},
+ {"Lay an image over the view and sculpt or paint through it: the sculpt brushes take its brightness (white = full effect), Vertex Paint its colours, only where it covers the model.",
+ "Pon una imagen sobre la vista y esculpe o pinta a través de ella: los pinceles de esculpir toman su brillo (blanco = efecto completo), Pintura de vértices sus colores, solo donde cubre el modelo."},
+ {"Hidden, the Stencil is off: the brushes work as if it weren't there.",
+ "Oculta, la plantilla está apagada: los pinceles trabajan como si no estuviera."},
+ {"Handles on the Stencil: drag inside it to move it, a corner to scale it, the round handle to turn it (Shift: 15 degree steps). Arrow keys move it, - and = scale it, comma and period turn it (Shift: finely). Enter or Esc goes back to sculpting.",
+ "Tiradores en la plantilla: arrastra dentro para moverla, una esquina para escalarla, el tirador redondo para girarla (Shift: pasos de 15 grados). Las flechas la mueven, - y = la escalan, coma y punto la giran (Shift: con precisión). Enter o Esc vuelve a esculpir."},
+ {"Make the brush's alpha (above, or one from the Library) the Stencil.",
+ "Usa el alpha del pincel (arriba, o uno de la Biblioteca) como plantilla."},
+ {"Lay an image over the view, then sculpt or paint through it. Move it and repeat.",
+ "Pon una imagen sobre la vista y esculpe o pinta a través de ella. Muévela y repite."},
+ {"Take the Stencil off the view.",
+ "Quita la plantilla de la vista."},
+ {"Use the image's negative: black works, white leaves the surface alone.",
+ "Usa el negativo de la imagen: el negro trabaja, el blanco deja la superficie como está."},
+ {"Repeat the image across the whole view, for skin, fabric and other patterns.",
+ "Repite la imagen por toda la vista, para piel, tela y otros patrones."},
+ {"Vertex Paint lays the image's own colours. Off, its brightness masks the paint colour instead.",
+ "Pintura de vértices pone los colores de la imagen. Desactivado, su brillo enmascara el color de pintura."},
+ {"Fade the Stencil while the view turns, moves or zooms, so you can see the model under it.",
+ "Atenúa la plantilla mientras la vista gira, se mueve o hace zoom, para ver el modelo debajo."},
+ {"How strongly the Stencil shows. The brushes always take all of it.",
+ "Cuánto se ve la plantilla. Los pinceles siempre la toman entera."},
+ {"The Stencil's height, in percent of the view's height.",
+ "La altura de la plantilla, en porcentaje de la altura de la vista."},
+ {"Turn the Stencil, in degrees counter-clockwise; Ctrl+click to type.",
+ "Gira la plantilla, en grados en sentido antihorario; Ctrl+clic para escribir."},
+ {"Centre the Stencil again, upright, 80% of the view's height.",
+ "Centra la plantilla de nuevo, derecha, al 80% de la altura de la vista."},
};
} // namespace
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index deab6e0f..fb71513e 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -4206,6 +4206,53 @@ constexpr Entry kTraditionalChinese[] = {
"工作室模式"},
{"Studio build for %s",
"%s 專用的工作室版本"},
+ // --- Alpha > Stencil (#155, StencilOverlay.cpp) ---
+ {"Stencil",
+ "模板"},
+ {"Load Stencil...",
+ "載入模板..."},
+ {"Show Stencil",
+ "顯示模板"},
+ {"Adjust Stencil",
+ "調整模板"},
+ {"Use alpha",
+ "使用 Alpha"},
+ {"Tile",
+ "平鋪"},
+ {"Paint its colours",
+ "繪製其顏色"},
+ {"Hide while navigating",
+ "導覽時隱藏"},
+ {"Reset placement",
+ "重設位置"},
+ {"Lay an image over the view and sculpt or paint through it: the sculpt brushes take its brightness (white = full effect), Vertex Paint its colours, only where it covers the model.",
+ "在視圖上放一張圖片,透過它雕刻或繪製:雕刻筆刷取其亮度(白色 = 完整效果),頂點繪製取其顏色,只在它覆蓋模型的地方。"},
+ {"Hidden, the Stencil is off: the brushes work as if it weren't there.",
+ "隱藏時模板關閉:筆刷如同沒有它一樣工作。"},
+ {"Handles on the Stencil: drag inside it to move it, a corner to scale it, the round handle to turn it (Shift: 15 degree steps). Arrow keys move it, - and = scale it, comma and period turn it (Shift: finely). Enter or Esc goes back to sculpting.",
+ "模板上的控制點:在內部拖曳以移動,拖曳角落以縮放,拖曳圓形控制點以旋轉(Shift:15 度一格)。方向鍵移動,- 和 = 縮放,逗號和句號旋轉(Shift:微調)。Enter 或 Esc 回到雕刻。"},
+ {"Make the brush's alpha (above, or one from the Library) the Stencil.",
+ "將筆刷的 Alpha(上方的,或資源庫中的)設為模板。"},
+ {"Lay an image over the view, then sculpt or paint through it. Move it and repeat.",
+ "在視圖上放一張圖片,然後透過它雕刻或繪製。移動它並重複。"},
+ {"Take the Stencil off the view.",
+ "從視圖中移除模板。"},
+ {"Use the image's negative: black works, white leaves the surface alone.",
+ "使用圖片的負片:黑色起作用,白色不改變表面。"},
+ {"Repeat the image across the whole view, for skin, fabric and other patterns.",
+ "在整個視圖中重複圖片,適用於皮膚、布料和其他圖案。"},
+ {"Vertex Paint lays the image's own colours. Off, its brightness masks the paint colour instead.",
+ "頂點繪製使用圖片本身的顏色。關閉時,其亮度遮罩繪製顏色。"},
+ {"Fade the Stencil while the view turns, moves or zooms, so you can see the model under it.",
+ "在視圖旋轉、移動或縮放時淡化模板,以便看到下方的模型。"},
+ {"How strongly the Stencil shows. The brushes always take all of it.",
+ "模板顯示的強度。筆刷總是取用全部。"},
+ {"The Stencil's height, in percent of the view's height.",
+ "模板的高度,以視圖高度的百分比表示。"},
+ {"Turn the Stencil, in degrees counter-clockwise; Ctrl+click to type.",
+ "旋轉模板,以逆時針度數表示;Ctrl+點擊以輸入。"},
+ {"Centre the Stencil again, upright, 80% of the view's height.",
+ "將模板重新置中、擺正,高度為視圖的 80%。"},
};
} // namespace
diff --git a/src/app/PanelBrushes.cpp b/src/app/PanelBrushes.cpp
index 1d411d26..4bdf16d6 100644
--- a/src/app/PanelBrushes.cpp
+++ b/src/app/PanelBrushes.cpp
@@ -68,7 +68,9 @@ void App::drawAlphaSection() {
ImGui::TextUnformatted(alpha.name.c_str());
drawAlphaOptions();
+ drawStencilSection(); // StencilOverlay.cpp (#155), above the long grid so it shows
// Built-in and library alphas, then Load image... and Invert loaded image (Pickers.cpp), as in the alpha picker.
+ ImGui::Separator();
drawAlphaGrid(*this, GridMode::Palette);
}
diff --git a/src/app/StencilOverlay.cpp b/src/app/StencilOverlay.cpp
new file mode 100644
index 00000000..4bbae211
--- /dev/null
+++ b/src/app/StencilOverlay.cpp
@@ -0,0 +1,357 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Stencil (#155, docs/design/stencil.md): the image over the view the brushes work through (core/Stencil.h). The
+// Alpha palette's Stencil section loads it (an image file, or the brush's alpha) and sets it up; the overlay draws it
+// under the panels, over the model. Adjust Stencil puts handles on it: drag inside to move it, a corner to scale it,
+// the round handle to turn it; the arrow keys move it, - and = scale it, , and . turn it (Shift: finely). Enter or
+// Esc leaves Adjust. It fades while the view moves (Hide while navigating), so the model shows as it turns under it.
+#include "app/App.h"
+#include "app/I18n.h"
+#include "app/Theme.h"
+#include "app/Ui.h"
+
+#include "render/GL.h"
+
+#include <IconsLucide.h>
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+namespace {
+
+constexpr float kCornerPx = 6.0f; // corner handle half-size, logical px
+constexpr float kRotatePx = 26.0f; // the turn handle's distance above the top edge
+const SDL_DialogFileFilter kStencilFilters[] = {{"Images", "png;jpg;jpeg;bmp;tga;psd;gif"}, {"All files", "*"}};
+
+glm::vec2 toWindow(const CanvasRect& c, glm::vec2 f) { return {c.x + f.x * c.w, c.y + f.y * c.h}; }
+ImVec2 im(glm::vec2 p) { return {p.x, p.y}; }
+
+} // namespace
+
+void SDLCALL App::onStencilChosen(void* userdata, const char* const* files, int) {
+ wakeMainLoop();
+ if (!files || !files[0]) return;
+ auto* app = static_cast<App*>(userdata);
+ std::lock_guard lock(app->alphaMutex_);
+ app->stencil_.pendingPath = files[0];
+}
+
+void App::pollStencilFile() {
+ std::string path;
+ {
+ std::lock_guard lock(alphaMutex_);
+ path.swap(stencil_.pendingPath);
+ }
+ if (!path.empty()) runCommand("stencil_load", {{"path", path}});
+}
+
+void App::registerStencilActions() {
+ Action a;
+ a.id = "stencil.load";
+ a.label = "Load Stencil...";
+ a.icon = ICON_LC_IMAGE;
+ a.palette = "Alpha > Stencil";
+ a.description = "Lay an image over the view and sculpt or paint through it: the sculpt brushes take its brightness "
+ "(white = full effect), Vertex Paint its colours, only where it covers the model.";
+ a.command = "stencil_load";
+ a.run = [this] { SDL_ShowOpenFileDialog(App::onStencilChosen, this, window_, kStencilFilters, 2, nullptr, false); };
+ actions_.add(a);
+
+ a = {};
+ a.id = "stencil.show";
+ a.label = "Show Stencil";
+ a.icon = ICON_LC_EYE;
+ a.palette = "Alpha > Stencil";
+ a.description = "Hidden, the Stencil is off: the brushes work as if it weren't there.";
+ a.command = "stencil_set";
+ a.run = [this] { runCommand("stencil_set", {{"visible", !doc_.stencil.visible}}); };
+ a.checked = [this] { return doc_.stencil.image && doc_.stencil.visible; };
+ a.enabled = [this] { return doc_.stencil.image != nullptr; };
+ actions_.add(a);
+
+ a = {};
+ a.id = "stencil.adjust";
+ a.label = "Adjust Stencil";
+ a.icon = ICON_LC_MOVE;
+ a.palette = "Alpha > Stencil";
+ a.description = "Handles on the Stencil: drag inside it to move it, a corner to scale it, the round handle to turn it "
+ "(Shift: 15 degree steps). Arrow keys move it, - and = scale it, comma and period turn it (Shift: "
+ "finely). Enter or Esc goes back to sculpting.";
+ a.run = [this] {
+ stencil_.adjust = !stencil_.adjust && doc_.stencil.active();
+ status_ = stencil_.adjust ? "Adjust Stencil: drag to move, a corner to scale, the round handle to turn (Enter: done)"
+ : "Adjust Stencil off";
+ };
+ a.checked = [this] { return stencil_.adjust; };
+ a.enabled = [this] { return doc_.stencil.active(); };
+ actions_.add(a);
+}
+
+// The handle under a window point: 0 inside (move), 1 a corner (scale), 2 the turn handle; -1 none.
+int App::stencilHandleAt(float x, float y) const {
+ const Stencil& st = doc_.stencil;
+ const CanvasRect c = canvasRect();
+ if (!st.active() || c.w <= 0.0f || c.h <= 0.0f) return -1;
+ const float aspect = c.w / c.h, s = uiScale_;
+ const glm::vec2 p(x, y);
+ const glm::vec2 centre = toWindow(c, st.center);
+ const glm::vec2 topMid = toWindow(c, st.canvasPoint({0.5f, 0.0f}, aspect));
+ const glm::vec2 up = glm::length(topMid - centre) > 1e-3f ? glm::normalize(topMid - centre) : glm::vec2(0, -1);
+ if (glm::distance(p, topMid + up * kRotatePx * s) <= (kCornerPx + 6.0f) * s) return 2;
+ for (glm::vec2 uv : {glm::vec2(0, 0), glm::vec2(1, 0), glm::vec2(1, 1), glm::vec2(0, 1)})
+ if (glm::distance(p, toWindow(c, st.canvasPoint(uv, aspect))) <= (kCornerPx + 6.0f) * s) return 1;
+ Stencil once = st; // (the image itself, not its tiles)
+ once.tile = false;
+ glm::vec2 uv;
+ return once.imageCoord({(x - c.x) / c.w, (y - c.y) / c.h}, aspect, uv) ? 0 : -1;
+}
+
+bool App::stencilMouseDown(float x, float y, SDL_Keymod mod) {
+ if (!stencil_.adjust || (mod & (SDL_KMOD_CTRL | SDL_KMOD_SHIFT | SDL_KMOD_ALT | SDL_KMOD_GUI))) return false;
+ if (!doc_.stencil.active()) {
+ stencil_.adjust = false;
+ return false;
+ }
+ stencil_.handle = stencilHandleAt(x, y);
+ if (stencil_.handle < 0) return true; // (off it: nothing, while adjusting; Enter goes back to sculpting)
+ stencil_.start = doc_.stencil;
+ stencil_.startMouse = glm::vec2(x, y);
+ drag_ = Drag::Stencil;
+ return true;
+}
+
+void App::stencilMouseMove(float x, float y) {
+ const CanvasRect c = canvasRect();
+ if (c.w <= 0.0f || c.h <= 0.0f || stencil_.handle < 0) return;
+ Stencil& st = doc_.stencil;
+ const Stencil& s0 = stencil_.start;
+ const glm::vec2 p(x, y), centre = toWindow(c, s0.center);
+ if (stencil_.handle == 0) {
+ st.center = s0.center + (p - stencil_.startMouse) / glm::vec2(c.w, c.h);
+ } else if (stencil_.handle == 1) {
+ const float d0 = glm::distance(stencil_.startMouse, centre), d1 = glm::distance(p, centre);
+ if (d0 > 1.0f) st.size = std::clamp(s0.size * d1 / d0, 0.02f, 20.0f);
+ } else {
+ const glm::vec2 a = stencil_.startMouse - centre, b = p - centre;
+ if (glm::length(a) > 1.0f && glm::length(b) > 1.0f) { // (y down: a turn seen counter-clockwise lowers atan2)
+ float turn = std::atan2(a.y, a.x) - std::atan2(b.y, b.x);
+ float deg = glm::degrees(s0.angle + turn);
+ if (inputMods() & SDL_KMOD_SHIFT) deg = std::round(deg / 15.0f) * 15.0f; // (Shift: 15 degree steps)
+ st.angle = glm::radians(std::remainder(deg, 360.0f));
+ }
+ }
+}
+
+void App::stencilMouseUp() { stencil_.handle = -1; }
+
+bool App::stencilKey(SDL_Keycode key, SDL_Keymod mod) {
+ if (!stencil_.adjust) return false;
+ if (key == SDLK_RETURN || key == SDLK_KP_ENTER || key == SDLK_ESCAPE) {
+ stencil_.adjust = false;
+ status_ = "Adjust Stencil off";
+ return true;
+ }
+ if (mod & (SDL_KMOD_CTRL | SDL_KMOD_ALT | SDL_KMOD_GUI)) return false;
+ Stencil& st = doc_.stencil;
+ const CanvasRect c = canvasRect();
+ const bool fine = mod & SDL_KMOD_SHIFT;
+ const float stepPx = (fine ? 1.0f : 10.0f) * uiScale_;
+ const float stepX = c.w > 0.0f ? stepPx / c.w : 0.01f, stepY = c.h > 0.0f ? stepPx / c.h : 0.01f;
+ switch (key) {
+ case SDLK_LEFT: st.center.x -= stepX; return true;
+ case SDLK_RIGHT: st.center.x += stepX; return true;
+ case SDLK_UP: st.center.y -= stepY; return true;
+ case SDLK_DOWN: st.center.y += stepY; return true;
+ case SDLK_MINUS: case SDLK_KP_MINUS: st.size = std::max(st.size / (fine ? 1.01f : 1.1f), 0.02f); return true;
+ case SDLK_EQUALS: case SDLK_KP_PLUS: st.size = std::min(st.size * (fine ? 1.01f : 1.1f), 20.0f); return true;
+ case SDLK_COMMA: case SDLK_PERIOD: {
+ const float deg = glm::degrees(st.angle) + (key == SDLK_COMMA ? 1.0f : -1.0f) * (fine ? 1.0f : 15.0f);
+ st.angle = glm::radians(std::remainder(deg, 360.0f));
+ return true;
+ }
+ default: return false;
+ }
+}
+
+void App::drawStencilOverlay() {
+ const Stencil& st = doc_.stencil;
+ if (!st.active()) {
+ stencil_.adjust = false;
+ if (!st.image && stencil_.tex) { // removed: its texture goes too
+ gl::DeleteTextures(1, &stencil_.tex);
+ stencil_.tex = 0;
+ stencil_.texImage = nullptr;
+ }
+ return;
+ }
+ const CanvasRect c = canvasRect();
+ if (c.w <= 0.0f || c.h <= 0.0f) return;
+ // The texture: the image as it shows (its negative when inverted), uploaded again only when either changes.
+ if (stencil_.texImage != st.image.get() || stencil_.texInvert != st.invert || !stencil_.tex) {
+ if (stencil_.tex) gl::DeleteTextures(1, &stencil_.tex);
+ Image shown = *st.image;
+ if (st.invert)
+ for (size_t i = 0; i < shown.rgba.size(); i += 4)
+ for (int k = 0; k < 3; ++k) shown.rgba[i + size_t(k)] = uint8_t(255 - shown.rgba[i + size_t(k)]);
+ gl::GenTextures(1, &stencil_.tex);
+ gl::BindTexture(GL_TEXTURE_2D, stencil_.tex);
+ gl::PixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_RGBA8), shown.width, shown.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, shown.rgba.data());
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_LINEAR));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_LINEAR));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GLint(GL_CLAMP_TO_EDGE));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GLint(GL_CLAMP_TO_EDGE));
+ gl::BindTexture(GL_TEXTURE_2D, 0);
+ stencil_.texImage = st.image.get();
+ stencil_.texInvert = st.invert;
+ }
+ const bool navigating = drag_ == Drag::Orbit || drag_ == Drag::Pan || drag_ == Drag::Zoom || drag_ == Drag::Roll;
+ const float fade = navigating && stencil_.hideWhileNavigating ? 0.15f : 1.0f;
+ const int alpha = int(std::clamp(st.opacity * fade, 0.0f, 1.0f) * 255.0f + 0.5f);
+ const float aspect = c.w / c.h, s = uiScale_;
+ ImDrawList* dl = ImGui::GetBackgroundDrawList(); // under the panels, over the model
+ dl->PushClipRect(ImVec2(c.x, c.y), ImVec2(c.x + c.w, c.y + c.h), true);
+ const ImTextureID tex = ImTextureID(uintptr_t(stencil_.tex));
+ auto quad = [&](glm::vec2 o) { // the image moved by `o` whole images (tiles)
+ const ImVec2 p0 = im(toWindow(c, st.canvasPoint(o + glm::vec2(0, 0), aspect)));
+ const ImVec2 p1 = im(toWindow(c, st.canvasPoint(o + glm::vec2(1, 0), aspect)));
+ const ImVec2 p2 = im(toWindow(c, st.canvasPoint(o + glm::vec2(1, 1), aspect)));
+ const ImVec2 p3 = im(toWindow(c, st.canvasPoint(o + glm::vec2(0, 1), aspect)));
+ dl->AddImageQuad(tex, p0, p1, p2, p3, ImVec2(0, 0), ImVec2(1, 0), ImVec2(1, 1), ImVec2(0, 1), IM_COL32(255, 255, 255, alpha));
+ };
+ if (alpha > 0) {
+ if (!st.tile) {
+ quad({0.0f, 0.0f});
+ } else { // every repeat the canvas's corners reach (at most 40 x 40)
+ glm::vec2 lo(1e9f), hi(-1e9f), uv;
+ for (glm::vec2 k : {glm::vec2(0, 0), glm::vec2(1, 0), glm::vec2(1, 1), glm::vec2(0, 1)}) {
+ st.imageCoord(k, aspect, uv);
+ lo = glm::min(lo, uv);
+ hi = glm::max(hi, uv);
+ }
+ const int i0 = std::max(int(std::floor(lo.x)), -20), i1 = std::min(int(std::floor(hi.x)), 20);
+ const int j0 = std::max(int(std::floor(lo.y)), -20), j1 = std::min(int(std::floor(hi.y)), 20);
+ for (int j = j0; j <= j1; ++j)
+ for (int i = i0; i <= i1; ++i) quad({float(i), float(j)});
+ }
+ }
+ // Its outline (always: a faint stencil still shows where it works) and, while adjusting, the handles.
+ glm::vec2 corner[4];
+ int k = 0;
+ for (glm::vec2 uv : {glm::vec2(0, 0), glm::vec2(1, 0), glm::vec2(1, 1), glm::vec2(0, 1)})
+ corner[k++] = toWindow(c, st.canvasPoint(uv, aspect));
+ const ImU32 edge = stencil_.adjust ? theme::u32(theme::accent) : IM_COL32(255, 255, 255, 90);
+ for (int i = 0; i < 4; ++i) {
+ dl->AddLine(im(corner[i]), im(corner[(i + 1) % 4]), IM_COL32(0, 0, 0, 120), 3.0f * s);
+ dl->AddLine(im(corner[i]), im(corner[(i + 1) % 4]), edge, 1.25f * s);
+ }
+ if (stencil_.adjust) {
+ const int hot = stencil_.handle >= 0 ? stencil_.handle : stencilHandleAt(mouseX_, mouseY_);
+ const float h = kCornerPx * s;
+ for (const glm::vec2& p : corner) {
+ dl->AddRectFilled(ImVec2(p.x - h - s, p.y - h - s), ImVec2(p.x + h + s, p.y + h + s), IM_COL32(0, 0, 0, 160));
+ dl->AddRectFilled(ImVec2(p.x - h, p.y - h), ImVec2(p.x + h, p.y + h), hot == 1 ? theme::u32(theme::accent) : IM_COL32(240, 240, 240, 255));
+ }
+ const glm::vec2 centre = toWindow(c, st.center), topMid = 0.5f * (corner[0] + corner[1]);
+ const glm::vec2 up = glm::length(topMid - centre) > 1e-3f ? glm::normalize(topMid - centre) : glm::vec2(0, -1);
+ const glm::vec2 knob = topMid + up * kRotatePx * s;
+ dl->AddLine(im(topMid), im(knob), edge, 1.25f * s);
+ dl->AddCircleFilled(im(knob), h + 2.0f * s, IM_COL32(0, 0, 0, 160), 24);
+ dl->AddCircleFilled(im(knob), h, hot == 2 ? theme::u32(theme::accent) : IM_COL32(240, 240, 240, 255), 24);
+ // The centre: a small cross, lit while it moves.
+ const ImU32 mid = hot == 0 ? theme::u32(theme::accent) : IM_COL32(240, 240, 240, 220);
+ dl->AddLine(ImVec2(centre.x - 2 * h, centre.y), ImVec2(centre.x + 2 * h, centre.y), mid, 1.5f * s);
+ dl->AddLine(ImVec2(centre.x, centre.y - 2 * h), ImVec2(centre.x, centre.y + 2 * h), mid, 1.5f * s);
+ }
+ dl->PopClipRect();
+}
+
+// Alpha palette: the Stencil section.
+void App::drawStencilSection() {
+ Stencil& st = doc_.stencil;
+ const char* where = "Alpha > Stencil";
+ ImGui::SeparatorText(tr("Stencil"));
+ const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
+ if (ImGui::Button(tr(ICON_LC_IMAGE " Load image...##stencil.load"), ImVec2(half, 0)))
+ SDL_ShowOpenFileDialog(App::onStencilChosen, this, window_, kStencilFilters, 2, nullptr, false);
+ ui::HelpText("Load image", nullptr,
+ "Lay an image over the view and sculpt or paint through it: the sculpt brushes take its brightness "
+ "(white = full effect), Vertex Paint its colours, only where it covers the model.",
+ where);
+ ImGui::SameLine();
+ ImGui::BeginDisabled(doc_.brushAlpha.empty());
+ if (ImGui::Button(tr(ICON_LC_CIRCLE_DASHED " Use alpha##stencil.use_alpha"), ImVec2(-1, 0)))
+ runCommand("stencil_load", {{"alpha", true}});
+ ImGui::EndDisabled();
+ ui::HelpText("Use alpha", nullptr, "Make the brush's alpha (above, or one from the Library) the Stencil.", where);
+ if (!st.image) {
+ ImGui::PushTextWrapPos(0.0f);
+ ImGui::TextDisabled("%s", tr("Lay an image over the view, then sculpt or paint through it. Move it and repeat."));
+ ImGui::PopTextWrapPos();
+ return;
+ }
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextUnformatted(st.name.c_str());
+ ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - ImGui::GetFrameHeight());
+ if (ui::GlyphButton("##stencil.clear", ICON_LC_X, ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight())))
+ runCommand("stencil_clear");
+ ui::HelpText("Remove", nullptr, "Take the Stencil off the view.", where);
+ if (!st.image) return;
+
+ const float column2 = ImGui::GetCursorPosX() + half + ImGui::GetStyle().ItemSpacing.x; // (the second of two columns)
+ if (ui::Checkbox(tr("Show##stencil.show"), &st.visible) && !st.visible) stencil_.adjust = false;
+ ui::HelpText("Show", nullptr, "Hidden, the Stencil is off: the brushes work as if it weren't there.", where);
+ ImGui::SameLine(column2);
+ bool adjust = stencil_.adjust;
+ ImGui::BeginDisabled(!st.visible);
+ if (ui::Checkbox(tr("Adjust##stencil.adjust"), &adjust)) stencil_.adjust = adjust;
+ ImGui::EndDisabled();
+ ui::HelpText("Adjust", nullptr,
+ "Handles on the Stencil: drag inside it to move it, a corner to scale it, the round handle to turn it "
+ "(Shift: 15 degree steps). Arrow keys move it, - and = scale it, comma and period turn it (Shift: "
+ "finely). Enter or Esc goes back to sculpting.",
+ where);
+ ui::Checkbox(tr("Invert##stencil.invert"), &st.invert);
+ ui::HelpText("Invert", nullptr, "Use the image's negative: black works, white leaves the surface alone.", where);
+ ImGui::SameLine(column2);
+ ui::Checkbox(tr("Tile##stencil.tile"), &st.tile);
+ ui::HelpText("Tile", nullptr, "Repeat the image across the whole view, for skin, fabric and other patterns.", where);
+ ui::Checkbox(tr("Paint its colours##stencil.colors"), &st.colors);
+ ui::HelpText("Paint its colours", nullptr,
+ "Vertex Paint lays the image's own colours. Off, its brightness masks the paint colour instead.", where);
+ ui::Checkbox(tr("Hide while navigating##stencil.hide_nav"), &stencil_.hideWhileNavigating);
+ ui::HelpText("Hide while navigating", nullptr,
+ "Fade the Stencil while the view turns, moves or zooms, so you can see the model under it.", where);
+ ImGui::SetNextItemWidth(-1);
+ ui::SliderInside("##stencil_opacity", &st.opacity, 0.0f, 1.0f, tr("Opacity %.2f"));
+ ui::HelpText("Opacity", nullptr, "How strongly the Stencil shows. The brushes always take all of it.", where);
+ ImGui::SetNextItemWidth(half);
+ float sizePct = st.size * 100.0f;
+ if (ui::SliderInside("##stencil_size", &sizePct, 2.0f, 400.0f, tr("Size %.0f%%"), ImGuiSliderFlags_Logarithmic))
+ st.size = std::clamp(sizePct / 100.0f, 0.02f, 20.0f);
+ ui::HelpText("Size", nullptr, "The Stencil's height, in percent of the view's height.", where);
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ float deg = glm::degrees(st.angle);
+ if (ui::SliderInside("##stencil_angle", &deg, -180.0f, 180.0f, tr("Angle %.0f"))) st.angle = glm::radians(deg);
+ ui::HelpText("Angle", nullptr, "Turn the Stencil, in degrees counter-clockwise; Ctrl+click to type.", where);
+ if (ImGui::Button(tr("Reset placement##stencil.reset"), ImVec2(-1, 0))) runCommand("stencil_set", {{"reset", true}});
+ ui::HelpText("Reset placement", nullptr, "Centre the Stencil again, upright, 80% of the view's height.", where);
+}
+
+bool App::stencilUiValue(const std::string& name, double& out) const {
+ const Stencil& st = doc_.stencil;
+ if (name == "stencil_active") out = st.active() ? 1.0 : 0.0;
+ else if (name == "stencil_adjust") out = stencil_.adjust ? 1.0 : 0.0;
+ else if (name == "stencil_x") out = std::round(double(st.center.x) * 1000.0); // x1000
+ else if (name == "stencil_y") out = std::round(double(st.center.y) * 1000.0);
+ else if (name == "stencil_size") out = std::round(double(st.size) * 1000.0);
+ else if (name == "stencil_angle") out = std::round(double(glm::degrees(st.angle)));
+ else return false;
+ return true;
+}
+
+} // namespace sf
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 3772ed00..5b102669 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -121,6 +121,8 @@
// dabs keep the volume now: the option, flipped by letting go of Shift mid-stroke),
// smooth_group_borders (Brush > Smooth face group borders only, #81),
// moved_out (summed movement along the snapshot's normals: > 0 out, < 0 in),
+// moved_off_stencil (moved vertices that showed off the Stencil's image), stencil_active,
+// stencil_adjust, stencil_x / stencil_y / stencil_size (x1000), stencil_angle (degrees),
// pen_pressure (raw), brush_pressure (after the curve; 1 for the mouse),
// pressure_status (0 no pen yet, 1 on, 2 not detected, 3 not known yet),
// stroke_continuous (Stroke > Continuous, 1 on),
@@ -773,6 +775,7 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "stroke_continuous") return app_.strokeContinuous_ ? 1.0 : 0.0; // Continuous (#31)
if (name == "vdms") return double(app_.doc_.vdms.size());
if (double gv = 0.0; app_.gradientUiValue(name, gv)) return gv; // gradient_armed, gradient_placed (LineGradient.cpp)
+ if (double sv = 0.0; app_.stencilUiValue(name, sv)) return sv; // stencil_active, stencil_x / y / size x1000 (StencilOverlay.cpp)
if (double kv = 0.0; app_.kelvinUiValue(name, kv)) return kv; // capture_*, kelvin_* (PanelKelvinlet.cpp)
// Facial shapes (PanelFace.cpp): landmarks placed, placing them, a take playing, and face_<shape>: that layer's weight.
if (name == "face_landmarks") return double(app_.faceLandmarks_.count());
@@ -1079,6 +1082,22 @@ double Demo::query(const std::string& name, bool& known) const {
}
return name == "moved" ? count : name == "moved_max" ? maxD : name == "moved_sum" ? sum : out;
}
+ if (name == "moved_off_stencil") { // vertices moved since `snapshot` that showed off the Stencil's image (#155)
+ const Stencil& st = app_.doc_.stencil;
+ if (basePositions_.size() != m.vertexCount() || !st.image) return -1.0;
+ const CanvasRect c = app_.canvasRect();
+ Stencil once = st;
+ once.tile = false;
+ once.visible = true;
+ const StencilView view{&once, app_.camera_.projection() * app_.camera_.view(), c.h > 0.0f ? c.w / c.h : 1.0f};
+ double count = 0.0;
+ for (size_t v = 0; v < basePositions_.size(); ++v) {
+ if (glm::length(m.positions[v] - basePositions_[v]) <= 1e-6f) continue;
+ glm::vec2 at, uv;
+ count += !view.canvasAt(basePositions_[v], at) || !once.imageCoord(at, view.canvasAspect, uv) ? 1.0 : 0.0;
+ }
+ return count;
+ }
if (name == "pen_pressure") return app_.penTracker_.raw();
if (name == "pressure_status") { // 0 no pen yet, 1 on, 2 not detected, 3 not known yet
const std::string st = app_.pressureStatus();
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index af1ef556..e5892385 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -684,6 +684,7 @@ CommandRegistry::CommandRegistry() {
}});
registerBrushLibraryCommands(*this); // brush_install, brush_code, brush_delete, ... (BrushLibrary.cpp)
registerBrushCommands(*this); // brush_set_alpha (BrushAlpha.cpp)
+ registerStencilCommands(*this); // stencil_load, stencil_set, stencil_clear (Stencil.cpp)
registerVdmCommands(*this); // vdm_set, vdm_capture, vdm_stamp, ... (Vdm.cpp)
registerKelvinletCommands(*this); // kelvinlet_settings (Kelvinlet.cpp)
registerCaptureCommands(*this); // capture_alpha, capture_vdm: alpha / VDM from the viewport (ViewCapture.cpp)
diff --git a/src/core/Document.h b/src/core/Document.h
index 8ef6ba2a..7a4f562b 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -10,6 +10,7 @@
#include "core/QRemeshGuides.h"
#include "core/Sculpt.h"
#include "core/Splats.h"
+#include "core/Stencil.h"
#include "core/TextureChannels.h"
#include "core/Undo.h"
#include "core/Uv.h"
@@ -89,6 +90,7 @@ struct Document {
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
+ Stencil stencil; // the image over the view the brushes work through (#155; stencil_load, core/Stencil.h)
glm::vec3 paintColor{0.22f, 0.22f, 0.22f}; // current vertex paint colour (linear RGB; see set_color); a mid grey
// Material texture painting (core/TextureChannels.h): what the Paint brush lays on the material channels
// (paint_material; its colour is paintColor), and the channel the view shows on its own (channel_view).
diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cpp
index 616682a4..6fb0c85b 100644
--- a/src/core/Sculpt.cpp
+++ b/src/core/Sculpt.cpp
@@ -169,6 +169,14 @@ namespace {
glm::vec3 projectOnPlane(const glm::vec3& v, const glm::vec3& n) { return v - n * glm::dot(v, n); }
+// A micro level's dab takes the Stencil as its per-point pattern (the points are in copy `m`'s place); empty without one.
+std::function<float(const glm::vec3&)> stencilTexture(const DabParams& p, const SymCopy& m) {
+ if (!p.stencil.active()) return {};
+ StencilView view = p.stencil;
+ view.copy = m;
+ return [view](const glm::vec3& x) { return view.weight(x); };
+}
+
// Smooth's keep-volume steps (Sculptor::taubinShrink): Taubin's own values, pass band 1/lambda + 1/mu = 0.1.
constexpr float kTaubinLambda = 0.6307f, kTaubinMu = -0.6732f;
@@ -423,7 +431,7 @@ bool Sculptor::microBaseDab(const Mesh& mesh, BrushType type, const DabParams& p
if (microBase_ < 0) { // (decided once a stroke: its dabs all go one way)
const MicroMesh& mm = *mesh.micro;
microBase_ = microBaseDabs && (type == BrushType::Standard || type == BrushType::Clay || type == BrushType::Inflate) &&
- !mm.hasMask() && mesh.mask.empty() && !mesh.hasHidden() && !(p.alpha && !p.alpha->empty()) &&
+ !mm.hasMask() && mesh.mask.empty() && !mesh.hasHidden() && !(p.alpha && !p.alpha->empty()) && !p.stencil.active() &&
mesh.layers.empty() && !dyntopo.enabled && mm.baseEdge > 0.0f &&
p.radius >= kMicroBaseSpan * mm.baseEdge
? 1
@@ -956,14 +964,14 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Sym
const uint64_t pts = micro_.points;
for (const SymCopy& m : copies(sym))
micro_.dab(mesh, bvh, type, m.point(p.center), m.dir(p.viewDir), p.radius, p.strength * std::clamp(p.pressure, 0.0f, 1.0f),
- p.invert, p.focal, m.dir(p.alphaUp), false, 0.0f, p.alpha, {}, m.dir(p.strokeDelta));
+ p.invert, p.focal, m.dir(p.alphaUp), false, 0.0f, p.alpha, stencilTexture(p, m), m.dir(p.strokeDelta));
timings.kernelMs += micro_.findMs + micro_.kernelMs - k0;
timings.normalsMs += micro_.stitchMs - s0;
timings.vertices += micro_.points - pts;
++timings.dabs;
return;
}
- lastFusable_ = adaptiveDabs && isPlaneKernelBrush(type) && type != BrushType::Trim && !(p.alpha && !p.alpha->empty()) &&
+ lastFusable_ = adaptiveDabs && isPlaneKernelBrush(type) && type != BrushType::Trim && !(p.alpha && !p.alpha->empty()) && !p.stencil.active() &&
!p.frontFacesOnly && !p.connectedOnly && !p.viewFalloff && !dyntopo.enabled;
if (batching_ && batchable(mesh, type, p, sym)) { // a fused batch's (SculptBatch.cpp)
pending_.push_back({type, p, sym});
@@ -996,6 +1004,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
auto clock = std::chrono::steady_clock::now();
// Alphas and the square Clay Block tip reach into the corners of their square.
const bool useAlpha = p.alpha && !p.alpha->empty();
+ const bool useStencil = p.stencil.active();
const float reach = useAlpha ? kAlphaReach : type == BrushType::ClayBlock ? 1.3f : 1.0f;
brushRegion(mesh, bvh, p.center, p.viewDir, p.radius * reach, p.connectedOnly, p.viewFalloff, verts_, connected_);
if (verts_.empty()) return;
@@ -1014,6 +1023,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
// (an alpha's fine pattern or Clay Block's square tip, which turn with the area normal, and the brushes that move along each vertex's own normal amplify a
// hair's difference in the normals the next dabs read)
type != BrushType::Nudge && type != BrushType::Inflate && type != BrushType::ClayBlock && !useAlpha &&
+ !p.stencil.active() && // (the stencil's detail, as an alpha's)
mesh.normals.size() == mesh.vertexCount();
if (adaptiveDab_ && (mesh.mask.size() == mesh.vertexCount() || mesh.hasHidden())) {
// A mask's edge is a step the adaptive normals don't see (they follow the brush, not the mask): regions
@@ -1086,8 +1096,9 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
// points next to it, which only the brushes that read nothing but the place, and v's own normal, are asked).
const auto offset = [&](size_t i, uint32_t v, const glm::vec3& x) -> glm::vec3 {
const glm::vec3 o = x - p.center;
- const float f = useAlpha ? p.alpha->stamp(glm::dot(o, right) / r, glm::dot(o, up) / r, p.focal)
- : brushFalloff(brushDistance(p, x), r, p.focal);
+ float f = useAlpha ? p.alpha->stamp(glm::dot(o, right) / r, glm::dot(o, up) / r, p.focal)
+ : brushFalloff(brushDistance(p, x), r, p.focal);
+ if (useStencil && f > 0.0f) f *= p.stencil.weight(x);
glm::vec3 d(0.0f);
switch (type) {
@@ -1355,9 +1366,14 @@ void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const
const float pressure = std::pow(std::clamp(p.pressure, 0.0f, 1.0f), recipe.pressureCurve);
const double k0 = micro_.findMs + micro_.kernelMs, s0 = micro_.stitchMs;
const uint64_t pts = micro_.points;
- for (const SymCopy& m : copies(sym))
+ for (const SymCopy& m : copies(sym)) {
+ const auto stencil = stencilTexture(p, m);
+ std::function<float(const glm::vec3&)> both = texture;
+ if (stencil && texture) both = [&texture, &stencil](const glm::vec3& x) { return texture(x) * stencil(x); };
+ else if (stencil) both = stencil;
micro_.dab(mesh, bvh, BrushType::Standard, m.point(p.center), m.dir(p.viewDir), p.radius, strength * pressure,
- invert, p.focal, m.dir(p.alphaUp), false, 0.0f, p.alpha, texture);
+ invert, p.focal, m.dir(p.alphaUp), false, 0.0f, p.alpha, both);
+ }
timings.kernelMs += micro_.findMs + micro_.kernelMs - k0;
timings.normalsMs += micro_.stitchMs - s0;
timings.vertices += micro_.points - pts;
@@ -1445,6 +1461,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]);
+ if (p.stencil.active() && w > 0.0f) w *= p.stencil.weight(pos[v]);
weights_[i] = w;
});
glm::vec3 areaNormal = sums.normal, areaCenter = sums.center;
diff --git a/src/core/Sculpt.h b/src/core/Sculpt.h
index fe054dde..9a9799a0 100644
--- a/src/core/Sculpt.h
+++ b/src/core/Sculpt.h
@@ -8,6 +8,7 @@
#include "core/IndexBits.h"
#include "core/Kelvinlet.h"
#include "core/Mesh.h"
+#include "core/Stencil.h"
#include "core/Symmetry.h"
#include "core/Undo.h"
@@ -88,6 +89,8 @@ struct DabParams {
// find where that ray meets the surface the batch's earlier dabs left.
glm::vec3 pickDir{0.0f};
glm::vec3 pickNormal{0.0f}; // the surface's normal there (zero: unknown)
+ // The Stencil (#155, core/Stencil.h): each vertex also takes the image at the place it shows on screen.
+ StencilView stencil;
};
// Local symmetry's centre for a Part: the middle of its bounding box (in parallel).
@@ -101,6 +104,7 @@ inline DabParams transformed(const DabParams& p, const SymCopy& c) {
o.alphaUp = c.dir(p.alphaUp);
o.pickDir = c.dir(p.pickDir);
o.pickNormal = c.dir(p.pickNormal);
+ o.stencil.copy = c; // (the mirror takes the stencil at its mirror image's place: the pattern mirrors)
return o;
}
diff --git a/src/core/SculptBatch.cpp b/src/core/SculptBatch.cpp
index 26bb8bd2..b676060e 100644
--- a/src/core/SculptBatch.cpp
+++ b/src/core/SculptBatch.cpp
@@ -32,7 +32,7 @@ namespace sf {
bool Sculptor::batchable(const Mesh& mesh, BrushType type, const DabParams& p, const Symmetry& sym) const {
if (!adaptiveDabs || !isPlaneKernelBrush(type) || type == BrushType::Trim || dyntopo.enabled || draft_ || (mesh.micro && !(microBase_ == 1 && microBaseFuse)))
return false;
- if ((p.alpha && !p.alpha->empty()) || p.frontFacesOnly || p.connectedOnly || p.viewFalloff) return false;
+ if ((p.alpha && !p.alpha->empty()) || p.stencil.active() || p.frontFacesOnly || p.connectedOnly || p.viewFalloff) return false;
if (mesh.normals.size() != mesh.vertexCount()) return false;
if (!pending_.empty()) {
const PendingDab& f = pending_.front();
diff --git a/src/core/Stencil.cpp b/src/core/Stencil.cpp
new file mode 100644
index 00000000..03bbf0da
--- /dev/null
+++ b/src/core/Stencil.cpp
@@ -0,0 +1,237 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Stencil.h"
+
+#include "core/BrushAlpha.h"
+#include "core/Commands.h"
+#include "core/Document.h"
+#include "core/ScreenSelect.h"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <filesystem>
+
+namespace sf {
+
+namespace {
+
+constexpr int kMaxSide = 2048; // a stencil spans the view: more detail than an alpha's 512, at most 16 MB
+
+// sRGB byte -> linear, once.
+const std::array<float, 256>& linearTable() {
+ static const std::array<float, 256> table = [] {
+ std::array<float, 256> t{};
+ for (int i = 0; i < 256; ++i) {
+ const float x = float(i) / 255.0f;
+ t[size_t(i)] = x <= 0.04045f ? x / 12.92f : std::pow((x + 0.055f) / 1.055f, 2.4f);
+ }
+ return t;
+ }();
+ return table;
+}
+
+// The four texels around (u, v) and their bilinear weights (texel centres at (i + 0.5) / size); tiled wraps, else
+// clamps to the edge.
+struct Taps {
+ size_t at[4];
+ float w[4];
+};
+Taps taps(const Image& img, glm::vec2 uv, bool tile) {
+ const float x = uv.x * float(img.width) - 0.5f, y = uv.y * float(img.height) - 0.5f;
+ const float fx0 = std::floor(x), fy0 = std::floor(y);
+ const float fx = x - fx0, fy = y - fy0;
+ auto wrap = [tile](int i, int n) { return tile ? ((i % n) + n) % n : std::clamp(i, 0, n - 1); };
+ const int x0 = wrap(int(fx0), img.width), x1 = wrap(int(fx0) + 1, img.width);
+ const int y0 = wrap(int(fy0), img.height), y1 = wrap(int(fy0) + 1, img.height);
+ auto idx = [&](int xi, int yi) { return (size_t(yi) * size_t(img.width) + size_t(xi)) * 4; };
+ return {{idx(x0, y0), idx(x1, y0), idx(x0, y1), idx(x1, y1)},
+ {(1 - fx) * (1 - fy), fx * (1 - fy), (1 - fx) * fy, fx * fy}};
+}
+
+// A grey image of an alpha's values (the built-ins are made in code, with no file behind them).
+Image alphaImage(const BrushAlpha& a) {
+ Image img;
+ img.width = a.width;
+ img.height = a.height;
+ img.rgba.resize(size_t(a.width) * size_t(a.height) * 4);
+ for (size_t i = 0; i < a.values.size(); ++i) {
+ const uint8_t g = uint8_t(std::lround(std::clamp(a.values[i], 0.0f, 1.0f) * 255.0f));
+ img.rgba[i * 4] = img.rgba[i * 4 + 1] = img.rgba[i * 4 + 2] = g;
+ img.rgba[i * 4 + 3] = 255;
+ }
+ return img;
+}
+
+std::string fileStem(const std::string& path) {
+ const auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();
+ return std::string(stem.begin(), stem.end());
+}
+
+} // namespace
+
+bool Stencil::imageCoord(glm::vec2 canvas, float canvasAspect, glm::vec2& uv) const {
+ if (!image || image->empty() || size <= 0.0f) return false;
+ // In canvas heights (so a turn keeps its shape on a wide canvas), y down; turned back by the angle (seen
+ // counter-clockwise: the screen's y points down).
+ const glm::vec2 d((canvas.x - center.x) * canvasAspect, canvas.y - center.y);
+ const float c = std::cos(angle), s = std::sin(angle);
+ const glm::vec2 local(c * d.x - s * d.y, s * d.x + c * d.y);
+ uv = glm::vec2(local.x / (size * aspect()) + 0.5f, local.y / size + 0.5f);
+ return tile || (uv.x >= 0.0f && uv.x <= 1.0f && uv.y >= 0.0f && uv.y <= 1.0f);
+}
+
+glm::vec2 Stencil::canvasPoint(glm::vec2 uv, float canvasAspect) const {
+ const glm::vec2 local((uv.x - 0.5f) * size * aspect(), (uv.y - 0.5f) * size);
+ const float c = std::cos(angle), s = std::sin(angle);
+ const glm::vec2 d(c * local.x + s * local.y, -s * local.x + c * local.y);
+ return glm::vec2(center.x + d.x / std::max(canvasAspect, 1e-6f), center.y + d.y);
+}
+
+float Stencil::value(glm::vec2 uv) const {
+ if (!image || image->empty()) return 0.0f;
+ const Taps t = taps(*image, uv, tile);
+ const uint8_t* px = image->rgba.data();
+ float out = 0.0f;
+ for (int k = 0; k < 4; ++k) {
+ const uint8_t* p = px + t.at[k];
+ float l = (0.2126f * p[0] + 0.7152f * p[1] + 0.0722f * p[2]) / 255.0f; // (BrushAlpha::fromImage's)
+ if (invert) l = 1.0f - l;
+ out += t.w[k] * l * (float(p[3]) / 255.0f);
+ }
+ return std::clamp(out, 0.0f, 1.0f);
+}
+
+glm::vec4 Stencil::color(glm::vec2 uv) const {
+ if (!image || image->empty()) return glm::vec4(0.0f);
+ const Taps t = taps(*image, uv, tile);
+ const uint8_t* px = image->rgba.data();
+ const auto& lin = linearTable();
+ glm::vec4 out(0.0f);
+ for (int k = 0; k < 4; ++k) {
+ const uint8_t* p = px + t.at[k];
+ auto ch = [&](int i) { return lin[invert ? 255 - p[i] : p[i]]; };
+ out += t.w[k] * glm::vec4(ch(0), ch(1), ch(2), float(p[3]) / 255.0f);
+ }
+ return out;
+}
+
+void Stencil::set(Image img, std::string n, std::string p) {
+ if (img.empty()) {
+ image.reset();
+ name.clear();
+ path.clear();
+ return;
+ }
+ image = std::make_shared<const Image>(img.downscaled(kMaxSide));
+ name = std::move(n);
+ path = std::move(p);
+}
+
+void Stencil::resetPlacement() {
+ center = {0.5f, 0.5f};
+ size = 0.8f;
+ angle = 0.0f;
+}
+
+bool StencilView::canvasAt(const glm::vec3& world, glm::vec2& canvas) const {
+ glm::vec2 ndc;
+ if (!projectToNdc(viewProj, copy.identity() ? world : copy.inversePoint(world), ndc)) return false;
+ canvas = glm::vec2((ndc.x + 1.0f) * 0.5f, (1.0f - ndc.y) * 0.5f);
+ return true;
+}
+
+float StencilView::weight(const glm::vec3& world) const {
+ glm::vec2 c, uv;
+ if (!canvasAt(world, c) || !stencil->imageCoord(c, canvasAspect, uv)) return 0.0f;
+ return stencil->value(uv);
+}
+
+glm::vec4 StencilView::paint(const glm::vec3& world, const glm::vec3& paintColor) const {
+ glm::vec2 c, uv;
+ if (!canvasAt(world, c) || !stencil->imageCoord(c, canvasAspect, uv)) return glm::vec4(paintColor, 0.0f);
+ if (!stencil->colors) return glm::vec4(paintColor, stencil->value(uv));
+ const glm::vec4 col = stencil->color(uv);
+ return col.w > 1e-6f ? glm::vec4(glm::vec3(col) / col.w, col.w) : glm::vec4(paintColor, 0.0f); // (un-premultiplied)
+}
+
+void registerStencilCommands(CommandRegistry& registry) {
+ using T = ParamSpec::Type;
+ registry.add({"stencil_load",
+ "Lay an image over the view as the Stencil: the brushes work through it (sculpt brushes take its "
+ "brightness, Vertex Paint its colours) wherever it covers the model.",
+ {{"path", T::String, "Image file (png, jpg, ...).", false},
+ {"alpha", T::Bool, "Use the brush's current alpha instead of a file.", false},
+ {"invert", T::Bool, "Use the image's negative.", false},
+ {"reset", T::Bool, "Centre it again, upright, 80% of the view's height (default: keep where it is).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Stencil& st = doc.stencil;
+ const std::string path = argString(a, "path");
+ if (!path.empty()) {
+ Image img;
+ std::string err;
+ if (!Image::load(path, img, err)) return {false, err};
+ st.set(std::move(img), fileStem(path), path);
+ } else if (argBool(a, "alpha", false)) {
+ const BrushAlpha& al = doc.brushAlpha;
+ if (al.empty()) return {false, "The brush has no alpha (Round): pick one, or load an image"};
+ Image img;
+ std::string err;
+ // An image alpha at its own resolution (the alpha keeps 512 px); a built-in as made.
+ if (al.path.empty() || !Image::load(al.path, img, err)) img = alphaImage(al);
+ else if (al.inverted) for (size_t i = 0; i < img.rgba.size(); i += 4)
+ for (int k = 0; k < 3; ++k) img.rgba[i + size_t(k)] = uint8_t(255 - img.rgba[i + size_t(k)]);
+ st.set(std::move(img), al.name, al.path);
+ } else {
+ return {false, "stencil_load needs path=<image> or alpha=true"};
+ }
+ if (a.contains("invert")) st.invert = argBool(a, "invert", false);
+ if (argBool(a, "reset", false)) st.resetPlacement();
+ st.visible = true;
+ return {true, "Stencil '" + st.name + "' (" + std::to_string(st.image->width) + "x" +
+ std::to_string(st.image->height) + ")"};
+ }});
+ registry.add({"stencil_set",
+ "Place and set up the Stencil: where it sits on the view, its size and turn, how it shows and how "
+ "the brushes take it.",
+ {{"x", T::Number, "Centre across the view, 0 (left) to 1 (right).", false},
+ {"y", T::Number, "Centre down the view, 0 (top) to 1 (bottom).", false},
+ {"size", T::Number, "Height as a fraction of the view's height (0.02-20).", false},
+ {"angle", T::Number, "Turn in degrees, counter-clockwise.", false},
+ {"opacity", T::Number, "How strongly the overlay shows, 0-1 (the brushes take it whole).", false},
+ {"invert", T::Bool, "Use the image's negative.", false},
+ {"tile", T::Bool, "Repeat the image across the whole view.", false},
+ {"visible", T::Bool, "Show it (hidden: the brushes ignore it).", false},
+ {"colors", T::Bool, "Vertex Paint lays the image's colours (off: its brightness masks the paint colour).", false},
+ {"reset", T::Bool, "Centre it, upright, 80% of the view's height (before the values above).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Stencil& st = doc.stencil;
+ if (argBool(a, "reset", false)) st.resetPlacement();
+ auto num = [&](const char* k, float& v, float lo, float hi) {
+ if (!a.contains(k)) return true;
+ const double d = argNumber(a, k, v);
+ if (!std::isfinite(d)) return false;
+ v = std::clamp(float(d), lo, hi);
+ return true;
+ };
+ float angleDeg = glm::degrees(st.angle);
+ if (!num("x", st.center.x, -10.0f, 11.0f) || !num("y", st.center.y, -10.0f, 11.0f) ||
+ !num("size", st.size, 0.02f, 20.0f) || !num("angle", angleDeg, -36000.0f, 36000.0f) ||
+ !num("opacity", st.opacity, 0.0f, 1.0f))
+ return {false, "stencil_set: numbers only"};
+ angleDeg = std::remainder(angleDeg, 360.0f);
+ st.angle = glm::radians(angleDeg);
+ if (a.contains("invert")) st.invert = argBool(a, "invert", st.invert);
+ if (a.contains("tile")) st.tile = argBool(a, "tile", st.tile);
+ if (a.contains("visible")) st.visible = argBool(a, "visible", st.visible);
+ if (a.contains("colors")) st.colors = argBool(a, "colors", st.colors);
+ return {true, st.image ? "Stencil '" + st.name + "'" : std::string("Stencil set (no image loaded)")};
+ }});
+ registry.add({"stencil_clear", "Take the Stencil off the view.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ doc.stencil.set({}, {}, {});
+ return {true, "Stencil off"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/Stencil.h b/src/core/Stencil.h
new file mode 100644
index 00000000..6324dc2f
--- /dev/null
+++ b/src/core/Stencil.h
@@ -0,0 +1,78 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Stencil (#155, docs/design/stencil.md): a reference image laid over the view that the brushes work through. It sits
+// in screen space (the model turns under it); each dab weighs every vertex by the stencil at the point where the
+// vertex shows on screen, times the brush's own falloff. Sculpt brushes take its brightness as their alpha, Vertex
+// Paint its colours (or its brightness masking the paint colour). Outside the image (unless tiled) brushes do
+// nothing. The image comes from the same loader as alphas (core/Image.h); the placement is kept relative to the
+// canvas, so it stays put when the window changes size.
+#pragma once
+
+#include "core/Image.h"
+#include "core/Symmetry.h"
+
+#include <glm/glm.hpp>
+
+#include <memory>
+#include <string>
+
+namespace sf {
+
+class CommandRegistry;
+
+struct Stencil {
+ std::shared_ptr<const Image> image; // null = no stencil (straight from the file; inverted on sampling)
+ std::string name, path; // shown in the Stencil section; path empty for one made from an alpha
+ // Placement. `center` in canvas fractions (0..1 across, 0..1 down); `size` the image's height as a fraction of the
+ // canvas height (its width follows the image's aspect); `angle` radians, counter-clockwise as seen.
+ glm::vec2 center{0.5f, 0.5f};
+ float size = 0.8f;
+ float angle = 0.0f;
+ float opacity = 0.5f; // how strongly the overlay shows (the brushes always take the whole image)
+ bool invert = false; // the image's negative: black works, white leaves the surface alone
+ bool tile = false; // the image repeats across the whole view
+ bool visible = true; // hidden: drawn nowhere and the brushes ignore it
+ bool colors = true; // Vertex Paint lays the image's colours; off, its brightness masks the paint colour
+
+ bool active() const { return visible && image && !image->empty(); }
+ float aspect() const { return image && !image->empty() ? image->aspect() : 1.0f; }
+
+ // Image coordinates (0..1, v down; tiled: any value, repeating) of a canvas point (fractions as `center`) on a
+ // canvas `canvasAspect` (width / height) wide. False outside the image when it isn't tiled.
+ bool imageCoord(glm::vec2 canvas, float canvasAspect, glm::vec2& uv) const;
+ // The reverse: where image coordinates (u, v) land on the canvas (corners, handles).
+ glm::vec2 canvasPoint(glm::vec2 uv, float canvasAspect) const;
+ // At image coordinates: the brightness the sculpt brushes take (luminance x the pixel's alpha, inverted), and
+ // the colour (linear) with how much of it Vertex Paint lays (.a: the pixel's alpha).
+ float value(glm::vec2 uv) const;
+ glm::vec4 color(glm::vec2 uv) const;
+
+ // Makes a stencil from an image (`image` empty: clears it); placement kept.
+ void set(Image image, std::string name, std::string path);
+ // Centred, the image's height 80% of the canvas's, upright.
+ void resetPlacement();
+};
+
+// A stencil as one dab sees it: the view it was made in, and the symmetry copy the dab is for (the mirror's
+// vertices take the stencil at their mirror image's place on screen, so the pattern mirrors across).
+struct StencilView {
+ const Stencil* stencil = nullptr;
+ glm::mat4 viewProj{1.0f};
+ float canvasAspect = 1.0f;
+ SymCopy copy; // identity: the stroke itself
+
+ bool active() const { return stencil && stencil->active(); }
+ // The canvas point (fractions) a world point shows at; false behind the camera.
+ bool canvasAt(const glm::vec3& world, glm::vec2& canvas) const;
+ // 0..1: how much a sculpt dab moves the vertex at `world` (0 off the image or behind the camera).
+ float weight(const glm::vec3& world) const;
+ // The colour (linear) and how much of it a paint dab lays at `world`: the image's own (colors) or the paint
+ // colour masked by its brightness.
+ glm::vec4 paint(const glm::vec3& world, const glm::vec3& paintColor) const;
+};
+
+// stencil_load, stencil_set, stencil_clear.
+void registerStencilCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/VertexPaint.cpp b/src/core/VertexPaint.cpp
index 774d3344..d7c3749f 100644
--- a/src/core/VertexPaint.cpp
+++ b/src/core/VertexPaint.cpp
@@ -129,12 +129,15 @@ size_t paintDab(Sculptor& sculptor, Mesh& mesh, const BVH& bvh, const DabParams&
// An alpha shapes the dab as it does a sculpt dab and a texture dab (#152): on the view plane, turned by alphaUp,
// reaching into its square's corners.
const bool useAlpha = p.alpha && !p.alpha->empty();
+ const bool useStencil = p.stencil.active();
for (const SymCopy& m : Sculptor::copies(sym)) {
const glm::vec3 center = m.point(p.center), viewDir = m.dir(p.viewDir);
glm::vec3 aUp = m.dir(p.alphaUp);
aUp -= viewDir * glm::dot(aUp, viewDir);
aUp = glm::length(aUp) > 1e-6f ? glm::normalize(aUp) : glm::vec3(0, 1, 0);
const glm::vec3 aRight = glm::cross(aUp, -viewDir);
+ StencilView stencil = p.stencil;
+ stencil.copy = m;
static thread_local ConnectedScratch connected;
brushRegion(mesh, bvh, center, viewDir, p.radius * (useAlpha ? kAlphaReach : 1.0f), p.connectedOnly, p.viewFalloff,
verts, connected);
@@ -143,10 +146,17 @@ size_t paintDab(Sculptor& sculptor, Mesh& mesh, const BVH& bvh, const DabParams&
const glm::vec3 o = mesh.positions[v] - center;
const float f = useAlpha ? p.alpha->stamp(glm::dot(o, aRight) / p.radius, glm::dot(o, aUp) / p.radius, p.focal)
: brushFalloff(brushDistance(mesh.positions[v], center, viewDir, p.viewFalloff), p.radius, p.focal);
- const float w = f * s * vertexInfluence(mesh, v);
+ float w = f * s * vertexInfluence(mesh, v);
if (w <= 0.0f) continue;
+ glm::vec3 c = color;
+ if (useStencil) { // the Stencil's colour (or its brightness masking the paint colour), #155
+ const glm::vec4 st = stencil.paint(mesh.positions[v], color);
+ w *= st.w;
+ if (w <= 0.0f) continue;
+ c = glm::vec3(st);
+ }
sculptor.recordColor(mesh, v);
- paintVertex(mesh, v, color, w, p.invert); // Alt paints Base back to white, erases a layer
+ paintVertex(mesh, v, c, w, p.invert); // Alt paints Base back to white, erases a layer
++changed;
}
sculptor.timings.vertices += verts.size();
diff --git a/tests/test_stencil.cpp b/tests/test_stencil.cpp
new file mode 100644
index 00000000..438ebd8a
--- /dev/null
+++ b/tests/test_stencil.cpp
@@ -0,0 +1,197 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// #155: the Stencil (core/Stencil.h): an image over the view the brushes work through. Its placement maps the right
+// texel when turned and scaled, nothing happens off it (unless tiled), and the sculpt brushes, Vertex Paint and the
+// symmetry copies take it at the place each vertex shows on screen.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "core/Stencil.h"
+#include "core/VertexPaint.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <cmath>
+
+using namespace sf;
+
+namespace {
+
+bool near(float a, float b, float eps = 1e-4f) { return std::abs(a - b) <= eps; }
+
+// w x h pixels, all black and opaque, with `white` (x, y) pixels white.
+Image blackImage(int w, int h, std::initializer_list<glm::ivec2> white = {}) {
+ Image img;
+ img.width = w;
+ img.height = h;
+ img.rgba.assign(size_t(w) * size_t(h) * 4, 0);
+ for (size_t i = 3; i < img.rgba.size(); i += 4) img.rgba[i] = 255;
+ for (glm::ivec2 p : white)
+ for (int k = 0; k < 3; ++k) img.rgba[(size_t(p.y) * size_t(w) + size_t(p.x)) * 4 + size_t(k)] = 255;
+ return img;
+}
+
+// Looking straight down at makePlane (the XZ plane), orthographic: x runs across the canvas, z down it.
+glm::mat4 topView() {
+ return glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, 0.1f, 10.0f) * glm::lookAt(glm::vec3(0, 5, 0), glm::vec3(0.0f), glm::vec3(0, 0, -1));
+}
+
+DabParams topDab(const glm::vec3& center, float radius) {
+ DabParams p;
+ p.center = center;
+ p.viewDir = glm::vec3(0, -1, 0);
+ p.radius = radius;
+ p.strength = 1.0f;
+ return p;
+}
+
+float maxRise(const Mesh& m, bool left) {
+ float best = 0.0f;
+ for (const glm::vec3& v : m.positions)
+ if ((v.x < -0.02f) == left && (v.x > 0.02f) == !left) best = std::max(best, std::abs(v.y));
+ return best;
+}
+
+} // namespace
+
+TEST(stencil_turned_scaled_maps_the_right_texel) {
+ Stencil st;
+ st.set(blackImage(2, 2, {{0, 0}}), "corner", ""); // the top-left pixel white
+ st.center = {0.5f, 0.5f};
+ st.size = 0.5f;
+ st.angle = glm::radians(90.0f); // counter-clockwise: the image's top goes to the left
+ const float aspect = 2.0f; // a canvas twice as wide as it is tall
+ // Round trip at a few points, turned and not.
+ for (float a : {0.0f, 30.0f, 90.0f, -135.0f}) {
+ st.angle = glm::radians(a);
+ for (glm::vec2 uv : {glm::vec2(0.1f, 0.2f), glm::vec2(0.5f), glm::vec2(0.9f, 0.7f)}) {
+ glm::vec2 back;
+ CHECK(st.imageCoord(st.canvasPoint(uv, aspect), aspect, back));
+ CHECK(near(back.x, uv.x) && near(back.y, uv.y));
+ }
+ }
+ st.angle = glm::radians(90.0f);
+ const glm::vec2 top = st.canvasPoint({0.5f, 0.0f}, aspect);
+ CHECK(near(top.x, 0.5f - 0.25f / aspect) && near(top.y, 0.5f)); // the top edge's middle: left of the centre
+ // The white top-left pixel lands below-left of the centre (top -> left, left -> bottom), the rest is black.
+ const glm::vec2 white = st.canvasPoint({0.25f, 0.25f}, aspect);
+ CHECK(white.x < 0.5f && white.y > 0.5f);
+ glm::vec2 uv;
+ CHECK(st.imageCoord(white, aspect, uv) && near(st.value(uv), 1.0f));
+ CHECK(st.imageCoord(glm::vec2(0.5f + (0.5f - white.x), white.y), aspect, uv) && near(st.value(uv), 0.0f));
+ // Twice the size: the same canvas point is nearer the centre of the image.
+ st.size = 1.0f;
+ CHECK(st.imageCoord(white, aspect, uv) && near(uv.x, 0.375f) && near(uv.y, 0.375f));
+ // Invert: the negative.
+ st.size = 0.5f;
+ st.invert = true;
+ CHECK(st.imageCoord(white, aspect, uv) && near(st.value(uv), 0.0f));
+}
+
+TEST(stencil_outside_is_no_effect_unless_tiled) {
+ Stencil st;
+ st.set(blackImage(4, 4, {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}}), "top", ""); // top half white
+ st.size = 0.2f;
+ glm::vec2 uv;
+ CHECK(!st.imageCoord({0.9f, 0.9f}, 1.0f, uv));
+ StencilView view{&st, topView(), 1.0f};
+ CHECK(view.weight(glm::vec3(0.0f, 0.0f, -0.05f)) > 0.99f); // on the image's top half
+ CHECK(view.weight(glm::vec3(0.0f, 0.0f, 0.05f)) < 0.01f); // its bottom half
+ CHECK(view.weight(glm::vec3(0.8f, 0.0f, 0.8f)) == 0.0f); // off the image
+ st.tile = true; // repeats: one image height (0.2 of the canvas = 0.4 world) further down is the top half again
+ CHECK(st.imageCoord({0.9f, 0.9f}, 1.0f, uv));
+ CHECK(view.weight(glm::vec3(0.0f, 0.0f, -0.05f + 0.4f)) > 0.99f);
+ st.visible = false;
+ CHECK(!view.active());
+ // Behind a perspective camera: nothing (in front, the same line of sight takes it).
+ st.visible = true;
+ st.tile = false;
+ const StencilView persp{&st, glm::perspective(glm::radians(50.0f), 1.0f, 0.1f, 100.0f) *
+ glm::lookAt(glm::vec3(0, 5, 0), glm::vec3(0.0f), glm::vec3(0, 0, -1)), 1.0f};
+ CHECK(persp.weight(glm::vec3(0.0f, 0.0f, -0.2f)) > 0.99f);
+ CHECK(persp.weight(glm::vec3(0.0f, 20.0f, -0.2f)) == 0.0f);
+}
+
+TEST(stencil_sculpts_only_under_the_image) {
+ Document doc = makeDoc(makePlane(80));
+ Mesh& m = doc.mesh;
+ // A white image whose right edge sits on the canvas centre: the brush's left half is under it.
+ Stencil st;
+ st.set(blackImage(1, 1, {{0, 0}}), "white", "");
+ st.size = 0.6f;
+ st.center = {0.5f - 0.3f, 0.5f};
+ DabParams p = topDab(glm::vec3(0.0f), 0.4f);
+ p.stencil = {&st, topView(), 1.0f};
+ CHECK(doc.sculptor.beginStroke(m, "Standard"));
+ for (int i = 0; i < 4; ++i) doc.sculptor.dab(m, doc.bvh, BrushType::Standard, p, Symmetry{false, false, false});
+ doc.sculptor.endStroke();
+ CHECK(maxRise(m, true) > 0.01f);
+ CHECK(maxRise(m, false) == 0.0f);
+ // Without the stencil the same dab raises both sides.
+ Document plain = makeDoc(makePlane(80));
+ DabParams q = topDab(glm::vec3(0.0f), 0.4f);
+ CHECK(plain.sculptor.beginStroke(plain.mesh, "Standard"));
+ plain.sculptor.dab(plain.mesh, plain.bvh, BrushType::Standard, q, Symmetry{false, false, false});
+ plain.sculptor.endStroke();
+ CHECK(maxRise(plain.mesh, true) > 0.0f && maxRise(plain.mesh, false) > 0.0f);
+}
+
+TEST(stencil_symmetry_mirrors_the_pattern) {
+ // The image covers only the right of the canvas; a dab there with X symmetry also raises its mirror on the left,
+ // which takes the stencil at its mirror image's place (the right), so the pattern mirrors across.
+ Document doc = makeDoc(makePlane(80));
+ Mesh& m = doc.mesh;
+ Stencil st;
+ st.set(blackImage(1, 1, {{0, 0}}), "white", "");
+ st.size = 0.4f;
+ st.center = {0.75f, 0.5f};
+ DabParams p = topDab(glm::vec3(0.5f, 0.0f, 0.0f), 0.25f);
+ p.stencil = {&st, topView(), 1.0f};
+ CHECK(doc.sculptor.beginStroke(m, "Standard"));
+ doc.sculptor.dab(m, doc.bvh, BrushType::Standard, p, Symmetry{true, false, false});
+ doc.sculptor.endStroke();
+ CHECK(maxRise(m, false) > 0.0f);
+ CHECK(near(maxRise(m, true), maxRise(m, false), 1e-5f));
+}
+
+TEST(stencil_vertex_paint_lays_its_colours) {
+ Document doc = makeDoc(makePlane(40));
+ Mesh& m = doc.mesh;
+ Image red = blackImage(1, 1);
+ red.rgba[0] = 255;
+ Stencil st;
+ st.set(red, "red", "");
+ st.size = 2.0f; // covers the whole view
+ DabParams p = topDab(glm::vec3(0.0f), 0.5f);
+ p.stencil = {&st, topView(), 1.0f};
+ CHECK(doc.sculptor.beginStroke(m, "Paint"));
+ CHECK(paintDab(doc.sculptor, m, doc.bvh, p, glm::vec3(0, 0, 1), Symmetry{false, false, false}) > 0);
+ const uint32_t centre = uint32_t(m.vertexCount() / 2);
+ CHECK(m.colors[centre].x > 0.99f && m.colors[centre].z < 0.01f); // red, not the blue paint colour
+ doc.sculptor.endStroke();
+ // Colours off: its brightness masks the paint colour; a black stencil (red's luminance is low) paints little.
+ st.set(blackImage(1, 1), "black", "");
+ st.colors = false;
+ Document doc2 = makeDoc(makePlane(40));
+ CHECK(doc2.sculptor.beginStroke(doc2.mesh, "Paint"));
+ CHECK(paintDab(doc2.sculptor, doc2.mesh, doc2.bvh, p, glm::vec3(0, 0, 1), Symmetry{false, false, false}) == 0);
+ doc2.sculptor.endStroke();
+}
+
+TEST(stencil_commands) {
+ Document doc = makeDoc(makePlane(4));
+ CommandRegistry reg;
+ CHECK(!reg.execute(doc, "stencil_load", {}).ok);
+ CHECK(!reg.execute(doc, "stencil_load", {{"alpha", true}}).ok); // Round: no alpha
+ CHECK(reg.execute(doc, "brush_set_alpha", {{"name", "cracks"}}).ok);
+ CHECK(reg.execute(doc, "stencil_load", {{"alpha", true}, {"reset", true}}).ok);
+ CHECK(doc.stencil.active() && doc.stencil.name == "Cracks");
+ CHECK(reg.execute(doc, "stencil_set", {{"x", 0.25}, {"angle", 450.0}, {"size", 100.0}, {"opacity", 2.0}, {"tile", true}}).ok);
+ CHECK(near(doc.stencil.center.x, 0.25f) && near(glm::degrees(doc.stencil.angle), 90.0f, 1e-3f));
+ CHECK(doc.stencil.size == 20.0f && doc.stencil.opacity == 1.0f && doc.stencil.tile);
+ CHECK(reg.execute(doc, "stencil_set", {{"visible", false}}).ok && !doc.stencil.active());
+ CHECK(reg.execute(doc, "stencil_clear", {}).ok && !doc.stencil.image);
+ CHECK(!reg.execute(doc, "stencil_load", {{"path", "/nonexistent/stencil.png"}}).ok);
+}
diff --git a/tests/ui/stencil.sfui b/tests/ui/stencil.sfui
new file mode 100644
index 00000000..3ddbc10e
--- /dev/null
+++ b/tests/ui/stencil.sfui
@@ -0,0 +1,54 @@
+# #155: the Stencil (Sculpt > Alpha > Stencil). Load it, move it with Adjust's handles, and a stroke across its edge
+# changes the mesh only where the stencil covers it; with it hidden the same stroke reaches past it.
+run ui_look look=classic layout=classic # written for the Classic look and the classic palette bar and shelves
+run new_sphere subdivisions=5
+key f
+click "Standard##brush.standard"
+# A stencil from a built-in pattern (Use alpha), then the brush goes back to round.
+run brush_set_alpha name=cobblestone
+run stencil_load alpha=true reset=true
+run brush_set_alpha name=round
+wait 0.1
+expect_value stencil_active == 1
+expect_value stencil_x == 500
+click "Alpha##palette.alpha"
+expect "Adjust##stencil.adjust"
+shot panel
+hold ctrl
+hover "Adjust##stencil.adjust"
+expect_help "corner to scale"
+hold none
+click "Adjust##stencil.adjust"
+expect_value stencil_adjust == 1
+click "Alpha##palette.alpha"
+
+# Smaller, then dragged left from inside: it moves (the view doesn't turn), Enter goes back to sculpting.
+run stencil_set size=0.35 angle=20
+remember camera_yaw yaw
+drag_path 0.5 0.5 0.3 0.5
+expect_value stencil_x < 480
+expect_value camera_yaw == $yaw
+key right
+key comma
+expect_value stencil_angle == 35
+shot adjust
+key enter
+expect_value stencil_adjust == 0
+shot overlay
+
+# One stroke across its edge, symmetry off: only vertices under the stencil move.
+click "X##transform.symmetry_x"
+expect_value symmetry_x == 0
+snapshot
+stroke 0.15 0.5 0.85 0.5
+expect_value moved > 0
+expect_value moved_off_stencil == 0
+expect_value can_undo == 1
+shot result
+
+# Hidden: the same stroke reaches past it.
+run stencil_set visible=false
+snapshot
+stroke 0.15 0.55 0.85 0.55
+expect_value moved_off_stencil > 0
+shot hidden