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.

UV Pack: fast, in the background, and no mirrored or overlapping islands

islandmedbd06416bdd0e
diff --git a/changes/fix-uv-pack-speed.md b/changes/fix-uv-pack-speed.md
new file mode 100644
index 00000000..035fb6c7
--- /dev/null
+++ b/changes/fix-uv-pack-speed.md
@@ -0,0 +1,21 @@
+---
+whats_new: **Faster Pack**: **UV Editor > Pack** across a UDIM grid takes well under a second on most models (it
+ could freeze the app for half a minute), runs in the background with a progress bar and **Cancel**, and lays islands
+ out tighter. Unwrap runs in the background too.
+fixed: UV Editor > Pack froze the app on UDIM grids (about 18 s for a 10 x 2 grid on the lion head on a laptop, 11 s
+ for 4 x 3): the shape packer's search now runs several densities at once, coarse first, stops as soon as an island
+ can't be kept whole, and keeps its quarter-resolution layout instead of packing everything again at full size.
+ 10 x 2 on the lion: 18 s -> 0.04 s. Pack, Pack at Density and every Unwrap now run on a worker thread with a
+ progress bar and Cancel under the view.
+fixed: Packing could shrink some islands and lay them over their neighbours: the shape packer's quarter turns mirror
+ an island, which the fit back onto the island couldn't follow. Islands are now only turned to their smallest box
+ first; layouts are up to 6% denser and no longer overlap.
+fixed: Pack's status line could report more than 100% of the space used (an island bigger than a tile is shrunk to
+ fit one); it is now measured.
+testers:
+ - Any OS: open a detailed model (40k+ triangles, e.g. a head), UV Editor (Alt+U), Unwrap; set Columns 10, Rows 2, click Pack: a progress
+ bar shows briefly, the window keeps drawing, the islands land in the grid, Ctrl+Z puts them back.
+ - Any OS: Auto Seams, Unwrap, then Pack with a 10 x 2 grid and click Cancel under the view while it runs: "Pack
+ cancelled", the UVs stay as they were.
+---
+Found by slowtests (ui_uv_editor). Numbers and shots in REPORT.md.
diff --git a/src/app/App.h b/src/app/App.h
index ce5edfe2..5ce18d71 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -1003,7 +1003,7 @@ private:
const MeshOverlay* uvEditorOverlay(uint32_t part); // what syncScene hands the renderer for the model
bool uvEditorBusy() const;
// UI test values: uv_editor_open, uv_islands, uv_seams, uv_selected, uv_select_mode, uv_pins, uv_tiles,
- // uv_stretch_x1000, uv_flipped_x1000, uv_density, uv_max_u, uv_unwrapping, uv_unwraps, uv_tool,
+ // uv_stretch_x1000, uv_flipped_x1000, uv_density, uv_max_u, uv_unwrapping, uv_unwraps, uv_packs, uv_tool,
// uv_view_triangles, uv_overlay, uv_pack_columns, uv_pack_rows (the Pack fields); NaN for other names.
double uvEditorTestValue(const std::string& name);
std::shared_ptr<struct UvEditorState> uvEditor_;
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index 094a3375..3961e727 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -2394,16 +2394,22 @@ constexpr Entry kSimplifiedChinese[] = {
{"Unwrap with the chosen method: the selected faces (fitted where they were), or the whole Part (packed). Least "
"Stretch keeps angles and lengths along the marked seams; Conformal keeps angles; By Face Groups cuts along the "
"face group borders too; Planar projects each piece; Unfold flattens the current islands again in place, "
- "keeping pins; Auto Seams finds its own. Closed pieces get cut automatically. Big meshes unwrap in the "
- "background.",
+ "keeping pins; Auto Seams finds its own. Closed pieces get cut automatically. Runs in the background (Cancel "
+ "under the view stops it).",
"以所选方法展开:所选的面(在原位拟合),或整个部件(并打包)。Least Stretch 沿标记的接缝保留角度与长度"
";Conformal 保留角度;By Face Groups 也沿面组边界切割;Planar 投影每个区块;Unfold 在原位重新摊平当前岛并保留"
- "固定;Auto Seams 自行找出接缝。封闭的区块会自动切开。大型网格会在后台展开。"},
+ "固定;Auto Seams 自行找出接缝。封闭的区块会自动切开。在后台运行(视图下方的取消可停止)。"},
{"Pack", "打包"},
{"Pack the selected islands (or all) as large as they fit into the 0-1 tile, or across the Columns x Rows grid of "
- "UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them.",
+ "UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them. "
+ "Runs in the background (Cancel under the view stops it).",
"将所选的岛(或全部)以能放下的最大尺寸打包到 0-1 图块,或打包到列数 x 行数的 UDIM 图块格中:旋转到最小包围框,缩"
- "放到相同纹素密度,并保留其间的边距。"},
+ "放到相同纹素密度,并保留其间的边距。在后台运行(视图下方的取消可停止)。"},
+ {"Packing...", "正在打包..."},
+ {"Packing: %d%%", "正在打包:%d%%"},
+ {"Unwrapping...", "正在展开..."},
+ {"Unwrapping: %d%%", "正在展开:%d%%"},
+ {"Stop the Unwrap or Pack that is running; the UVs stay as they are.", "停止正在运行的展开或打包;UV 维持原样。"},
{"Mark Seam", "标记接缝"},
{"Mark the selected edges (or the border of the selected faces) as seams: Unwrap cuts there.",
"将所选的边(或所选面的边界)标记为接缝:展开时会在此切开。"},
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index 43f863c4..184e78a8 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -2767,19 +2767,25 @@ constexpr Entry kSpanish[] = {
{"Unwrap with the chosen method: the selected faces (fitted where they were), or the whole Part (packed). Least "
"Stretch keeps angles and lengths along the marked seams; Conformal keeps angles; By Face Groups cuts along the "
"face group borders too; Planar projects each piece; Unfold flattens the current islands again in place, "
- "keeping pins; Auto Seams finds its own. Closed pieces get cut automatically. Big meshes unwrap in the "
- "background.",
+ "keeping pins; Auto Seams finds its own. Closed pieces get cut automatically. Runs in the background (Cancel "
+ "under the view stops it).",
"Desenvuelve con el método elegido: las caras seleccionadas (ajustadas donde estaban), o toda la Pieza "
"(empaquetada). Least Stretch conserva ángulos y longitudes a lo largo de las costuras marcadas; Conformal "
"conserva ángulos; By Face Groups corta también por los bordes de grupos de caras; Planar proyecta cada pieza; "
"Unfold vuelve a aplanar las islas actuales en su sitio, respetando los anclajes; Auto Seams busca sus propias "
- "costuras. Las piezas cerradas se cortan automáticamente. Las mallas grandes se desenvuelven en segundo plano."},
+ "costuras. Las piezas cerradas se cortan automáticamente. Se ejecuta en segundo plano (Cancelar, bajo la vista, lo detiene)."},
{"Pack", "Empaquetar"},
{"Pack the selected islands (or all) as large as they fit into the 0-1 tile, or across the Columns x Rows grid of "
- "UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them.",
+ "UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them. "
+ "Runs in the background (Cancel under the view stops it).",
"Empaqueta las islas seleccionadas (o todas) lo más grandes que quepan en el mosaico 0-1, o en la rejilla "
"Columnas x Filas de mosaicos UDIM: giradas a su caja más pequeña, escaladas a una densidad de téxeles, con el "
- "margen entre ellas."},
+ "margen entre ellas. Se ejecuta en segundo plano (Cancelar, bajo la vista, lo detiene)."},
+ {"Packing...", "Empaquetando..."},
+ {"Packing: %d%%", "Empaquetando: %d%%"},
+ {"Unwrapping...", "Desenvolviendo..."},
+ {"Unwrapping: %d%%", "Desenvolviendo: %d%%"},
+ {"Stop the Unwrap or Pack that is running; the UVs stay as they are.", "Detiene el Desenvolver o Empaquetar en curso; las UV se quedan como están."},
{"Mark Seam", "Marcar costura"},
{"Mark the selected edges (or the border of the selected faces) as seams: Unwrap cuts there.",
"Marca como costuras las aristas seleccionadas (o el borde de las caras seleccionadas): Desenvolver corta ahí."},
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index b71f139a..e1dd9c28 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -2394,16 +2394,22 @@ constexpr Entry kTraditionalChinese[] = {
{"Unwrap with the chosen method: the selected faces (fitted where they were), or the whole Part (packed). Least "
"Stretch keeps angles and lengths along the marked seams; Conformal keeps angles; By Face Groups cuts along the "
"face group borders too; Planar projects each piece; Unfold flattens the current islands again in place, "
- "keeping pins; Auto Seams finds its own. Closed pieces get cut automatically. Big meshes unwrap in the "
- "background.",
+ "keeping pins; Auto Seams finds its own. Closed pieces get cut automatically. Runs in the background (Cancel "
+ "under the view stops it).",
"以所選方法展開:所選的面(在原位擬合),或整個部件(並排列)。Least Stretch 沿標記的接縫保留角度與長度;"
"Conformal 保留角度;By Face Groups 也沿面群組邊界切割;Planar 投射每個區塊;Unfold 在原位重新攤平目前的島並保留"
- "釘選;Auto Seams 自行找出接縫。封閉的區塊會自動切開。大型網格會在背景中展開。"},
+ "釘選;Auto Seams 自行找出接縫。封閉的區塊會自動切開。在背景中執行(檢視下方的取消可停止)。"},
{"Pack", "排列"},
{"Pack the selected islands (or all) as large as they fit into the 0-1 tile, or across the Columns x Rows grid of "
- "UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them.",
+ "UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them. "
+ "Runs in the background (Cancel under the view stops it).",
"將所選的島(或全部)以能放下的最大尺寸排列到 0-1 圖塊,或排列到欄數 x 列數的 UDIM 圖塊格中:旋轉到最小外框,縮"
- "放到相同紋素密度,並保留其間的邊距。"},
+ "放到相同紋素密度,並保留其間的邊距。在背景中執行(檢視下方的取消可停止)。"},
+ {"Packing...", "正在排列..."},
+ {"Packing: %d%%", "正在排列:%d%%"},
+ {"Unwrapping...", "正在展開..."},
+ {"Unwrapping: %d%%", "正在展開:%d%%"},
+ {"Stop the Unwrap or Pack that is running; the UVs stay as they are.", "停止正在執行的展開或排列;UV 維持原樣。"},
{"Mark Seam", "標記接縫"},
{"Mark the selected edges (or the border of the selected faces) as seams: Unwrap cuts there.",
"將所選的邊(或所選面的邊界)標記為接縫:展開時會在此切開。"},
diff --git a/src/app/PanelUvEditor.cpp b/src/app/PanelUvEditor.cpp
index 039a0b04..5de32b09 100644
--- a/src/app/PanelUvEditor.cpp
+++ b/src/app/PanelUvEditor.cpp
@@ -160,7 +160,7 @@ struct UvEditorState {
// Seams drawn on the model.
std::vector<uint32_t> seamCorners;
uint64_t seamKey = ~uint64_t(0);
- // Background unwrap.
+ // Unwrap and Pack on a worker thread (progress and Cancel under the view).
struct Job {
std::future<bool> done;
std::shared_ptr<std::atomic<float>> progress;
@@ -171,9 +171,18 @@ struct UvEditorState {
size_t triangles = 0;
UvUnwrapMethod method = UvUnwrapMethod::Isometric;
bool keepTexture = true;
+ // Pack: the packed copy, its result and the arguments (for the grid fields); the UVs it started from,
+ // which must still be the Part's when it lands.
+ bool pack = false;
+ std::shared_ptr<Mesh> packed;
+ std::shared_ptr<UvPackResult> packResult;
+ UvPackOptions packOptions;
+ Args packArgs;
+ std::vector<glm::vec2> uvsBefore;
};
std::unique_ptr<Job> job;
int unwraps = 0; // finished (UI tests)
+ int packs = 0; // background packs finished, landed or not (UI tests: uv_packs)
int frames = 0; // Frame clicks and F presses (UI tests: uv_frames)
// The toolbar's items as drawn last frame and the window's right edge (UI tests: uv_toolbar_overlap / _clipped).
struct Box { ImVec2 Min, Max; };
@@ -628,11 +637,6 @@ struct UvEditorUi {
Args a = packArgs();
a["method"] = std::string(uvUnwrapMethodId(method));
a["iterations"] = double(s.iterations);
- if (m.triangleCount() < 60000) { // quick enough to wait for
- run("uv_unwrap", a);
- ++s.unwraps;
- return;
- }
auto job = std::make_unique<UvEditorState::Job>();
job->progress = std::make_shared<std::atomic<float>>(0.0f);
job->cancel = std::make_shared<std::atomic<bool>>(false);
@@ -684,17 +688,57 @@ struct UvEditorUi {
app.status_ = std::string("Unwrapping (") + uvUnwrapMethodLabel(method) + ") " + std::to_string(m.triangleCount()) + " triangles...";
}
+ // Pack (the button, Pack at Density): uv_pack's work on a copy of the Part on a worker thread; the result
+ // lands as uv_pack's undo step and status line would.
+ void pack(Args a) {
+ Mesh& m = mesh();
+ if (s.job || !m.hasUvs()) return;
+ auto job = std::make_unique<UvEditorState::Job>();
+ job->pack = true;
+ job->progress = std::make_shared<std::atomic<float>>(0.0f);
+ job->cancel = std::make_shared<std::atomic<bool>>(false);
+ job->error = std::make_shared<std::string>();
+ job->part = app.doc_.activePartInfo().id;
+ job->triangles = m.triangleCount();
+ job->keepTexture = argBool(a, "keep_texture", true);
+ job->packOptions = uvPackOptions(app.doc_, a);
+ job->packArgs = a;
+ job->uvsBefore = m.uvs;
+ job->packResult = std::make_shared<UvPackResult>();
+ job->packed = std::make_shared<Mesh>();
+ job->packed->positions = m.positions;
+ job->packed->triangles = m.triangles;
+ job->packed->uvs = m.uvs;
+ job->packed->uvFlags = m.uvFlags;
+ std::promise<bool> promise;
+ job->done = promise.get_future();
+ std::thread([promise = std::move(promise), copy = job->packed, sel = app.doc_.uvSelection, o = job->packOptions,
+ progress = job->progress, cancel = job->cancel, result = job->packResult, error = job->error]() mutable {
+ const UvTopology topo = buildUvTopology(*copy);
+ const std::vector<uint8_t> islands = uvSelectedIslands(*copy, topo, sel, true);
+ const bool ok = uvPack(*copy, topo, islands, o, *result, *error, [&](float f) {
+ progress->store(f);
+ return !cancel->load();
+ });
+ promise.set_value(ok);
+ wakeMainLoop();
+ }).detach();
+ s.job = std::move(job);
+ app.status_ = "Packing...";
+ }
+
void poll() {
if (!s.job) return;
if (s.job->done.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
- app.status_ = "Unwrapping: " + std::to_string(int(s.job->progress->load() * 100.0f)) + "%";
+ app.status_ = std::string(s.job->pack ? "Packing: " : "Unwrapping: ") + std::to_string(int(s.job->progress->load() * 100.0f)) + "%";
return;
}
if (app.jobWaitsForStroke()) return; // (the result lands when the stroke ends)
const std::unique_ptr<UvEditorState::Job> job = std::move(s.job);
+ if (job->pack) return landPack(*job);
++s.unwraps;
if (!job->done.get()) {
- app.status_ = *job->error;
+ app.status_ = *job->error == "Unwrap was cancelled" || *job->error == "Cancelled" ? "Unwrap cancelled" : *job->error;
return;
}
int index = -1;
@@ -713,6 +757,29 @@ struct UvEditorUi {
s.dirty = true;
}
+ void landPack(UvEditorState::Job& job) {
+ ++s.packs;
+ if (!job.done.get()) {
+ app.status_ = *job.error == "Cancelled" ? "Pack cancelled: the UVs stay as they were" : *job.error;
+ return;
+ }
+ int index = -1;
+ for (int i = 0; i < app.doc_.partCount(); ++i)
+ if (app.doc_.parts[size_t(i)].id == job.part) index = i;
+ if (index < 0 || app.doc_.partMesh(index).triangleCount() != job.triangles || app.doc_.partMesh(index).uvs != job.uvsBefore) {
+ app.status_ = "Pack skipped: the UVs changed while they were being packed";
+ return;
+ }
+ const App::JobPart part(app, index);
+ UvEditStep step(app.doc_, "Pack UVs", job.keepTexture);
+ mesh().uvs = std::move(job.packed->uvs);
+ const std::string note = step.commit();
+ app.status_ = uvPackNote(*job.packResult, job.packOptions) + note;
+ app.uvEditorChanged();
+ app.uvPackGridUsed(job.packArgs);
+ s.dirty = true;
+ }
+
// --- The 3D tool ----------------------------------------------------------------------------------------
const std::vector<uint32_t>& twins() {
@@ -840,12 +907,14 @@ void App::registerUvEditorActions() {
"Unwrap with the chosen method: the selected faces (fitted where they were), or the whole Part (packed). Least "
"Stretch keeps angles and lengths along the marked seams; Conformal keeps angles; By Face Groups cuts along the "
"face group borders too; Planar projects each piece; Unfold flattens the current islands again in place, keeping "
- "pins; Auto Seams finds its own. Closed pieces get cut automatically. Big meshes unwrap in the background.",
+ "pins; Auto Seams finds its own. Closed pieces get cut automatically. Runs in the background (Cancel under the "
+ "view stops it).",
"uv_unwrap");
- add("uv.pack", "Pack", ICON_LC_PACKAGE, "", [this] { uvUi(*this, uvEditor_).run("uv_pack", uvUi(*this, uvEditor_).packArgs()); },
- nullptr, uvs,
+ add("uv.pack", "Pack", ICON_LC_PACKAGE, "", [this] { uvUi(*this, uvEditor_).pack(uvUi(*this, uvEditor_).packArgs()); },
+ nullptr, [this] { return doc_.mesh.hasUvs() && !(uvEditor_ && uvEditor_->job); },
"Pack the selected islands (or all) as large as they fit into the 0-1 tile, or across the Columns x Rows grid "
- "of UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them.",
+ "of UDIM tiles: turned to their smallest box, scaled to one texel density, with the margin between them. "
+ "Runs in the background (Cancel under the view stops it).",
"uv_pack");
add("uv.seam_mark", "Mark Seam", ICON_LC_SCISSORS, "", [runUv] { runUv("uv_seam", {{"op", std::string("mark")}}); }, nullptr,
selected, "Mark the selected edges (or the border of the selected faces) as seams: Unwrap cuts there.", "uv_seam");
@@ -917,9 +986,9 @@ void App::registerUvEditorActions() {
UvEditorUi u = uvUi(*this, uvEditor_);
Args a = u.packArgs();
a["density"] = double(uvEditor_->targetDensity);
- u.run("uv_pack", a);
+ u.pack(a);
},
- nullptr, uvs,
+ nullptr, [this] { return doc_.mesh.hasUvs() && !(uvEditor_ && uvEditor_->job); },
"Pack at exactly the target texel density, using as many UDIM tiles as it takes (1001, 1002, ..., Columns "
"wide, then the next row up): every island keeps the same texels per unit across the tiles.",
"uv_pack");
@@ -1275,7 +1344,8 @@ void App::drawUvEditor() {
const ImVec2 a(viewMin.x + viewSize.x * 0.25f, viewMin.y + viewSize.y * 0.5f), b(viewMin.x + viewSize.x * 0.75f, a.y + 8 * scale);
dl->AddRectFilled(a, b, IM_COL32(40, 40, 44, 230), 4 * scale);
dl->AddRectFilled(a, ImVec2(a.x + (b.x - a.x) * f, b.y), theme::u32(theme::accent), 4 * scale);
- dl->AddText(ImVec2(a.x, a.y - ImGui::GetTextLineHeight() - 4 * scale), IM_COL32(220, 220, 225, 255), "Unwrapping...");
+ dl->AddText(ImVec2(a.x, a.y - ImGui::GetTextLineHeight() - 4 * scale), IM_COL32(220, 220, 225, 255),
+ tr(s.job->pack ? "Packing..." : "Unwrapping..."));
}
dl->PopClipRect();
dl->AddRect(viewMin, viewMax, IM_COL32(60, 60, 66, 255));
@@ -1300,6 +1370,12 @@ void App::drawUvEditor() {
double(s.meanDensity), u.resolution() / 1024, tiles.c_str());
else
std::snprintf(line, sizeof line, tr("%zu seam edges marked"), uvSeamCount(m));
+ if (s.job) { // (the running Unwrap or Pack: Cancel, and how far it is)
+ if (ImGui::SmallButton((std::string(tr("Cancel")) + "##uvjobcancel").c_str())) s.job->cancel->store(true);
+ ui::HelpText("Cancel", nullptr, "Stop the Unwrap or Pack that is running; the UVs stay as they are.", kPath);
+ ImGui::SameLine();
+ std::snprintf(line, sizeof line, tr(s.job->pack ? "Packing: %d%%" : "Unwrapping: %d%%"), int(s.job->progress->load() * 100.0f));
+ }
ImGui::TextDisabled("%s", line);
}
@@ -1650,7 +1726,8 @@ double App::uvEditorTestValue(const std::string& name) {
if (name == "uv_seams") return double(uvSeamCount(m));
if (name == "uv_selected") return doc_.uvSelection.valid(m) ? double(doc_.uvSelection.count()) : 0.0;
if (name == "uv_select_mode") return double(int(doc_.uvSelection.mode));
- if (name == "uv_unwrapping") return uvEditor_ && uvEditor_->job ? 1.0 : 0.0;
+ if (name == "uv_unwrapping") return uvEditor_ && uvEditor_->job ? 1.0 : 0.0; // (an Unwrap or Pack running)
+ if (name == "uv_packs") return uvEditor_ ? double(uvEditor_->packs) : 0.0;
if (name == "uv_unwraps") return uvEditor_ ? double(uvEditor_->unwraps) : 0.0;
if (name == "uv_pack_columns") return double(uvPackColumns_); // the Pack fields
if (name == "uv_pack_rows") return double(uvPackRows_);
diff --git a/src/core/Uv.h b/src/core/Uv.h
index b113e816..fca718be 100644
--- a/src/core/Uv.h
+++ b/src/core/Uv.h
@@ -200,10 +200,12 @@ struct UvPackResult {
float coverage = 0.0f; // UV area of the islands over the area of the tiles used
float density = 0.0f; // texel density after packing (the mean)
};
+using UvProgress = std::function<bool(float fraction)>; // false: cancel
// Packs the islands in `islands` (all when empty) of `mesh` per `options`. Islands not packed stay where they
-// are (and may then overlap the packed ones). False with `error` when nothing could be packed.
+// are (and may then overlap the packed ones). False with `error` when nothing could be packed, or "Cancelled"
+// when `progress` returned false (the UVs are then as they were). `progress` is called on the calling thread.
bool uvPack(Mesh& mesh, const UvTopology& topo, const std::vector<uint8_t>& islands, const UvPackOptions& options,
- UvPackResult& result, std::string& error);
+ UvPackResult& result, std::string& error, const UvProgress& progress = {});
// Lower-level packing of rectangles into unit tiles (exposed for the tests): sizes in, positions and 90-degree
// turns out; returns the tiles used (0 when something doesn't fit even alone). Rectangles already include
@@ -240,7 +242,6 @@ struct UvUnwrapResult {
size_t extraCuts = 0; // edges cut automatically so closed or looped pieces could flatten
UvPackResult packing;
};
-using UvProgress = std::function<bool(float fraction)>; // false: cancel
// Unwraps `mesh` (its UVs, seams and pins are read; nothing is written). False with `error` on failure or cancel.
bool uvUnwrap(const Mesh& mesh, const UvUnwrapOptions& options, UvUnwrapResult& result, std::string& error,
const UvProgress& progress = {});
diff --git a/src/core/UvCommands.cpp b/src/core/UvCommands.cpp
index 12da169b..e39841d9 100644
--- a/src/core/UvCommands.cpp
+++ b/src/core/UvCommands.cpp
@@ -51,7 +51,16 @@ std::vector<uint32_t> targetCorners(const Document& doc, const UvTopology& topo)
return all;
}
-UvPackOptions packOptions(const Document& doc, const Args& a) {
+// A fit pack that left part of the grid empty says why first (the status line may cut the rest off).
+std::string gridNote(const UvPackResult& p, const UvPackOptions& o) {
+ if (o.density > 0.0f || o.tiles <= 1 || p.tilesUsed <= 0 || p.tilesUsed >= o.tiles) return {};
+ return std::to_string(p.tilesUsed) + " of " + std::to_string(o.tiles) +
+ " tiles used: the largest island limits the scale; Pack at Density fills more. ";
+}
+
+} // namespace
+
+UvPackOptions uvPackOptions(const Document& doc, const Args& a) {
UvPackOptions o;
o.resolution = resolutionArg(doc, a);
o.marginPx = float(std::clamp(argNumber(a, "margin", 8.0), 0.0, 256.0));
@@ -69,14 +78,7 @@ UvPackOptions packOptions(const Document& doc, const Args& a) {
return o;
}
-// A fit pack that left part of the grid empty says why first (the status line may cut the rest off).
-std::string gridNote(const UvPackResult& p, const UvPackOptions& o) {
- if (o.density > 0.0f || o.tiles <= 1 || p.tilesUsed <= 0 || p.tilesUsed >= o.tiles) return {};
- return std::to_string(p.tilesUsed) + " of " + std::to_string(o.tiles) +
- " tiles used: the largest island limits the scale; Pack at Density fills more. ";
-}
-
-std::string packNote(const UvPackResult& p, const UvPackOptions& o) {
+std::string uvPackNote(const UvPackResult& p, const UvPackOptions& o) {
std::string s = gridNote(p, o) + plural(p.islands, "island") + " packed";
if (p.tilesUsed > 1) s += " into " + std::to_string(p.tilesUsed) + " UDIM tiles";
s += ", " + fmt("%.0f", double(p.coverage) * 100.0) + "% of the space used, " + fmt("%.1f", double(p.density)) +
@@ -84,8 +86,6 @@ std::string packNote(const UvPackResult& p, const UvPackOptions& o) {
return s;
}
-} // namespace
-
UvEditStep::UvEditStep(Document& doc, std::string label, bool keepTexture) : doc_(doc), texture_(keepTexture && hasTexture(doc.mesh)) {
if (texture_) record_ = captureTexture(doc.mesh, label);
else record_.label = std::move(label);
@@ -168,7 +168,7 @@ void registerUvCommands(CommandRegistry& reg) {
return {false, "method must be isometric, conformal, facegroups, planar, unfold or auto"};
o.resolution = resolutionArg(doc, a);
o.iterations = std::clamp(int(argNumber(a, "iterations", 10)), 0, 100);
- o.packing = packOptions(doc, a);
+ o.packing = uvPackOptions(doc, a);
o.pack = argBool(a, "pack", o.method != UvUnwrapMethod::Unfold);
const bool haveSel = doc.uvSelection.valid(m) && !doc.uvSelection.empty();
std::vector<uint8_t> faces;
@@ -221,10 +221,10 @@ void registerUvCommands(CommandRegistry& reg) {
UvEditStep edit(doc, "Pack UVs", argBool(a, "keep_texture", true));
UvPackResult r;
std::string err;
- const UvPackOptions po = packOptions(doc, a);
+ const UvPackOptions po = uvPackOptions(doc, a);
if (!uvPack(m, topo, islands, po, r, err)) return {false, err};
const std::string note = edit.commit();
- return {true, packNote(r, po) + note};
+ return {true, uvPackNote(r, po) + note};
}});
reg.add({"uv_seam",
diff --git a/src/core/UvEdit.h b/src/core/UvEdit.h
index 74aa92b3..a85d6951 100644
--- a/src/core/UvEdit.h
+++ b/src/core/UvEdit.h
@@ -7,7 +7,9 @@
// layout so the model looks the same (core/TextureTransfer.h), the old texture in the same step.
#pragma once
+#include "core/Commands.h"
#include "core/Document.h"
+#include "core/Uv.h"
#include <string>
@@ -29,4 +31,9 @@ private:
UndoRecord record_;
};
+// The uv_pack command's options from its arguments, and the status line it ends with (core/UvCommands.cpp; the
+// UV Editor's Pack, which runs on a worker thread, uses them too).
+UvPackOptions uvPackOptions(const Document& doc, const Args& args);
+std::string uvPackNote(const UvPackResult& result, const UvPackOptions& options);
+
} // namespace sf
diff --git a/src/core/UvPack.cpp b/src/core/UvPack.cpp
index 859ed5ec..e9f6528c 100644
--- a/src/core/UvPack.cpp
+++ b/src/core/UvPack.cpp
@@ -13,6 +13,12 @@
#include <xatlas.h>
#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <functional>
+#include <mutex>
+#include <thread>
#include <cmath>
#include <limits>
#include <memory>
@@ -77,22 +83,79 @@ struct Skyline {
}
};
+using AtlasPtr = std::unique_ptr<xatlas::Atlas, void (*)(xatlas::Atlas*)>;
+
+// xatlas's progress callback: stop (false) once `stop` is set, so a cancelled pack ends within a chart.
+bool keepPacking(xatlas::ProgressCategory, int, void* stop) { return !static_cast<const std::atomic<bool>*>(stop)->load(); }
+
+// An xatlas atlas holding triangles `idx` of the UV mesh `verts` (`material`: the island of each), charts computed.
+AtlasPtr shapeAtlas(const std::vector<glm::vec2>& verts, const std::vector<uint32_t>& idx, const std::vector<uint32_t>& material,
+ std::atomic<bool>& stop) {
+ AtlasPtr atlas(xatlas::Create(), xatlas::Destroy);
+ xatlas::SetProgressCallback(atlas.get(), keepPacking, &stop);
+ xatlas::UvMeshDecl decl;
+ decl.vertexUvData = verts.data();
+ decl.vertexStride = sizeof(glm::vec2);
+ decl.vertexCount = uint32_t(verts.size());
+ decl.indexData = idx.data();
+ decl.indexCount = uint32_t(idx.size());
+ decl.indexFormat = xatlas::IndexFormat::UInt32;
+ decl.faceMaterialData = material.data(); // (one per island: islands that overlap stay apart)
+ if (xatlas::AddUvMesh(atlas.get(), decl) != xatlas::AddMeshError::Success) return AtlasPtr(nullptr, xatlas::Destroy);
+ xatlas::ComputeCharts(atlas.get());
+ return atlas;
+}
+
+// Runs job(i) for every i in [0, n) on up to `threads` threads while the calling thread reports progress (the
+// jobs done, mapped to [from, to]). False when the progress callback asked to stop: `stop` is set, which the
+// jobs' packs watch too, so they end early.
+bool runJobs(size_t n, int threads, const std::function<void(size_t)>& job, const UvProgress& progress, std::atomic<bool>& stop,
+ float from, float to) {
+ std::mutex mutex;
+ std::condition_variable cv;
+ std::atomic<size_t> next{0};
+ size_t done = 0;
+ auto work = [&] {
+ for (size_t i; !stop && (i = next++) < n;) {
+ job(i);
+ std::lock_guard lock(mutex);
+ ++done;
+ cv.notify_one();
+ }
+ };
+ std::vector<std::thread> pool;
+ for (size_t t = 0; t < std::min(n, size_t(std::max(threads, 1))); ++t) pool.emplace_back(work);
+ {
+ std::unique_lock lock(mutex);
+ while (done < n && !stop) {
+ const float f = from + (to - from) * float(done) / float(std::max<size_t>(n, 1));
+ lock.unlock();
+ if (progress && !progress(f)) stop = true;
+ lock.lock();
+ if (!stop) cv.wait_for(lock, std::chrono::milliseconds(25), [&] { return done >= n; });
+ }
+ }
+ for (std::thread& t : pool) t.join();
+ return !stop;
+}
+
// The shape packer (xatlas, on the islands as a UV mesh): islands are rasterised and fitted by their outlines, so
// far less space goes to waste than with boxes. The islands go in scaled to one density (UV area = surface area,
// or kept relative with k = 1), so xatlas's texels per unit is the texel density itself: with `density` it packs at
-// exactly that and opens as many tiles as it needs; otherwise the largest density that fits `tiles` is found by
-// bisection at a quarter of the resolution, then packed at full resolution. False when xatlas can't (the box
-// packer takes over).
+// exactly that and opens as many tiles as it needs; otherwise the largest density that fits `tiles` is searched
+// for at a quarter of the resolution (several densities at once, one atlas per thread, at an eighth first). False
+// when xatlas can't (the box packer takes over) or `stop` was set (the progress callback cancelled).
bool packByShape(Mesh& m, const UvTopology& topo, const std::vector<uint32_t>& list, const std::vector<uint32_t>& offsets,
const std::vector<uint32_t>& corners, const std::vector<float>& k, const std::vector<float>& angle,
- const UvPackOptions& o, UvPackResult& result) {
+ const UvPackOptions& o, UvPackResult& result, const UvProgress& progress, std::atomic<bool>& stop) {
const int res = std::clamp(o.resolution, 64, 16384);
std::vector<uint32_t> vid(topo.uvVertexCount, ~0u);
std::vector<glm::vec2> verts;
- std::vector<uint32_t> idx, cornerOf, material;
+ std::vector<uint32_t> idx, cornerOf, material, start(list.size() + 1, 0); // start: each island's first index
double total = 0.0;
for (size_t p = 0; p < list.size(); ++p) {
const uint32_t i = list[p];
+ start[p] = uint32_t(idx.size());
glm::vec2 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
for (uint32_t c = offsets[i]; c < offsets[i + 1]; ++c) lo = glm::min(lo, m.uvs[corners[c]]), hi = glm::max(hi, m.uvs[corners[c]]);
const glm::vec2 mid = (lo + hi) * 0.5f;
@@ -108,72 +171,121 @@ bool packByShape(Mesh& m, const UvTopology& topo, const std::vector<uint32_t>& l
if (idx.size() % 3 == 0) material.push_back(uint32_t(p));
}
}
+ start[list.size()] = uint32_t(idx.size());
for (size_t t = 0; t + 2 < idx.size(); t += 3) // (the islands' area as they go in)
total += 0.5 * std::abs(double(cross2(verts[idx[t + 1]] - verts[idx[t]], verts[idx[t + 2]] - verts[idx[t]])));
if (idx.empty() || total <= 0.0) return false;
- std::unique_ptr<xatlas::Atlas, void (*)(xatlas::Atlas*)> atlas(xatlas::Create(), xatlas::Destroy);
- xatlas::UvMeshDecl decl;
- decl.vertexUvData = verts.data();
- decl.vertexStride = sizeof(glm::vec2);
- decl.vertexCount = uint32_t(verts.size());
- decl.indexData = idx.data();
- decl.indexCount = uint32_t(idx.size());
- decl.indexFormat = xatlas::IndexFormat::UInt32;
- decl.faceMaterialData = material.data(); // (one per island: islands that overlap stay apart)
- if (xatlas::AddUvMesh(atlas.get(), decl) != xatlas::AddMeshError::Success) return false;
- xatlas::ComputeCharts(atlas.get());
- auto pack = [&](float texelsPerUnit, int resolution) {
+ const int lanes = std::clamp(ThreadPool::shared().threads(), 1, 8);
+ auto pack = [&](xatlas::Atlas& atlas, float texelsPerUnit, int resolution) {
xatlas::PackOptions po;
- po.padding = uint32_t(std::lround(std::max(o.marginPx, 0.0f) * float(resolution) / float(res)));
+ const float margin = std::max(o.marginPx, 0.0f) * float(resolution) / float(res);
+ po.padding = uint32_t(resolution == res ? std::lround(margin) : std::ceil(margin - 1e-3f)); // (never under it, scaled up)
po.texelsPerUnit = texelsPerUnit;
po.resolution = uint32_t(resolution);
po.bilinear = false;
po.blockAlign = resolution > 1024;
- po.rotateCharts = o.rotate; // (quarter turns, undone exactly by the fit below)
- po.rotateChartsToAxis = false; // (turned to their smallest box above: xatlas's own turn could mirror)
- xatlas::PackCharts(atlas.get(), po);
- return atlas->meshCount == 1 ? int(std::max(atlas->atlasCount, 1u)) : 0;
+ // (Turned to their smallest box above. xatlas's own quarter turn swaps x and y, a mirror the fit below can't
+ // undo: those islands came out shrunk and overlapping their neighbours.)
+ po.rotateCharts = false;
+ po.rotateChartsToAxis = false;
+ xatlas::PackCharts(&atlas, po);
+ return atlas.meshCount == 1 && !stop ? int(std::max(atlas.atlasCount, 1u)) : 0;
+ };
+ // xatlas may split an island it finds folded or pinched into several charts: then the islands wouldn't stay
+ // whole, and the box packer takes over. (Charts don't depend on the density, so one small pack shows it.)
+ auto whole = [&](const xatlas::Atlas& atlas, const std::vector<uint32_t>& mat) {
+ const xatlas::Mesh& out = atlas.meshes[0];
+ for (size_t i = 3; i < out.indexCount; ++i)
+ if (mat[i / 3] == mat[(i - 1) / 3] &&
+ out.vertexArray[out.indexArray[i]].chartIndex != out.vertexArray[out.indexArray[i - 1]].chartIndex)
+ return false;
+ return true;
+ };
+ std::vector<AtlasPtr> atlas;
+ atlas.reserve(size_t(lanes));
+ for (int l = 0; l < lanes; ++l) atlas.emplace_back(nullptr, xatlas::Destroy);
+ auto lane = [&](size_t l) -> xatlas::Atlas* {
+ if (!atlas[l]) atlas[l] = shapeAtlas(verts, idx, material, stop);
+ return atlas[l].get();
};
const int maxTiles = uvPackMaxTiles(o), tiles = std::clamp(o.tiles, 1, maxTiles);
+ const int lowRes = std::min(std::max(res / 4, 256), res), coarseRes = std::min(std::max(res / 8, 128), res);
+ const float inv = 1.0f / float(res);
+ std::vector<glm::vec2> placed(idx.size()); // where each corner went, in UDIM space
+ // Where xatlas put each corner of `a`'s pack at `resolution`, scaled to the full resolution.
+ auto layout = [&](const xatlas::Atlas& a, int resolution, std::vector<glm::vec2>& to) {
+ const xatlas::Mesh& out = a.meshes[0];
+ const float scale = float(res) / float(resolution) * inv;
+ for (uint32_t i = 0; i < out.indexCount; ++i) {
+ const xatlas::Vertex& v = out.vertexArray[out.indexArray[i]];
+ to[i] = udimOrigin(uvPackTile(o, std::max(v.atlasIndex, 0))) + glm::vec2(v.uv[0], v.uv[1]) * scale;
+ }
+ };
float density = o.density;
int used = 0;
+ if (!lane(0)) return false;
+ // Split check first (charts don't depend on the density): the islands into about half of one small atlas.
+ const float hi0 = float(std::sqrt(double(tiles) * double(res) * double(res) / total)); // (every tile full)
+ if (!pack(*atlas[0], hi0 * float(coarseRes) / float(res) * std::sqrt(0.5f / float(tiles)), coarseRes) || !whole(*atlas[0], material) ||
+ atlas[0]->meshes[0].indexCount != idx.size())
+ return false;
+ if (progress && !progress(0.05f)) {
+ stop = true;
+ return false;
+ }
if (density > 0.0f) {
- used = pack(density, res);
+ used = pack(*atlas[0], density, res);
if (used == 0 || used > maxTiles) return false;
+ layout(*atlas[0], res, placed);
} else {
- // Bisection at a quarter of the resolution (fast), then the full pack, a little smaller until it fits.
- const int lowRes = std::max(res / 4, 256);
- const float rel = float(lowRes) / float(res);
- float lo = 0.0f, hi = float(std::sqrt(double(tiles) * double(res) * double(res) / total));
- for (int it = 0; it < 12; ++it) {
- const float mid = lo > 0.0f ? 0.5f * (lo + hi) : hi * 0.6f;
- const int count = pack(mid * rel, lowRes);
- if (count > 0 && count <= tiles) lo = mid;
- else hi = mid;
- if (lo > 0.0f && hi / lo < 1.01f) break;
+ // The search: each round packs up to `lanes` densities (one atlas per thread) between the largest that
+ // fitted (lo) and the smallest that didn't (hi), at an eighth of the resolution until they are 5% apart,
+ // then at a quarter until 1%. The best quarter-resolution layout is the result, scaled up: xatlas marks
+ // every texel a chart touches, and the margin rounds up, so nothing comes closer than at full resolution.
+ float lo = 0.0f, hi = hi0;
+ int resolution = coarseRes;
+ std::vector<float> ds(static_cast<size_t>(lanes));
+ std::vector<int> counts(static_cast<size_t>(lanes));
+ std::vector<std::vector<glm::vec2>> laneLayout(static_cast<size_t>(lanes));
+ bool haveLayout = false;
+ for (int round = 0; round < 16; ++round) {
+ if (lo > 0.0f && hi / lo < (resolution == lowRes ? 1.01f : 1.05f)) {
+ if (resolution == lowRes) break;
+ resolution = lowRes; // (finer, so what fitted may not: the bracket opens a little)
+ lo *= 0.96f, hi *= 1.02f;
+ for (int l = 0; l < lanes; ++l) ds[size_t(l)] = lo + (hi - lo) * float(l) / float(std::max(lanes - 1, 1));
+ lo = 0.0f;
+ } else {
+ for (int l = 0; l < lanes; ++l) // (nothing fitted yet: from 40% of every tile full up)
+ ds[size_t(l)] = lo > 0.0f ? lo + (hi - lo) * float(l + 1) / float(lanes + 1) : hi * (0.4f + 0.55f * float(l + 1) / float(lanes + 1));
+ }
+ const float f = 0.05f + 0.9f * float(std::min(round, 7)) / 8.0f;
+ if (!runJobs(size_t(lanes), lanes, [&](size_t l) {
+ xatlas::Atlas* a = lane(l);
+ counts[l] = a ? pack(*a, ds[l] * float(resolution) / float(res), resolution) : 0;
+ if (resolution == lowRes && counts[l] > 0 && counts[l] <= tiles) {
+ laneLayout[l].resize(idx.size());
+ layout(*a, resolution, laneLayout[l]);
+ }
+ }, progress, stop, f, f + 0.9f / 8.0f))
+ return false;
+ float newLo = lo;
+ int best = -1;
+ for (int l = 0; l < lanes; ++l)
+ if (counts[size_t(l)] > 0 && counts[size_t(l)] <= tiles && ds[size_t(l)] > newLo) newLo = ds[size_t(l)], best = l;
+ for (int l = 0; l < lanes; ++l)
+ if (!(counts[size_t(l)] > 0 && counts[size_t(l)] <= tiles) && ds[size_t(l)] > newLo) hi = std::min(hi, ds[size_t(l)]);
+ if (best >= 0) {
+ lo = newLo;
+ used = counts[size_t(best)];
+ if (resolution == lowRes) placed.swap(laneLayout[size_t(best)]), haveLayout = true;
+ }
}
- if (lo <= 0.0f) return false;
+ if (lo <= 0.0f || !haveLayout) return false;
density = lo;
- for (int tries = 0; tries < 8; ++tries, density *= 0.97f)
- if ((used = pack(density, res)) > 0 && used <= tiles) break;
- if (used == 0 || used > tiles) return false;
}
- const xatlas::Mesh& out = atlas->meshes[0];
- if (out.indexCount != idx.size()) return false;
- const float inv = 1.0f / float(res);
// Only where xatlas put each island is taken: the move (and scale) that best maps the island onto its packed
// copy is applied to the island's own UVs, so its shape stays exactly as it was.
- // xatlas may split an island it finds folded or pinched into several charts: then the islands wouldn't stay
- // whole, and the box packer takes over.
- for (size_t i = 3; i < idx.size(); ++i)
- if (material[i / 3] == material[(i - 1) / 3] &&
- out.vertexArray[out.indexArray[i]].chartIndex != out.vertexArray[out.indexArray[i - 1]].chartIndex)
- return false;
- std::vector<glm::vec2> placed(out.indexCount);
- for (uint32_t i = 0; i < out.indexCount; ++i) {
- const xatlas::Vertex& v = out.vertexArray[out.indexArray[i]];
- placed[i] = udimOrigin(uvPackTile(o, std::max(v.atlasIndex, 0))) + glm::vec2(v.uv[0], v.uv[1]) * inv;
- }
for (size_t b = 0; b < idx.size();) {
size_t e = b;
while (e < idx.size() && material[e / 3] == material[b / 3]) e += 3;
@@ -195,11 +307,16 @@ bool packByShape(Mesh& m, const UvTopology& topo, const std::vector<uint32_t>& l
}
b = e;
}
- const double uvArea = total;
+ // (Measured: xatlas shrinks an island bigger than a tile to fit one, so it isn't density^2 x their area.)
+ double uvArea = 0.0;
+ for (uint32_t i : list)
+ for (uint32_t k = topo.islandOffsets[i]; k < topo.islandOffsets[i + 1]; ++k) {
+ const glm::vec2* u = m.uvs.data() + size_t(topo.islandTriangles[k]) * 3;
+ uvArea += 0.5 * std::abs(double(cross2(u[1] - u[0], u[2] - u[0])));
+ }
result.islands = list.size();
result.tilesUsed = used;
- // (UV area after packing = surface area x (density / res)^2 when the islands went in at one density.)
- result.coverage = float(uvArea * double(density) * double(density) * double(inv) * double(inv) / double(std::max(used, 1)));
+ result.coverage = float(uvArea / double(std::max(used, 1)));
result.density = uvMeshDensity(m, res);
m.facesDirty = true;
return true;
@@ -276,7 +393,7 @@ int packRectangles(const std::vector<glm::vec2>& sizes, int maxTiles, bool allow
}
bool uvPack(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands, const UvPackOptions& o,
- UvPackResult& result, std::string& error) {
+ UvPackResult& result, std::string& error, const UvProgress& progress) {
result = UvPackResult();
const size_t nt = m.triangleCount();
if (m.uvs.size() != nt * 3 || topo.island.size() != nt) {
@@ -337,8 +454,13 @@ bool uvPack(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands
std::vector<double> a3(n);
for (size_t p = 0; p < n; ++p) k[p] = pieces[p].k, angle[p] = pieces[p].angle, a3[p] = pieces[p].area3;
const std::vector<glm::vec2> before = m.uvs;
- if (packByShape(m, topo, list, offsets, corners, k, angle, o, shapeResult)) shapeUvs = m.uvs;
+ std::atomic<bool> stop{false};
+ if (packByShape(m, topo, list, offsets, corners, k, angle, o, shapeResult, progress, stop)) shapeUvs = m.uvs;
m.uvs = before;
+ if (stop) {
+ error = "Cancelled";
+ return false;
+ }
}
auto useShapes = [&] {
if (shapeUvs.empty()) return false;
diff --git a/src/core/UvUnwrap.cpp b/src/core/UvUnwrap.cpp
index b7d42a33..a137f625 100644
--- a/src/core/UvUnwrap.cpp
+++ b/src/core/UvUnwrap.cpp
@@ -704,7 +704,7 @@ bool uvUnwrap(const Mesh& m, const UvUnwrapOptions& o, UvUnwrapResult& result, s
for (uint32_t t : list) isl[topo.island[t]] = 1;
UvPackOptions po = o.packing;
if (faces) po.tiles = 1, po.density = 0.0f;
- if (!uvPack(tmp, topo, isl, po, result.packing, error)) return false;
+ if (!uvPack(tmp, topo, isl, po, result.packing, error, [&](float f) { return report(0.9f + 0.1f * f); })) return false;
if (faces && hadUvs) { // into the old place of the selection
glm::vec2 lo(1e30f), hi(-1e30f);
for (uint32_t t : list)
@@ -941,7 +941,8 @@ bool uvUnwrap(const Mesh& m, const UvUnwrapOptions& o, UvUnwrapResult& result, s
UvPackOptions po = o.packing;
po.resolution = o.resolution;
if (faces && hadUvs) po.tiles = 1, po.density = 0.0f;
- if (std::find(isl.begin(), isl.end(), uint8_t(1)) != isl.end() && !uvPack(tmp, pt, isl, po, result.packing, error))
+ if (std::find(isl.begin(), isl.end(), uint8_t(1)) != isl.end() &&
+ !uvPack(tmp, pt, isl, po, result.packing, error, [&](float f) { return report(0.9f + 0.1f * f); }))
return false;
if (faces && hadUvs) { // the selection's new islands go where its old ones were
glm::vec2 lo(1e30f), hi(-1e30f);
diff --git a/tests/test_uv_editor.cpp b/tests/test_uv_editor.cpp
index 78c32c71..46357b44 100644
--- a/tests/test_uv_editor.cpp
+++ b/tests/test_uv_editor.cpp
@@ -16,6 +16,7 @@
#include <chrono>
#include <cmath>
#include <cstdio>
+#include <thread>
using namespace sf;
@@ -82,6 +83,46 @@ Mesh squares(int n) {
return m;
}
+// `n` L-shaped islands of different sizes and arm lengths, every other one standing, flat in the y = 0 plane; their
+// UVs are the shape itself (counter-clockwise). Enough for the shape packer, and long enough that it wants to turn some.
+Mesh lShapes(int n) {
+ Mesh m;
+ for (int i = 0; i < n; ++i) {
+ const float s = 0.5f + 0.25f * float(i % 5), x0 = 12.0f * float(i), arm = 1.0f + 1.5f * float(i % 4);
+ glm::vec2 v[] = {{0, 0}, {1 + arm, 0}, {1 + arm, 1}, {0, 1}, {1, 1}, {1, 2 + arm * 0.5f}, {0, 2 + arm * 0.5f}};
+ if (i % 2)
+ for (glm::vec2& p : v) p = glm::vec2(-p.y, p.x);
+ const uint32_t b = uint32_t(m.positions.size());
+ for (const glm::vec2& p : v) m.positions.push_back(glm::vec3(x0 + p.x * s, 0.0f, -p.y * s));
+ const uint32_t tris[][3] = {{0, 1, 2}, {0, 2, 4}, {0, 4, 3}, {3, 4, 5}, {3, 5, 6}};
+ for (const auto& t : tris) {
+ m.triangles.push_back({b + t[0], b + t[1], b + t[2]});
+ for (uint32_t j : t) m.uvs.push_back(v[j] * 0.1f);
+ }
+ }
+ m.recomputeAllNormals();
+ return m;
+}
+
+double uvCross(glm::vec2 a, glm::vec2 b) { return double(a.x) * double(b.y) - double(a.y) * double(b.x); }
+
+// Two UV triangles overlap by more than `eps` (no separating axis among their edges).
+bool uvTrianglesOverlap(const glm::vec2* a, const glm::vec2* b, float eps) {
+ for (int k = 0; k < 2; ++k) {
+ const glm::vec2 *p = k ? b : a, *o = k ? a : b;
+ for (int e = 0; e < 3; ++e) {
+ const glm::vec2 d = p[(e + 1) % 3] - p[e], n = glm::normalize(glm::vec2(-d.y, d.x));
+ float pLo = 1e30f, pHi = -1e30f, oLo = 1e30f, oHi = -1e30f;
+ for (int j = 0; j < 3; ++j) {
+ pLo = std::min(pLo, glm::dot(n, p[j])), pHi = std::max(pHi, glm::dot(n, p[j]));
+ oLo = std::min(oLo, glm::dot(n, o[j])), oHi = std::max(oHi, glm::dot(n, o[j]));
+ }
+ if (pHi < oLo + eps || oHi < pLo + eps) return false;
+ }
+ }
+ return true;
+}
+
std::vector<int> usedTiles(const Mesh& m) {
std::vector<int> tiles;
for (uint32_t t = 0; t < m.triangleCount(); ++t) tiles.push_back(udimTile((m.uvs[t * 3] + m.uvs[t * 3 + 1] + m.uvs[t * 3 + 2]) / 3.0f));
@@ -337,6 +378,78 @@ TEST(uv_pack_udim_grid_columns_by_rows) {
CHECK(usedTiles(doc.mesh).back() == 1012);
}
+TEST(uv_pack_by_shape_keeps_islands_apart_unmirrored_and_at_one_density) {
+ // xatlas's quarter turn swaps u and v (a mirror): islands it turned were fitted back shrunk and on top of their
+ // neighbours. Islands are now only turned to their smallest box before xatlas sees them.
+ for (int tiles : {1, 4}) {
+ Mesh m = lShapes(24);
+ const UvTopology topo = buildUvTopology(m);
+ std::vector<double> before(m.triangleCount());
+ for (size_t t = 0; t < m.triangleCount(); ++t) before[t] = uvCross(m.uvs[t * 3 + 1] - m.uvs[t * 3], m.uvs[t * 3 + 2] - m.uvs[t * 3]);
+ UvPackOptions o;
+ o.tiles = tiles;
+ o.columns = tiles > 1 ? 2 : 0;
+ UvPackResult r;
+ std::string err;
+ CHECK(uvPack(m, topo, {}, o, r, err));
+ CHECK(r.tilesUsed == tiles);
+ CHECK(r.coverage > 0.45f && r.coverage <= 1.0f); // (measured: the islands' UV area over the tiles)
+ std::vector<double> uvArea(topo.islandCount, 0.0), area(topo.islandCount, 0.0);
+ size_t mirrored = 0, overlaps = 0;
+ for (size_t t = 0; t < m.triangleCount(); ++t) {
+ const double c = uvCross(m.uvs[t * 3 + 1] - m.uvs[t * 3], m.uvs[t * 3 + 2] - m.uvs[t * 3]);
+ if ((c > 0.0) != (before[t] > 0.0)) ++mirrored;
+ uvArea[topo.island[t]] += 0.5 * std::abs(c);
+ const glm::uvec3 tri = m.triangles[t];
+ area[topo.island[t]] += 0.5 * double(glm::length(glm::cross(m.positions[tri.y] - m.positions[tri.x], m.positions[tri.z] - m.positions[tri.x])));
+ for (size_t u = t + 1; u < m.triangleCount(); ++u)
+ if (topo.island[t] != topo.island[u] && uvTrianglesOverlap(&m.uvs[t * 3], &m.uvs[u * 3], 1e-5f)) ++overlaps;
+ }
+ CHECK(mirrored == 0);
+ CHECK(overlaps == 0);
+ if (tiles == 1) { // (across tiles the largest island may be shrunk to fit one)
+ std::vector<double> d;
+ for (uint32_t i = 0; i < topo.islandCount; ++i) d.push_back(std::sqrt(uvArea[i] / area[i]));
+ std::vector<double> sorted = d;
+ std::sort(sorted.begin(), sorted.end());
+ for (double x : d) CHECK(std::abs(x / sorted[sorted.size() / 2] - 1.0) < 0.025);
+ }
+ }
+}
+
+TEST(uv_pack_reports_progress_and_cancels) {
+ Mesh m = lShapes(24);
+ const UvTopology topo = buildUvTopology(m);
+ UvPackOptions o;
+ o.tiles = 4;
+ o.columns = 2;
+ UvPackResult r;
+ std::string err;
+ // Progress comes on the calling thread, rising.
+ const std::thread::id caller = std::this_thread::get_id();
+ std::vector<float> seen;
+ bool otherThread = false;
+ CHECK(uvPack(m, topo, {}, o, r, err, [&](float f) {
+ otherThread |= std::this_thread::get_id() != caller;
+ seen.push_back(f);
+ return true;
+ }));
+ CHECK(!otherThread);
+ CHECK(seen.size() >= 2);
+ CHECK(std::is_sorted(seen.begin(), seen.end()));
+ CHECK(seen.back() <= 1.0f);
+ // Cancelled at once, or part way: false, "Cancelled", the UVs as they were.
+ for (int after : {0, 3}) {
+ Mesh c = lShapes(24);
+ const std::vector<glm::vec2> uvs = c.uvs;
+ int calls = 0;
+ err.clear();
+ CHECK(!uvPack(c, topo, {}, o, r, err, [&](float) { return calls++ < after; }));
+ CHECK(err == "Cancelled");
+ CHECK(c.uvs == uvs);
+ }
+}
+
TEST(uv_pack_rectangles) {
// Sixteen quarter-tile squares fill one tile; a seventeenth needs a second; an oversized one never fits.
std::vector<glm::vec2> sizes(16, glm::vec2(0.25f)), pos;
diff --git a/tests/ui/uv_editor.sfui b/tests/ui/uv_editor.sfui
index 2c0576ae..983294d8 100644
--- a/tests/ui/uv_editor.sfui
+++ b/tests/ui/uv_editor.sfui
@@ -73,10 +73,16 @@ remember uv_tiles grid
expect_value uv_pack_columns == 4
expect_value uv_pack_rows == 3
shot udim-4x3
-# The Pack button packs with the fields: still 4 x 3.
+# The Pack button packs with the fields: still 4 x 3, on a worker thread (the window keeps drawing; Cancel under
+# the view), landing as one undo step with uv_pack's status line.
click "UV Editor/Pack##uv.pack"
+wait_value uv_packs >= 1 60
+expect_value uv_unwrapping == 0
expect_value uv_tiles == $grid
expect_value uv_max_u <= 4
+expect_status "UDIM tiles"
+expect_value uv_pack_columns == 4
+shot pack-button
run uv_pack tiles=1
expect_value uv_tiles == 1
expect_value uv_pack_columns == 1