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.

No first-dab stutter on dense textured meshes

islandmed74e7f336f1e5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d57c65b0..b1e3356f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,7 +32,10 @@ All notable changes to SculptForge are listed here. The format follows
finds the texture tiles under it from the BVH and paints each texel from a cached triangle-and-barycentrics
map, tiles in parallel. A 0.35-radius dab with X symmetry on a 21M-triangle sphere: 4K 150-360 ms -> 24-39 ms,
8K 240-350 ms -> 39-55 ms (M1 Pro, ranges over a busy and a quiet machine); results match the old dab within
- 1/255. Lighter meshes keep the per-triangle dab.
+ 1/255. Lighter meshes keep the per-triangle dab. No first-dab stutter: the UV bins are shared by every texture on
+ the same UVs (undo steps, copies) and built in parallel when painting starts (about 45 ms at 21M), the area under
+ the hovering brush is readied before it lands, and a stroke into a fresh area stays under 20 ms at 4K.
+ Preferences > Performance counts these caches.
- Project format 7 stores material channels. It is written only when a texture has them: other projects are
still saved as format 6, and every older project opens as before.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 05addaa8..3864149f 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -380,6 +380,7 @@ int App::runUiTest(int w, int h, int fps) {
ImGui::LogFinish();
ImGui::Render();
+ prewarmTexturePaint(); // dense textured meshes: ready the area under the hovering Paint brush (PanelPbr.cpp)
const auto syncStart = std::chrono::steady_clock::now();
syncScene();
notePerformanceFrame(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - syncStart).count());
@@ -801,6 +802,7 @@ int App::run() {
drawUi();
ImGui::Render();
+ prewarmTexturePaint(); // dense textured meshes: ready the area under the hovering Paint brush (PanelPbr.cpp)
const auto syncStart = std::chrono::steady_clock::now();
syncScene();
notePerformanceFrame(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - syncStart).count());
diff --git a/src/app/App.h b/src/app/App.h
index bb5569cf..144ee5c0 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -509,6 +509,11 @@ private:
void registerPbrUiActions();
double pbrTestValue(const std::string& name) const; // UI test values (UiTest.cpp), NaN when not one of ours
int exportPresetChoice_ = 0;
+ // Dense textured meshes: while the Paint brush hovers, the texture painting caches for the area under it are
+ // built ahead of the first dab (PanelPbr.cpp; TexturePainter::prewarm).
+ void prewarmTexturePaint();
+ glm::vec3 prewarmCenter_{1e30f};
+ float prewarmRadius_ = 0.0f;
// Bake sub-palette (PanelBake.cpp): normal / displacement / AO / cavity / colour maps from a high-poly onto
// the active SubTool's UVs (core/Bake.h), on a worker thread, and the baked normal map shown on the model.
void drawBakeContents();
diff --git a/src/app/PanelPbr.cpp b/src/app/PanelPbr.cpp
index 54f62bc9..cf0641ba 100644
--- a/src/app/PanelPbr.cpp
+++ b/src/app/PanelPbr.cpp
@@ -328,6 +328,28 @@ Args App::drawLayerChannelChips(int layer) {
return run;
}
+void App::prewarmTexturePaint() {
+ Mesh& m = doc_.mesh;
+ if (!(paintMode_ || paintRgb_) || drag_ == Drag::Stroke || !paintsTexture(m)) return;
+ // The UV bins (once per UV layout; cheap to check every frame).
+ prewarmTexturePainting(m);
+ // The texel maps under the hovering brush, again once it has moved a quarter of its size.
+ const CanvasRect canvas = canvasRect();
+ if (ImGui::GetIO().WantCaptureMouse || mouseX_ < canvas.x || mouseY_ < canvas.y || mouseX_ > canvas.x + canvas.w ||
+ mouseY_ > canvas.y + canvas.h)
+ return;
+ doc_.syncBvh();
+ RayHit hit;
+ if (!pick(mouseX_, mouseY_, hit)) return;
+ const float r = radiusPx_ * camera_.worldPerPixel(hit.position, canvasHeight());
+ if (glm::distance(hit.position, prewarmCenter_) < 0.25f * r && std::abs(r - prewarmRadius_) < 0.2f * r) return;
+ prewarmCenter_ = hit.position;
+ prewarmRadius_ = r;
+ std::vector<glm::vec3> centers;
+ for (const glm::vec3& mirror : Sculptor::mirrors(symmetry_)) centers.push_back(hit.position * mirror);
+ prewarmTexturePainting(m, &doc_.bvh, centers, r * 1.25f); // a little wider: the pen moves before it lands
+}
+
double App::pbrTestValue(const std::string& name) const {
const Mesh& m = doc_.mesh;
const bool tex = hasTexture(m);
diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cpp
index e72d414c..70e10964 100644
--- a/src/app/PanelPerformance.cpp
+++ b/src/app/PanelPerformance.cpp
@@ -177,6 +177,7 @@ void App::drawPerformanceSection() {
const std::string mem = "Meshes " + megabytes(m.mesh) + " BVH " + megabytes(m.bvh) + "\nSubdivision levels " +
megabytes(m.levels) + "\nUndo " + megabytes(m.undo) + " of " + megabytes(doc_.undo.byteBudget) +
"\nTextures " + megabytes(m.textures) + " (material channels " + megabytes(m.channels) + ")" +
+ (m.paintCaches ? "\nTexture painting caches " + megabytes(m.paintCaches) : std::string()) +
"\nGPU buffers about " + megabytes(m.gpu);
ImGui::TextUnformatted(mem.c_str());
ImGui::LogText("%s", mem.c_str());
diff --git a/src/core/Benchmark.cpp b/src/core/Benchmark.cpp
index 9952dbe8..88c6c817 100644
--- a/src/core/Benchmark.cpp
+++ b/src/core/Benchmark.cpp
@@ -88,6 +88,7 @@ MemoryUse documentMemory(const Document& doc) {
u.gpu += m.vertexCount() * (12 + (m.hasColors() ? 4 : 0) + (m.hasMask() ? 1 : 0)) * 11 / 10 +
m.triangleCount() * (6 + (m.hasPolygroups() ? 2 : 0));
}
+ u.paintCaches = texturePaintCacheBytes();
return u;
}
@@ -103,8 +104,8 @@ void registerPerformanceCommands(CommandRegistry& registry) {
(ThreadPool::shared().serial() ? " (multithreading off)" : "") + "; " +
millions(double(u.triangles)) + " triangles; memory " + mb(u.total()) + " (meshes " +
mb(u.mesh) + ", BVH " + mb(u.bvh) + ", subdivision levels " + mb(u.levels) +
- ", undo " + mb(u.undo) + ", textures " + mb(u.textures) + " of which material channels " +
- mb(u.channels) + "), GPU buffers about " + mb(u.gpu);
+ ", undo " + mb(u.undo) + ", textures " + mb(u.textures) + " of which material channels " + mb(u.channels) + ", texture painting caches " + mb(u.paintCaches) +
+ "), GPU buffers about " + mb(u.gpu);
return {true, msg};
}});
registry.add({"set_multithreading",
diff --git a/src/core/Benchmark.h b/src/core/Benchmark.h
index 73b106e9..797fcd3f 100644
--- a/src/core/Benchmark.h
+++ b/src/core/Benchmark.h
@@ -85,8 +85,9 @@ struct MemoryUse {
size_t gpu = 0; // vertex and index buffers the renderer keeps for the visible SubTools (an estimate)
size_t textures = 0; // painted textures (core/Texture.h): colour, layers, material channels (each texture once)
size_t channels = 0; // of `textures`, the material channel tiles (core/TextureChannels.h)
+ size_t paintCaches = 0; // texture painting caches of dense meshes (UV tile bins, texel maps), shared per UV layout
size_t triangles = 0, vertices = 0;
- size_t total() const { return mesh + bvh + levels + undo + textures; }
+ size_t total() const { return mesh + bvh + levels + undo + textures + paintCaches; }
};
MemoryUse documentMemory(const Document& doc);
diff --git a/src/core/Texture.cpp b/src/core/Texture.cpp
index 087ff4aa..f6cd3efd 100644
--- a/src/core/Texture.cpp
+++ b/src/core/Texture.cpp
@@ -12,6 +12,7 @@
#include <cmath>
#include <cstring>
#include <limits>
+#include <chrono>
#include <cstdio>
#include <thread>
@@ -655,9 +656,21 @@ PaintTexture& mutableTexture(Mesh& m) {
return *m.texture;
}
+// The coverage of a dense mesh's UVs from the texture-painting cache (defined with the tile dabs below); null if it
+// can't be made that way.
+std::shared_ptr<const std::vector<uint8_t>> cachedCoverage(const Mesh& m, int w, int h);
+
void ensureCoverage(const Mesh& m, PaintTexture& tex, bool force) {
const uint64_t fp = uvFingerprint(m);
if (!force && tex.coverageUvs == fp && tex.coverage.size() == (tex.texelCount() + 7) / 8) return;
+ // Dense meshes: from the shared texture-painting cache, built tile by tile in parallel.
+ if (!force && m.triangleCount() >= 200000 && m.uvs.size() == m.triangleCount() * 3)
+ if (std::shared_ptr<const std::vector<uint8_t>> c = cachedCoverage(m, tex.width, tex.height);
+ c && c->size() == (tex.texelCount() + 7) / 8) {
+ tex.coverage = *c;
+ tex.coverageUvs = fp;
+ return;
+ }
tex.coverage.assign((tex.texelCount() + 7) / 8, 0);
tex.coverageUvs = fp;
if (m.uvs.size() != m.triangleCount() * 3) return;
@@ -744,7 +757,7 @@ bool TexturePainter::begin(Mesh& mesh, uint32_t channels) {
if (!channels_) return false;
PaintTexture& tex = mutableTexture(mesh);
syncLayerChannels(tex); // every layer has an image for every enabled channel
- ensureCoverage(mesh, tex);
+ if (!useTilePath(mesh, tex)) ensureCoverage(mesh, tex); // (the per-triangle dab pads islands with it)
tilesX_ = (tex.width + kTextureTile - 1) / kTextureTile;
tilesY_ = (tex.height + kTextureTile - 1) / kTextureTile;
tiles_.resize(size_t(tilesX_) * size_t(tilesY_));
@@ -852,20 +865,19 @@ struct TexelMapCache {
namespace {
-uint64_t texelMapKey(const Mesh& m, const PaintTexture& t) {
- uint64_t h = mixKey(uvFingerprint(m), m.triangleCount());
- h = mixKey(h, uint64_t(t.width) << 32 | uint64_t(t.height));
- return mixKey(h, t.coverageUvs);
+uint64_t paintKey(const Mesh& m, int w, int h) {
+ return mixKey(mixKey(uvFingerprint(m), m.triangleCount()), uint64_t(uint32_t(w)) << 32 | uint64_t(uint32_t(h)));
}
+uint64_t texelMapKey(const Mesh& m, const PaintTexture& t) { return paintKey(m, t.width, t.height); }
-std::shared_ptr<const UvTileIndex> buildUvIndex(const Mesh& m, const PaintTexture& t, uint64_t key) {
+std::shared_ptr<const UvTileIndex> buildUvIndex(const Mesh& m, int width, int height, uint64_t key) {
auto idx = std::make_shared<UvTileIndex>();
idx->key = key;
- idx->tilesX = tileCount(t.width);
- idx->tilesY = tileCount(t.height);
+ idx->tilesX = tileCount(width);
+ idx->tilesY = tileCount(height);
const size_t nt = m.triangleCount();
idx->triTiles.resize(nt * 4);
- const float w = float(t.width), h = float(t.height), pad = float(kTextureGutter + 1);
+ const float w = float(width), h = float(height), pad = float(kTextureGutter + 1);
const int tx1max = idx->tilesX - 1, ty1max = idx->tilesY - 1;
poolFor(nt, [&](size_t b, size_t e) {
for (size_t i = b; i < e; ++i) {
@@ -883,26 +895,91 @@ std::shared_ptr<const UvTileIndex> buildUvIndex(const Mesh& m, const PaintTextur
o[3] = uint8_t(std::clamp(int(std::ceil(maxY)) / kTextureTile, 0, ty1max));
}
}, 65536);
+ // Bins in triangle order, on every core: each block of triangles counts its tiles, a prefix over (tile,
+ // block) gives every block its place in each bin, then the blocks fill in parallel.
const size_t tiles = size_t(idx->tilesX) * size_t(idx->tilesY);
- idx->binStart.assign(tiles + 1, 0);
- for (size_t i = 0; i < nt; ++i) {
+ const size_t blocks = std::clamp<size_t>(nt / 65536, 1, 32), per = (nt + blocks - 1) / blocks;
+ std::vector<uint32_t> counts(blocks * tiles, 0);
+ auto forTiles = [&](size_t i, auto&& fn) {
const uint8_t* o = &idx->triTiles[i * 4];
- if (o[0] > o[2]) continue;
+ if (o[0] > o[2]) return;
for (int ty = o[1]; ty <= o[3]; ++ty)
- for (int tx = o[0]; tx <= o[2]; ++tx) ++idx->binStart[size_t(ty) * size_t(idx->tilesX) + size_t(tx) + 1];
- }
- for (size_t k = 0; k < tiles; ++k) idx->binStart[k + 1] += idx->binStart[k];
- idx->bins.resize(idx->binStart[tiles]);
- std::vector<uint32_t> fill(idx->binStart.begin(), idx->binStart.end() - 1);
- for (size_t i = 0; i < nt; ++i) {
- const uint8_t* o = &idx->triTiles[i * 4];
- if (o[0] > o[2]) continue;
- for (int ty = o[1]; ty <= o[3]; ++ty)
- for (int tx = o[0]; tx <= o[2]; ++tx) idx->bins[fill[size_t(ty) * size_t(idx->tilesX) + size_t(tx)]++] = uint32_t(i);
+ for (int tx = o[0]; tx <= o[2]; ++tx) fn(size_t(ty) * size_t(idx->tilesX) + size_t(tx));
+ };
+ ThreadPool::shared().run(blocks, [&](size_t b) {
+ uint32_t* c = &counts[b * tiles];
+ for (size_t i = b * per; i < std::min(nt, (b + 1) * per); ++i) forTiles(i, [&](size_t k) { ++c[k]; });
+ });
+ idx->binStart.assign(tiles + 1, 0);
+ uint32_t running = 0;
+ for (size_t k = 0; k < tiles; ++k) {
+ idx->binStart[k] = running;
+ for (size_t b = 0; b < blocks; ++b) {
+ const uint32_t n = counts[b * tiles + k];
+ counts[b * tiles + k] = running; // now: where block b writes into bin k
+ running += n;
+ }
}
+ idx->binStart[tiles] = running;
+ idx->bins.resize(running);
+ ThreadPool::shared().run(blocks, [&](size_t b) {
+ uint32_t* at = &counts[b * tiles];
+ for (size_t i = b * per; i < std::min(nt, (b + 1) * per); ++i) forTiles(i, [&](size_t k) { idx->bins[at[k]++] = uint32_t(i); });
+ });
return idx;
}
+// The coverage bitmap (PaintTexture::coverage) from the bins, tiles in parallel: a tile's texels are whole bytes
+// of the bitmap (64 texels per row), so tiles never share a byte. Needs widths that are multiples of 64.
+std::vector<uint8_t> coverageFromIndex(const Mesh& m, int w, int h, const UvTileIndex& idx) {
+ std::vector<uint8_t> cov((size_t(w) * size_t(h) + 7) / 8, 0);
+ poolFor(size_t(idx.tilesX) * size_t(idx.tilesY), [&](size_t b, size_t e) {
+ for (size_t ti = b; ti < e; ++ti) {
+ const int x0 = int(ti % size_t(idx.tilesX)) * kTextureTile, y0 = int(ti / size_t(idx.tilesX)) * kTextureTile;
+ const int x1 = std::min(x0 + kTextureTile, w) - 1, y1 = std::min(y0 + kTextureTile, h) - 1;
+ for (uint32_t k = idx.binStart[ti]; k < idx.binStart[ti + 1]; ++k) {
+ const uint32_t tri = idx.bins[k];
+ const TriSetup s(m.uvs[size_t(tri) * 3], m.uvs[size_t(tri) * 3 + 1], m.uvs[size_t(tri) * 3 + 2], w, h);
+ visitTriangle(s, w, h, 0, nullptr, x0, y0, x1, y1, [&](int x, int y, const glm::vec3&, bool) {
+ const size_t i = size_t(y) * size_t(w) + size_t(x);
+ cov[i >> 3] |= uint8_t(1u << (i & 7));
+ });
+ }
+ }
+ }, 1);
+ return cov;
+}
+
+// Texture-painting caches by UV layout and texture size (not by texture: copies, undo steps and new textures on
+// the same UVs share them): the UV bins, the texel maps and the coverage. The two most recent layouts are kept.
+struct PaintCacheEntry {
+ uint64_t key = 0;
+ std::shared_ptr<const UvTileIndex> index;
+ std::shared_ptr<TexelMapCache> maps;
+ std::shared_ptr<const std::vector<uint8_t>> coverage;
+};
+std::mutex gPaintCacheMutex;
+std::vector<PaintCacheEntry> gPaintCache; // most recent first
+
+PaintCacheEntry paintCache(const Mesh& m, int w, int h, uint64_t key) {
+ std::lock_guard lock(gPaintCacheMutex);
+ for (size_t i = 0; i < gPaintCache.size(); ++i)
+ if (gPaintCache[i].key == key) {
+ std::rotate(gPaintCache.begin(), gPaintCache.begin() + std::ptrdiff_t(i), gPaintCache.begin() + std::ptrdiff_t(i) + 1);
+ return gPaintCache[0];
+ }
+ PaintCacheEntry e;
+ e.key = key;
+ e.index = buildUvIndex(m, w, h, key);
+ auto maps = std::make_shared<TexelMapCache>();
+ maps->key = key;
+ maps->tiles.resize(size_t(e.index->tilesX) * size_t(e.index->tilesY));
+ e.maps = std::move(maps);
+ gPaintCache.insert(gPaintCache.begin(), e);
+ if (gPaintCache.size() > 2) gPaintCache.resize(2);
+ return e;
+}
+
// The texel map of tile `ti`: every island texel's triangle (exact top-left rule, as rasterizeUvTriangle), and
// every gutter texel's nearest island point within kTextureGutter texels.
std::unique_ptr<TexelMapTile> buildTexelMap(const Mesh& m, const PaintTexture& t, const UvTileIndex& idx, size_t ti) {
@@ -918,22 +995,55 @@ std::unique_ptr<TexelMapTile> buildTexelMap(const Mesh& m, const PaintTexture& t
map->bary[li * 2] = uint16_t(std::lround(std::clamp(b.y, 0.0f, 1.0f) * 65535.0f));
map->bary[li * 2 + 1] = uint16_t(std::lround(std::clamp(b.z, 0.0f, 1.0f) * 65535.0f));
};
+ // Pass 1, island texels: every bin triangle without the gutter. The bin holds every triangle that reaches the
+ // tile, so this is also the tile's coverage (no texture-wide coverage needed).
for (uint32_t k = idx.binStart[ti]; k < idx.binStart[ti + 1]; ++k) {
const uint32_t tri = idx.bins[k];
const TriSetup s(m.uvs[size_t(tri) * 3], m.uvs[size_t(tri) * 3 + 1], m.uvs[size_t(tri) * 3 + 2], t.width, t.height);
- visitTriangle(s, t.width, t.height, kTextureGutter, &t, x0, y0, x1, y1, [&](int x, int y, const glm::vec3& b, bool inside) {
+ visitTriangle(s, t.width, t.height, 0, nullptr, x0, y0, x1, y1, [&](int x, int y, const glm::vec3& b, bool) {
const size_t li = size_t(y - y0) * kTextureTile + size_t(x - x0);
- if (dist[li] < 0.0f) { // an island texel that already has a triangle: overlapping UVs
- if (inside)
- map->extras.push_back({uint16_t(li), uint16_t(std::lround(std::clamp(b.y, 0.0f, 1.0f) * 65535.0f)),
- uint16_t(std::lround(std::clamp(b.z, 0.0f, 1.0f) * 65535.0f)), tri});
- return;
- }
- if (inside) {
- dist[li] = -1.0f;
- put(li, tri, b);
+ if (dist[li] < 0.0f) { // overlapping UVs: the texel's other triangles
+ map->extras.push_back({uint16_t(li), uint16_t(std::lround(std::clamp(b.y, 0.0f, 1.0f) * 65535.0f)),
+ uint16_t(std::lround(std::clamp(b.z, 0.0f, 1.0f) * 65535.0f)), tri});
return;
}
+ dist[li] = -1.0f;
+ put(li, tri, b);
+ });
+ }
+ // Uncovered texels of the tile as a summed-area table: a triangle needs the gutter pass only when its grown
+ // box holds one (most triangles of a dense mesh lie inside an island and cost nothing more).
+ constexpr int S = kTextureTile + 1;
+ std::array<uint16_t, size_t(S) * S> sat{};
+ for (int y = y0; y <= y1; ++y)
+ for (int x = x0; x <= x1; ++x) {
+ const int ly = y - y0 + 1, lx = x - x0 + 1;
+ const bool cov = dist[size_t(y - y0) * kTextureTile + size_t(x - x0)] < 0.0f;
+ sat[size_t(ly) * S + size_t(lx)] = uint16_t((cov ? 0 : 1) + sat[size_t(ly - 1) * S + size_t(lx)] +
+ sat[size_t(ly) * S + size_t(lx - 1)] - sat[size_t(ly - 1) * S + size_t(lx - 1)]);
+ }
+ auto uncovered = [&](int bx0, int by0, int bx1, int by1) { // texel box (inclusive), clipped to the tile
+ bx0 = std::max(bx0, x0) - x0, by0 = std::max(by0, y0) - y0, bx1 = std::min(bx1, x1) - x0, by1 = std::min(by1, y1) - y0;
+ if (bx0 > bx1 || by0 > by1) return false;
+ return sat[size_t(by1 + 1) * S + size_t(bx1 + 1)] - sat[size_t(by0) * S + size_t(bx1 + 1)] -
+ sat[size_t(by1 + 1) * S + size_t(bx0)] + sat[size_t(by0) * S + size_t(bx0)] > 0;
+ };
+ // Pass 2, gutter texels: the nearest island point of the triangles near uncovered texels.
+ for (uint32_t k = idx.binStart[ti]; k < idx.binStart[ti + 1]; ++k) {
+ const uint32_t tri = idx.bins[k];
+ // The texel box (as TriSetup::bounds) from the UVs alone: most triangles are skipped without a setup.
+ const glm::vec2 a = m.uvs[size_t(tri) * 3], bb = m.uvs[size_t(tri) * 3 + 1], cc = m.uvs[size_t(tri) * 3 + 2];
+ const float fw = float(t.width), fh = float(t.height);
+ const int bx0 = int(std::floor(std::min({a.x, bb.x, cc.x}) * fw - 0.5f)) - kTextureGutter;
+ const int by0 = int(std::floor(std::min({a.y, bb.y, cc.y}) * fh - 0.5f)) - kTextureGutter;
+ const int bx1 = int(std::ceil(std::max({a.x, bb.x, cc.x}) * fw - 0.5f)) + kTextureGutter;
+ const int by1 = int(std::ceil(std::max({a.y, bb.y, cc.y}) * fh - 0.5f)) + kTextureGutter;
+ if (!uncovered(bx0, by0, bx1, by1)) continue;
+ const TriSetup s(a, bb, cc, t.width, t.height);
+ if (!s.valid) continue;
+ visitTriangle(s, t.width, t.height, kTextureGutter, nullptr, x0, y0, x1, y1, [&](int x, int y, const glm::vec3& b, bool inside) {
+ const size_t li = size_t(y - y0) * kTextureTile + size_t(x - x0);
+ if (inside || dist[li] < 0.0f) return; // island texels came from pass 1
const glm::vec2 q = s.t[0] * b.x + s.t[1] * b.y + s.t[2] * b.z, c(float(x) + 0.5f, float(y) + 0.5f);
const float d2 = glm::dot(q - c, q - c);
if (d2 < dist[li]) {
@@ -984,8 +1094,6 @@ bool sphereTiles(const Mesh& m, uint32_t tri, int w, int h, const glm::vec3& cen
} // namespace
-void TexturePainter::setPath(Path path) { gDabPath = int(path); }
-
struct TexturePainter::DabContext {
Mesh& mesh;
const BVH& bvh;
@@ -998,20 +1106,75 @@ struct TexturePainter::DabContext {
const std::vector<DabMirror>& mirrors;
};
+void TexturePainter::setPath(Path path) { gDabPath = int(path); }
+
+void TexturePainter::prewarm(Mesh& mesh, const BVH* bvh, std::span<const glm::vec3> centers, float radius) {
+ if (!paintsTexture(mesh)) return;
+ PaintTexture& tex = *mesh.texture; // (only its caches change)
+ if (!useTilePath(mesh, tex)) {
+ ensureCoverage(mesh, tex);
+ return;
+ }
+ if (!bvh || centers.empty() || radius <= 0.0f) return;
+ std::vector<DabMirror> mirrors;
+ for (const glm::vec3& c : centers) mirrors.push_back({c, glm::vec3(0, 0, -1), glm::vec3(0, 1, 0), glm::vec3(1, 0, 0), 0});
+ DabParams dp;
+ dp.center = centers[0];
+ dp.radius = radius;
+ dp.strength = 0.0f;
+ const DabContext ctx{mesh, *bvh, dp, tex, tex.pixels, 0.0f, false, false, false, radius, radius * radius, mirrors};
+ std::vector<std::pair<glm::ivec2, glm::ivec2>> rects;
+ dabTiles(ctx, [](Tile&, size_t, int, int, float) {}, false, rects);
+}
+
+void prewarmTexturePainting(Mesh& mesh, const BVH* bvh, std::span<const glm::vec3> centers, float radius) {
+ TexturePainter painter;
+ painter.prewarm(mesh, bvh, centers, radius);
+}
+
+std::shared_ptr<const std::vector<uint8_t>> cachedCoverage(const Mesh& m, int w, int h) {
+ if (w % kTextureTile != 0 || tileCount(w) > 256 || tileCount(h) > 256) return nullptr;
+ const uint64_t key = paintKey(m, w, h);
+ const PaintCacheEntry e = paintCache(m, w, h, key);
+ if (e.coverage) return e.coverage;
+ auto cov = std::make_shared<const std::vector<uint8_t>>(coverageFromIndex(m, w, h, *e.index));
+ std::lock_guard lock(gPaintCacheMutex);
+ for (PaintCacheEntry& c : gPaintCache)
+ if (c.key == key) c.coverage = cov;
+ return cov;
+}
+
+void clearTexturePaintCaches() {
+ std::lock_guard lock(gPaintCacheMutex);
+ gPaintCache.clear();
+}
+
+size_t texturePaintCacheBytes() {
+ std::lock_guard lock(gPaintCacheMutex);
+ size_t n = 0;
+ for (const PaintCacheEntry& e : gPaintCache) {
+ if (e.index) n += e.index->triTiles.size() + (e.index->binStart.size() + e.index->bins.size()) * sizeof(uint32_t);
+ if (e.coverage) n += e.coverage->size();
+ if (e.maps)
+ for (const auto& t : e.maps->tiles)
+ if (t) n += t->tri.size() * 4 + t->bary.size() * 2 + t->extras.size() * sizeof(TexelMapTile::Extra);
+ }
+ return n;
+}
+
+
bool TexturePainter::useTilePath(const Mesh& mesh, PaintTexture& tex) const {
const Path path = Path(gDabPath.load());
if (path == Path::Triangles) return false;
if (tileCount(tex.width) > 256 || tileCount(tex.height) > 256) return false;
if (path == Path::Auto && mesh.triangleCount() * 64 < tex.texelCount()) return false;
const uint64_t key = texelMapKey(mesh, tex);
- if (!tex.uvIndex || tex.uvIndex->key != key) tex.uvIndex = buildUvIndex(mesh, tex, key);
- if (!tex.texelMaps || tex.texelMaps->key != key) {
- auto cache = std::make_shared<TexelMapCache>();
- cache->key = key;
- cache->tiles.resize(size_t(tex.uvIndex->tilesX) * size_t(tex.uvIndex->tilesY));
- tex.texelMaps = std::move(cache);
+ if (!tex.uvIndex || tex.uvIndex->key != key || !tex.texelMaps || tex.texelMaps->key != key) {
+ const PaintCacheEntry e = paintCache(mesh, tex.width, tex.height, key);
+ tex.uvIndex = e.index;
+ tex.texelMaps = e.maps;
}
- return true;
+ return true; // (the tile path needs no texture-wide coverage: each texel map finds its tile's own)
}
template <class Paint>
@@ -1087,6 +1250,7 @@ size_t TexturePainter::dabTiles(const DabContext& c, const Paint& paint, bool co
slot->used = cache.clock;
}
const TexelMapTile& map = *slot;
+ if (c.s <= 0.0f) return; // prewarm: only the texel maps
Result& res = results[job];
const int x0 = int(ti % uint32_t(idx.tilesX)) * kTextureTile, y0 = int(ti / uint32_t(idx.tilesX)) * kTextureTile;
const int x1 = std::min(x0 + kTextureTile, w), y1 = std::min(y0 + kTextureTile, h);
diff --git a/src/core/Texture.h b/src/core/Texture.h
index 579e4fe0..86a4d0d1 100644
--- a/src/core/Texture.h
+++ b/src/core/Texture.h
@@ -37,6 +37,7 @@
#include <atomic>
#include <functional>
#include <mutex>
+#include <span>
#include <memory>
#include <string>
#include <vector>
@@ -122,6 +123,12 @@ struct PaintTexture {
size_t bytes() const;
};
+// Bytes of the texture-painting caches shared by every texture on the same UVs (UV tile bins, coverage, texel
+// maps of dense meshes): Preferences > Performance.
+size_t texturePaintCacheBytes();
+// Drops those caches (tests and benchmarks measure building them; textures keep theirs until repainted).
+void clearTexturePaintCaches();
+
// Texels a view that is up to date except for the latest changes would upload now (benchmarks, tests).
size_t textureUploadTexels(const PaintTexture& tex);
@@ -205,6 +212,9 @@ public:
// (tests compare them).
enum class Path { Auto, Tiles, Triangles };
static void setPath(Path path);
+ // Readies dense-mesh painting before a dab needs it: the UV bins and coverage (shared per UV layout), and the
+ // texel maps of the tiles a dab of `radius` at each of `centers` would reach (with `bvh`). Paints nothing.
+ void prewarm(Mesh& mesh, const BVH* bvh, std::span<const glm::vec3> centers, float radius);
private:
// Dense meshes (texels outnumber what each triangle covers): the brush finds the texture tiles under it from
@@ -238,6 +248,10 @@ private:
std::vector<std::vector<uint32_t>> bandTris_; // per 16-row band: indices into dabTris_, in serial order
};
+// TexturePainter::prewarm without a stroke (the app calls it while the Paint brush hovers a dense textured mesh,
+// so the first dab doesn't build what it needs).
+void prewarmTexturePainting(Mesh& mesh, const BVH* bvh = nullptr, std::span<const glm::vec3> centers = {}, float radius = 0.0f);
+
// --- Whole-texture operations (callers record undo: TextureStackUndo or captureTexture) ---
// Calls fn(triangle, b0, b1, b2, x, y) for every texel inside a UV triangle plus the gutter around the
// islands (gutter texels get the nearest island point). Hidden triangles are skipped when `skipHidden`.
diff --git a/tests/test_texture_channels.cpp b/tests/test_texture_channels.cpp
index 1c589a0e..64c07ec6 100644
--- a/tests/test_texture_channels.cpp
+++ b/tests/test_texture_channels.cpp
@@ -519,7 +519,7 @@ TEST(material_dense_mesh_benchmark) {
for (float radius : {0.05f, 0.35f}) {
// Pass 0: colour with the per-triangle dab (as 0.10 shipped); 1: colour with texel tiles; 2: five
// channels with texel tiles. `cold`: the first dab of pass 1 (the UV bins and texel tiles are made).
- double t[3] = {0, 0, 0}, cold = 0;
+ double t[3] = {0, 0, 0}, cold = 0, beginMs = 0, prefetchMs = 0, prefetchedFirst = 0, worst = 0;
for (int pass = 0; pass < 3; ++pass) {
TexturePainter::setPath(pass == 0 ? TexturePainter::Path::Triangles : TexturePainter::Path::Auto);
Mesh& m = base;
@@ -529,8 +529,11 @@ TEST(material_dense_mesh_benchmark) {
mat.channels = pass == 2 ? five : channelBit(Channel::BaseColor);
if (pass == 2)
for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Height, Channel::AO}) setChannelEnabled(*m.texture, c, true);
+ if (pass == 1) clearTexturePaintCaches(); // measure building them
TexturePainter painter;
+ const auto b0 = now();
CHECK(painter.begin(m, mat.channels));
+ if (pass == 1) beginMs = ms(b0, now());
DabParams p = dab(glm::vec3(0, 0, 1), radius, 0.5f);
p.viewDir = glm::vec3(0, 0, -1);
const auto c0 = now();
@@ -540,15 +543,33 @@ TEST(material_dense_mesh_benchmark) {
p.center = glm::normalize(glm::vec3(-0.15f + 0.03f * float(i), 0.2f, 1.0f));
const auto t0 = now();
painter.dab(m, bvh, p, mat, Symmetry{true, false, false});
- t[pass] += ms(t0, now());
+ const double one = ms(t0, now());
+ t[pass] += one;
+ if (pass > 0) worst = std::max(worst, one);
+ }
+ if (pass == 1) {
+ // A fresh area, as the app does it: the brush hovers there first (prewarm), then paints.
+ const glm::vec3 c2 = glm::normalize(glm::vec3(0.2f, 0.3f, -1.0f));
+ const glm::vec3 centers[2] = {c2, c2 * glm::vec3(-1, 1, 1)};
+ const auto h0 = now();
+ prewarmTexturePainting(m, &bvh, centers, radius);
+ prefetchMs = ms(h0, now());
+ p.center = c2;
+ p.viewDir = glm::vec3(0, 0, 1);
+ const auto d0 = now();
+ painter.dab(m, bvh, p, mat, Symmetry{true, false, false});
+ prefetchedFirst = ms(d0, now());
}
UndoRecord rec;
painter.end(rec);
t[pass] /= 10.0;
}
TexturePainter::setPath(TexturePainter::Path::Auto);
- std::printf(" %5.1fM / %dK / %.2f: triangles %7.2f ms -> tiles %6.2f ms (first dab %6.0f ms), 5 channels %6.2f ms (%.2fx)\n",
- double(base.triangleCount()) / 1e6, size / 1024, radius, t[0], t[1], cold, t[2], t[2] / t[1]);
+ std::printf(" %5.1fM / %dK / %.2f: triangles %7.2f ms -> tiles %6.2f ms, 5 channels %6.2f ms (%.2fx); worst dab %.1f ms; "
+ "UV bins %.0f ms (once per UV layout; the app builds them when painting starts), first dab cold %.1f ms, "
+ "hover prefetch %.1f ms then first dab %.1f ms\n",
+ double(base.triangleCount()) / 1e6, size / 1024, radius, t[0], t[1], t[2], t[2] / t[1], worst, beginMs, cold,
+ prefetchMs, prefetchedFirst);
}
// Memory: 5 channels, Base plus 3 layers, each with a big stroke on every channel; then one layer painted
// everywhere (its tiles all dense), and export_maps of the result.