Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Stencil: average a disc as wide as the vertices' spacing where they are many pixels apart (mips down to 512 px only), so fine photos don't speckle on light meshes
islandmed80b43bff54d0
diff --git a/changes/fix-stencil-filter.md b/changes/fix-stencil-filter.mdnew file mode 100644index 00000000..24717c26--- /dev/null+++ b/changes/fix-stencil-filter.md@@ -0,0 +1,10 @@+---+fixed: **Stencil** photos on lighter meshes sculpt and paint evenly instead of as noise: where a dab's vertices+ are many image pixels apart, each reads the average of a disc as wide as their spacing (from the image or a+ half / quarter size copy, never below 512 px), not the one pixel it lands on, so a fine photo doesn't speckle or+ shimmer as you move the stencil.+---+Follow-up to fix-stencil-edges (merge-0106-4b review). tests/test_stencil.cpp stencil_fine_image_on_a_light_mesh_sculpts_evenly:+a 2048 px one-pixel checker on 40- and 160-cell planes; plateau sd/mean within 0.01 of the same stroke without a stencil+(0.041 vs 0.038, 0.026 vs 0.025; point by point it was 0.065 and 0.17). The groove test (< 1%) still passes: the+coarsest level is 512 px, so no square-pixel stair-steps.diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 6fb0c85b..a25257e5 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -1008,6 +1008,8 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&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;+ StencilView stencil = p.stencil; // (averaged over the vertices' spacing where they are many pixels apart)+ if (useStencil) stencil.setSpacing(p.center, p.viewDir, p.radius * reach, verts_.size());auto& pos = mesh.positions;const auto& nrm = mesh.normals;@@ -1098,7 +1100,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&const glm::vec3 o = x - p.center;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);+ if (useStencil && f > 0.0f) f *= stencil.weight(x);glm::vec3 d(0.0f);switch (type) {@@ -1409,6 +1411,8 @@ void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, constbrushRegion(mesh, bvh, p.center, p.viewDir, p.radius * (useAlpha ? kAlphaReach : 1.0f), p.connectedOnly,p.viewFalloff, verts_, connected_);if (verts_.empty()) return;+ StencilView stencil = p.stencil;+ if (stencil.active()) stencil.setSpacing(p.center, p.viewDir, p.radius * (useAlpha ? kAlphaReach : 1.0f), verts_.size());const auto& pos = mesh.positions;const auto& nrm = mesh.normals;glm::vec3 aUp = projectOnPlane(p.alphaUp, p.viewDir);@@ -1461,7 +1465,7 @@ void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, constif (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]);+ if (stencil.active() && w > 0.0f) w *= stencil.weight(pos[v]);weights_[i] = w;});glm::vec3 areaNormal = sums.normal, areaCenter = sums.center;diff --git a/src/core/Stencil.cpp b/src/core/Stencil.cppindex 1c5da817..f766bf28 100644--- a/src/core/Stencil.cpp+++ b/src/core/Stencil.cpp@@ -17,6 +17,7 @@ namespace sf {namespace {constexpr int kMaxSide = 2048; // a stencil spans the view: more detail than an alpha's 512, at most 16 MB+constexpr int kMinLevel = 512; // the smallest mip level (Stencil::mips)constexpr int kBuiltinStencilSize = 1024; // a built-in pattern made into a Stencil (BrushAlpha::builtinAt)// sRGB byte -> linear, once.@@ -89,10 +90,37 @@ glm::vec2 Stencil::canvasPoint(glm::vec2 uv, float canvasAspect) const {return glm::vec2(center.x + d.x / std::max(canvasAspect, 1e-6f), center.y + d.y);}-float Stencil::value(glm::vec2 uv) const {+const Image& Stencil::level(int l) const {+ if (l <= 0 || !mips || mips->empty()) return *image;+ return (*mips)[size_t(std::min(l, int(mips->size()))) - 1];+}++// A disc of 17 taps `spacing` image pixels across (a centre, 8 at half the radius, 8 at the radius turned half a step),+// weighted 4 / 2 / 1, from the level where the taps are still 4 of its pixels apart or more.+template <class T, class Read>+T Stencil::disc(glm::vec2 uv, float spacing, Read&& read) const {+ const int l = std::clamp(int(std::floor(std::log2(spacing / 4.0f))), 0, mips ? int(mips->size()) : 0);+ const Image& img = level(l);+ const glm::vec2 px(0.5f * spacing / float(image->width), 0.5f * spacing / float(image->height)); // the radius, in uv+ T sum = read(img, uv) * 4.0f;+ for (int i = 0; i < 8; ++i) {+ const float a = float(i) * 0.785398163f, b = a + 0.392699082f;+ sum += read(img, uv + 0.5f * px * glm::vec2(std::cos(a), std::sin(a))) * 2.0f;+ sum += read(img, uv + px * glm::vec2(std::cos(b), std::sin(b)));+ }+ return sum * (1.0f / 28.0f);+}++float Stencil::value(glm::vec2 uv, float spacing) const {if (!image || image->empty()) return 0.0f;- const Taps t = taps(*image, uv, tile);- const uint8_t* px = image->rgba.data();+ if (spacing > 1.5f)+ return disc<float>(uv, spacing, [this](const Image& img, glm::vec2 at) { return valueAt(img, at); });+ return valueAt(*image, uv);+}++float Stencil::valueAt(const Image& img, glm::vec2 uv) const {+ const Taps t = taps(img, uv, tile);+ const uint8_t* px = img.rgba.data();float out = 0.0f;for (int k = 0; k < 4; ++k) {const uint8_t* p = px + t.at[k];@@ -103,10 +131,16 @@ float Stencil::value(glm::vec2 uv) const {return std::clamp(out, 0.0f, 1.0f);}-glm::vec4 Stencil::color(glm::vec2 uv) const {+glm::vec4 Stencil::color(glm::vec2 uv, float spacing) const {if (!image || image->empty()) return glm::vec4(0.0f);- const Taps t = taps(*image, uv, tile);- const uint8_t* px = image->rgba.data();+ if (spacing > 1.5f)+ return disc<glm::vec4>(uv, spacing, [this](const Image& img, glm::vec2 at) { return colorAt(img, at); });+ return colorAt(*image, uv);+}++glm::vec4 Stencil::colorAt(const Image& img, glm::vec2 uv) const {+ const Taps t = taps(img, uv, tile);+ const uint8_t* px = img.rgba.data();const auto& lin = linearTable();glm::vec4 out(0.0f);for (int k = 0; k < 4; ++k) {@@ -120,11 +154,16 @@ glm::vec4 Stencil::color(glm::vec2 uv) const {void Stencil::set(Image img, std::string n, std::string p) {if (img.empty()) {image.reset();+ mips.reset();name.clear();path.clear();return;}image = std::make_shared<const Image>(img.downscaled(kMaxSide));+ auto levels = std::make_shared<std::vector<Image>>();+ for (const Image* at = image.get(); std::max(at->width, at->height) / 2 >= kMinLevel; at = &levels->back())+ levels->push_back(at->downscaled(std::max(at->width, at->height) / 2));+ mips = std::move(levels);name = std::move(n);path = std::move(p);}@@ -142,17 +181,29 @@ bool StencilView::canvasAt(const glm::vec3& world, glm::vec2& canvas) const {return true;}+void StencilView::setSpacing(const glm::vec3& center, const glm::vec3& viewDir, float radius, size_t vertices) {+ spacing = 0.0f;+ if (!active() || vertices == 0 || radius <= 0.0f || stencil->size <= 0.0f) return;+ // A direction across the view: the radius as it shows, in canvas heights (canvasAt maps a symmetry copy back).+ const glm::vec3 d = glm::length(viewDir) > 1e-12f ? glm::normalize(viewDir) : glm::vec3(0, 0, -1);+ const glm::vec3 across = glm::normalize(glm::cross(d, std::abs(d.y) < 0.9f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0)));+ glm::vec2 a, b;+ if (!canvasAt(center, a) || !canvasAt(center + across * radius, b)) return;+ const float r = glm::length(glm::vec2((b.x - a.x) * canvasAspect, b.y - a.y));+ spacing = r * std::sqrt(3.14159265f / float(vertices)) / stencil->size * float(stencil->image->height);+}+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);+ return stencil->value(uv, spacing);}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);+ if (!stencil->colors) return glm::vec4(paintColor, stencil->value(uv, spacing));+ const glm::vec4 col = stencil->color(uv, spacing);return col.w > 1e-6f ? glm::vec4(glm::vec3(col) / col.w, col.w) : glm::vec4(paintColor, 0.0f); // (un-premultiplied)}diff --git a/src/core/Stencil.h b/src/core/Stencil.hindex 6324dc2f..cb4c2d4a 100644--- a/src/core/Stencil.h+++ b/src/core/Stencil.h@@ -16,6 +16,7 @@#include <memory>#include <string>+#include <vector>namespace sf {@@ -23,6 +24,10 @@ class CommandRegistry;struct Stencil {std::shared_ptr<const Image> image; // null = no stencil (straight from the file; inverted on sampling)+ // The image halved (box filtered) while it stays 512 px or more: where a dab's vertices are many pixels apart it+ // reads a disc of taps from the level that resolves them (finer levels' square pixels never stair-step an edge+ // at the mesh's scale, as levels down to 128 px did).+ std::shared_ptr<const std::vector<Image>> mips;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.@@ -44,14 +49,22 @@ struct Stencil {// 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;+ // the colour (linear) with how much of it Vertex Paint lays (.a: the pixel's alpha). `spacing`: how many image+ // pixels apart the vertices reading it are; past 1.5 the read averages a disc that wide (a fine photo on a+ // light mesh then gives each vertex its neighbourhood's brightness, not one pixel's: no noise, no shimmer).+ float value(glm::vec2 uv, float spacing = 0.0f) const;+ glm::vec4 color(glm::vec2 uv, float spacing = 0.0f) 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();++private:+ const Image& level(int l) const; // 0 the image, l > 0 mips[l - 1] (the smallest past the end)+ float valueAt(const Image& img, glm::vec2 uv) const;+ glm::vec4 colorAt(const Image& img, glm::vec2 uv) const;+ template <class T, class Read> T disc(glm::vec2 uv, float spacing, Read&& read) const;};// A stencil as one dab sees it: the view it was made in, and the symmetry copy the dab is for (the mirror's@@ -61,6 +74,11 @@ struct StencilView {glm::mat4 viewProj{1.0f};float canvasAspect = 1.0f;SymCopy copy; // identity: the stroke itself+ float spacing = 0.0f; // how many image pixels apart the dab's vertices show (0: read point by point)++ // Sets `spacing` for a dab of `radius` at `center` holding `vertices` vertices: its circle on screen shared out+ // evenly among them, in image pixels.+ void setSpacing(const glm::vec3& center, const glm::vec3& viewDir, float radius, size_t vertices);bool active() const { return stencil && stencil->active(); }// The canvas point (fractions) a world point shows at; false behind the camera.diff --git a/src/core/VertexPaint.cpp b/src/core/VertexPaint.cppindex d7c3749f..0f9c5f00 100644--- a/src/core/VertexPaint.cpp+++ b/src/core/VertexPaint.cpp@@ -141,6 +141,7 @@ size_t paintDab(Sculptor& sculptor, Mesh& mesh, const BVH& bvh, const DabParams&static thread_local ConnectedScratch connected;brushRegion(mesh, bvh, center, viewDir, p.radius * (useAlpha ? kAlphaReach : 1.0f), p.connectedOnly, p.viewFalloff,verts, connected);+ if (useStencil) stencil.setSpacing(center, viewDir, p.radius * (useAlpha ? kAlphaReach : 1.0f), verts.size());for (uint32_t v : verts) {if (p.frontFacesOnly && v < mesh.normals.size() && glm::dot(mesh.normals[v], viewDir) > 0.0f) continue;const glm::vec3 o = mesh.positions[v] - center;diff --git a/tests/test_stencil.cpp b/tests/test_stencil.cppindex 4754700b..4a88b88c 100644--- a/tests/test_stencil.cpp+++ b/tests/test_stencil.cpp@@ -282,3 +282,46 @@ TEST(stencil_groove_walls_are_smooth_along_the_groove) {coarse.size = 1.0f;CHECK(grooveRoughness(coarse, angle, 160) > 2.0f * r);}++TEST(stencil_fine_image_on_a_light_mesh_sculpts_evenly) {+ // A 2048 px one-pixel checker over the view: each vertex of a light mesh is many pixels from the next, so read+ // point by point it got whatever pixel it landed on (noise that shimmers as the stencil moves); averaged over the+ // vertices' spacing it is an even grey, so the stroke raises an even plateau.+ Image checker = blackImage(2048, 2048);+ for (int y = 0; y < 2048; ++y)+ for (int x = 0; x < 2048; ++x)+ if ((x + y) % 2 == 0)+ for (int k = 0; k < 3; ++k) checker.rgba[(size_t(y) * 2048 + size_t(x)) * 4 + size_t(k)] = 255;+ Stencil st;+ st.set(checker, "checker", "");+ CHECK(st.mips && st.mips->size() == 2); // 1024, 512 (no coarser: their square pixels would stair-step edges)+ st.size = 1.0f;+ // The plateau's unevenness (sd / mean of the heights along the stroke's middle), with and without the stencil:+ // the stencil may add next to nothing to what the stroke itself leaves on the grid.+ auto unevenness = [&](int res, const Stencil* with) {+ Document doc = makeDoc(makePlane(res));+ Mesh& m = doc.mesh;+ CHECK(doc.sculptor.beginStroke(m, "Standard"));+ for (float s = -0.5f; s <= 0.5f; s += 0.02f) {+ DabParams p = topDab(glm::vec3(s, 0, 0), 0.3f);+ p.strength = 0.3f;+ if (with) p.stencil = {with, topView(), 1.0f};+ doc.sculptor.dab(m, doc.bvh, BrushType::Standard, p, Symmetry{false, false, false});+ }+ doc.sculptor.endStroke();+ double sum = 0, sq = 0, n = 0;+ for (const glm::vec3& v : m.positions)+ if (std::abs(v.x) < 0.3f && std::abs(v.z) < 0.05f) {+ sum += v.y;+ sq += double(v.y) * v.y;+ n += 1;+ }+ const double mean = sum / n;+ return mean > 0.0 ? std::sqrt(std::max(0.0, sq / n - mean * mean)) / mean : 1.0;+ };+ for (int res : {40, 160}) {+ const double plain = unevenness(res, nullptr), stencilled = unevenness(res, &st);+ std::printf(" %d cells: plateau sd / mean %.4f (no stencil %.4f)\n", res, stencilled, plain);+ CHECK(stencilled < plain + 0.01); // (point by point: 0.065 at 40 cells, 0.17 at 160)+ }+}