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.

Draft strokes; no stalls when a stroke leaves the position grid or ends; parallel full normal recompute

islandmedaa1530a9cc03
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 2effd83e..2961b36a 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -660,6 +660,10 @@ int App::run() {
// The brush behind the pointer is measured twice: the surface (the last dab whose result is on the GPU) and
// the preview (the predictive stroke's head, render/Ghost.h; the surface when there is none). Release is how
// long letting go holds up the UI, then how long until the last dab is on screen.
+ struct MeasureView {
+ float distance, aspect, w, h;
+ bool operator==(const MeasureView&) const = default;
+ };
struct StrokeMeasure {
bool started = false, moving = false; // moving: the press's first frame is on screen, the pointer moves
bool releasing = false; // let go: waiting for the last dab to reach the screen
@@ -669,6 +673,9 @@ int App::run() {
uint64_t frames = 0, samples = 0, lagSamples = 0;
float cx = 0.0f, cy = 0.0f, r = 0.0f;
std::vector<glm::vec2> dabs;
+ MeasureView view{}; // the view before the stroke (it starts once this has held still for a second)
+ double viewSince = 0.0;
+ std::vector<double> frameTimes; // seconds, for the percentiles
// SF_MEASURE_VERIFY=1: the mesh before the stroke, to check undo and replay the dabs (verifyStroke).
uint64_t before = 0;
// SF_MEASURE_SNAPSHOT=prefix: the canvas at a few points of the stroke, as prefix-N.png.
@@ -737,7 +744,18 @@ int App::run() {
mark();
while (SDL_PollEvent(&e)) onEvent(e);
mark();
- if (options_.measureStroke > 0.0f && !sm.started && t0 - started >= kMeasureSettle && !backgroundBusy()) {
+ // (The window must have settled too: a window manager that maximises it late, on a busy machine, changes
+ // the canvas and with it the brush's size in the world mid-stroke.)
+ if (options_.measureStroke > 0.0f && !sm.started) {
+ const CanvasRect c = canvasRect();
+ const MeasureView v{camera_.distance, camera_.aspect, c.w, c.h};
+ if (!(v == sm.view)) {
+ sm.view = v;
+ sm.viewSince = t0;
+ }
+ }
+ if (options_.measureStroke > 0.0f && !sm.started && t0 - started >= kMeasureSettle && t0 - sm.viewSince >= 1.0 &&
+ !backgroundBusy()) {
const CanvasRect c = canvasRect();
sm.cx = c.x + c.w * 0.5f;
sm.cy = c.y + c.h * 0.5f;
@@ -774,6 +792,12 @@ int App::run() {
std::sort(off.begin(), off.end());
const auto pct = [&](double q) { return off.empty() ? 0.0f : off[std::min(off.size() - 1, size_t(q * off.size()))]; };
const double frameMean = sm.frames ? sm.sumFrames / double(sm.frames) * 1000.0 : 0.0;
+ std::sort(sm.frameTimes.begin(), sm.frameTimes.end());
+ const auto framePct = [&](double q) {
+ return sm.frameTimes.empty() ? 0.0
+ : sm.frameTimes[std::min(sm.frameTimes.size() - 1, size_t(q * double(sm.frameTimes.size())))] * 1000.0;
+ };
+ std::printf(" frame percentiles: p50 %.1f ms, p95 %.1f ms, p99 %.1f ms\n", framePct(0.5), framePct(0.95), framePct(0.99));
const double lagMean = sm.lagSamples ? sm.sumLag / double(sm.lagSamples) : 0.0;
const double previewMean = sm.lagSamples ? sm.sumPreviewLag / double(sm.lagSamples) : 0.0;
std::printf("Stroke (%s%s): %zu dabs from %llu pointer samples in %.1f s, circle radius %.0f px, brush radius %.0f px\n"
@@ -787,15 +811,19 @@ int App::run() {
sm.firstSurfaceMs, (unsigned long long)sm.frames, frameMean, sm.maxFrame * 1000.0, lagMean, sm.maxLag,
previewMean, sm.maxPreviewLag, releaseMs, releaseDoneMs);
// tools/bench_strokes.sh reads this line.
- std::printf("bench: %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f\n", frameMean, sm.maxFrame * 1000.0, lagMean, previewMean,
- sm.pressMs, sm.firstSurfaceMs, releaseMs, releaseDoneMs);
+ std::printf("bench: %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f\n", frameMean, sm.maxFrame * 1000.0, lagMean,
+ previewMean, sm.pressMs, sm.firstSurfaceMs, releaseMs, releaseDoneMs, framePct(0.95), framePct(0.99));
if (popProbe_ && popCommits_ > 0)
std::printf("pop: when the solver's dabs replace their preview the view changes by %.3f on average "
"(worst %.3f); without the preview those dabs would change it by %.3f (%llu commits)\n",
popWith_ / double(popCommits_), popWorst_, popWithout_ / double(popCommits_),
(unsigned long long)popCommits_);
std::fflush(stdout);
- if (verify && !verifyStroke(sm.before, sm.dabs)) return 1;
+ const MeasureView now{camera_.distance, camera_.aspect, canvasRect().w, canvasRect().h};
+ if (verify && !(now == sm.view))
+ std::printf("verify: skipped (the view changed during the stroke: distance %.3f -> %.3f, canvas %.0fx%.0f -> %.0fx%.0f)\n",
+ double(sm.view.distance), double(now.distance), double(sm.view.w), double(sm.view.h), double(now.w), double(now.h));
+ else if (verify && !verifyStroke(sm.before, sm.dabs)) return 1;
// The test (ui_stroke_path, a light sphere): every dab placed, all of them on the circle.
const float spacing = std::max(1.0f, radiusPx_ * 0.15f);
const double expected = 4.0 * 3.14159265358979 * double(sm.r) / double(spacing);
@@ -912,6 +940,7 @@ int App::run() {
const double now = seconds();
sm.maxFrame = std::max(sm.maxFrame, now - sm.lastFrame);
sm.sumFrames += now - sm.lastFrame;
+ sm.frameTimes.push_back(now - sm.lastFrame);
sm.lastFrame = now;
++sm.frames;
if (!sm.dabs.empty()) { // how far round the circle the brush is behind the pointer, on screen now
@@ -1208,7 +1237,7 @@ void App::onMouseUp() {
// Predictive strokes: letting go doesn't wait for the dabs still to place; the solver carries on and
// pumpStroke ends the stroke once they are on screen (anything that needs the document first ends it).
strokeFinishing_ = true;
- if (!solverBusy() && dabQueue_.empty()) endStroke();
+ // (even with nothing left to place: the stroke's end work runs on the solver thread, pumpStroke)
} else if (drag_ == Drag::Stroke) endStroke();
if (drag_ == Drag::MaskCanvas) maskCanvasRelease();
if (drag_ == Drag::SubToolClick) subtoolClickRelease();
@@ -1245,6 +1274,7 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
strokeSculpt_ = !(strokePaint_ && paintMode_);
const BrushRecipe* recipe = strokeRecipe();
haveLastDab_ = false;
+ doc_.sculptor.draftStrokes = draftStrokes() && asyncStrokeAllowed(); // (AsyncStroke.cpp)
if (!doc_.sculptor.beginStroke(doc_.mesh,
!strokeSculpt_ ? std::string("Paint") : recipe ? recipe->name : brushName(strokeBrush_),
strokeSculpt_ ? doc_.activeLayer : -1)) {
diff --git a/src/app/App.h b/src/app/App.h
index c86123da..26a1a58d 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -240,6 +240,7 @@ private:
bool asyncStroke_ = false; // this stroke's dabs go to the solver thread
bool strokeFinishing_ = false; // released: the solver places the last dabs, the UI carries on
bool predictiveStrokes() const; // the preference (and its environment override)
+ bool draftStrokes() const; // Draft Strokes (SF_DRAFT_STROKE=0 / 1 overrides)
bool asyncStrokeAllowed() const; // the stroke beginning now may use the solver thread
bool solverBusy() const;
void solverWait(); // waits for the dabs in flight and commits them
diff --git a/src/app/AsyncStroke.cpp b/src/app/AsyncStroke.cpp
index dd583c6d..987c0e84 100644
--- a/src/app/AsyncStroke.cpp
+++ b/src/app/AsyncStroke.cpp
@@ -64,6 +64,11 @@ void App::StrokeSolver::loop() {
double spent = 0.0;
const SculptTimings before = app.doc_.sculptor.timings;
app.dabView_ = &view;
+ if (finalize) { // a draft stroke's end: every normal and cavity term it touched
+ const auto t0 = std::chrono::steady_clock::now();
+ app.doc_.sculptor.flushDraft(app.doc_.mesh, app.doc_.bvh);
+ spent += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ }
for (const PathDab& d : batch) {
const auto t0 = std::chrono::steady_clock::now();
app.dabAt(d.x, d.y, d.pressure);
@@ -75,6 +80,7 @@ void App::StrokeSolver::loop() {
dabSeconds = batch.empty() ? 0.0 : spent / double(batch.size());
const auto prepStart = std::chrono::steady_clock::now();
uploadReady = prepare && app.renderer_.prepareStrokeUpload(uploadId, app.doc_.mesh, upload, app.doc_.sculptor.strokeCurvature());
+ if (finalize && uploadReady) app.renderer_.refineStrokeBoundsInto(uploadId, app.doc_.mesh, upload);
static const bool log = std::getenv("SF_STROKE_LOG") != nullptr;
if (log) {
const SculptTimings& t = app.doc_.sculptor.timings;
@@ -105,6 +111,14 @@ bool App::predictiveStrokes() const {
return env >= 0 ? env == 1 : uiPrefs_.predictiveStrokes;
}
+bool App::draftStrokes() const {
+ static const int env = [] {
+ const char* v = std::getenv("SF_DRAFT_STROKE");
+ return v && *v ? (*v == '0' ? 0 : 1) : -1;
+ }();
+ return predictiveStrokes() && (env >= 0 ? env == 1 : uiPrefs_.draftStrokes);
+}
+
bool App::asyncStrokeAllowed() const {
// Sculpt strokes of queued dabs only: Move, Snake Hook and the drag strokes work in strokeTo itself; painting,
// masking and dynamic topology (which changes the layout the renderer packs for) stay in the frame loop.
@@ -212,6 +226,20 @@ void App::pumpStroke() {
if (!solver_) solver_ = std::make_unique<StrokeSolver>(*this);
if (solver_->busy()) return;
if (solver_->done) commitSolverBatch();
+ if (dabQueue_.empty() && strokeFinishing_ && !solver_->finalize) {
+ // Released: the stroke's end work on the solver thread too (a draft's normals and cavities, the exact
+ // culling bounds of what it moved), then the end.
+ StrokeSolver& s = *solver_;
+ s.batch.clear();
+ s.finalize = true;
+ s.view.camera = camera_;
+ s.view.canvas = canvasRect();
+ s.view.probe = nullptr;
+ s.uploadId = doc_.activeSubtoolInfo().id;
+ s.prepare = &displayedMesh() == &doc_.mesh;
+ s.start();
+ return;
+ }
if (dabQueue_.empty()) {
if (strokeFinishing_) finishStrokeNow(); // released, and every dab is on the GPU
return;
@@ -226,10 +254,14 @@ void App::pumpStroke() {
s.view.probe = strokeProbe_ ? &s.probe : nullptr;
s.uploadId = doc_.activeSubtoolInfo().id;
s.prepare = &displayedMesh() == &doc_.mesh; // (a previewed LOD shows instead: nothing to pack)
+ renderer_.setDraftNormals(doc_.sculptor.draftActive() ? s.uploadId : 0);
s.start();
}
void App::finishStrokeNow() {
+ if (solver_) solver_->finalize = false;
+ doc_.sculptor.flushDraft(doc_.mesh, doc_.bvh); // (a draft stroke ended here rather than on the solver thread)
+ renderer_.setDraftNormals(0);
if (asyncStroke_) renderer_.refineStrokeBounds(doc_.activeSubtoolInfo().id, displayedMesh()); // (the quick ones)
strokeFinishing_ = false;
asyncStroke_ = false;
@@ -397,15 +429,25 @@ bool App::verifyStroke(uint64_t before, const std::vector<glm::vec2>& dabs) {
const bool wasAsync = asyncStroke_;
asyncStroke_ = false;
haveLastDab_ = false;
- doc_.syncBvh();
- doc_.sculptor.beginStroke(doc_.mesh, brushName(strokeBrush_), doc_.activeLayer);
- for (const glm::vec2& d : dabs) dabAt(d.x, d.y, 1.0f);
- UndoRecord r = doc_.sculptor.endStroke();
- const uint64_t replay = meshStateHash(doc_.mesh);
+ const auto place = [&] {
+ doc_.syncBvh();
+ haveLastDab_ = false;
+ doc_.sculptor.draftStrokes = draftStrokes(); // (the measured stroke is one the solver thread takes)
+ doc_.sculptor.beginStroke(doc_.mesh, brushName(strokeBrush_), doc_.activeLayer);
+ for (const glm::vec2& d : dabs) dabAt(d.x, d.y, 1.0f);
+ doc_.sculptor.flushDraft(doc_.mesh, doc_.bvh);
+ doc_.undo.push(doc_.sculptor.endStroke());
+ return meshStateHash(doc_.mesh);
+ };
+ const uint64_t replay = place();
+ // And once more: the frame-loop path against itself (anything here that isn't deterministic shows).
+ runCommand("undo", {});
+ const uint64_t again = place();
asyncStroke_ = wasAsync;
const bool same = replay == after;
- std::printf("verify: undo %s; %zu dabs replayed without the solver thread: %s\n", undoOk ? "restores the mesh" : "DIFFERS",
- dabs.size(), same ? "identical" : "DIFFERENT");
+ std::printf("verify: undo %s; %zu dabs replayed without the solver thread: %s (replayed twice: %s)\n",
+ undoOk ? "restores the mesh" : "DIFFERS", dabs.size(), same ? "identical" : "DIFFERENT",
+ again == replay ? "identical" : "DIFFERENT");
std::fflush(stdout);
return undoOk && same;
}
diff --git a/src/app/AsyncStroke.h b/src/app/AsyncStroke.h
index bd83052f..5734af48 100644
--- a/src/app/AsyncStroke.h
+++ b/src/app/AsyncStroke.h
@@ -33,6 +33,7 @@ struct App::StrokeSolver {
double dabSeconds = 0.0; // the batch's mean cost per dab
uint32_t uploadId = 0; // the active SubTool's renderer slot
bool prepare = true; // pack the upload on the thread
+ bool finalize = false; // before the batch: Sculptor::flushDraft (a draft stroke's end)
Renderer::StrokeUpload upload;
bool uploadReady = false; // packed (else the main thread's syncScene sends the change)
bool done = false; // a finished batch waits for its commit
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 8fc24b1e..8662a010 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -57,6 +57,7 @@ Json toJson(const UiPrefs& p) {
j.set("fastNavigation", p.fastNavigation);
j.set("multithreading", p.multithreading);
j.set("predictiveStrokes", p.predictiveStrokes);
+ j.set("draftStrokes", p.draftStrokes);
j.set("dyntopoConstantDetail", p.dyntopoConstantDetail);
j.set("flatShading", p.flatShading);
j.set("background", std::string(p.gradientBackground ? "gradient" : "flat"));
@@ -93,6 +94,7 @@ void fromJson(const Json& j, UiPrefs& p) {
p.fastNavigation = j["fastNavigation"].asBool(p.fastNavigation);
p.multithreading = j["multithreading"].asBool(p.multithreading);
p.predictiveStrokes = j["predictiveStrokes"].asBool(p.predictiveStrokes);
+ p.draftStrokes = j["draftStrokes"].asBool(p.draftStrokes);
p.dyntopoConstantDetail = j["dyntopoConstantDetail"].asBool(p.dyntopoConstantDetail);
p.flatShading = j["flatShading"].asBool(p.flatShading);
if (j["background"].isString()) p.gradientBackground = j["background"].asString() != "flat";
diff --git a/src/app/Config.h b/src/app/Config.h
index faf2f3d1..8df2d7e9 100644
--- a/src/app/Config.h
+++ b/src/app/Config.h
@@ -43,6 +43,10 @@ struct UiPrefs {
// Sculpt strokes solved on their own thread with a GPU preview of the dabs still to come, the cursor and the
// stroke's head predicted a frame ahead (app/AsyncStroke.cpp). Off: the dabs are placed in the frame loop.
bool predictiveStrokes = true;
+ // Draft strokes (with predictive strokes): dabs move the vertices only; the normals, cavities and culling
+ // bounds of what they touched are worked out once, when the pen lifts (Sculptor::draftStrokes). Off by
+ // default; meant for laptops and battery (a hardware tier will turn it on).
+ bool draftStrokes = false;
// Dynamic topology (Draw palette): false = the detail follows the brush size on screen (Sculptris Pro);
// true = one detail size for the whole mesh.
bool dyntopoConstantDetail = false;
diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cpp
index 6ed6ff9e..d44d80ab 100644
--- a/src/app/PanelPerformance.cpp
+++ b/src/app/PanelPerformance.cpp
@@ -94,6 +94,16 @@ void App::registerPerformanceUiActions() {
"the dabs still being worked out as a preview on the surface, with the cursor and the stroke's head drawn "
"where the pen is about to be. On a heavy mesh the surface moves under the pen at once and lifting the pen "
"is instant. The finished sculpt is exactly the same either way.");
+ add("perf.draft_strokes", "Draft Strokes",
+ [this] {
+ uiPrefs_.draftStrokes = !uiPrefs_.draftStrokes;
+ status_ = uiPrefs_.draftStrokes ? "Draft strokes on" : "Draft strokes off";
+ },
+ [this] { return uiPrefs_.draftStrokes; },
+ "With Predictive Strokes: while you sculpt, the brush only moves the surface and shades the moved part from "
+ "its facets; the smooth shading, the cavities and the rest are worked out once when you lift the pen. "
+ "Lighter on laptops and on battery. Brushes that follow the surface's direction (Inflate, the plane brushes) "
+ "use its direction from the stroke's start, so the result can differ slightly from a full stroke.");
}
void App::applyPerformancePrefs() { ThreadPool::shared().setSerial(!uiPrefs_.multithreading); }
@@ -148,6 +158,9 @@ void App::drawPerformanceSection() {
bool predictive = uiPrefs_.predictiveStrokes;
if (ImGui::Checkbox("Predictive Strokes", &predictive)) actions_.find("perf.predictive_strokes")->run();
ui::HelpAction(*this, "perf.predictive_strokes");
+ bool draft = uiPrefs_.draftStrokes;
+ if (ImGui::Checkbox("Draft Strokes", &draft)) actions_.find("perf.draft_strokes")->run();
+ ui::HelpAction(*this, "perf.draft_strokes");
// --- Threads ---
bool threads = !ThreadPool::shared().serial();
diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cpp
index 84c94f35..14346481 100644
--- a/src/core/Mesh.cpp
+++ b/src/core/Mesh.cpp
@@ -584,6 +584,22 @@ void Mesh::clearDirty() {
void Mesh::recomputeAllNormals() {
// Area-weighted face normals summed in triangle order (each vertex's sum in the same order as
// updateNormals adds them); the faces and the normalising run in parallel.
+ const bool listed = vtOffsets_.size() == positions.size() + 1 && (!vtEnds_.empty() || vtList_.size() == triangles.size() * 3);
+ if (implicit_ || listed) {
+ // With the topology: each vertex sums its own triangles (listed in ascending order, so in the same order
+ // as the serial sum below, and to the same bits), in parallel, without a face array (12 bytes a triangle).
+ normals.resize(positions.size());
+ poolFor(positions.size(), [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) {
+ glm::vec3 sum(0.0f);
+ for (uint32_t t : vertexTriangles(uint32_t(v))) sum += faceNormal(positions, triangles[t]);
+ const float len = glm::length(sum);
+ normals[v] = len > 1e-20f ? sum / len : glm::vec3(0, 1, 0);
+ }
+ }, 1 << 14);
+ markAllDirty();
+ return;
+ }
std::vector<glm::vec3> faces(triangles.size());
poolFor(triangles.size(), [&](size_t b, size_t e) {
for (size_t i = b; i < e; ++i) faces[i] = faceNormal(positions, triangles[i]);
@@ -623,6 +639,12 @@ void Mesh::updateNormalsAround(size_t count, size_t grain, const std::function<v
finishNormals(curvature);
}
+void Mesh::markDirtyAround(size_t count, size_t grain, const std::function<void(size_t, size_t, IndexBits&)>& fill) {
+ if (!beginNormalSet()) return;
+ normalBits_.insertParallel(count, grain, fill);
+ finishNormals(nullptr, false);
+}
+
float Mesh::curvatureAt(uint32_t v) const {
if (v >= positions.size() || v >= normals.size()) return 0.0f;
const glm::vec3 p = positions[v];
@@ -650,7 +672,7 @@ bool Mesh::beginNormalSet() {
return true;
}
-void Mesh::finishNormals(float* curvature) {
+void Mesh::finishNormals(float* curvature, bool computeNormals) {
// Listing the set also marks it dirty: its words are laid out like dirtyBits, and each 2048-vertex dirty
// block lies in one of its chunks (so no two threads write the same word).
static_assert(IndexBits::kChunk % kDirtyBlock == 0);
@@ -662,6 +684,7 @@ void Mesh::finishNormals(float* curvature) {
if (scratchVerts_.empty()) return;
dirtyBegin = std::min(dirtyBegin, scratchVerts_.front());
dirtyEnd = std::max(dirtyEnd, scratchVerts_.back() + 1);
+ if (!computeNormals) return;
poolFor(scratchVerts_.size(), [&](size_t b, size_t e) {
for (size_t i = b; i < e; ++i) {
// The faces around later vertices are scattered over memory: ask for them ahead (their triangles
diff --git a/src/core/Mesh.h b/src/core/Mesh.h
index 9902268c..4c9fa8c1 100644
--- a/src/core/Mesh.h
+++ b/src/core/Mesh.h
@@ -213,6 +213,9 @@ public:
// gives the corners of the BVH leaves its query listed, which is cheaper than every moved vertex's ring.
void updateNormalsAround(size_t count, size_t grain, const std::function<void(size_t, size_t, IndexBits&)>& fill,
float* curvature = nullptr);
+ // Marks the vertices fill() lists dirty for the GPU without recomputing their normals (a draft stroke, whose
+ // normals wait for its end: Sculptor::draftStrokes).
+ void markDirtyAround(size_t count, size_t grain, const std::function<void(size_t, size_t, IndexBits&)>& fill);
// The renderer's cavity term at `v` (render/Clusters.h): how far the average of the other corners of its
// triangles sits above the vertex along its normal (> 0 in a crease), over their mean distance. Each
// neighbour of an inner vertex of a manifold is the corner of two of its triangles, so this is the average
@@ -288,7 +291,7 @@ public:
private:
void finishTopology();
bool beginNormalSet(); // updateNormals: room for the set (false: no topology)
- void finishNormals(float* curvature); // ... then each member's normal (and curvatureAt)
+ void finishNormals(float* curvature, bool computeNormals = true); // ... then each member's normal (and curvatureAt)
IndexRing implicitTriangles(uint32_t v) const;
IndexRing implicitNeighbors(uint32_t v) const;
diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cpp
index 75c082b7..8c1f892b 100644
--- a/src/core/Sculpt.cpp
+++ b/src/core/Sculpt.cpp
@@ -206,6 +206,9 @@ bool Sculptor::beginStroke(const Mesh& mesh, std::string label, int layer) {
colored_.assign(words, 0);
}
++strokeId_;
+ draft_ = draftStrokes && !dyntopo.enabled;
+ draftStrokes = false; // (asked for per stroke)
+ draftLeaves_.clear();
strokeDiagonal_ = 0.0f;
lastRemesh_ = false;
topologyHeld_ = false;
@@ -431,6 +434,17 @@ void Sculptor::displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::spa
}, kBlock);
}
+void Sculptor::flushDraft(Mesh& mesh, const BVH& bvh) {
+ if (!draft_ || draftLeaves_.empty()) return;
+ std::sort(draftLeaves_.begin(), draftLeaves_.end());
+ draftLeaves_.erase(std::unique(draftLeaves_.begin(), draftLeaves_.end()), draftLeaves_.end());
+ dabLeaves_.swap(draftLeaves_);
+ draft_ = false; // (updateDabNormals in full)
+ updateDabNormals(mesh, bvh);
+ draft_ = true;
+ draftLeaves_.clear();
+}
+
UndoRecord Sculptor::endStroke() {
if (dynTopo_.active()) {
Mesh& mesh = *dynTopo_.strokeMesh();
@@ -663,7 +677,33 @@ void Sculptor::finishDab(Mesh& mesh, BVH& bvh, std::chrono::steady_clock::time_p
// as it remeshed, so there the rings are used.
void Sculptor::updateDabNormals(Mesh& mesh, const BVH& bvh) {
auto clock = std::chrono::steady_clock::now();
- if (curvature_.size() != mesh.vertexCount()) curvature_.assign(mesh.vertexCount(), 0.0f);
+ if (curvature_.size() != mesh.vertexCount() || curvatureMesh_ != &mesh) {
+ curvature_.assign(mesh.vertexCount(), 0.0f);
+ curvatureFilled_ = false;
+ curvatureMesh_ = &mesh;
+ }
+ if (draft_ && !dynTopo_.active() && !dabLeaves_.empty()) {
+ // A draft: the vertices go up with the normals and cavity terms they had (filled in once for the mesh).
+ if (!curvatureFilled_) {
+ poolFor(mesh.vertexCount(), [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) curvature_[v] = mesh.curvatureAt(uint32_t(v));
+ }, 8192);
+ curvatureFilled_ = true;
+ }
+ mesh.markDirtyAround(dabLeaves_.size(), 64, [&](size_t b, size_t e, IndexBits& set) {
+ for (size_t i = b; i < e; ++i)
+ for (uint32_t t : bvh.leafTriangles(dabLeaves_[i])) {
+ const glm::uvec3& tri = mesh.triangles[t];
+ set.insertLocal(tri.x);
+ set.insertLocal(tri.y);
+ set.insertLocal(tri.z);
+ }
+ });
+ draftLeaves_.insert(draftLeaves_.end(), dabLeaves_.begin(), dabLeaves_.end());
+ dabLeaves_.clear();
+ timings.normalsMs += lapMs(clock);
+ return;
+ }
if (dynTopo_.active() || dabLeaves_.empty()) {
mesh.updateNormals(dabVerts_, curvature_.data());
} else {
diff --git a/src/core/Sculpt.h b/src/core/Sculpt.h
index 0057166c..f4fe0d17 100644
--- a/src/core/Sculpt.h
+++ b/src/core/Sculpt.h
@@ -130,6 +130,16 @@ public:
// stroke. Entries of other vertices are stale.
const float* strokeCurvature() const { return active_ && !curvature_.empty() ? curvature_.data() : nullptr; }
+ // Draft strokes (Preferences > Performance > Draft Strokes): when set before beginStroke (it asks once), dabs move the vertices
+ // and refit the BVH but leave the normals and the cavity term as they were (the brushes that read normals see
+ // the stroke-start ones, so the result differs slightly from a full stroke); the vertices are only marked
+ // for the GPU. flushDraft works out every normal and cavity term the stroke touched, once (the app calls
+ // it before endStroke). Not with dynamic topology.
+ bool draftStrokes = false;
+ bool draftActive() const { return draft_; }
+ bool draftPending() const { return draft_ && !draftLeaves_.empty(); }
+ void flushDraft(Mesh& mesh, const BVH& bvh);
+
// Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).
static std::vector<glm::vec3> mirrors(Symmetry sym);
@@ -175,6 +185,10 @@ private:
std::vector<uint32_t> verts_, dabVerts_; // one mirror's vertices; every mirror's (for the normals)
std::vector<uint32_t> dabLeaves_; // the BVH leaves every mirror's query listed (the normals' set)
std::vector<float> curvature_; // strokeCurvature
+ bool curvatureFilled_ = false; // every entry current (a draft stroke packs them as they are)
+ const Mesh* curvatureMesh_ = nullptr; // the mesh curvature_ is for
+ bool draft_ = false; // this stroke is a draft
+ std::vector<uint32_t> draftLeaves_; // the BVH leaves its dabs touched (flushDraft)
std::vector<glm::vec3> scratch_;
std::vector<float> weights_, influence_;
std::vector<uint8_t> firstTouch_;
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index c5c5f883..2adaf9bc 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -2419,25 +2419,33 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS
if (cullBackfaces_) gl::Enable(GL_CULL_FACE);
// The predictive preview (render/Ghost.h): the clusters a ghost dab reaches draw with the GHOST program, the
// rest as usual (most of the mesh, which then doesn't pay for the preview).
- ghostClusters_.clear();
- if (ghost) {
+ // A draft stroke (Sculptor::draftStrokes) left the normals of the clusters it moved as they were: those draw
+ // with normals from the moved triangles themselves (the FLAT program's per-pixel face normals) until it ends.
+ const bool draft = active && s.id == draftId_ && !perTriangle && s.looseMark.size() == s.bounds.size();
+ for (auto& list : extraClusters_) list.clear();
+ if (ghost || draft) {
size_t kept = 0;
for (uint32_t c : drawClusters_) {
const ClusterBounds& b = s.bounds[c];
- bool reached = b.radius < 0.0f;
- for (size_t i = 0; i < ghost_.dabs.size() && !reached; ++i)
- reached = glm::distance(b.center, ghost_.dabs[i].center) < b.radius + ghost_.dabs[i].radius * 1.05f;
- if (reached) ghostClusters_.push_back(c);
+ bool reached = false;
+ if (ghost) {
+ reached = b.radius < 0.0f;
+ for (size_t i = 0; i < ghost_.dabs.size() && !reached; ++i)
+ reached = glm::distance(b.center, ghost_.dabs[i].center) < b.radius + ghost_.dabs[i].radius * 1.05f;
+ }
+ const bool rough = draft && s.looseMark[c];
+ if (reached || rough) extraClusters_[(reached ? 1 : 0) | (rough ? 2 : 0)].push_back(c);
else drawClusters_[kept++] = c;
}
drawClusters_.resize(kept);
}
drawClusters(s, drawClusters_, GL_TRIANGLES, Part::Triangles, perTriangle ? p->primBase : -1);
- if (!ghostClusters_.empty()) {
- if (const MeshProgram* pg = meshProgram(features | kGhost)) {
+ for (int k = 1; k < 4; ++k) {
+ if (extraClusters_[k].empty()) continue;
+ if (const MeshProgram* pg = meshProgram(features | ((k & 1) ? kGhost : 0) | ((k & 2) ? kFlat : 0))) {
bind(pg);
- setGhostUniforms(*pg);
- drawClusters(s, ghostClusters_, GL_TRIANGLES, Part::Triangles, perTriangle ? pg->primBase : -1);
+ if (k & 1) setGhostUniforms(*pg);
+ drawClusters(s, extraClusters_[k], GL_TRIANGLES, Part::Triangles, -1);
bind(p);
}
}
@@ -2522,6 +2530,9 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
out.ranges.clear();
out.movedClusters.clear();
out.bounds.clear();
+ out.exactClusters.clear();
+ out.exactBounds.clear();
+ out.regrid = false;
out.packMs = out.boundsMs = 0.0;
const auto clock = std::chrono::steady_clock::now();
MeshSlot* found = nullptr;
@@ -2556,18 +2567,25 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
size_t offset;
};
std::vector<Piece> pieces;
- size_t total = 0;
- for (const auto& [b, e] : runs)
- for (uint32_t c = b; c < e; c += kPiece) {
- const uint32_t ce = std::min(e, c + kPiece);
- pieces.push_back({c, ce, total});
- total += ce - c;
- }
- out.data.resize(total);
+ const auto cut = [&] {
+ pieces.clear();
+ size_t total = 0;
+ for (const auto& [b, e] : runs)
+ for (uint32_t c = b; c < e; c += kPiece) {
+ const uint32_t ce = std::min(e, c + kPiece);
+ pieces.push_back({c, ce, total});
+ total += ce - c;
+ }
+ out.data.resize(total);
+ };
+ cut();
std::atomic<bool> outside{false};
std::vector<uint64_t> hashes(nb * 2, 0); // (written per block, then compared: a failed prepare keeps the old)
std::vector<AABB> boxes(nb);
s.blockBox.resize(nb);
+ PositionGrid grid = s.grid;
+ bool everything = false;
+ const auto pack = [&] {
poolFor(pieces.size(), [&](size_t i0, size_t i1) {
for (size_t pi = i0; pi < i1; ++pi) {
const Piece& pc = pieces[pi];
@@ -2579,7 +2597,7 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
const uint32_t v = order[i];
PackedVertex pv{};
if (v < nv) {
- inside &= packVertex(s.grid, mesh.positions[v], mesh.normals[v], curvature ? curvature[v] : curvatureAt(mesh, v), pv);
+ inside &= packVertex(grid, mesh.positions[v], mesh.normals[v], curvature ? curvature[v] : curvatureAt(mesh, v), pv);
box.expand(mesh.positions[v]);
}
dst[i - pc.begin] = pv;
@@ -2589,7 +2607,7 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
const size_t g = i >> UploadOrder::kBlockShift;
hashes[g * 2] = hp;
hashes[g * 2 + 1] = hn;
- out.blockMoved[g] = s.blockHash[g * 2] != hp;
+ out.blockMoved[g] = everything || s.blockHash[g * 2] != hp;
out.blockChanged[g] = out.blockMoved[g] || s.blockHash[g * 2 + 1] != hn;
boxes[g] = box;
hp = hn = 0;
@@ -2599,9 +2617,21 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
if (!inside) outside.store(true, std::memory_order_relaxed);
}
}, 1, 2);
+ };
+ pack();
if (outside.load()) {
- s.regrid = true; // the next syncScene makes a new grid and sends everything (the mesh stays dirty)
- return false;
+ // A vertex left the position grid: a new one round the mesh, and every vertex packed again, here on this
+ // thread (the GL thread keeps drawing with the old grid and data until the commit swaps both; the
+ // regular sync did this in the frame, a stall of seconds at 33M triangles).
+ grid = PositionGrid::around(meshBounds(mesh));
+ runs.assign(1, {0u, uint32_t(ns)});
+ cut();
+ everything = true;
+ outside = false;
+ pack();
+ if (outside.load()) return false; // (can't happen: the grid holds the mesh)
+ out.regrid = true;
+ out.grid = grid;
}
out.packMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count();
// The changed blocks' GPU ranges and where they are in `data`.
@@ -2662,6 +2692,7 @@ void Renderer::commitStrokeUpload(StrokeUpload& up) {
if (s.id == up.id) found = &s;
if (!found) return;
MeshSlot& s = *found;
+ if (up.regrid) s.grid = up.grid; // (with every vertex, packed on it)
if (!up.ranges.empty()) {
gl::BindBuffer(GL_ARRAY_BUFFER, s.vertexBuffer);
for (const StrokeUpload::Range& r : up.ranges)
@@ -2677,6 +2708,17 @@ void Renderer::commitStrokeUpload(StrokeUpload& up) {
s.proxyStale[up.movedClusters[i]] = 1;
}
s.looseClusters.insert(s.looseClusters.end(), up.movedClusters.begin(), up.movedClusters.end());
+ s.looseMark.resize(s.bounds.size(), 0);
+ for (uint32_t c : up.movedClusters) s.looseMark[c] = 1;
+ }
+ if (up.exact) { // the stroke's end (refineStrokeBoundsInto): exact bounds for every cluster it moved
+ s.bounds.resize(s.order.clusters().size());
+ for (size_t i = 0; i < up.exactClusters.size(); ++i)
+ if (up.exactClusters[i] < s.bounds.size()) s.bounds[up.exactClusters[i]] = up.exactBounds[i];
+ s.looseClusters.clear();
+ std::fill(s.looseMark.begin(), s.looseMark.end(), 0);
+ }
+ if (!up.movedClusters.empty() || up.exact) {
s.box = AABB();
s.volume = 0.0;
for (const ClusterBounds& b : s.bounds) {
@@ -2689,11 +2731,40 @@ void Renderer::commitStrokeUpload(StrokeUpload& up) {
}
}
+void Renderer::setDraftNormals(uint32_t id) { draftId_ = id; }
+
+void Renderer::refineStrokeBoundsInto(uint32_t id, const Mesh& mesh, StrokeUpload& up) {
+ up.exact = false;
+ up.exactClusters.clear();
+ up.exactBounds.clear();
+ MeshSlot* found = nullptr;
+ for (MeshSlot& s : slots_)
+ if (s.id == id) found = &s;
+ if (!found) return;
+ MeshSlot& s = *found;
+ const size_t nc = s.order.clusters().size();
+ if (s.fresh || mesh.topologyDirty || s.bounds.size() != nc) return;
+ // Those moved before and those this upload moves (the main thread doesn't touch the list while we run).
+ up.exactClusters = s.looseClusters;
+ up.exactClusters.insert(up.exactClusters.end(), up.movedClusters.begin(), up.movedClusters.end());
+ std::sort(up.exactClusters.begin(), up.exactClusters.end());
+ up.exactClusters.erase(std::unique(up.exactClusters.begin(), up.exactClusters.end()), up.exactClusters.end());
+ while (!up.exactClusters.empty() && up.exactClusters.back() >= nc) up.exactClusters.pop_back();
+ up.exactBounds.resize(up.exactClusters.size());
+ poolFor(up.exactClusters.size(), [&](size_t i0, size_t i1) {
+ for (size_t i = i0; i < i1; ++i) up.exactBounds[i] = clusterBounds(mesh, s.order, up.exactClusters[i]);
+ }, 1, 2);
+ up.exact = true;
+ up.ready = true;
+}
+
void Renderer::refineStrokeBounds(uint32_t id, const Mesh& mesh) {
MeshSlot* found = nullptr;
for (MeshSlot& s : slots_)
if (s.id == id) found = &s;
- if (!found || found->looseClusters.empty()) return;
+ if (!found) return;
+ std::fill(found->looseMark.begin(), found->looseMark.end(), 0);
+ if (found->looseClusters.empty()) return;
MeshSlot& s = *found;
std::sort(s.looseClusters.begin(), s.looseClusters.end());
s.looseClusters.erase(std::unique(s.looseClusters.begin(), s.looseClusters.end()), s.looseClusters.end());
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index 08301e65..cdd04f98 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -129,6 +129,11 @@ public:
std::vector<ClusterBounds> bounds; // of movedClusters
std::vector<uint8_t> blockChanged, blockMoved; // scratch, per block
double packMs = 0.0, boundsMs = 0.0; // where prepare's time went
+ bool regrid = false; // every vertex, packed on a new grid
+ PositionGrid grid;
+ bool exact = false; // refineStrokeBoundsInto: exact bounds to set
+ std::vector<uint32_t> exactClusters;
+ std::vector<ClusterBounds> exactBounds;
size_t bytes() const { return data.size() * sizeof(PackedVertex); }
};
// `curvature` (optional, by vertex): the cavity term of every vertex the mesh marked dirty, already worked
@@ -139,6 +144,12 @@ public:
// packing finds anyway, without the normal cone, so they are never culled as facing away); at the stroke's
// end this works out the exact ones (GL thread, the mesh no longer changing).
void refineStrokeBounds(uint32_t id, const Mesh& mesh);
+ // A draft stroke on SubTool `id` (0: none): the clusters its uploads moved draw with per-pixel face normals
+ // (theirs are stale) until refineStrokeBounds.
+ void setDraftNormals(uint32_t id);
+ // refineStrokeBounds on the solver thread at a stroke's end, after prepareStrokeUpload: the exact bounds go
+ // into `up` and commitStrokeUpload sets them.
+ void refineStrokeBoundsInto(uint32_t id, const Mesh& mesh, StrokeUpload& up);
// Bytes of GPU buffers and textures the mesh slots hold.
size_t gpuBytes() const;
@@ -221,6 +232,7 @@ private:
// Clusters whose culling bounds a stroke upload set from blockBox (a sphere round the box, no normal cone,
// the old volume): refineStrokeBounds makes them exact.
std::vector<uint32_t> looseClusters;
+ std::vector<uint8_t> looseMark; // per cluster: in looseClusters
size_t bytes[8] = {}; // GPU sizes: vertices, indices, lines, colours, mask, groups, prims, uvs + tangents
// Dynamic topology (Mesh::changedTriangles, core/Dyntopo.h): the clusters whose triangles changed since
@@ -294,7 +306,8 @@ private:
std::vector<const void*> drawOffsets_;
std::vector<GLint> drawBases_;
std::vector<uint32_t> drawClusters_;
- std::vector<uint32_t> ghostClusters_; // drawSlot: the clusters a ghost dab reaches
+ std::vector<uint32_t> extraClusters_[4]; // drawSlot: clusters a ghost dab reaches (1), a draft moved (2), both
+ uint32_t draftId_ = 0; // setDraftNormals
bool cullBackfaces_ = false; // the last cull(): back faces can't show (so the GPU may skip them too)
std::vector<uint32_t> cullScratch_;
size_t lastDrawn_ = 0;
diff --git a/tools/bench_strokes.sh b/tools/bench_strokes.sh
index c5d5c0c2..5cfe82a0 100644
--- a/tools/bench_strokes.sh
+++ b/tools/bench_strokes.sh
@@ -63,17 +63,17 @@ for size in "${sizeList[@]}"; do
fi
label=$([ "$b" = 0 ] && echo A || echo B)
out=$(env ${envs[@]+"${envs[@]}"} ${own[@]+"${own[@]}"} "$bin" --run "$scene" --measure-stroke "$seconds,$radius" 2>&1 || true)
- line=$(printf '%s\n' "$out" | grep -A3 '^Stroke' || true)
+ line=$(printf '%s\n' "$out" | grep -E '^Stroke|^ (off|press|brush|release|frame)' || true)
echo "== ${size}M $label run $i (${bins[$b]})"
printf '%s\n' "$line"
- # The machine-readable line: frames mean, worst, surface lag mean, preview lag mean, press, release.
+ # The machine-readable line: frames mean, worst, surface lag, preview lag, press, first surface, release, until done, p95, p99.
printf '%s\n' "$out" | sed -n "s/^bench: /$size $label /p" >>"$results"
done
done
done
echo
-echo "Means (ms / px): size, binary, frame mean, frame worst, surface lag, preview lag, press, first surface, release, release until done"
+echo "Means (ms / px): size, binary, frame mean, frame worst, surface lag, preview lag, press, first surface, release, release until done, frame p95, frame p99"
awk '{ k = $1 " " $2; n[k]++; for (i = 3; i <= NF; i++) s[k, i] += $i; nf[k] = NF }
END { for (k in n) { printf "%-6s", k; for (i = 3; i <= nf[k]; i++) printf " %8.1f", s[k, i] / n[k]; printf " (%d runs)\n", n[k] } }' \
"$results" | sort -n