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 Editor window: GPU-drawn 2D layout over UDIM tiles, selection modes and transform gizmo, Seam / Select in 3D tools, live stretch / density / checker on the model, background unwraps; shape packing via xatlas when it beats boxes, Auto Seams charts for tangled pieces

islandmedac4d3f50efd8
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 46cdfc15..5b0afe1c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -273,6 +273,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelPolypaint.cpp
src/app/PanelPaintLayers.cpp
src/app/PanelTexture.cpp
+ src/app/PanelUvEditor.cpp
src/app/PanelPbr.cpp
src/app/PanelGeometry.cpp
src/app/Gizmo.cpp
@@ -302,6 +303,7 @@ if(SCULPTFORGE_BUILD_APP)
src/render/Clusters.cpp
src/render/Ghost.cpp
src/render/Renderer.cpp
+ src/render/UvView.cpp
src/render/MicroRenderer.cpp
)
target_link_libraries(sculptforge PRIVATE sculptforge_core sculptforge_ai sculptforge_phone imgui SDL3::SDL3)
diff --git a/src/app/App.cpp b/src/app/App.cpp
index b4ba1440..90f49a99 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -395,6 +395,7 @@ int App::runUiTest(int w, int h, int fps) {
pollMaya(); // (tests and recordings never read the user's Maya folder: maya.json isn't loaded)
pollPhone();
pollAutoUv();
+ pollUvEditor();
pollBake();
pollQRemesh();
pollSplatTrain();
@@ -565,6 +566,7 @@ int App::runRecording() {
pollBrushRequest();
pollUnreal();
pollAutoUv();
+ pollUvEditor();
pollBake();
pollQRemesh();
pollSplatTrain();
@@ -642,7 +644,7 @@ bool App::backgroundBusy() const {
auto running = [](const auto& f) { return f.valid() && f.wait_for(std::chrono::seconds(0)) != std::future_status::ready; };
return running(pendingBrush_) || running(pendingGenerator_) || running(pendingModels_) || running(pendingUnreal_) ||
running(pendingComfyCheck_) || galleryBusy() || thumbs_.busy() || libraryScanner_.busy() || autoUv_ ||
- bakeBusy() || qremesh_ || voxelRemesh_ || updateJob_ || splatTrainBusy() || sculptableBusy() || phoneBusy() ||
+ bakeBusy() || qremesh_ || voxelRemesh_ || updateJob_ || splatTrainBusy() || sculptableBusy() || phoneBusy() || uvEditorBusy() ||
supportCardLoading();
}
@@ -917,6 +919,8 @@ int App::run() {
pollMaya();
pollPhone();
pollAutoUv();
+ pollUvEditor();
+ pollUvEditor();
pollBake();
pollQRemesh();
pollSplatTrain();
@@ -1192,6 +1196,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {
if (polygroupMouseDown(x, y, mod)) return;
if (maskSelectMouseDown(x, y, mod)) return;
if (gizmoMouseDown(x, y, mod)) return; // Gizmo 3D handles, pivot clicks (Gizmo.cpp)
+ if (uvToolMouseDown(x, y, mod)) return; // the UV Editor's Seam / Select in 3D tool (PanelUvEditor.cpp)
if (guideMouseDown(x, y, mod)) return; // the QRemesh Guides brush (PanelRetopo.cpp)
if (faceMouseDown(x, y, mod)) return; // placing facial landmarks (PanelFace.cpp)
if (sculptableMouseDown(x, y)) return; // Make sculptable: landmarks, crop box (PanelSculptable.cpp)
@@ -1333,6 +1338,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
case Drag::Select: selectionMove(x, y); break;
case Drag::Gizmo: gizmoDragTo(x, y); break;
case Drag::Guide: guideDragTo(x, y); break;
+ case Drag::UvTool: uvToolDragTo(x, y); break;
case Drag::Sculptable: sculptableMouseMove(x, y); break;
case Drag::Capture: captureMouseMove(x, y); break;
case Drag::ZSphere: zsphereDragTo(x, y); break;
@@ -1408,6 +1414,7 @@ void App::onMouseUp() {
if (drag_ == Drag::MaskCanvas) maskCanvasRelease();
if (drag_ == Drag::SubToolClick) subtoolClickRelease();
if (drag_ == Drag::Guide) guideRelease();
+ if (drag_ == Drag::UvTool) uvToolRelease();
if (drag_ == Drag::Sculptable) sculptableMouseUp();
if (drag_ == Drag::Capture) captureMouseUp();
if (drag_ == Drag::ZSphere) zsphereRelease();
@@ -1428,6 +1435,7 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
return;
}
if (captureShortcutKey(key, mod)) return; // Ctrl+Alt+click a button, then press its new key
+ if (uvEditorKey(key, mod)) return; // keys over the UV Editor's view (PanelUvEditor.cpp)
if (key == SDLK_ESCAPE && capture_.armed) { // Capture from view waiting for its square (PanelKelvinlet.cpp)
capture_.armed = false;
status_ = "Capture cancelled";
@@ -1752,6 +1760,7 @@ void App::runCommand(const std::string& name, const Args& args) {
crashlog::action(name); // (failures reach the log through SDL_Log below)
CommandResult r = commands_.execute(doc_, name, args);
status_ = r.message;
+ if (name.rfind("uv_", 0) == 0 || name == "texture_create" || name == "texture_delete") uvEditorChanged();
lastCommandOk_ = r.ok;
if (r.ok && name != "export_glb" && name != "export_lods" && name != "export_usd" && name != "export_fbx" &&
name != "export_unreal" && name.rfind("unreal_", 0) != 0 && name != "save_obj" && name != "save_project" &&
@@ -1955,6 +1964,7 @@ void App::syncScene() {
if (mesh->texture) syncChannelView(*mesh->texture, doc_.channelView);
const bool flat = s.shading == Shading::Flat || (s.shading == Shading::Default && renderSettings_.flatShading);
scene.push_back({s.id, mesh, active, s.visible, bakeNormalMap(s.id, *mesh), renderSettings_.wireframe, flat});
+ if (active && &shown == &doc_.mesh) scene.back().overlay = uvEditorOverlay(s.id); // the UV Editor's colours
}
renderer_.syncScene(scene);
renderer_.syncSplats(doc_.splats, doc_.splatsVersion);
@@ -2024,6 +2034,7 @@ void App::drawUi() {
drawBrushGallery();
if (showImageTo3D_) drawImageTo3D();
drawPhoneWindow(); // File > Capture from phone (PanelPhone.cpp)
+ drawUvEditor(); // Tool > Texture Map > UV Editor (PanelUvEditor.cpp)
drawTimelineUi(); // the Sculpt Timeline strip, timelapse, proof mode HUD (PanelTimeline.cpp, ProofMode.cpp)
pollAlphaFile();
pollVdm();
@@ -2038,6 +2049,7 @@ void App::drawUi() {
const ImVec2 mouse(mouseX_, mouseY_);
drawGizmo(); // Gizmo 3D handles and panel (Gizmo.cpp)
drawQRemeshGuides(); // QRemesh Guides curves (PanelRetopo.cpp)
+ drawUvEditorOverlay(); // UV seams on the model, the Seam tool's cursor (PanelUvEditor.cpp)
drawZSphereOverlay(); // the sphere under the cursor (PanelZSpheres.cpp)
drawFaceOverlay(); // facial landmarks (PanelFace.cpp)
drawSplatTrainOverlay(); // splat training progress (PanelSplatTrain.cpp)
@@ -2050,7 +2062,8 @@ void App::drawUi() {
theme::u32(theme::accent), 48, 2.0f * uiScale_);
}
// In Gizmo mode (and with the QRemesh Guides brush) the brush ring shows only while Ctrl masks or Shift smooths.
- const bool ringOff = gizmoActive() || (guidesMode_ && !(inputMods() & SDL_KMOD_SHIFT)) || sculptableHot() || zsphereActive();
+ const bool ringOff = gizmoActive() || (guidesMode_ && !(inputMods() & SDL_KMOD_SHIFT)) || sculptableHot() || zsphereActive() ||
+ uvToolActive();
if (((!ImGui::GetIO().WantCaptureMouse && canvasRect().contains(mouse.x, mouse.y)) || drag_ == Drag::Stroke) &&
!hideBrushCursor_ && radial_.menu < 0 && drag_ != Drag::Select && drag_ != Drag::Guide && // (no ring under a pie)
(!ringOff || drag_ == Drag::Stroke || ctrlDown(inputMods())))
diff --git a/src/app/App.h b/src/app/App.h
index 71a2d9b0..c29609d4 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -134,7 +134,7 @@ public:
void queueFile(FileAction action, std::string path);
private:
- enum class Drag { None, Stroke, Orbit, Pan, Zoom, Roll, MaskCanvas, SubToolClick, Select, Gizmo, Guide, Sculptable, ZSphere, Insert, Capture };
+ enum class Drag { None, Stroke, Orbit, Pan, Zoom, Roll, MaskCanvas, SubToolClick, Select, Gizmo, Guide, Sculptable, ZSphere, Insert, Capture, UvTool };
void handleEvent(const SDL_Event& e);
void onMouseDown(float x, float y, Uint8 button);
@@ -655,6 +655,27 @@ private:
// Texture Map sub-palette (PanelTexture.cpp): texture painting on UVs, Auto UV, the UV view.
void drawTextureMapContents();
void registerTextureUiActions();
+ // UV Editor (PanelUvEditor.cpp): the window with the 2D UV layout and its tools, the 3D Seam / Select tool, the
+ // seams and colours on the model, a background unwrap. UvEditorUi (that file) does the work.
+ friend struct UvEditorUi;
+ void registerUvEditorActions();
+ void drawUvEditor();
+ void drawUvEditorOverlay(); // the marked seams on the model, the 3D tool's cursor
+ void pollUvEditor();
+ void uvEditorChanged(); // a uv_* command ran: the editor's caches are stale
+ bool uvEditorKey(SDL_Keycode key, SDL_Keymod mod); // keys over the UV view (true: taken)
+ bool uvToolActive() const;
+ bool uvToolMouseDown(float x, float y, SDL_Keymod mod);
+ void uvToolDragTo(float x, float y);
+ void uvToolRelease();
+ const MeshOverlay* uvEditorOverlay(uint32_t subtool); // 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_view_triangles, uv_overlay; NaN for other names.
+ double uvEditorTestValue(const std::string& name);
+ std::shared_ptr<struct UvEditorState> uvEditor_;
+ bool showUvEditor_ = false;
void startAutoUv();
void startNewTexture(); // New Texture on the top shelf / Color palette: Auto UV first when there are no UVs
void pollAutoUv();
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 431fddb1..b3e61d80 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -527,6 +527,7 @@ void App::initActions() {
registerPbrUiActions(); // material channels, solo view, map export (PanelPbr.cpp)
registerGizmoActions(); // Q W E R: Draw, and the Gizmo 3D's Move, Scale, Rotate (Gizmo.cpp)
registerBakeUiActions(); // Tool > Bake (PanelBake.cpp)
+ registerUvEditorActions(); // UV Editor (PanelUvEditor.cpp)
registerRetopoUiActions(); // Geometry > QRemesh, SubTool > ProjectAll (PanelRetopo.cpp)
registerZSphereUiActions(); // Tool > ZSpheres (PanelZSpheres.cpp)
registerSplatTrainUi(); // Splats > Train from capture (PanelSplatTrain.cpp)
diff --git a/src/app/PanelTexture.cpp b/src/app/PanelTexture.cpp
index d94dcabc..35a1dabb 100644
--- a/src/app/PanelTexture.cpp
+++ b/src/app/PanelTexture.cpp
@@ -276,6 +276,7 @@ void App::drawTextureMapContents() {
ui::ActionButton(*this, "texture.auto_uv", ImVec2(half, 0));
ImGui::SameLine();
ui::ActionButton(*this, "texture.show_uvs", ImVec2(-1, 0));
+ ui::ActionButton(*this, "ui.uv_editor", ImVec2(-1, 0), ui::Look::IconLabel);
ImGui::SetNextItemWidth(half);
ImGui::Combo("##texsize", &textureSizeChoice_, kSizeLabels, 4);
diff --git a/src/app/PanelUvEditor.cpp b/src/app/PanelUvEditor.cpp
new file mode 100644
index 00000000..9d92763f
--- /dev/null
+++ b/src/app/PanelUvEditor.cpp
@@ -0,0 +1,1594 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The UV Editor (Tool > Texture Map > UV Editor, Shift+U): a window with the active Part's UV layout in 2D,
+// drawn on the GPU (render/UvView.h) over the UDIM tile grid with a checker or the painted texture behind it.
+//
+// - Select vertices, edges, faces or islands (1-4) by clicking or dragging a box (Shift adds, Ctrl removes), or
+// on the model with Select in 3D; move, rotate and scale them with the box's handles or G / R / S.
+// - Mark and clear seams on the model with the Seam tool (drag along edges; Alt clears), or from polygroups,
+// island borders or sharp edges; Unwrap (least stretch, conformal, by polygroups, planar, unfold, auto seams),
+// Pack into one tile or across UDIM tiles, set or match texel density, lay islands into trim sheet strips,
+// pin, weld, split, straighten and flip.
+// - The model shows the same colours live: islands, stretch or texel density, the selection and a checker, so
+// distortion shows on the surface while the UVs are edited; with "Paint stays on the model" a painted texture
+// moves with every edit (core/TextureTransfer.h), so the model keeps its look.
+//
+// Every operation goes through the uv_* commands (core/UvCommands.cpp) or one UvEditStep (core/UvEdit.h), so it
+// is one undo step and scriptable; big unwraps run in the background.
+#include "app/App.h"
+#include "app/Theme.h"
+#include "app/Ui.h"
+
+#include "core/Texture.h"
+#include "core/Uv.h"
+#include "core/UvEdit.h"
+#include "render/UvView.h"
+
+#include <IconsLucide.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <future>
+#include <limits>
+#include <thread>
+
+namespace sf {
+
+namespace {
+
+constexpr const char* kPath = "UV Editor";
+constexpr int kSizes[] = {1024, 2048, 4096, 8192};
+constexpr const char* kSizeLabels[] = {"1K", "2K", "4K", "8K"};
+constexpr UvUnwrapMethod kMethods[] = {UvUnwrapMethod::Isometric, UvUnwrapMethod::Conformal, UvUnwrapMethod::Polygroups,
+ UvUnwrapMethod::Planar, UvUnwrapMethod::Unfold, UvUnwrapMethod::Auto};
+constexpr const char* kColorLabels[] = {"Islands", "Stretch", "Texel Density", "Plain"};
+constexpr const char* kImageLabels[] = {"No Image", "Checker", "Texture"};
+
+bool ctrlKey(SDL_Keymod mod) { return (mod & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0; }
+
+// RGBA8 as the GPU and ImGui read it (0xAABBGGRR).
+uint32_t pack(glm::vec3 c, float a) {
+ auto b = [](float x) { return uint32_t(std::lround(std::clamp(x, 0.0f, 1.0f) * 255.0f)); };
+ return b(c.x) | b(c.y) << 8 | b(c.z) << 16 | b(a) << 24;
+}
+
+// A pleasant, stable colour per island (golden-ratio hues, soft saturation).
+glm::vec3 islandColor(uint32_t i) {
+ const float h = std::fmod(0.07f + float(i) * 0.61803399f, 1.0f);
+ const glm::vec3 rgb = glm::clamp(glm::abs(glm::fract(glm::vec3(h) + glm::vec3(0.0f, 2.0f / 3.0f, 1.0f / 3.0f)) * 6.0f - 3.0f) -
+ 1.0f,
+ 0.0f, 1.0f);
+ return glm::mix(glm::vec3(1.0f), rgb, 0.55f) * (0.78f + 0.16f * float((i * 7u) % 3u) / 2.0f);
+}
+
+const glm::vec3 kSelect(1.0f, 0.55f, 0.16f); // the accent, for the selection
+const glm::vec3 kSeam(0.96f, 0.30f, 0.26f);
+
+float distToSegment(glm::vec2 p, glm::vec2 a, glm::vec2 b) {
+ const glm::vec2 d = b - a;
+ const float l = glm::dot(d, d);
+ const float t = l > 0.0f ? std::clamp(glm::dot(p - a, d) / l, 0.0f, 1.0f) : 0.0f;
+ return glm::length(p - (a + d * t));
+}
+
+bool insideTriangle(glm::vec2 p, glm::vec2 a, glm::vec2 b, glm::vec2 c) {
+ const float d1 = (p.x - b.x) * (a.y - b.y) - (a.x - b.x) * (p.y - b.y);
+ const float d2 = (p.x - c.x) * (b.y - c.y) - (b.x - c.x) * (p.y - c.y);
+ const float d3 = (p.x - a.x) * (c.y - a.y) - (c.x - a.x) * (p.y - a.y);
+ const bool neg = d1 < 0 || d2 < 0 || d3 < 0, pos = d1 > 0 || d2 > 0 || d3 > 0;
+ return !(neg && pos);
+}
+
+} // namespace
+
+struct UvEditorState {
+ UvViewRenderer gpu;
+ bool gpuTried = false;
+ std::string gpuError;
+ // The view: the UV point at its centre and pixels per UV unit (0: frame on the next draw).
+ glm::vec2 center{0.5f};
+ float zoom = 0.0f;
+ ImVec2 viewMin{0, 0}, viewSize{0, 0};
+ bool hovered = false;
+ // Display.
+ int color = 0; // kColorLabels
+ int image = 1; // kImageLabels
+ float imageOpacity = 0.55f;
+ float checkerScale = 8.0f;
+ bool modelColors = true;
+ bool modelChecker = true;
+ bool keepTexture = true; // paint stays on the model
+ int sizeChoice = 1; // texture size for density and margins without a texture
+ // Caches of the active mesh's UVs, rebuilt when they change.
+ uint32_t subtool = ~0u;
+ uint64_t revision = ~uint64_t(0);
+ const void* uvData = nullptr;
+ size_t uvCount = 0, flagCount = 0;
+ bool dirty = true; // everything again
+ bool colorsDirty = true; // colours only (selection, display)
+ bool hasUvs = false;
+ UvTopology topo;
+ UvStretchCache stretchCache;
+ std::vector<float> stretch, density;
+ float meanDensity = 0.0f, meanStretch = 0.0f, flipped = 0.0f;
+ std::vector<uint32_t> faceCol, edgeCol, edges;
+ std::vector<uint8_t> moving, faceSel;
+ std::vector<uint32_t> selCorners; // what the selection moves
+ glm::vec2 selLo{0.0f}, selHi{0.0f};
+ size_t selIslands = 0;
+ float selDensity = 0.0f;
+ glm::ivec2 tiles{1, 1};
+ std::vector<int> tileList;
+ MeshOverlay overlay;
+ // Interaction.
+ enum class Drag { None, Pan, Box, Move, Rotate, Scale };
+ Drag drag = Drag::None;
+ bool modal = false; // started by G / R / S: follows the mouse until a click
+ ImVec2 pressAt{0, 0};
+ glm::vec2 pressUv{0.0f}, pivot{0.0f};
+ int axis = 0; // 1: u only, 2: v only
+ glm::mat3 live{1.0f};
+ std::vector<glm::vec2> orig; // dragged corners' UVs at the start
+ std::unique_ptr<UvEditStep> step;
+ double lastLive = 0.0;
+ bool boxAdd = false, boxRemove = false;
+ // Panel options.
+ int method = 0; // kMethods
+ int iterations = 10;
+ float marginPx = 8.0f;
+ int packTiles = 1;
+ bool rotate = true;
+ bool equalDensity = true;
+ float targetDensity = 512.0f;
+ char strips[64] = "4";
+ int strip = 0;
+ bool fitWidth = false;
+ float seamAngle = 60.0f;
+ // The 3D tool: 0 off, 1 Seams, 2 Select.
+ int tool = 0;
+ bool toolClearing = false, toolAdding = true;
+ uint32_t toolVertex = ~0u;
+ std::unique_ptr<UvEditStep> toolStep;
+ std::vector<uint32_t> twin; // cornerTwins of the mesh the tool works on
+ uint64_t twinKey = 0;
+ // Seams drawn on the model.
+ std::vector<uint32_t> seamCorners;
+ uint64_t seamKey = ~uint64_t(0);
+ // Background unwrap.
+ struct Job {
+ std::future<bool> done;
+ std::shared_ptr<std::atomic<float>> progress;
+ std::shared_ptr<std::atomic<bool>> cancel;
+ std::shared_ptr<UvUnwrapResult> result;
+ std::shared_ptr<std::string> error;
+ uint32_t subtool = 0;
+ size_t triangles = 0;
+ UvUnwrapMethod method = UvUnwrapMethod::Isometric;
+ bool keepTexture = true;
+ };
+ std::unique_ptr<Job> job;
+ int unwraps = 0; // finished (UI tests)
+};
+
+// The UV Editor's work, with App's internals (a friend of App).
+struct UvEditorUi {
+ App& app;
+ UvEditorState& s;
+ Mesh& mesh() { return app.doc_.mesh; }
+ int resolution() {
+ const Mesh& m = mesh();
+ return m.texture ? std::max(m.texture->width, m.texture->height) : kSizes[std::clamp(s.sizeChoice, 0, 3)];
+ }
+
+ // --- Caches ---------------------------------------------------------------------------------------------
+
+ void refresh() {
+ const Mesh& m = mesh();
+ const uint32_t id = app.doc_.activeSubtoolInfo().id;
+ if (s.drag != UvEditorState::Drag::None) return; // (the drag keeps its own caches up to date)
+ if (id != s.subtool || app.doc_.undo.revision() != s.revision || m.uvs.data() != s.uvData || m.uvs.size() != s.uvCount ||
+ m.uvFlags.size() != s.flagCount)
+ s.dirty = true;
+ if (!s.dirty && !s.colorsDirty) return;
+ if (s.dirty) rebuildTopology();
+ rebuildColors();
+ s.dirty = s.colorsDirty = false;
+ }
+
+ void rebuildTopology() {
+ Mesh& m = mesh();
+ s.subtool = app.doc_.activeSubtoolInfo().id;
+ s.revision = app.doc_.undo.revision();
+ s.uvData = m.uvs.data();
+ s.uvCount = m.uvs.size();
+ s.flagCount = m.uvFlags.size();
+ s.hasUvs = m.hasUvs() && m.uvs.size() == m.triangleCount() * 3;
+ if (!app.doc_.uvSelection.valid(m)) {
+ const UvSelectMode mode = app.doc_.uvSelection.mode;
+ app.doc_.uvSelection.clear();
+ app.doc_.uvSelection.mode = mode;
+ }
+ if (!s.hasUvs) {
+ s.topo = UvTopology();
+ s.stretch.clear();
+ s.density.clear();
+ if (s.gpu.triangles()) s.gpu.setUvs({});
+ s.tiles = {1, 1};
+ s.tileList.clear();
+ return;
+ }
+ s.topo = buildUvTopology(m);
+ s.stretchCache = uvStretchCache(m, s.topo);
+ const size_t nt = m.triangleCount();
+ s.stretch.resize(nt);
+ for (uint32_t t = 0; t < nt; ++t) s.stretch[t] = uvTriangleStretchAt(m, t, s.topo, s.stretchCache);
+ uvTriangleDensity(m, resolution(), s.density);
+ s.meanDensity = uvMeshDensity(m, resolution());
+ double sum = 0.0, w = 0.0, flipped = 0.0;
+ for (uint32_t t = 0; t < nt; ++t) {
+ const glm::vec2* u = m.uvs.data() + size_t(t) * 3;
+ const double a = 0.5 * std::abs(double((u[1].x - u[0].x) * (u[2].y - u[0].y) - (u[2].x - u[0].x) * (u[1].y - u[0].y)));
+ w += a;
+ if (s.stretch[t] < 0.0f) flipped += a;
+ else sum += a * double(s.stretch[t]);
+ }
+ s.meanStretch = w > 0.0 ? float(sum / w) : 0.0f;
+ s.flipped = w > 0.0 ? float(flipped / w) : 0.0f;
+ // Edges: island borders once per side, inner edges once.
+ s.edges.clear();
+ for (uint32_t c = 0; c < s.topo.twin.size(); ++c)
+ if (s.topo.border[c] || c < s.topo.twin[c]) s.edges.push_back(c);
+ // UDIM tiles in use.
+ s.tileList.clear();
+ glm::ivec2 hi(1, 1);
+ for (uint32_t i = 0; i < s.topo.islandCount; ++i) {
+ const uint32_t t = s.topo.islandTriangles[s.topo.islandOffsets[i]];
+ const glm::vec2 c = (m.uvs[t * 3] + m.uvs[t * 3 + 1] + m.uvs[t * 3 + 2]) / 3.0f;
+ const int tile = udimTile(c);
+ s.tileList.push_back(tile);
+ const glm::vec2 o = udimOrigin(tile);
+ hi = glm::max(hi, glm::ivec2(o) + 1);
+ }
+ std::sort(s.tileList.begin(), s.tileList.end());
+ s.tileList.erase(std::unique(s.tileList.begin(), s.tileList.end()), s.tileList.end());
+ s.tiles = hi;
+ s.gpu.setUvs(m.uvs);
+ s.gpu.setEdges(s.edges);
+ s.moving.assign(m.uvs.size(), 0);
+ }
+
+ // Faces the selection covers (all of them in face modes; those touching a selected corner otherwise).
+ void selectionFaces() {
+ const Mesh& m = mesh();
+ const UvSelection& sel = app.doc_.uvSelection;
+ const size_t nt = m.triangleCount();
+ s.faceSel.assign(nt, 0);
+ if (!sel.valid(m)) return;
+ if (sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island) {
+ s.faceSel = sel.faces;
+ } else {
+ for (uint32_t c = 0; c < sel.corners.size(); ++c)
+ if (sel.corners[c]) s.faceSel[c / 3] = 2; // touched
+ }
+ }
+
+ void rebuildColors() {
+ const Mesh& m = mesh();
+ const size_t nt = m.triangleCount(), nc = nt * 3;
+ if (!s.hasUvs) {
+ s.overlay.colors.clear();
+ s.overlay.checker = false;
+ ++s.overlay.serial;
+ return;
+ }
+ const UvSelection& sel = app.doc_.uvSelection;
+ selectionFaces();
+ s.selCorners = uvSelectedCorners(m, s.topo, sel);
+ s.selLo = glm::vec2(std::numeric_limits<float>::max());
+ s.selHi = glm::vec2(std::numeric_limits<float>::lowest());
+ for (uint32_t c : s.selCorners) s.selLo = glm::min(s.selLo, m.uvs[c]), s.selHi = glm::max(s.selHi, m.uvs[c]);
+ const std::vector<uint8_t> isl = uvSelectedIslands(m, s.topo, sel, false);
+ s.selIslands = size_t(std::count(isl.begin(), isl.end(), uint8_t(1)));
+ {
+ const std::vector<float> d = uvIslandDensity(m, s.topo, resolution());
+ double sum = 0.0, w = 0.0;
+ for (uint32_t i = 0; i < s.topo.islandCount; ++i) {
+ if (s.selIslands && !isl[i]) continue;
+ const double k = double(s.topo.islandOffsets[i + 1] - s.topo.islandOffsets[i]);
+ sum += double(d[i]) * k, w += k;
+ }
+ s.selDensity = w > 0.0 ? float(sum / w) : 0.0f;
+ }
+ s.faceCol.resize(nc);
+ s.edgeCol.resize(nc);
+ const bool colors3d = s.modelColors && s.color != 3;
+ s.overlay.colors.assign(colors3d || std::any_of(s.faceSel.begin(), s.faceSel.end(), [](uint8_t f) { return f; }) ? nt : 0, 0);
+ const float faint = nt > 300000 ? 0.10f : 0.18f;
+ for (uint32_t t = 0; t < nt; ++t) {
+ glm::vec3 c(0.85f);
+ float a = 0.13f;
+ switch (s.color) {
+ case 0: c = islandColor(s.topo.island[t]), a = 0.40f; break;
+ case 1: c = s.stretch[t] < 0.0f ? glm::vec3(0.85f, 0.2f, 0.85f) : uvHeatColor(std::clamp(s.stretch[t] * 3.0f, 0.0f, 1.0f)), a = 0.72f; break;
+ case 2: {
+ const float x = s.meanDensity > 0.0f && s.density[t] > 0.0f ? std::log2(s.density[t] / s.meanDensity) : 0.0f;
+ c = uvHeatColor(x * 1.5f), a = 0.72f;
+ break;
+ }
+ default: break;
+ }
+ glm::vec3 model = c;
+ if (s.faceSel[t] == 1) c = kSelect, a = 0.62f, model = glm::mix(c, kSelect, 1.0f);
+ else if (s.faceSel[t] == 2) model = glm::mix(model, kSelect, 0.45f);
+ const uint32_t fc = pack(c, a);
+ s.faceCol[t * 3] = s.faceCol[t * 3 + 1] = s.faceCol[t * 3 + 2] = fc;
+ if (!s.overlay.colors.empty())
+ s.overlay.colors[t] = (pack(colors3d || s.faceSel[t] ? model : glm::vec3(0.62f, 0.58f, 0.53f), 1.0f) & 0x00FFFFFFu);
+ }
+ const bool flags = m.uvFlags.size() == nc;
+ std::vector<uint8_t> hitVertex;
+ if (sel.valid(m) && sel.mode == UvSelectMode::Vertex) {
+ hitVertex.assign(s.topo.uvVertexCount, 0);
+ for (uint32_t c = 0; c < nc; ++c)
+ if (sel.corners[c]) hitVertex[s.topo.uvVertex[c]] = 1;
+ }
+ for (uint32_t c = 0; c < nc; ++c) {
+ bool selected = false;
+ if (sel.valid(m) && sel.mode == UvSelectMode::Edge) selected = sel.corners[c] || (s.topo.twin[c] != kNoCorner && !s.topo.border[c] && sel.corners[s.topo.twin[c]]);
+ if (!hitVertex.empty()) selected = hitVertex[s.topo.uvVertex[c]] && hitVertex[s.topo.uvVertex[cornerNext(c)]];
+ if (selected) s.edgeCol[c] = pack(kSelect, 1.0f);
+ else if (flags && (m.uvFlags[c] & kUvSeam)) s.edgeCol[c] = pack(kSeam, 0.95f);
+ else if (s.topo.border[c]) s.edgeCol[c] = pack(glm::vec3(0.93f), 0.82f);
+ else s.edgeCol[c] = pack(glm::vec3(0.9f), faint);
+ }
+ std::fill(s.moving.begin(), s.moving.end(), uint8_t(0));
+ s.moving.resize(nc, 0);
+ s.gpu.setColors(s.faceCol, s.edgeCol, s.moving);
+ s.overlay.checker = s.modelChecker;
+ s.overlay.checkerScale = float(resolution()) / 32.0f; // a square per 32 texels, as the texture will hold them
+ ++s.overlay.serial;
+ }
+
+ // --- View ----------------------------------------------------------------------------------------------
+
+ ImVec2 toScreen(glm::vec2 uv) const {
+ return ImVec2(s.viewMin.x + s.viewSize.x * 0.5f + (uv.x - s.center.x) * s.zoom,
+ s.viewMin.y + s.viewSize.y * 0.5f - (uv.y - s.center.y) * s.zoom);
+ }
+ glm::vec2 toUv(ImVec2 p) const {
+ return glm::vec2(s.center.x + (p.x - s.viewMin.x - s.viewSize.x * 0.5f) / s.zoom,
+ s.center.y - (p.y - s.viewMin.y - s.viewSize.y * 0.5f) / s.zoom);
+ }
+ void frame(glm::vec2 lo, glm::vec2 hi) {
+ if (s.viewSize.x <= 0 || s.viewSize.y <= 0) return;
+ const glm::vec2 size = glm::max(hi - lo, glm::vec2(1e-4f));
+ s.center = (lo + hi) * 0.5f;
+ s.zoom = std::min(s.viewSize.x / size.x, s.viewSize.y / size.y) * 0.88f;
+ }
+ void frameAll() {
+ const Mesh& m = mesh();
+ if (!s.selCorners.empty() && !app.doc_.uvSelection.empty()) {
+ frame(s.selLo, s.selHi);
+ return;
+ }
+ glm::vec2 lo(0.0f), hi(float(s.tiles.x), float(s.tiles.y));
+ for (const glm::vec2& u : m.uvs) lo = glm::min(lo, u), hi = glm::max(hi, u);
+ frame(lo, hi);
+ }
+
+ // --- Picking -------------------------------------------------------------------------------------------
+
+ // The triangle under `uv` (the smallest when they overlap), or -1.
+ int64_t faceAt(glm::vec2 uv) {
+ const Mesh& m = mesh();
+ const size_t nt = m.triangleCount();
+ const size_t block = 1 << 15, blocks = (nt + block - 1) / block;
+ std::vector<std::pair<float, int64_t>> best(blocks, {std::numeric_limits<float>::max(), -1});
+ poolFor(nt, [&](size_t b, size_t e) {
+ auto& r = best[b / block];
+ for (size_t t = b; t < e; ++t) {
+ const glm::vec2* u = m.uvs.data() + t * 3;
+ if (!insideTriangle(uv, u[0], u[1], u[2]) || m.triangleHidden(uint32_t(t))) continue;
+ const float a = std::abs((u[1].x - u[0].x) * (u[2].y - u[0].y) - (u[2].x - u[0].x) * (u[1].y - u[0].y));
+ if (a < r.first) r = {a, int64_t(t)};
+ }
+ }, block);
+ std::pair<float, int64_t> r{std::numeric_limits<float>::max(), -1};
+ for (const auto& b : best)
+ if (b.first < r.first) r = b;
+ return r.second;
+ }
+ // The nearest corner within `radius` UV units (vertex mode), or the corner starting the nearest edge.
+ int64_t cornerAt(glm::vec2 uv, float radius, bool edge) {
+ const Mesh& m = mesh();
+ const size_t nc = m.uvs.size();
+ const size_t block = 1 << 15, blocks = (nc + block - 1) / block;
+ std::vector<std::pair<float, int64_t>> best(blocks, {radius, -1});
+ poolFor(nc, [&](size_t b, size_t e) {
+ auto& r = best[b / block];
+ for (size_t c = b; c < e; ++c) {
+ const float d = edge ? distToSegment(uv, m.uvs[c], m.uvs[cornerNext(uint32_t(c))]) : glm::distance(uv, m.uvs[c]);
+ if (d < r.first) r = {d, int64_t(c)};
+ }
+ }, block);
+ std::pair<float, int64_t> r{radius, -1};
+ for (const auto& b : best)
+ if (b.first < r.first) r = b;
+ return r.second;
+ }
+
+ // Applies a pick to the selection: faces (per triangle flags) or corners, replacing, adding or removing.
+ void applyPick(const std::vector<uint8_t>& faces, const std::vector<uint8_t>& corners, bool add, bool remove) {
+ Mesh& m = mesh();
+ UvSelection& sel = app.doc_.uvSelection;
+ const bool faceMode = sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island;
+ std::vector<uint8_t>& dst = faceMode ? sel.faces : sel.corners;
+ const std::vector<uint8_t>& src = faceMode ? faces : corners;
+ const size_t n = faceMode ? m.triangleCount() : m.triangleCount() * 3;
+ if (dst.size() != n || (!add && !remove)) dst.assign(n, 0);
+ if (src.size() == n)
+ for (size_t i = 0; i < n; ++i)
+ if (src[i]) dst[i] = remove ? 0 : 1;
+ if (sel.mode == UvSelectMode::Island) uvConvertSelection(m, s.topo, sel, UvSelectMode::Island);
+ s.colorsDirty = true;
+ }
+
+ void clickSelect(glm::vec2 uv, bool add, bool remove) {
+ Mesh& m = mesh();
+ const UvSelection& sel = app.doc_.uvSelection;
+ const size_t nt = m.triangleCount();
+ std::vector<uint8_t> faces, corners;
+ const float radius = 9.0f * app.uiScale_ / s.zoom;
+ if (sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island) {
+ const int64_t t = faceAt(uv);
+ faces.assign(nt, 0);
+ if (t >= 0) {
+ if (sel.mode == UvSelectMode::Island) {
+ const uint32_t i = s.topo.island[size_t(t)];
+ for (uint32_t k = s.topo.islandOffsets[i]; k < s.topo.islandOffsets[i + 1]; ++k) faces[s.topo.islandTriangles[k]] = 1;
+ } else {
+ faces[size_t(t)] = 1;
+ }
+ }
+ } else {
+ const int64_t c = cornerAt(uv, radius, sel.mode == UvSelectMode::Edge);
+ corners.assign(nt * 3, 0);
+ if (c >= 0) {
+ if (sel.mode == UvSelectMode::Vertex) {
+ for (uint32_t k = 0; k < nt * 3; ++k)
+ if (s.topo.uvVertex[k] == s.topo.uvVertex[size_t(c)]) corners[k] = 1;
+ } else {
+ corners[size_t(c)] = 1;
+ }
+ }
+ }
+ applyPick(faces, corners, add, remove);
+ }
+
+ void boxSelect(glm::vec2 a, glm::vec2 b, bool add, bool remove) {
+ Mesh& m = mesh();
+ const UvSelection& sel = app.doc_.uvSelection;
+ const glm::vec2 lo = glm::min(a, b), hi = glm::max(a, b);
+ const size_t nt = m.triangleCount();
+ std::vector<uint8_t> faces, corners;
+ if (sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island) {
+ std::vector<uint32_t> list;
+ uvFacesInRect(m, lo, hi, sel.mode == UvSelectMode::Island, list);
+ faces.assign(nt, 0);
+ for (uint32_t t : list) faces[t] = 1;
+ } else {
+ corners.assign(nt * 3, 0);
+ auto in = [&](glm::vec2 p) { return p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y; };
+ for (uint32_t c = 0; c < nt * 3; ++c)
+ corners[c] = sel.mode == UvSelectMode::Vertex ? in(m.uvs[c]) : in(m.uvs[c]) && in(m.uvs[cornerNext(c)]);
+ if (sel.mode == UvSelectMode::Vertex) { // whole UV vertices
+ std::vector<uint8_t> hit(s.topo.uvVertexCount, 0);
+ for (uint32_t c = 0; c < nt * 3; ++c)
+ if (corners[c]) hit[s.topo.uvVertex[c]] = 1;
+ for (uint32_t c = 0; c < nt * 3; ++c) corners[c] = hit[s.topo.uvVertex[c]];
+ }
+ }
+ applyPick(faces, corners, add, remove);
+ }
+
+ // --- Transforms ----------------------------------------------------------------------------------------
+
+ bool beginTransform(UvEditorState::Drag kind, ImVec2 at, bool modal) {
+ Mesh& m = mesh();
+ if (s.selCorners.empty() || !s.hasUvs) return false;
+ s.drag = kind;
+ s.modal = modal;
+ s.pressAt = at;
+ s.pressUv = toUv(at);
+ s.pivot = (s.selLo + s.selHi) * 0.5f;
+ s.axis = 0;
+ s.live = glm::mat3(1.0f);
+ s.orig.resize(s.selCorners.size());
+ for (size_t i = 0; i < s.selCorners.size(); ++i) s.orig[i] = m.uvs[s.selCorners[i]];
+ const char* label = kind == UvEditorState::Drag::Move ? "Move UVs" : kind == UvEditorState::Drag::Rotate ? "Rotate UVs" : "Scale UVs";
+ s.step = std::make_unique<UvEditStep>(app.doc_, label, s.keepTexture);
+ std::fill(s.moving.begin(), s.moving.end(), uint8_t(0));
+ for (uint32_t c : s.selCorners) s.moving[c] = 1;
+ s.gpu.setColors(s.faceCol, s.edgeCol, s.moving);
+ return true;
+ }
+
+ void updateTransform(ImVec2 at, SDL_Keymod mod) {
+ const glm::vec2 uv = toUv(at);
+ glm::mat3 mat(1.0f);
+ const bool snap = ctrlKey(mod);
+ if (s.drag == UvEditorState::Drag::Move) {
+ glm::vec2 d = uv - s.pressUv;
+ if (s.axis == 1) d.y = 0.0f;
+ if (s.axis == 2) d.x = 0.0f;
+ if (snap) d = glm::round(d * 64.0f) / 64.0f;
+ mat[2] = glm::vec3(d, 1.0f);
+ } else {
+ const glm::vec2 a = s.pressUv - s.pivot, b = uv - s.pivot;
+ glm::mat2 lin(1.0f);
+ if (s.drag == UvEditorState::Drag::Rotate) {
+ float ang = std::atan2(b.y, b.x) - std::atan2(a.y, a.x);
+ if (snap) ang = glm::radians(std::round(glm::degrees(ang) / 15.0f) * 15.0f);
+ lin = glm::mat2(std::cos(ang), std::sin(ang), -std::sin(ang), std::cos(ang));
+ } else {
+ float k = glm::length(a) > 1e-6f ? glm::length(b) / glm::length(a) : 1.0f;
+ if (snap) k = std::max(std::round(k * 10.0f) / 10.0f, 0.1f);
+ lin = glm::mat2(s.axis == 2 ? 1.0f : k, 0.0f, 0.0f, s.axis == 1 ? 1.0f : k);
+ }
+ const glm::vec2 t = s.pivot - lin * s.pivot;
+ mat = glm::mat3(glm::vec3(lin[0], 0.0f), glm::vec3(lin[1], 0.0f), glm::vec3(t, 1.0f));
+ }
+ s.live = mat;
+ // The mesh follows at once (the 2D view through the matrix, the model at a rate it can keep up with).
+ Mesh& m = mesh();
+ poolFor(s.selCorners.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) m.uvs[s.selCorners[i]] = glm::vec2(mat * glm::vec3(s.orig[i], 1.0f));
+ }, 1 << 15);
+ const double now = double(SDL_GetTicksNS()) * 1e-9;
+ const double interval = m.triangleCount() > 200000 ? 0.06 : 0.0;
+ if (now - s.lastLive >= interval) {
+ s.lastLive = now;
+ liveUpdate();
+ }
+ }
+
+ // During a drag: the stretch of the moved triangles, on the model and in the view.
+ void liveUpdate() {
+ Mesh& m = mesh();
+ std::vector<uint8_t> touched(m.triangleCount(), 0);
+ for (uint32_t c : s.selCorners) touched[c / 3] = 1;
+ if (s.color == 1) {
+ poolFor(m.triangleCount(), [&](size_t b, size_t e) {
+ for (size_t t = b; t < e; ++t) {
+ if (!touched[t]) continue;
+ s.stretch[t] = uvTriangleStretchAt(m, uint32_t(t), s.topo, s.stretchCache);
+ const glm::vec3 c = s.stretch[t] < 0.0f ? glm::vec3(0.85f, 0.2f, 0.85f) : uvHeatColor(std::clamp(s.stretch[t] * 3.0f, 0.0f, 1.0f));
+ if (s.faceSel[t] != 1) s.faceCol[t * 3] = s.faceCol[t * 3 + 1] = s.faceCol[t * 3 + 2] = pack(c, 0.72f);
+ if (!s.overlay.colors.empty()) s.overlay.colors[t] = pack(s.faceSel[t] ? glm::mix(c, kSelect, s.faceSel[t] == 1 ? 1.0f : 0.45f) : c, 1.0f) & 0x00FFFFFFu;
+ }
+ }, 1 << 14);
+ s.gpu.setColors(s.faceCol, s.edgeCol, s.moving);
+ }
+ ++s.overlay.serial;
+ m.facesDirty = true; // the model's UVs (checker, texture)
+ }
+
+ void endTransform(bool cancel) {
+ Mesh& m = mesh();
+ if (cancel) {
+ for (size_t i = 0; i < s.selCorners.size(); ++i) m.uvs[s.selCorners[i]] = s.orig[i];
+ }
+ s.live = glm::mat3(1.0f);
+ s.drag = UvEditorState::Drag::None;
+ s.modal = false;
+ std::string note;
+ if (s.step) note = s.step->commit();
+ s.step.reset();
+ m.facesDirty = true;
+ s.dirty = true;
+ if (!cancel) app.status_ = "UVs moved" + note;
+ else app.status_ = "Cancelled";
+ }
+
+ // --- Commands -------------------------------------------------------------------------------------------
+
+ void run(const char* name, Args args = {}) {
+ app.runCommand(name, args);
+ s.dirty = true;
+ }
+
+ Args packArgs() {
+ Args a{{"margin", double(s.marginPx)},
+ {"tiles", double(s.packTiles)},
+ {"rotate", s.rotate},
+ {"equal_density", s.equalDensity},
+ {"resolution", double(resolution())},
+ {"keep_texture", s.keepTexture}};
+ return a;
+ }
+
+ void unwrap() {
+ Mesh& m = mesh();
+ if (s.job || m.triangleCount() == 0) return;
+ const UvUnwrapMethod method = kMethods[std::clamp(s.method, 0, 5)];
+ 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);
+ job->result = std::make_shared<UvUnwrapResult>();
+ job->error = std::make_shared<std::string>();
+ job->subtool = app.doc_.activeSubtoolInfo().id;
+ job->triangles = m.triangleCount();
+ job->method = method;
+ job->keepTexture = s.keepTexture;
+ auto copy = std::make_shared<Mesh>();
+ copy->positions = m.positions;
+ copy->triangles = m.triangles;
+ copy->uvs = m.uvs;
+ copy->uvFlags = m.uvFlags;
+ copy->polygroups = m.polygroups;
+ auto faces = std::make_shared<std::vector<uint8_t>>();
+ const UvSelection& sel = app.doc_.uvSelection;
+ if (sel.valid(m) && !sel.empty() && m.hasUvs()) {
+ faces->assign(m.triangleCount(), 0);
+ if (sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island) *faces = sel.faces;
+ else
+ for (uint32_t c : s.selCorners) (*faces)[c / 3] = 1;
+ }
+ UvUnwrapOptions o;
+ o.method = method;
+ o.resolution = resolution();
+ o.iterations = s.iterations;
+ o.pack = method != UvUnwrapMethod::Unfold;
+ o.packing.resolution = resolution();
+ o.packing.marginPx = s.marginPx;
+ o.packing.tiles = s.packTiles;
+ o.packing.rotate = s.rotate;
+ o.packing.equalDensity = s.equalDensity;
+ std::promise<bool> promise;
+ job->done = promise.get_future();
+ std::thread([promise = std::move(promise), copy, faces, o, progress = job->progress, cancel = job->cancel,
+ result = job->result, error = job->error]() mutable {
+ UvUnwrapOptions opt = o;
+ if (!faces->empty()) opt.faces = faces.get();
+ const bool ok = uvUnwrap(*copy, opt, *result, *error, [&](float f) {
+ progress->store(f);
+ return !cancel->load();
+ });
+ promise.set_value(ok);
+ wakeMainLoop();
+ }).detach();
+ s.job = std::move(job);
+ app.status_ = std::string("Unwrapping (") + uvUnwrapMethodLabel(method) + ") " + std::to_string(m.triangleCount()) + " triangles...";
+ }
+
+ 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)) + "%";
+ return;
+ }
+ const std::unique_ptr<UvEditorState::Job> job = std::move(s.job);
+ ++s.unwraps;
+ if (!job->done.get()) {
+ app.status_ = *job->error;
+ return;
+ }
+ int index = -1;
+ for (int i = 0; i < app.doc_.subtoolCount(); ++i)
+ if (app.doc_.subtools[size_t(i)].id == job->subtool) index = i;
+ if (index < 0 || app.doc_.subtoolMesh(index).triangleCount() != job->triangles) {
+ app.status_ = "Unwrap skipped: the mesh changed while it was being unwrapped";
+ return;
+ }
+ if (index != app.doc_.activeSubtool) app.doc_.selectSubtool(index);
+ if (app.doc_.sculptor.strokeActive()) app.endStroke();
+ UvEditStep step(app.doc_, std::string("Unwrap (") + uvUnwrapMethodLabel(job->method) + ")", job->keepTexture);
+ mesh().uvs = std::move(job->result->uvs);
+ const std::string note = step.commit();
+ app.status_ = std::string("Unwrapped (") + uvUnwrapMethodLabel(job->method) + "): " +
+ std::to_string(job->result->islands) + " islands" + note;
+ s.dirty = true;
+ }
+
+ // --- The 3D tool ----------------------------------------------------------------------------------------
+
+ const std::vector<uint32_t>& twins() {
+ const Mesh& m = mesh();
+ const uint64_t key = (uint64_t(uintptr_t(m.triangles.data())) << 8) ^ m.triangles.size() ^ (uint64_t(app.doc_.activeSubtoolInfo().id) << 48);
+ if (key != s.twinKey || s.twin.size() != m.triangleCount() * 3) {
+ s.twin = cornerTwins(m);
+ s.twinKey = key;
+ }
+ return s.twin;
+ }
+
+ uint32_t nearestVertex(const RayHit& hit) {
+ const Mesh& m = mesh();
+ const glm::uvec3 tri = m.triangles[hit.triangle];
+ uint32_t best = tri.x;
+ for (int j = 1; j < 3; ++j)
+ if (glm::distance(m.positions[tri[j]], hit.position) < glm::distance(m.positions[best], hit.position)) best = tri[j];
+ return best;
+ }
+
+ void toolSelectAt(const RayHit& hit, bool first) {
+ Mesh& m = mesh();
+ if (!s.hasUvs) return;
+ const UvSelection& sel = app.doc_.uvSelection;
+ const size_t nt = m.triangleCount();
+ std::vector<uint8_t> faces, corners;
+ const uint32_t t = hit.triangle;
+ if (sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island) {
+ faces.assign(nt, 0);
+ if (sel.mode == UvSelectMode::Island) {
+ const uint32_t i = s.topo.island[t];
+ for (uint32_t k = s.topo.islandOffsets[i]; k < s.topo.islandOffsets[i + 1]; ++k) faces[s.topo.islandTriangles[k]] = 1;
+ } else {
+ faces[t] = 1;
+ }
+ } else {
+ corners.assign(nt * 3, 0);
+ if (sel.mode == UvSelectMode::Vertex) {
+ const uint32_t v = nearestVertex(hit);
+ for (uint32_t tt : m.vertexTriangles(v))
+ for (uint32_t j = 0; j < 3; ++j)
+ if (m.triangles[tt][j] == v) corners[tt * 3 + j] = 1;
+ } else {
+ float best = std::numeric_limits<float>::max();
+ uint32_t bc = t * 3;
+ for (uint32_t j = 0; j < 3; ++j) {
+ const glm::vec3 a = m.positions[m.triangles[t][j]], b = m.positions[m.triangles[t][(j + 1) % 3]];
+ const glm::vec3 d = b - a;
+ const float k = std::clamp(glm::dot(hit.position - a, d) / std::max(glm::dot(d, d), 1e-20f), 0.0f, 1.0f);
+ const float dist = glm::distance(hit.position, a + d * k);
+ if (dist < best) best = dist, bc = t * 3 + j;
+ }
+ corners[bc] = 1;
+ }
+ }
+ applyPick(faces, corners, !first || s.toolAdding, !s.toolAdding);
+ }
+};
+
+// ---------------------------------------------------------------------------------------------------------------
+
+namespace {
+UvEditorUi uvUi(App& app, std::shared_ptr<UvEditorState>& state) {
+ if (!state) state = std::make_shared<UvEditorState>();
+ return UvEditorUi{app, *state};
+}
+} // namespace
+
+void App::registerUvEditorActions() {
+ auto add = [this](const char* id, const char* label, const char* icon, const char* shortcut, std::function<void()> run,
+ std::function<bool()> checked, std::function<bool()> enabled, const char* description,
+ const char* command = "") {
+ Action a;
+ a.id = id;
+ a.label = label;
+ a.icon = icon;
+ a.palette = kPath;
+ a.shortcut = shortcut;
+ a.run = std::move(run);
+ a.checked = std::move(checked);
+ a.enabled = std::move(enabled);
+ a.description = description;
+ a.command = command;
+ actions_.add(std::move(a));
+ };
+ auto st = [this]() -> UvEditorState& {
+ if (!uvEditor_) uvEditor_ = std::make_shared<UvEditorState>();
+ return *uvEditor_;
+ };
+ auto uvs = [this] { return doc_.mesh.hasUvs(); };
+ auto selected = [this] { return doc_.mesh.hasUvs() && doc_.uvSelection.valid(doc_.mesh) && !doc_.uvSelection.empty(); };
+ auto runUv = [this](const char* name, Args a = {}) {
+ runCommand(name, a);
+ if (uvEditor_) uvEditor_->dirty = true;
+ };
+ add("ui.uv_editor", "UV Editor", ICON_LC_GRID_2X2, "Shift+U",
+ [this] {
+ showUvEditor_ = !showUvEditor_;
+ if (showUvEditor_) { // the model to the left of the window, which opens over the right of the canvas
+ const CanvasRect cr = canvasRect();
+ camera_.frame(sceneBounds());
+ camera_.zoom(-1.5f);
+ camera_.pan(-cr.w * 0.33f, 0.0f, cr.h);
+ }
+ },
+ [this] { return showUvEditor_; }, nullptr,
+ "Open the UV Editor: the Part's UV layout in 2D over the UDIM tiles. Select vertices, edges, faces or islands "
+ "(here or on the model), move, rotate and scale them, mark seams, unwrap, pack, set texel density and lay islands "
+ "into trim sheet strips. Stretch and texel density show live on the model while you edit.");
+ const char* modeIds[] = {"uv.mode_vertex", "uv.mode_edge", "uv.mode_face", "uv.mode_island"};
+ const char* modeLabels[] = {"Vertex", "Edge", "Face", "Island"};
+ const char* modeKeys[] = {"", "", "", ""};
+ for (int i = 0; i < 4; ++i) {
+ const UvSelectMode mode = UvSelectMode(i);
+ add(modeIds[i], modeLabels[i], nullptr, modeKeys[i],
+ [this, mode, runUv] { runUv("uv_select", {{"op", std::string("mode")}, {"mode", std::string(uvSelectModeId(mode))}}); },
+ [this, mode] { return doc_.uvSelection.mode == mode; }, uvs,
+ "Select UV vertices, edges, faces or whole islands (1-4 while the pointer is over the UV view). The "
+ "selection converts when you switch.",
+ "uv_select");
+ }
+ add("uv.unwrap", "Unwrap", ICON_LC_UNFOLD_HORIZONTAL, "", [this] { uvUi(*this, uvEditor_).unwrap(); }, nullptr,
+ [this] { return doc_.mesh.triangleCount() > 0 && !(uvEditor_ && uvEditor_->job); },
+ "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 Polygroups cuts along the "
+ "polygroup 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.",
+ "uv_unwrap");
+ add("uv.pack", "Pack", ICON_LC_PACKAGE, "", [this] { uvUi(*this, uvEditor_).run("uv_pack", uvUi(*this, uvEditor_).packArgs()); },
+ nullptr, uvs,
+ "Pack the selected islands (or all) as large as they fit into the 0-1 tile, or across the chosen number of UDIM "
+ "tiles: turned to their smallest box, scaled to one texel density, with the margin between them.",
+ "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");
+ add("uv.seam_clear", "Clear Seam", nullptr, "", [runUv] { runUv("uv_seam", {{"op", std::string("clear")}}); }, nullptr,
+ selected, "Clear the seams on the selected edges (or the border of the selected faces).", "uv_seam");
+ add("uv.seam_polygroups", "From Polygroups", nullptr, "", [runUv] { runUv("uv_seam", {{"op", std::string("polygroups")}}); },
+ nullptr, nullptr, "Mark every polygroup border as a seam.", "uv_seam");
+ add("uv.seam_islands", "From Islands", nullptr, "", [runUv] { runUv("uv_seam", {{"op", std::string("islands")}}); }, nullptr,
+ uvs, "Mark every current UV island border as a seam (keeps an imported layout's cuts for Unwrap).", "uv_seam");
+ add("uv.seam_angle", "Sharp Edges", nullptr, "",
+ [this, runUv] { runUv("uv_seam", {{"op", std::string("angle")}, {"angle", double(uvEditor_ ? uvEditor_->seamAngle : 60.0f)}}); },
+ nullptr, nullptr, "Mark every edge sharper than the angle as a seam (hard-surface models).", "uv_seam");
+ add("uv.seam_clear_all", "Clear All", nullptr, "", [runUv] { runUv("uv_seam", {{"op", std::string("clear_all")}}); }, nullptr,
+ nullptr, "Clear every marked seam.", "uv_seam");
+ add("uv.tool_seams", "Seam Tool", ICON_LC_SPLINE, "",
+ [this, st] { st().tool = st().tool == 1 ? 0 : 1; }, [this] { return uvEditor_ && uvEditor_->tool == 1; },
+ [this] { return doc_.mesh.triangleCount() > 0; },
+ "Draw seams on the model: drag along the edges you want cut (each stretch follows the shortest edge path); "
+ "Alt+drag clears them. Seams show in red on the model while the UV Editor is open.");
+ add("uv.tool_select", "Select in 3D", ICON_LC_BOX_SELECT, "",
+ [this, st] { st().tool = st().tool == 2 ? 0 : 2; }, [this] { return uvEditor_ && uvEditor_->tool == 2; }, uvs,
+ "Select on the model: click or drag over it to select faces, islands, vertices or edges (the UV Editor's mode); "
+ "Alt removes. The selection shows in both views.");
+ add("uv.pin", "Pin", ICON_LC_PIN, "", [runUv] { runUv("uv_edit", {{"op", std::string("pin")}}); }, nullptr, selected,
+ "Pin the selected UVs: Unfold and Unwrap keep them where they are (P over the UV view).", "uv_edit");
+ add("uv.unpin", "Unpin", ICON_LC_PIN_OFF, "", [runUv] { runUv("uv_edit", {{"op", std::string("unpin")}}); }, nullptr,
+ selected, "Unpin the selected UVs (Alt+P over the UV view).", "uv_edit");
+ add("uv.weld", "Weld", ICON_LC_MERGE, "",
+ [this, runUv] { runUv("uv_edit", {{"op", std::string("weld")}, {"keep_texture", uvEditor_ ? uvEditor_->keepTexture : true}}); },
+ nullptr, selected,
+ "Weld the selected vertices: where they meet across a seam they become one UV each (the seam goes). W over the "
+ "UV view.",
+ "uv_edit");
+ add("uv.split", "Split", ICON_LC_SPLIT, "", [runUv] { runUv("uv_edit", {{"op", std::string("split")}}); }, nullptr, selected,
+ "Split the selection off: the selected edges, or the border of the selected faces, become seams so the faces move "
+ "on their own (Y over the UV view).",
+ "uv_edit");
+ add("uv.straighten", "Straighten", ICON_LC_ALIGN_HORIZONTAL_JUSTIFY_CENTER, "",
+ [this, runUv] { runUv("uv_edit", {{"op", std::string("straighten")}, {"keep_texture", uvEditor_ ? uvEditor_->keepTexture : true}}); },
+ nullptr, selected, "Line the selected vertices up on one horizontal or vertical line (an edge loop, a border).",
+ "uv_edit");
+ add("uv.flip_u", "Flip U", ICON_LC_FLIP_HORIZONTAL, "",
+ [this, runUv] { runUv("uv_edit", {{"op", std::string("flip_u")}, {"keep_texture", uvEditor_ ? uvEditor_->keepTexture : true}}); },
+ nullptr, uvs, "Mirror the selected islands (or all) left to right.", "uv_edit");
+ add("uv.flip_v", "Flip V", ICON_LC_FLIP_VERTICAL, "",
+ [this, runUv] { runUv("uv_edit", {{"op", std::string("flip_v")}, {"keep_texture", uvEditor_ ? uvEditor_->keepTexture : true}}); },
+ nullptr, uvs, "Mirror the selected islands (or all) top to bottom.", "uv_edit");
+ add("uv.rotate_90", "Rotate 90", ICON_LC_ROTATE_CCW, "",
+ [this, runUv] { runUv("uv_transform", {{"rotate", 90.0}, {"keep_texture", uvEditor_ ? uvEditor_->keepTexture : true}}); },
+ nullptr, uvs, "Turn the selection (or everything) a quarter turn counter-clockwise.", "uv_transform");
+ add("uv.density_set", "Set", nullptr, "",
+ [this, runUv] {
+ UvEditorState& s = *uvEditor_;
+ runUv("uv_density", {{"op", std::string("set")}, {"value", double(s.targetDensity)},
+ {"resolution", double(uvUi(*this, uvEditor_).resolution())}, {"keep_texture", s.keepTexture}});
+ },
+ nullptr, uvs, "Scale the selected islands (or all) to the target texel density.", "uv_density");
+ add("uv.density_match", "Match", nullptr, "",
+ [this, runUv] {
+ runUv("uv_density", {{"op", std::string("match")}, {"resolution", double(uvUi(*this, uvEditor_).resolution())},
+ {"keep_texture", uvEditor_->keepTexture}});
+ },
+ nullptr, uvs, "Give the selected islands (or all) one texel density: their mean, so their sizes match on the surface.",
+ "uv_density");
+ add("uv.density_pick", "Pick", nullptr, "", [this] { if (uvEditor_) uvEditor_->targetDensity = std::round(uvEditor_->selDensity); },
+ nullptr, uvs, "Take the target texel density from the selected islands (or the whole Part).");
+ add("uv.density_pack", "Pack at Density", nullptr, "",
+ [this] {
+ UvEditorUi u = uvUi(*this, uvEditor_);
+ Args a = u.packArgs();
+ a["density"] = double(uvEditor_->targetDensity);
+ u.run("uv_pack", a);
+ },
+ nullptr, uvs,
+ "Pack at exactly the target texel density, using as many UDIM tiles as it takes (1001, 1002, ...): every island "
+ "keeps the same texels per unit across the tiles.",
+ "uv_pack");
+ add("uv.trim", "Assign to Strip", ICON_LC_STRETCH_HORIZONTAL, "",
+ [this, runUv] {
+ UvEditorState& s = *uvEditor_;
+ runUv("uv_trim", {{"strip", double(s.strip + 1)}, {"strips", std::string(s.strips)}, {"fit_width", s.fitWidth},
+ {"resolution", double(uvUi(*this, uvEditor_).resolution())}});
+ },
+ nullptr, uvs,
+ "Lay the selected islands into the chosen trim sheet strip: turned lengthwise, scaled to the strip's height and "
+ "lined up along u. The texture stays put, so the islands pick up the strip's look.",
+ "uv_trim");
+ add("uv.frame", "Frame", ICON_LC_SCAN, "", [this] { uvUi(*this, uvEditor_).frameAll(); }, nullptr, nullptr,
+ "Fit the selection (or the whole layout) in the UV view (F over it).");
+}
+
+bool App::uvEditorBusy() const { return uvEditor_ && uvEditor_->job; }
+
+void App::pollUvEditor() {
+ if (uvEditor_) uvUi(*this, uvEditor_).poll();
+}
+
+void App::uvEditorChanged() {
+ if (uvEditor_) uvEditor_->dirty = true;
+}
+
+const MeshOverlay* App::uvEditorOverlay(uint32_t subtool) {
+ if (!showUvEditor_ || !uvEditor_ || subtool != doc_.activeSubtoolInfo().id) return nullptr;
+ if (!uvEditor_->hasUvs || uvEditor_->subtool != subtool) return nullptr;
+ return &uvEditor_->overlay;
+}
+
+void App::drawUvEditor() {
+ if (!showUvEditor_) {
+ if (uvEditor_ && uvEditor_->tool) uvEditor_->tool = 0;
+ return;
+ }
+ UvEditorUi u = uvUi(*this, uvEditor_);
+ UvEditorState& s = *uvEditor_;
+ const float scale = uiScale_;
+ if (!s.gpuTried) {
+ s.gpuTried = true;
+ if (!s.gpu.init(s.gpuError)) SDL_Log("UV Editor: %s", s.gpuError.c_str());
+ }
+ u.refresh();
+ const CanvasRect cr = canvasRect();
+ ImGui::SetNextWindowPos(ImVec2(cr.x + cr.w * 0.34f, cr.y + 6 * scale), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(cr.w * 0.66f - 6 * scale, cr.h - 12 * scale), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(520 * scale, 360 * scale), ImVec2(FLT_MAX, FLT_MAX));
+ ImGui::SetNextWindowBgAlpha(1.0f);
+ if (!ImGui::Begin("UV Editor", &showUvEditor_, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar)) {
+ ImGui::End();
+ return;
+ }
+ Mesh& m = doc_.mesh;
+ const ImGuiStyle& style = ImGui::GetStyle();
+
+ // Toolbar: selection mode, colours, image, the model overlay, frame.
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextDisabled("Select");
+ ImGui::SameLine();
+ ui::Segmented(*this, {"uv.mode_vertex", "uv.mode_edge", "uv.mode_face", "uv.mode_island"}, 248 * scale);
+ // The rest of the toolbar wraps onto a second line when the window is narrow.
+ const float frameW = 74 * scale;
+ const float rowStart = ImGui::GetCursorPosX();
+ auto nextOnLine = [&](float itemW, float gap) {
+ ImGui::SameLine(0, gap);
+ if (ImGui::GetContentRegionAvail().x < itemW + frameW + style.ItemSpacing.x) {
+ ImGui::NewLine();
+ ImGui::SetCursorPosX(rowStart);
+ }
+ };
+ nextOnLine(130 * scale, 14 * scale);
+ ImGui::SetNextItemWidth(130 * scale);
+ if (ImGui::Combo("##uvcolor", &s.color, kColorLabels, 4)) s.colorsDirty = true;
+ ui::HelpText("Colours", nullptr,
+ "What the faces show, here and on the model: Islands (a colour each), Stretch (green: true to the surface; "
+ "yellow to red: stretched or squashed; magenta: folded over), Texel Density (blue: fewer texels than the "
+ "mean, red: more) or Plain.",
+ kPath);
+ nextOnLine(110 * scale, style.ItemSpacing.x);
+ ImGui::SetNextItemWidth(110 * scale);
+ ImGui::Combo("##uvimage", &s.image, kImageLabels, 3);
+ ui::HelpText("Image", nullptr, "Behind the layout: nothing, a checker, or the painted texture (tile 1001).", kPath);
+ nextOnLine(ImGui::CalcTextSize("Model").x + ImGui::GetFrameHeight() * 2, 14 * scale);
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextDisabled("On model");
+ ImGui::SameLine();
+ if (ui::Checkbox("Colours##uvmodel", &s.modelColors)) s.colorsDirty = true;
+ ui::HelpText("Colours on the model", nullptr,
+ "Show the same colours on the model (islands, stretch, density and the selection), live while you edit.",
+ kPath);
+ ImGui::SameLine();
+ if (ui::Checkbox("Checker##uvchecker", &s.modelChecker)) s.colorsDirty = true;
+ ui::HelpText("Checker on the model", nullptr,
+ "A checker on the model's UVs (tinted per UDIM tile): squares that stay square mean no stretch.", kPath);
+ ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - frameW);
+ ui::ActionButton(*this, "uv.frame", ImVec2(frameW, 0));
+
+ // Sidebar on the right, the view in the rest.
+ const float sideW = 236 * scale;
+ const ImVec2 avail = ImGui::GetContentRegionAvail();
+ const float statusH = ImGui::GetTextLineHeightWithSpacing() + 2 * scale;
+ const ImVec2 viewSize(std::max(avail.x - sideW - style.ItemSpacing.x, 64.0f), std::max(avail.y - statusH, 64.0f));
+ const ImVec2 viewMin = ImGui::GetCursorScreenPos();
+ s.viewMin = viewMin;
+ s.viewSize = viewSize;
+ if (s.zoom <= 0.0f) {
+ u.frame(glm::vec2(0.0f), glm::vec2(float(s.tiles.x), float(s.tiles.y)));
+ if (s.zoom <= 0.0f) s.zoom = 400.0f * scale;
+ }
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ ImGui::InvisibleButton("##uvview", viewSize, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight |
+ ImGuiButtonFlags_MouseButtonMiddle);
+ s.hovered = ImGui::IsItemHovered();
+ const ImGuiIO& io = ImGui::GetIO();
+ const ImVec2 mouse = io.MousePos;
+ const SDL_Keymod mod = SDL_GetModState();
+ using D = UvEditorState::Drag;
+
+ // The gizmo: the selection's box, its corners scale, the knob above rotates, inside moves.
+ glm::vec2 boxLo = s.selLo, boxHi = s.selHi;
+ const bool haveSel = s.hasUvs && !s.selCorners.empty() && !doc_.uvSelection.empty();
+ auto gizmoCorners = [&](ImVec2 out[4]) {
+ const glm::vec2 p[4] = {boxLo, {boxHi.x, boxLo.y}, boxHi, {boxLo.x, boxHi.y}};
+ for (int i = 0; i < 4; ++i) out[i] = u.toScreen(glm::vec2(s.live * glm::vec3(p[i], 1.0f)));
+ };
+ auto handleAt = [&](ImVec2 p) -> D {
+ if (!haveSel) return D::None;
+ ImVec2 c[4];
+ gizmoCorners(c);
+ const float r = 7.0f * scale;
+ for (int i = 0; i < 4; ++i)
+ if (std::abs(p.x - c[i].x) <= r && std::abs(p.y - c[i].y) <= r) return D::Scale;
+ const ImVec2 top((c[2].x + c[3].x) * 0.5f, std::min(c[2].y, c[3].y) - 22 * scale);
+ if (std::hypot(p.x - top.x, p.y - top.y) <= r + 2 * scale) return D::Rotate;
+ const float x0 = std::min(c[0].x, c[2].x), x1 = std::max(c[0].x, c[2].x), y0 = std::min(c[0].y, c[2].y), y1 = std::max(c[0].y, c[2].y);
+ if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1) return D::Move;
+ return D::None;
+ };
+
+ // Input over the view.
+ if (s.hovered && io.MouseWheel != 0.0f && s.drag == D::None) {
+ const glm::vec2 before = u.toUv(mouse);
+ s.zoom = std::clamp(s.zoom * std::pow(1.18f, io.MouseWheel), 8.0f, 1e6f);
+ const glm::vec2 after = u.toUv(mouse);
+ s.center += before - after;
+ }
+ if (s.hovered && s.drag == D::None && !s.modal &&
+ (ImGui::IsMouseClicked(ImGuiMouseButton_Middle) || ImGui::IsMouseClicked(ImGuiMouseButton_Right) ||
+ (ImGui::IsMouseClicked(ImGuiMouseButton_Left) && spaceHeld_))) {
+ s.drag = D::Pan;
+ }
+ if (s.drag == D::Pan) {
+ s.center -= glm::vec2(io.MouseDelta.x, -io.MouseDelta.y) / s.zoom;
+ if (!ImGui::IsMouseDown(ImGuiMouseButton_Middle) && !ImGui::IsMouseDown(ImGuiMouseButton_Right) &&
+ !ImGui::IsMouseDown(ImGuiMouseButton_Left))
+ s.drag = D::None;
+ }
+ if (s.modal) { // G / R / S: follows the mouse; click or Enter confirms, right click or Esc cancels
+ u.updateTransform(mouse, mod);
+ if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) u.endTransform(false);
+ else if (ImGui::IsMouseClicked(ImGuiMouseButton_Right)) u.endTransform(true);
+ } else if (s.hovered && s.drag == D::None && ImGui::IsMouseClicked(ImGuiMouseButton_Left) && s.hasUvs) {
+ const D h = handleAt(mouse);
+ if (h != D::None && !(mod & (SDL_KMOD_SHIFT | SDL_KMOD_CTRL))) {
+ u.beginTransform(h, mouse, false);
+ } else {
+ s.pressAt = mouse;
+ s.pressUv = u.toUv(mouse);
+ s.boxAdd = (mod & SDL_KMOD_SHIFT) != 0;
+ s.boxRemove = ctrlKey(mod);
+ s.drag = D::Box;
+ }
+ }
+ if (!s.modal && (s.drag == D::Move || s.drag == D::Rotate || s.drag == D::Scale)) {
+ u.updateTransform(mouse, mod);
+ if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) u.endTransform(false);
+ }
+ if (s.drag == D::Box && !ImGui::IsMouseDown(ImGuiMouseButton_Left)) {
+ const float moved = std::hypot(mouse.x - s.pressAt.x, mouse.y - s.pressAt.y);
+ if (moved < 4.0f * scale) {
+ u.clickSelect(s.pressUv, s.boxAdd, s.boxRemove);
+ // A click on something already part of the selection then dragged moves it: handled by the gizmo.
+ } else {
+ u.boxSelect(s.pressUv, u.toUv(mouse), s.boxAdd, s.boxRemove);
+ }
+ s.drag = D::None;
+ u.refresh();
+ }
+
+ // Draw: the GPU view, then the overlays.
+ const glm::vec2 half = glm::vec2(viewSize.x, viewSize.y) * 0.5f / s.zoom;
+ UvViewRenderer::View v;
+ v.min = s.center - half;
+ v.max = s.center + half;
+ v.imageMode = s.image;
+ v.image = s.image == 2 && hasTexture(m) ? renderer_.paintTexture(doc_.activeSubtoolInfo().id) : 0;
+ v.imageOpacity = s.image == 2 ? 1.0f : s.imageOpacity;
+ v.checkerScale = s.checkerScale;
+ v.tiles = s.tiles;
+ v.move = s.live;
+ const int fbw = int(viewSize.x * io.DisplayFramebufferScale.x), fbh = int(viewSize.y * io.DisplayFramebufferScale.y);
+ const GLuint tex = s.gpu.draw(fbw, fbh, v);
+ const ImVec2 viewMax(viewMin.x + viewSize.x, viewMin.y + viewSize.y);
+ if (tex) dl->AddImage(ImTextureID(uintptr_t(tex)), viewMin, viewMax, ImVec2(0, 1), ImVec2(1, 0));
+ else dl->AddRectFilled(viewMin, viewMax, IM_COL32(25, 25, 27, 255));
+ dl->PushClipRect(viewMin, viewMax, true);
+ // UDIM tile numbers.
+ for (int ty = 0; ty < std::max(s.tiles.y, 1) + 1; ++ty)
+ for (int tx = 0; tx < std::min(std::max(s.tiles.x, 1) + 1, 10); ++tx) {
+ const ImVec2 p = u.toScreen(glm::vec2(float(tx), float(ty) + 1.0f));
+ const bool used = tx < s.tiles.x && ty < s.tiles.y;
+ char label[8];
+ std::snprintf(label, sizeof label, "%d", 1001 + tx + 10 * ty);
+ dl->AddText(ImVec2(p.x + 5 * scale, p.y + 3 * scale), used ? IM_COL32(170, 170, 182, 210) : IM_COL32(110, 110, 118, 150), label);
+ }
+ // Trim strips (while the Trim Sheet section is open).
+ if (ImGui::GetStateStorage()->GetBool(ImGui::GetID("uvtrimopen"), false)) {
+ std::vector<TrimStrip> strips;
+ std::string err;
+ if (parseTrimStrips(s.strips, strips, err))
+ for (size_t i = 0; i < strips.size(); ++i) {
+ const ImVec2 a = u.toScreen(glm::vec2(0.0f, strips[i].v1)), b = u.toScreen(glm::vec2(1.0f, strips[i].v0));
+ const bool on = int(i) == s.strip;
+ dl->AddRectFilled(a, b, on ? IM_COL32(240, 136, 46, 38) : IM_COL32(120, 160, 255, 14));
+ dl->AddRect(a, b, on ? IM_COL32(240, 136, 46, 200) : IM_COL32(150, 180, 255, 90), 0, 0, on ? 2.0f : 1.0f);
+ dl->AddText(ImVec2(b.x + 6 * scale, a.y + 2 * scale), on ? IM_COL32(255, 180, 110, 255) : IM_COL32(160, 180, 220, 200),
+ strips[i].name.c_str());
+ }
+ }
+ // Pins and selected vertices.
+ if (s.hasUvs && m.uvFlags.size() == m.uvs.size()) {
+ size_t drawn = 0;
+ for (uint32_t c = 0; c < m.uvFlags.size() && drawn < 5000; ++c)
+ if ((m.uvFlags[c] & kUvPin) && s.topo.uvVertex.size() > c) {
+ const ImVec2 p = u.toScreen(m.uvs[c]);
+ dl->AddCircleFilled(p, 4.0f * scale, IM_COL32(90, 200, 255, 255));
+ dl->AddCircle(p, 4.0f * scale, IM_COL32(10, 30, 50, 255));
+ ++drawn;
+ }
+ }
+ if (s.hasUvs && doc_.uvSelection.mode == UvSelectMode::Vertex && s.selCorners.size() < 60000) {
+ for (uint32_t c : s.selCorners) {
+ const ImVec2 p = u.toScreen(glm::vec2(s.live * glm::vec3(m.uvs[c], 1.0f)));
+ if (s.drag == D::None || s.step == nullptr) dl->AddRectFilled(ImVec2(p.x - 2.5f * scale, p.y - 2.5f * scale), ImVec2(p.x + 2.5f * scale, p.y + 2.5f * scale), theme::u32(theme::accent));
+ }
+ }
+ // The gizmo.
+ if (haveSel && s.drag != D::Box) {
+ ImVec2 c[4];
+ if (s.drag != D::None) boxLo = s.selLo, boxHi = s.selHi;
+ gizmoCorners(c);
+ const ImU32 col = IM_COL32(255, 168, 80, 230);
+ dl->AddPolyline(c, 4, col, ImDrawFlags_Closed, 1.2f * scale);
+ const D hot = s.drag != D::None ? s.drag : s.hovered ? handleAt(mouse) : D::None;
+ for (int i = 0; i < 4; ++i) {
+ const float r = 4.5f * scale;
+ dl->AddRectFilled(ImVec2(c[i].x - r, c[i].y - r), ImVec2(c[i].x + r, c[i].y + r), hot == D::Scale ? IM_COL32(255, 220, 160, 255) : col);
+ }
+ const ImVec2 topMid((c[2].x + c[3].x) * 0.5f, (c[2].y + c[3].y) * 0.5f);
+ const ImVec2 knob(topMid.x, std::min(c[2].y, c[3].y) - 22 * scale);
+ dl->AddLine(topMid, knob, col, 1.2f * scale);
+ dl->AddCircleFilled(knob, 6.0f * scale, hot == D::Rotate ? IM_COL32(255, 220, 160, 255) : col);
+ const ImVec2 mid((c[0].x + c[2].x) * 0.5f, (c[0].y + c[2].y) * 0.5f);
+ dl->AddLine(ImVec2(mid.x - 6 * scale, mid.y), ImVec2(mid.x + 6 * scale, mid.y), col, 1.2f * scale);
+ dl->AddLine(ImVec2(mid.x, mid.y - 6 * scale), ImVec2(mid.x, mid.y + 6 * scale), col, 1.2f * scale);
+ }
+ if (s.drag == D::Box) {
+ const ImVec2 a = s.pressAt;
+ dl->AddRectFilled(ImVec2(std::min(a.x, mouse.x), std::min(a.y, mouse.y)), ImVec2(std::max(a.x, mouse.x), std::max(a.y, mouse.y)),
+ IM_COL32(240, 136, 46, 30));
+ dl->AddRect(ImVec2(std::min(a.x, mouse.x), std::min(a.y, mouse.y)), ImVec2(std::max(a.x, mouse.x), std::max(a.y, mouse.y)),
+ IM_COL32(240, 136, 46, 220), 0, 0, 1.0f * scale);
+ }
+ if (!s.hasUvs) {
+ const char* msg = m.triangleCount() ? "No UVs yet: pick a method and Unwrap (or mark seams first)" : "No mesh";
+ const ImVec2 ts = ImGui::CalcTextSize(msg);
+ const ImVec2 at(viewMin.x + (viewSize.x - ts.x) * 0.5f, viewMin.y + viewSize.y * 0.5f - ts.y);
+ dl->AddRectFilled(ImVec2(at.x - 12 * scale, at.y - 8 * scale), ImVec2(at.x + ts.x + 12 * scale, at.y + ts.y + 8 * scale),
+ IM_COL32(24, 24, 27, 235), 6 * scale);
+ dl->AddText(at, IM_COL32(215, 215, 220, 255), msg);
+ }
+ if (s.job) {
+ const float f = s.job->progress->load();
+ 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->PopClipRect();
+ dl->AddRect(viewMin, viewMax, IM_COL32(60, 60, 66, 255));
+ ui::HelpText("UV view", nullptr,
+ "Click to select (Shift adds, Ctrl removes), drag a box; drag the box handles to move, scale (corners) or "
+ "rotate (the knob). Keys over the view: 1-4 modes, A all, Alt+A none, Ctrl+I invert, G / R / S move, rotate, "
+ "scale (X / Y lock an axis, Ctrl snaps), F frame, P / Alt+P pin, W weld, Y split. Wheel zooms, right or "
+ "middle drag pans.",
+ kPath);
+
+ // Status line under the view.
+ {
+ char line[256];
+ const UvSelection& sel = doc_.uvSelection;
+ const size_t nsel = sel.valid(m) ? sel.count() : 0;
+ std::string tiles;
+ for (size_t i = 0; i < s.tileList.size() && i < 6; ++i) tiles += (i ? ", " : "") + std::to_string(s.tileList[i]);
+ if (s.tileList.size() > 6) tiles += "...";
+ if (s.hasUvs)
+ std::snprintf(line, sizeof line, "%u islands | %zu selected | stretch %.3f%s | %.0f tx/u at %dK | %s",
+ s.topo.islandCount, nsel, double(s.meanStretch), s.flipped > 0.001f ? " (folds)" : "",
+ double(s.meanDensity), u.resolution() / 1024, tiles.c_str());
+ else
+ std::snprintf(line, sizeof line, "%zu seam edges marked", uvSeamCount(m));
+ ImGui::TextDisabled("%s", line);
+ }
+
+ // Sidebar.
+ ImGui::SetCursorScreenPos(ImVec2(viewMax.x + style.ItemSpacing.x, viewMin.y));
+ ImGui::BeginChild("##uvside", ImVec2(sideW, avail.y), false);
+ const float w = ImGui::GetContentRegionAvail().x;
+ const float halfW = (w - style.ItemSpacing.x) * 0.5f;
+ auto section = [&](const char* title, bool open) { return ImGui::CollapsingHeader(title, open ? ImGuiTreeNodeFlags_DefaultOpen : 0); };
+ if (section("Unwrap", true)) {
+ const char* labels[6];
+ for (int i = 0; i < 6; ++i) labels[i] = uvUnwrapMethodLabel(kMethods[i]);
+ ImGui::SetNextItemWidth(w);
+ ImGui::Combo("##uvmethod", &s.method, labels, 6);
+ ui::HelpText("Method", nullptr,
+ "Least Stretch: angles and lengths, along the marked seams (the default). Conformal (LSCM): angles only. "
+ "By Polygroups: also cuts along the polygroup borders. Planar: each piece projected flat. Unfold Islands: "
+ "the current islands flattened again where they are, keeping pins. Auto Seams: finds its own seams.",
+ kPath);
+ if (kMethods[std::clamp(s.method, 0, 5)] == UvUnwrapMethod::Isometric || kMethods[s.method] == UvUnwrapMethod::Polygroups ||
+ kMethods[s.method] == UvUnwrapMethod::Unfold) {
+ float it = float(s.iterations);
+ ImGui::SetNextItemWidth(w);
+ if (ui::SliderInside("##uviter", &it, 0.0f, 40.0f, "Refine %.0f")) s.iterations = int(it);
+ ui::HelpText("Refine", nullptr, "Least-stretch steps after the conformal start: more keeps lengths better (0 = conformal).", kPath);
+ }
+ const bool sel = doc_.uvSelection.valid(m) && !doc_.uvSelection.empty() && s.hasUvs;
+ ImGui::PushStyleColor(ImGuiCol_Button, theme::accent);
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, theme::accentHover);
+ ImGui::PushStyleColor(ImGuiCol_Text, theme::textOnAccent);
+ ImGui::BeginDisabled(s.job != nullptr || m.triangleCount() == 0);
+ if (ImGui::Button(sel ? "Unwrap Selected##uvunwrap" : "Unwrap##uvunwrap", ImVec2(w, 0))) u.unwrap();
+ ImGui::EndDisabled();
+ ImGui::PopStyleColor(3);
+ ui::HelpAction(*this, "uv.unwrap");
+ ImGui::Spacing();
+ ImGui::TextDisabled("Seams (%zu edges)", uvSeamCount(m));
+ ui::ActionButton(*this, "uv.tool_seams", ImVec2(halfW, 0), ui::Look::IconLabel);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.tool_select", ImVec2(-1, 0), ui::Look::IconLabel);
+ ui::ActionButton(*this, "uv.seam_mark", ImVec2(halfW, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.seam_clear", ImVec2(-1, 0));
+ ui::ActionButton(*this, "uv.seam_polygroups", ImVec2(halfW, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.seam_islands", ImVec2(-1, 0));
+ ImGui::SetNextItemWidth(halfW);
+ ui::SliderInside("##uvangle", &s.seamAngle, 10.0f, 150.0f, "%.0f deg");
+ ui::HelpText("Sharp angle", nullptr, "Sharp Edges marks the edges whose faces meet at more than this angle.", kPath);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.seam_angle", ImVec2(-1, 0));
+ ui::ActionButton(*this, "uv.seam_clear_all", ImVec2(w, 0));
+ }
+ if (section("Pack", true)) {
+ ImGui::SetNextItemWidth(w);
+ ui::SliderInside("##uvmargin", &s.marginPx, 0.0f, 64.0f, "Margin %.0f px");
+ ui::HelpText("Margin", nullptr, "Texels kept free between islands (half of it at the tile borders), at the texture's size.", kPath);
+ float tiles = float(s.packTiles);
+ ImGui::SetNextItemWidth(w);
+ if (ui::SliderInside("##uvtiles", &tiles, 1.0f, 10.0f, "UDIM Tiles %.0f")) s.packTiles = int(std::round(tiles));
+ ui::HelpText("UDIM tiles", nullptr, "Pack across this many tiles (1001 onwards, along u): more tiles, more texels per island.", kPath);
+ ui::Checkbox("Rotate##uvrot", &s.rotate);
+ ui::HelpText("Rotate", nullptr, "Turn islands to their smallest box and allow quarter turns, so more fit.", kPath);
+ ImGui::SameLine();
+ ui::Checkbox("Equal density##uveq", &s.equalDensity);
+ ui::HelpText("Equal density", nullptr, "Scale the islands to one texel density before packing (off: they keep their sizes relative to each other).", kPath);
+ ui::ActionButton(*this, "uv.pack", ImVec2(w, 0), ui::Look::IconLabel);
+ }
+ if (section("Texel Density", true)) {
+ ImGui::SetNextItemWidth(halfW);
+ if (m.texture) {
+ ImGui::BeginDisabled();
+ int texChoice = 1;
+ for (int i = 0; i < 4; ++i)
+ if (kSizes[i] == u.resolution()) texChoice = i;
+ ImGui::Combo("##uvres", &texChoice, kSizeLabels, 4);
+ ImGui::EndDisabled();
+ } else if (ImGui::Combo("##uvres", &s.sizeChoice, kSizeLabels, 4)) {
+ s.dirty = true;
+ }
+ ui::HelpText("Texture size", nullptr, "The texture size densities and margins are measured at (the Part's texture's when it has one).", kPath);
+ ImGui::SameLine();
+ ImGui::TextDisabled("%s %.0f", s.selIslands ? "Selected" : "Mean", double(s.selDensity));
+ ImGui::SetNextItemWidth(halfW);
+ ImGui::InputFloat("##uvtarget", &s.targetDensity, 0.0f, 0.0f, "%.0f tx/u");
+ s.targetDensity = std::clamp(s.targetDensity, 1.0f, 65536.0f);
+ ui::HelpText("Target density", nullptr, "Texels per unit of surface length that Set and Pack at Density give the islands.", kPath);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.density_pick", ImVec2(-1, 0));
+ ui::ActionButton(*this, "uv.density_set", ImVec2(halfW, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.density_match", ImVec2(-1, 0));
+ ui::ActionButton(*this, "uv.density_pack", ImVec2(w, 0));
+ }
+ const bool trimOpen = section("Trim Sheet", false);
+ ImGui::GetStateStorage()->SetBool(ImGui::GetID("uvtrimopen"), trimOpen);
+ if (trimOpen) {
+ ImGui::SetNextItemWidth(w);
+ ImGui::InputText("##uvstrips", s.strips, sizeof s.strips);
+ ui::HelpText("Strips", nullptr,
+ "The sheet's horizontal strips: a count (4 equal strips), heights from the top (0.5,0.25,0.25), or v "
+ "ranges (0-0.5;0.5-1). They show over tile 1001.",
+ kPath);
+ std::vector<TrimStrip> strips;
+ std::string err;
+ if (parseTrimStrips(s.strips, strips, err)) {
+ s.strip = std::clamp(s.strip, 0, int(strips.size()) - 1);
+ for (size_t i = 0; i < strips.size(); ++i) {
+ char label[64];
+ std::snprintf(label, sizeof label, "%s (%.2f-%.2f)##uvstrip%zu", strips[i].name.c_str(), double(strips[i].v0),
+ double(strips[i].v1), i);
+ if (ImGui::RadioButton(label, s.strip == int(i))) s.strip = int(i);
+ }
+ } else {
+ ImGui::TextColored(ImVec4(0.9f, 0.4f, 0.3f, 1.0f), "%s", err.c_str());
+ }
+ ui::Checkbox("Fit width##uvfit", &s.fitWidth);
+ ui::HelpText("Fit width", nullptr, "Squeeze or stretch the row to fill u 0-1 exactly; off keeps the islands' proportions (trims repeat in u).", kPath);
+ ui::ActionButton(*this, "uv.trim", ImVec2(w, 0), ui::Look::IconLabel);
+ }
+ if (section("Edit", true)) {
+ ui::ActionButton(*this, "uv.pin", ImVec2(halfW, 0), ui::Look::IconLabel);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.unpin", ImVec2(-1, 0), ui::Look::IconLabel);
+ ui::ActionButton(*this, "uv.weld", ImVec2(halfW, 0), ui::Look::IconLabel);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.split", ImVec2(-1, 0), ui::Look::IconLabel);
+ ui::ActionButton(*this, "uv.straighten", ImVec2(halfW, 0), ui::Look::IconLabel);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.rotate_90", ImVec2(-1, 0), ui::Look::IconLabel);
+ ui::ActionButton(*this, "uv.flip_u", ImVec2(halfW, 0), ui::Look::IconLabel);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "uv.flip_v", ImVec2(-1, 0), ui::Look::IconLabel);
+ }
+ if (section("Display", false)) {
+ if (s.image == 1) {
+ ImGui::SetNextItemWidth(w);
+ if (ui::SliderInside("##uvcheckscale", &s.checkerScale, 2.0f, 32.0f, "Checker %.0f per tile")) s.colorsDirty = true;
+ }
+ if (s.image != 0) {
+ ImGui::SetNextItemWidth(w);
+ ui::SliderInside("##uvimgop", &s.imageOpacity, 0.0f, 1.0f, "Image %.2f");
+ }
+ }
+ ImGui::Spacing();
+ ui::Checkbox("Paint stays on the model##uvkeep", &s.keepTexture);
+ ui::HelpText("Paint stays on the model", nullptr,
+ "When the Part has a painted texture, every UV edit moves the paint with it (re-projected onto the new "
+ "layout in the same undo step), so the model looks the same. Off: the texture stays put and the model "
+ "shows the UVs' new place on it (what trim sheets want).",
+ kPath);
+ ImGui::EndChild();
+ ImGui::End();
+}
+
+bool App::uvEditorKey(SDL_Keycode key, SDL_Keymod mod) {
+ if (!showUvEditor_ || !uvEditor_) return false;
+ auto runAction = [this](const char* id) {
+ const Action* a = actions_.find(id);
+ if (a && a->run && (!a->enabled || a->enabled())) a->run();
+ };
+ UvEditorState& s = *uvEditor_;
+ UvEditorUi u = uvUi(*this, uvEditor_);
+ using D = UvEditorState::Drag;
+ if (s.modal) {
+ if (key == SDLK_ESCAPE) u.endTransform(true);
+ else if (key == SDLK_RETURN || key == SDLK_KP_ENTER) u.endTransform(false);
+ else if (key == SDLK_X) s.axis = s.axis == 1 ? 0 : 1;
+ else if (key == SDLK_Y) s.axis = s.axis == 2 ? 0 : 2;
+ return true;
+ }
+ if (!s.hovered || s.drag != D::None) return false;
+ const bool ctrl = ctrlKey(mod), alt = (mod & SDL_KMOD_ALT) != 0, shift = (mod & SDL_KMOD_SHIFT) != 0;
+ if (key >= SDLK_1 && key <= SDLK_4 && !ctrl && !alt && !shift) {
+ runCommand("uv_select", {{"op", std::string("mode")}, {"mode", std::string(uvSelectModeId(UvSelectMode(key - SDLK_1)))}});
+ s.dirty = true;
+ return true;
+ }
+ if (key == SDLK_A && !ctrl && !shift) {
+ runCommand("uv_select", {{"op", std::string(alt ? "none" : "all")}});
+ s.dirty = true;
+ return true;
+ }
+ if (key == SDLK_I && ctrl) {
+ runCommand("uv_select", {{"op", std::string("invert")}});
+ s.dirty = true;
+ return true;
+ }
+ if ((key == SDLK_G || key == SDLK_R || key == SDLK_S) && !ctrl && !alt && !shift) {
+ if (!u.beginTransform(key == SDLK_G ? D::Move : key == SDLK_R ? D::Rotate : D::Scale, ImGui::GetIO().MousePos, true))
+ status_ = "Select some UVs first";
+ return true;
+ }
+ if (key == SDLK_F && !ctrl && !alt) {
+ u.frameAll();
+ return true;
+ }
+ if (key == SDLK_HOME) {
+ u.frame(glm::vec2(0.0f), glm::vec2(1.0f));
+ return true;
+ }
+ if (key == SDLK_P && !ctrl) {
+ runAction(alt ? "uv.unpin" : "uv.pin");
+ return true;
+ }
+ if (key == SDLK_W && !ctrl && !alt) {
+ runAction("uv.weld");
+ return true;
+ }
+ if (key == SDLK_Y && !ctrl && !alt) {
+ runAction("uv.split");
+ return true;
+ }
+ return false;
+}
+
+bool App::uvToolActive() const { return showUvEditor_ && uvEditor_ && uvEditor_->tool != 0; }
+
+bool App::uvToolMouseDown(float x, float y, SDL_Keymod mod) {
+ if (!uvToolActive() || ctrlKey(mod) || previewLod_ >= 0) return false;
+ UvEditorState& s = *uvEditor_;
+ UvEditorUi u = uvUi(*this, uvEditor_);
+ RayHit hit;
+ if (!pick(x, y, hit)) return false; // the background navigates
+ u.refresh();
+ if (s.tool == 1) {
+ s.toolClearing = (mod & SDL_KMOD_ALT) != 0;
+ s.toolVertex = u.nearestVertex(hit);
+ u.twins();
+ s.toolStep = std::make_unique<UvEditStep>(doc_, s.toolClearing ? "Clear Seams" : "Mark Seams", false);
+ } else {
+ s.toolAdding = !(mod & SDL_KMOD_ALT);
+ const bool add = (mod & SDL_KMOD_SHIFT) != 0;
+ if (!add && s.toolAdding) doc_.uvSelection.clear();
+ u.toolSelectAt(hit, !add);
+ }
+ drag_ = Drag::UvTool;
+ return true;
+}
+
+void App::uvToolDragTo(float x, float y) {
+ if (!uvEditor_) return;
+ UvEditorState& s = *uvEditor_;
+ UvEditorUi u = uvUi(*this, uvEditor_);
+ RayHit hit;
+ if (!pick(x, y, hit)) return;
+ if (s.tool == 1) {
+ const uint32_t v = u.nearestVertex(hit);
+ if (v == s.toolVertex || s.toolVertex == ~0u) return;
+ const std::vector<uint32_t> path = uvEdgePath(doc_.mesh, s.toolVertex, v);
+ uvSetSeams(doc_.mesh, u.twins(), path, !s.toolClearing);
+ s.toolVertex = v;
+ s.seamKey = ~uint64_t(0);
+ s.colorsDirty = true;
+ } else {
+ u.toolSelectAt(hit, false);
+ u.rebuildColors();
+ }
+}
+
+void App::uvToolRelease() {
+ if (!uvEditor_) return;
+ UvEditorState& s = *uvEditor_;
+ if (s.toolStep) {
+ s.toolStep->commit();
+ s.toolStep.reset();
+ status_ = std::to_string(uvSeamCount(doc_.mesh)) + " seam edges marked (Unwrap cuts along them)";
+ }
+ s.toolVertex = ~0u;
+ s.dirty = true;
+}
+
+void App::drawUvEditorOverlay() {
+ if (!showUvEditor_ || !uvEditor_ || !doc_.activeSubtoolInfo().visible) return;
+ UvEditorState& s = *uvEditor_;
+ const Mesh& m = doc_.mesh;
+ const size_t nc = m.triangleCount() * 3;
+ // The marked seams, in red on the model (the side facing the camera).
+ if (m.uvFlags.size() == nc) {
+ const uint64_t key = (uint64_t(uintptr_t(m.uvFlags.data())) << 4) ^ doc_.undo.revision() ^ (uint64_t(nc) << 40) ^
+ (s.toolStep ? uint64_t(SDL_GetTicksNS()) : 0);
+ if (key != s.seamKey) {
+ s.seamCorners.clear();
+ const std::vector<uint32_t>& twin = UvEditorUi{*this, s}.twins();
+ for (uint32_t c = 0; c < nc; ++c)
+ if ((m.uvFlags[c] & kUvSeam) && (twin[c] == kNoCorner || c < twin[c])) s.seamCorners.push_back(c);
+ s.seamKey = key;
+ }
+ const glm::vec3 eye = camera_.position();
+ ImDrawList* dl = ImGui::GetBackgroundDrawList();
+ const CanvasRect cr = canvasRect();
+ dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);
+ const size_t step = std::max<size_t>(1, s.seamCorners.size() / 150000);
+ const std::vector<uint32_t>& twin = s.twin;
+ auto faces = [&](uint32_t t, const glm::vec3& p) {
+ const glm::uvec3 tri = m.triangles[t];
+ const glm::vec3 n = glm::cross(m.positions[tri.y] - m.positions[tri.x], m.positions[tri.z] - m.positions[tri.x]);
+ return glm::dot(n, eye - p) > 0.0f;
+ };
+ for (size_t i = 0; i < s.seamCorners.size(); i += step) {
+ const uint32_t c = s.seamCorners[i];
+ const glm::vec3 a = m.positions[m.triangles[c / 3][c % 3]], b = m.positions[m.triangles[c / 3][(c % 3 + 1) % 3]];
+ const glm::vec3 mid = (a + b) * 0.5f;
+ const bool front = faces(c / 3, mid) || (twin.size() == nc && twin[c] != kNoCorner && faces(twin[c] / 3, mid));
+ if (!front) continue;
+ ImVec2 pa, pb;
+ if (!gizmoProject(a, pa) || !gizmoProject(b, pb)) continue;
+ dl->AddLine(pa, pb, IM_COL32(245, 78, 64, 225), 1.6f * uiScale_);
+ }
+ dl->PopClipRect();
+ }
+ // The Seam tool's cursor: the vertex a press would start from.
+ if (s.tool != 0 && !ImGui::GetIO().WantCaptureMouse) {
+ RayHit hit;
+ const ImVec2 mouse(mouseX_, mouseY_);
+ if (canvasRect().contains(mouse.x, mouse.y) && pick(mouse.x, mouse.y, hit)) {
+ ImVec2 p;
+ const glm::vec3 at = s.tool == 1 ? m.positions[UvEditorUi{*this, s}.nearestVertex(hit)] : hit.position;
+ if (gizmoProject(at, p)) {
+ ImDrawList* fg = ImGui::GetForegroundDrawList();
+ const ImU32 col = s.tool == 1 ? ((inputMods() & SDL_KMOD_ALT) ? IM_COL32(150, 200, 255, 255) : IM_COL32(245, 78, 64, 255))
+ : theme::u32(theme::accent);
+ fg->AddCircle(p, 7.0f * uiScale_, col, 24, 2.0f * uiScale_);
+ fg->AddCircleFilled(p, 2.5f * uiScale_, col);
+ }
+ }
+ }
+}
+
+double App::uvEditorTestValue(const std::string& name) {
+ const double nan = std::numeric_limits<double>::quiet_NaN();
+ if (name.rfind("uv_", 0) != 0) return nan;
+ if (name == "uv_editor_open") return showUvEditor_ ? 1.0 : 0.0;
+ const Mesh& m = doc_.mesh;
+ 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_unwraps") return uvEditor_ ? double(uvEditor_->unwraps) : 0.0;
+ if (name == "uv_tool") return uvEditor_ ? double(uvEditor_->tool) : 0.0;
+ if (name == "uv_view_triangles") return uvEditor_ ? double(uvEditor_->gpu.triangles()) : 0.0;
+ if (name == "uv_overlay") return uvEditorOverlay(doc_.activeSubtoolInfo().id) && !uvEditor_->overlay.colors.empty() ? 1.0 : 0.0;
+ if (name == "uv_pins") {
+ double n = 0;
+ for (uint8_t f : m.uvFlags) n += (f & kUvPin) != 0;
+ return n;
+ }
+ if (!m.hasUvs())
+ return name == "uv_islands" || name == "uv_tiles" || name == "uv_stretch_x1000" || name == "uv_flipped_x1000" || name == "uv_density" || name == "uv_max_u" ? 0.0 : nan;
+ const UvTopology topo = buildUvTopology(m);
+ if (name == "uv_islands") return double(topo.islandCount);
+ if (name == "uv_stretch_x1000") return double(uvStretchStats(m).mean) * 1000.0;
+ if (name == "uv_flipped_x1000") return double(uvStretchStats(m).flipped) * 1000.0;
+ if (name == "uv_density") return double(uvMeshDensity(m, m.texture ? std::max(m.texture->width, m.texture->height) : 2048));
+ if (name == "uv_tiles") {
+ 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));
+ std::sort(tiles.begin(), tiles.end());
+ return double(std::unique(tiles.begin(), tiles.end()) - tiles.begin());
+ }
+ if (name == "uv_max_u") {
+ float hi = 0.0f;
+ for (const glm::vec2& u : m.uvs) hi = std::max(hi, u.x);
+ return double(hi);
+ }
+ return nan;
+}
+
+} // namespace sf
diff --git a/src/app/Ui.cpp b/src/app/Ui.cpp
index 1f674c17..96bce54d 100644
--- a/src/app/Ui.cpp
+++ b/src/app/Ui.cpp
@@ -119,7 +119,7 @@ bool IsModeAction(std::string_view id) {
bool IsChoiceAction(std::string_view id) {
return id == "draw.zadd" || id == "draw.zsub" || id == "material.smooth" || id == "material.flat" ||
id == "view.background_gradient" || id == "view.background_flat" ||
- id.substr(0, 16) == "subtool.shading_";
+ id.substr(0, 16) == "subtool.shading_" || id.substr(0, 8) == "uv.mode_";
}
bool Checkbox(const char* label, bool* v) {
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index d57c1394..ab4137b1 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -380,6 +380,7 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "active_texture_layer") return hasTexture(m) && !m.texture->layers.empty() ? double(m.texture->activeLayer) : -1.0;
if (name == "auto_uv_running") return app_.autoUv_ ? 1.0 : 0.0;
if (const double v = app_.bakeTestValue(name); !std::isnan(v)) return v;
+ if (const double v = app_.uvEditorTestValue(name); !std::isnan(v)) return v;
if (const double v = app_.pbrTestValue(name); !std::isnan(v)) return v; // material_channels, channel_view, ...
if (const double v = app_.splatTrainTestValue(name); !std::isnan(v)) return v; // splat_training, ...
if (const double v = app_.sculptableTestValue(name); !std::isnan(v)) return v;
diff --git a/src/core/AutoUv.cpp b/src/core/AutoUv.cpp
index 04374f39..1eb6c276 100644
--- a/src/core/AutoUv.cpp
+++ b/src/core/AutoUv.cpp
@@ -105,6 +105,47 @@ bool computeAutoUv(const std::vector<glm::vec3>& positions, const std::vector<gl
return true;
}
+bool computeAutoCharts(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles,
+ std::vector<uint32_t>& chartOfTriangle, int& charts, std::string& error) {
+ chartOfTriangle.assign(triangles.size(), 0);
+ charts = 0;
+ if (positions.empty() || triangles.empty()) {
+ error = "There is no mesh to cut into charts";
+ return false;
+ }
+ std::unique_ptr<xatlas::Atlas, void (*)(xatlas::Atlas*)> atlas(xatlas::Create(), xatlas::Destroy);
+ xatlas::MeshDecl decl;
+ decl.vertexPositionData = positions.data();
+ decl.vertexPositionStride = sizeof(glm::vec3);
+ decl.vertexCount = uint32_t(positions.size());
+ decl.indexData = triangles.data();
+ decl.indexCount = uint32_t(triangles.size() * 3);
+ decl.indexFormat = xatlas::IndexFormat::UInt32;
+ if (xatlas::AddMesh(atlas.get(), decl, 1) != xatlas::AddMeshError::Success) {
+ error = "Couldn't cut the piece into charts";
+ return false;
+ }
+ xatlas::AddMeshJoin(atlas.get());
+ xatlas::ChartOptions options;
+ xatlas::PackOptions pack;
+ pack.resolution = 256; // (only the charts matter)
+ pack.padding = 0;
+ pack.blockAlign = true;
+ xatlas::Generate(atlas.get(), options, pack);
+ if (atlas->meshCount != 1) {
+ error = "Couldn't cut the piece into charts";
+ return false;
+ }
+ const xatlas::Mesh& m = atlas->meshes[0];
+ for (uint32_t c = 0; c < m.chartCount; ++c)
+ for (uint32_t k = 0; k < m.chartArray[c].faceCount; ++k) {
+ const uint32_t f = m.chartArray[c].faceArray[k];
+ if (f < chartOfTriangle.size()) chartOfTriangle[f] = c;
+ }
+ charts = int(m.chartCount);
+ return true;
+}
+
bool computeAutoUv(const Mesh& mesh, AutoUvResult& out, std::string& error, const AutoUvProgress& progress) {
const int res = mesh.texture ? std::max(mesh.texture->width, mesh.texture->height) : kDefaultTextureSize;
return computeAutoUv(mesh.positions, mesh.triangles, res, out, error, progress);
diff --git a/src/core/AutoUv.h b/src/core/AutoUv.h
index 19d323d4..4b243fdb 100644
--- a/src/core/AutoUv.h
+++ b/src/core/AutoUv.h
@@ -30,6 +30,10 @@ struct AutoUvResult {
// failure or cancel.
bool computeAutoUv(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles, int resolution,
AutoUvResult& out, std::string& error, const AutoUvProgress& progress = {});
+// Only the charts xatlas would cut `triangles` into (per triangle, 0 .. charts - 1), for the UV Editor's unwrap of
+// pieces too tangled to cut into a disk by itself (core/UvUnwrap.cpp). False with `error` on failure.
+bool computeAutoCharts(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles,
+ std::vector<uint32_t>& chartOfTriangle, int& charts, std::string& error);
// The same for a mesh (its texture size, or 2048 without one).
bool computeAutoUv(const Mesh& mesh, AutoUvResult& out, std::string& error, const AutoUvProgress& progress = {});
diff --git a/src/core/Uv.cpp b/src/core/Uv.cpp
index cf3198c1..ac0b7e53 100644
--- a/src/core/Uv.cpp
+++ b/src/core/Uv.cpp
@@ -258,6 +258,7 @@ bool triangleJacobian(const Mesh& m, uint32_t t, float& s1, float& s2, bool& fli
s1 = Q + R;
s2 = std::abs(Q - R);
flipped = (a * d - b * c) < 0.0f;
+ if (!std::isfinite(s1) || !std::isfinite(s2)) return false; // (a sliver: no meaningful stretch)
return true;
}
@@ -300,6 +301,38 @@ void uvTriangleStretch(const Mesh& m, std::vector<float>& out) {
}, 1 << 14);
}
+UvStretchCache uvStretchCache(const Mesh& m, const UvTopology& topo) {
+ UvStretchCache cache;
+ cache.scale.assign(topo.islandCount, 0.0f);
+ cache.mirrored.assign(topo.islandCount, 0);
+ if (m.uvs.size() != m.triangleCount() * 3) return cache;
+ poolFor(topo.islandCount, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ double a = 0.0, u = 0.0, sense = 0.0;
+ for (uint32_t k = topo.islandOffsets[i]; k < topo.islandOffsets[i + 1]; ++k) {
+ const uint32_t t = topo.islandTriangles[k];
+ const float su = signedAreaUv(m, t);
+ a += area3(m, t);
+ u += std::abs(su);
+ sense += su;
+ }
+ cache.scale[i] = a > 0.0 ? float(std::sqrt(u / a)) : 0.0f;
+ cache.mirrored[i] = sense < 0.0;
+ }
+ }, 64);
+ return cache;
+}
+
+float uvTriangleStretchAt(const Mesh& m, uint32_t t, const UvTopology& topo, const UvStretchCache& cache) {
+ float s1 = 0, s2 = 0;
+ bool flipped = false;
+ const uint32_t i = topo.island[t];
+ const float s = cache.scale[i];
+ if (s <= 0.0f || !triangleJacobian(m, t, s1, s2, flipped)) return 0.0f;
+ if (flipped != bool(cache.mirrored[i])) return -1.0f;
+ return std::log2(std::max(std::max(s1 / s, 1e-6f), s / std::max(s2, 1e-6f * s)));
+}
+
UvStretchStats uvStretchStats(const Mesh& m) {
UvStretchStats st;
std::vector<float> s;
diff --git a/src/core/Uv.h b/src/core/Uv.h
index faf42ecb..279473c7 100644
--- a/src/core/Uv.h
+++ b/src/core/Uv.h
@@ -68,6 +68,14 @@ float uvMeshDensity(const Mesh& mesh, int resolution);
// Jacobian, measured against its island's mean scale: 0 = no stretch, 1 = twice or half as long in some
// direction (log2 of the worst of s1 and 1/s2 over the mean). Triangles folded over their island get -1.
void uvTriangleStretch(const Mesh& mesh, std::vector<float>& out);
+// The same for one triangle, with each island's scale and sense computed once (uvStretchCache) so a drag can
+// update the triangles it moves without measuring everything again.
+struct UvStretchCache {
+ std::vector<float> scale; // per island
+ std::vector<uint8_t> mirrored; // per island
+};
+UvStretchCache uvStretchCache(const Mesh& mesh, const UvTopology& topo);
+float uvTriangleStretchAt(const Mesh& mesh, uint32_t triangle, const UvTopology& topo, const UvStretchCache& cache);
// Summary for the status line and the tests: area-weighted mean stretch, and the share of flipped triangles.
struct UvStretchStats {
float mean = 0.0f, worst = 0.0f;
diff --git a/src/core/UvCommands.cpp b/src/core/UvCommands.cpp
index 125f57b3..cff6a6e0 100644
--- a/src/core/UvCommands.cpp
+++ b/src/core/UvCommands.cpp
@@ -11,6 +11,7 @@
#include "core/TextureTransfer.h"
#include "core/Undo.h"
#include "core/Uv.h"
+#include "core/UvEdit.h"
#include <algorithm>
#include <cmath>
@@ -24,40 +25,6 @@ using T = ParamSpec::Type;
const char* kNoUvs = "The Part has no UVs: unwrap it first (UV Editor > Unwrap, or uv_unwrap)";
-// One undoable UV edit: captures the UVs (and the texture when it should follow) before, pushes the step after.
-class UvEdit {
-public:
- UvEdit(Document& doc, std::string label, bool keepTexture) : doc_(doc), tex_(keepTexture && hasTexture(doc.mesh)) {
- if (tex_) r_ = captureTexture(doc.mesh, label);
- else r_.label = std::move(label);
- r_.uv = UvUndo::capture(doc.mesh);
- }
- // Pushes the step if anything changed; returns the texture note (" ; paint moved ...").
- std::string commit() {
- Mesh& m = doc_.mesh;
- if (m.uvs == r_.uv->uvs && m.uvFlags == r_.uv->flags) {
- if (tex_) r_.texture->swapWith(m); // (put back the untouched original)
- return {};
- }
- std::string note;
- if (tex_ && m.uvs.size() == r_.uv->uvs.size() && m.uvs != r_.uv->uvs) {
- std::vector<glm::vec2> fresh = std::move(m.uvs);
- m.uvs = r_.uv->uvs;
- note = setUvsKeepingTexture(m, std::move(fresh), true);
- }
- m.facesDirty = true;
- r_.uv->commit(m);
- if (tex_) finishTextureUndo(r_, m);
- doc_.undo.push(std::move(r_));
- return note;
- }
-
-private:
- Document& doc_;
- bool tex_;
- UndoRecord r_;
-};
-
int resolutionArg(const Document& doc, const Args& a) {
if (a.contains("resolution")) return std::clamp(int(argNumber(a, "resolution", kDefaultTextureSize)), 64, 16384);
return doc.mesh.texture ? std::max(doc.mesh.texture->width, doc.mesh.texture->height) : kDefaultTextureSize;
@@ -106,6 +73,34 @@ std::string packNote(const UvPackResult& p) {
} // 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);
+ record_.uv = UvUndo::capture(doc.mesh);
+}
+
+std::string UvEditStep::commit() {
+ Mesh& m = doc_.mesh;
+ if (!record_.uv) return {};
+ if (m.uvs == record_.uv->uvs && m.uvFlags == record_.uv->flags) {
+ if (texture_) record_.texture->swapWith(m); // (put back the untouched original)
+ record_.uv.reset();
+ return {};
+ }
+ std::string note;
+ if (texture_ && m.uvs.size() == record_.uv->uvs.size() && m.uvs != record_.uv->uvs) {
+ std::vector<glm::vec2> fresh = std::move(m.uvs);
+ m.uvs = record_.uv->uvs;
+ note = setUvsKeepingTexture(m, std::move(fresh), true);
+ }
+ m.facesDirty = true;
+ record_.uv->commit(m);
+ if (texture_) finishTextureUndo(record_, m);
+ doc_.undo.push(std::move(record_));
+ record_.uv.reset();
+ return note;
+}
+
std::string uvInfoText(const Mesh& m, int resolution) {
if (!m.hasUvs()) {
const size_t seams = uvSeamCount(m);
@@ -176,7 +171,7 @@ void registerUvCommands(CommandRegistry& reg) {
UvUnwrapResult r;
std::string err;
if (!uvUnwrap(m, o, r, err)) return {false, err};
- UvEdit edit(doc, std::string("Unwrap (") + uvUnwrapMethodLabel(o.method) + ")", argBool(a, "keep_texture", true));
+ UvEditStep edit(doc, std::string("Unwrap (") + uvUnwrapMethodLabel(o.method) + ")", argBool(a, "keep_texture", true));
m.uvs = std::move(r.uvs);
const std::string note = edit.commit();
std::string msg = std::string("Unwrapped (") + uvUnwrapMethodLabel(o.method) + "): " + plural(r.islands, "island");
@@ -205,7 +200,7 @@ void registerUvCommands(CommandRegistry& reg) {
if (!m.hasUvs()) return {false, kNoUvs};
const UvTopology topo = buildUvTopology(m);
const std::vector<uint8_t> islands = targetIslands(doc, topo);
- UvEdit edit(doc, "Pack UVs", argBool(a, "keep_texture", true));
+ UvEditStep edit(doc, "Pack UVs", argBool(a, "keep_texture", true));
UvPackResult r;
std::string err;
if (!uvPack(m, topo, islands, packOptions(doc, a), r, err)) return {false, err};
@@ -228,7 +223,7 @@ void registerUvCommands(CommandRegistry& reg) {
if (m.triangleCount() == 0) return {false, "There is no mesh"};
const std::string op = argString(a, "op");
const size_t before = uvSeamCount(m);
- UvEdit edit(doc, "UV Seams", false);
+ UvEditStep edit(doc, "UV Seams", false);
const std::vector<uint32_t> twin = cornerTwins(m);
if (op == "mark" || op == "clear") {
const UvSelection& sel = doc.uvSelection;
@@ -383,7 +378,7 @@ void registerUvCommands(CommandRegistry& reg) {
const float ang = glm::radians(float(argNumber(a, "rotate", 0.0)));
const glm::mat2 rot(std::cos(ang), std::sin(ang), -std::sin(ang), std::cos(ang));
const glm::mat2 mat = rot * glm::mat2(su, 0.0f, 0.0f, sv);
- UvEdit edit(doc, "Transform UVs", argBool(a, "keep_texture", true));
+ UvEditStep edit(doc, "Transform UVs", argBool(a, "keep_texture", true));
uvTransform(m.uvs, corners, mat, uvCenter(m.uvs, corners),
glm::vec2(float(argNumber(a, "move_u", 0.0)), float(argNumber(a, "move_v", 0.0))));
const std::string note = edit.commit();
@@ -405,7 +400,7 @@ void registerUvCommands(CommandRegistry& reg) {
const UvTopology topo = buildUvTopology(m);
const bool haveSel = doc.uvSelection.valid(m) && !doc.uvSelection.empty();
const std::vector<uint32_t> corners = targetCorners(doc, topo);
- UvEdit edit(doc, "UV " + op, argBool(a, "keep_texture", true));
+ UvEditStep edit(doc, "UV " + op, argBool(a, "keep_texture", true));
std::string msg;
if (op == "pin" || op == "unpin") {
if (!haveSel) return {false, "Select the UVs to " + op + " first"};
@@ -471,7 +466,7 @@ void registerUvCommands(CommandRegistry& reg) {
else if (op == "match") target = argString(a, "match", "mean") == "first" ? d[size_t(first)] : mean;
else return {false, "op must be set, match or info"};
if (!(target > 0.0f)) return {false, "Give the texel density: value (texels per unit)"};
- UvEdit edit(doc, "Texel Density", argBool(a, "keep_texture", true));
+ UvEditStep edit(doc, "Texel Density", argBool(a, "keep_texture", true));
const size_t n = uvSetDensity(m, topo, islands, target, res);
const std::string note = edit.commit();
return {true, plural(n, "island") + " at " + fmt("%.1f", double(target)) + " texels per unit" + note};
@@ -501,7 +496,7 @@ void registerUvCommands(CommandRegistry& reg) {
const UvTopology topo = buildUvTopology(m);
const std::vector<uint8_t> islands = targetIslands(doc, topo);
const float margin = float(std::max(argNumber(a, "margin", 4.0), 0.0)) / float(resolutionArg(doc, a));
- UvEdit edit(doc, "Trim Sheet", argBool(a, "keep_texture", false));
+ UvEditStep edit(doc, "Trim Sheet", argBool(a, "keep_texture", false));
const size_t n = uvTrimIslands(m, topo, islands, strips[size_t(k - 1)], argBool(a, "fit_width", false), margin);
if (!n) return {false, "Nothing to lay into the strip (it may be too thin for the margin)"};
const std::string note = edit.commit();
diff --git a/src/core/UvEdit.h b/src/core/UvEdit.h
new file mode 100644
index 00000000..74aa92b3
--- /dev/null
+++ b/src/core/UvEdit.h
@@ -0,0 +1,32 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// One undoable UV edit on the active Part (the uv_* commands, core/UvCommands.cpp, and the UV Editor's drags,
+// app/PanelUvEditor.cpp): construct it before changing Document::mesh's UVs or seams, commit() after. The step
+// holds the old UVs and flags (UvUndo) and, with keepTexture on a painted Part, moves the texture onto the new
+// layout so the model looks the same (core/TextureTransfer.h), the old texture in the same step.
+#pragma once
+
+#include "core/Document.h"
+
+#include <string>
+
+namespace sf {
+
+class UvEditStep {
+public:
+ UvEditStep(Document& doc, std::string label, bool keepTexture);
+ UvEditStep(const UvEditStep&) = delete;
+ UvEditStep& operator=(const UvEditStep&) = delete;
+ // The UVs as they were when the step began.
+ const std::vector<glm::vec2>& before() const { return record_.uv->uvs; }
+ // Pushes the step if anything changed; returns the texture note ("; paint moved to the new UVs ...").
+ std::string commit();
+
+private:
+ Document& doc_;
+ bool texture_;
+ UndoRecord record_;
+};
+
+} // namespace sf
diff --git a/src/core/UvPack.cpp b/src/core/UvPack.cpp
index e786d724..f96514e4 100644
--- a/src/core/UvPack.cpp
+++ b/src/core/UvPack.cpp
@@ -10,10 +10,14 @@
#include "core/Uv.h"
#include "core/UvInternal.h"
+#include <xatlas.h>
+
#include <algorithm>
#include <cmath>
#include <limits>
+#include <memory>
#include <numeric>
+#include <cstdio>
namespace sf {
@@ -73,6 +77,136 @@ struct Skyline {
}
};
+// 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).
+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 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;
+ double total = 0.0;
+ for (size_t p = 0; p < list.size(); ++p) {
+ const uint32_t i = list[p];
+ 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;
+ const float ca = std::cos(angle[p]), sa = std::sin(angle[p]);
+ for (uint32_t c = offsets[i]; c < offsets[i + 1]; ++c) {
+ const uint32_t corner = corners[c], v = topo.uvVertex[corner];
+ if (vid[v] == ~0u) {
+ vid[v] = uint32_t(verts.size());
+ verts.push_back(rotate(m.uvs[corner] - mid, ca, sa) * k[p]);
+ }
+ idx.push_back(vid[v]);
+ cornerOf.push_back(corner);
+ if (idx.size() % 3 == 0) material.push_back(uint32_t(p));
+ }
+ }
+ 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) {
+ xatlas::PackOptions po;
+ po.padding = uint32_t(std::lround(std::max(o.marginPx, 0.0f) * float(resolution) / float(res)));
+ 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;
+ };
+ const int tiles = std::clamp(o.tiles, 1, 100);
+ float density = o.density;
+ int used = 0;
+ if (density > 0.0f) {
+ used = pack(density, res);
+ if (used == 0 || used > 100) return false;
+ } 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;
+ }
+ if (lo <= 0.0f) 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 int first = std::max(o.firstTile, 1001) - 1001;
+ 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]];
+ const int t = first + std::max(v.atlasIndex, 0);
+ placed[i] = glm::vec2(float(t % 10), float(t / 10)) + 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;
+ glm::dvec2 ca(0.0), cb(0.0);
+ for (size_t i = b; i < e; ++i) ca += glm::dvec2(verts[idx[i]]), cb += glm::dvec2(placed[i]);
+ ca /= double(e - b), cb /= double(e - b);
+ double dotSum = 0.0, crossSum = 0.0, norm = 0.0;
+ for (size_t i = b; i < e; ++i) {
+ const glm::dvec2 p = glm::dvec2(verts[idx[i]]) - ca, q = glm::dvec2(placed[i]) - cb;
+ dotSum += p.x * q.x + p.y * q.y;
+ crossSum += p.x * q.y - p.y * q.x;
+ norm += p.x * p.x + p.y * p.y;
+ }
+ const double s = norm > 0.0 ? std::sqrt(dotSum * dotSum + crossSum * crossSum) / norm : 1.0;
+ const double a = std::atan2(crossSum, dotSum), c = std::cos(a) * s, sn = std::sin(a) * s;
+ for (size_t i = b; i < e; ++i) {
+ const glm::dvec2 p = glm::dvec2(verts[idx[i]]) - ca;
+ m.uvs[cornerOf[i]] = glm::vec2(cb + glm::dvec2(c * p.x - sn * p.y, sn * p.x + c * p.y));
+ }
+ b = e;
+ }
+ const double uvArea = total;
+ 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.density = uvMeshDensity(m, res);
+ m.facesDirty = true;
+ return true;
+}
+
} // namespace
int packRectangles(const std::vector<glm::vec2>& sizes, int maxTiles, bool allowTurn, float border,
@@ -183,6 +317,25 @@ bool uvPack(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands
pc.k = equal && pc.areaUv > 1e-20 && pc.area3 > 0.0 ? float(std::sqrt(pc.area3 / pc.areaUv)) : 1.0f;
}
}, 16);
+ // The shape packer when there are enough islands for their shapes to matter (and not so many triangles that
+ // rasterising them would keep you waiting); the box packer always runs too, and the denser layout wins.
+ std::vector<glm::vec2> shapeUvs;
+ UvPackResult shapeResult;
+ if (n >= 8 && m.triangleCount() <= 600000) {
+ std::vector<float> k(n), angle(n);
+ 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;
+ m.uvs = before;
+ }
+ auto useShapes = [&] {
+ if (shapeUvs.empty()) return false;
+ m.uvs = std::move(shapeUvs);
+ result = shapeResult;
+ m.facesDirty = true;
+ return true;
+ };
const float margin = std::max(o.marginPx, 0.0f) / float(res);
std::vector<glm::vec2> sizes(n), pos;
std::vector<uint8_t> turned;
@@ -197,6 +350,7 @@ bool uvPack(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands
scale = o.density / float(res); // UV units per surface unit
used = tryScale(scale, 100);
if (!used) {
+ if (useShapes()) return true;
error = "At that texel density an island is bigger than a tile (or it needs over 100 tiles): lower it";
return false;
}
@@ -216,6 +370,7 @@ bool uvPack(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands
if (tryScale(s, tiles)) fits = s;
}
if (fits == 0.0f) {
+ if (useShapes()) return true;
error = "The islands don't fit: lower the margin or use more tiles";
return false;
}
@@ -254,6 +409,9 @@ bool uvPack(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands
result.coverage = float(uvArea / double(std::max(used, 1)));
result.density = uvMeshDensity(m, res);
m.facesDirty = true;
+ // Fixed density: the layout that needs fewer tiles; fitting tiles: the denser one.
+ if (!shapeUvs.empty() && (o.density > 0.0f ? shapeResult.tilesUsed < used : shapeResult.density > result.density * 1.005f))
+ useShapes();
return true;
}
diff --git a/src/core/UvUnwrap.cpp b/src/core/UvUnwrap.cpp
index 8a4d20fa..6777dc8a 100644
--- a/src/core/UvUnwrap.cpp
+++ b/src/core/UvUnwrap.cpp
@@ -345,6 +345,8 @@ bool flattenIsometricImpl(const std::vector<glm::vec3>& pos, const std::vector<g
harmonic.solve(hv, nullptr, 1e-8, 300);
uv.resize(n);
for (uint32_t i = 0; i < n; ++i) uv[i] = glm::vec2(float(hu[i]), float(hv[i]));
+ for (const glm::vec2& x : uv)
+ if (!std::isfinite(x.x) || !std::isfinite(x.y)) return flattenConformalImpl(pos, tris, uv = {}, pins, parallel);
iterations += 10; // (further from the result than LSCM: a few more steps)
}
}
@@ -434,7 +436,7 @@ Pieces buildPieces(const Mesh& m, const std::vector<uint32_t>& twin, const std::
// The cut-graph edges (corners) that make piece `triangles` a disk, or empty when it already is one.
std::vector<uint32_t> diskCuts(const Mesh& m, const std::vector<uint32_t>& twin, const std::vector<uint8_t>& cut,
- const Pieces& pc, const std::vector<uint32_t>& triangles) {
+ const Pieces& pc, const std::vector<uint32_t>& triangles, long long* eulerOut = nullptr) {
// Local numbering of the piece's vertices.
std::vector<uint32_t> vlist;
for (uint32_t t : triangles)
@@ -452,7 +454,35 @@ std::vector<uint32_t> diskCuts(const Mesh& m, const std::vector<uint32_t>& twin,
}
const long long E = (3 * (long long)F + (long long)boundary) / 2;
const long long chi = (long long)V - E + (long long)F;
+ if (eulerOut) *eulerOut = chi;
if (chi == 1) return {};
+ if (chi < 0 && eulerOut) {
+ // Tangled (several holes or handles): a cut graph would make one island with slits everywhere. Cut it into
+ // charts the way Auto Seams does instead (each then flattened like any piece).
+ std::vector<uint32_t> vmap(m.vertexCount(), ~0u);
+ std::vector<glm::vec3> pos;
+ std::vector<glm::uvec3> tris(F);
+ for (size_t k = 0; k < F; ++k)
+ for (int j = 0; j < 3; ++j) {
+ const uint32_t v = m.triangles[triangles[k]][j];
+ if (vmap[v] == ~0u) vmap[v] = uint32_t(pos.size()), pos.push_back(m.positions[v]);
+ tris[k][j] = vmap[v];
+ }
+ std::vector<uint32_t> chart;
+ int charts = 0;
+ std::string error;
+ if (computeAutoCharts(pos, tris, chart, charts, error) && charts > 1) {
+ std::vector<uint32_t> out;
+ for (size_t k = 0; k < F; ++k)
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = triangles[k] * 3 + j, d = twin[c];
+ if (cut[c] || d == kNoCorner || d < c || !std::binary_search(triangles.begin(), triangles.end(), d / 3)) continue;
+ const size_t kd = size_t(std::lower_bound(triangles.begin(), triangles.end(), d / 3) - triangles.begin());
+ if (chart[k] != chart[kd]) out.push_back(c);
+ }
+ if (!out.empty()) return out;
+ }
+ }
// Dual spanning tree (breadth first from the first triangle) over the piece's inner edges.
auto inner = [&](uint32_t c) {
const uint32_t d = twin[c];
@@ -734,7 +764,8 @@ bool uvUnwrap(const Mesh& m, const UvUnwrapOptions& o, UvUnwrapResult& result, s
poolFor(pc.count, [&](size_t b, size_t e) {
for (size_t i = b; i < e; ++i) {
const std::vector<uint32_t> list(tris.begin() + offsets[i], tris.begin() + offsets[i + 1]);
- extra[i] = diskCuts(m, twin, cut, pc, list);
+ long long euler = 1;
+ extra[i] = diskCuts(m, twin, cut, pc, list, round == 0 ? &euler : nullptr);
}
}, 1);
size_t added = 0;
@@ -807,7 +838,10 @@ bool uvUnwrap(const Mesh& m, const UvUnwrapOptions& o, UvUnwrapResult& result, s
} else {
ok = flattenIsometricImpl(pos, lt, uv, std::max(o.iterations, 0), pins, parallel);
}
- if (!ok) uv = project(pos, lt); // (a piece the solver can't flatten still gets UVs)
+ if (ok)
+ for (const glm::vec2& x : uv)
+ if (!std::isfinite(x.x) || !std::isfinite(x.y)) ok = false;
+ if (!ok || uv.size() != pos.size()) uv = project(pos, lt); // (a piece the solver can't flatten still gets UVs)
if (pins.size() < 2) {
// One texel density: UV area = surface area, centred.
double a3 = 0.0, au = 0.0;
@@ -892,6 +926,8 @@ bool uvUnwrap(const Mesh& m, const UvUnwrapOptions& o, UvUnwrapResult& result, s
pt.islandCount = pc.count;
for (uint32_t t = 0; t < nt; ++t) pt.island[t] = pc.piece[t] == kNoCorner ? pc.count : pc.piece[t];
pt.islandCount = pc.count + (faces ? 1 : 0);
+ pt.uvVertex = pc.vertex; // (the corners each flattened vertex joins)
+ pt.uvVertexCount = pc.vertexCount;
pt.islandOffsets.assign(pt.islandCount + 1, 0);
for (uint32_t t = 0; t < nt; ++t) ++pt.islandOffsets[pt.island[t] + 1];
for (uint32_t i = 0; i < pt.islandCount; ++i) pt.islandOffsets[i + 1] += pt.islandOffsets[i];
diff --git a/src/render/GL.h b/src/render/GL.h
index 23ec83dc..67218d11 100644
--- a/src/render/GL.h
+++ b/src/render/GL.h
@@ -147,6 +147,7 @@ constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;
X(void, UseProgram, GLuint) \
X(GLint, GetUniformLocation, GLuint, const GLchar*) \
X(void, UniformMatrix4fv, GLint, GLsizei, GLboolean, const GLfloat*) \
+ X(void, UniformMatrix3fv, GLint, GLsizei, GLboolean, const GLfloat*) \
X(void, Uniform3fv, GLint, GLsizei, const GLfloat*) \
X(void, Uniform4fv, GLint, GLsizei, const GLfloat*) \
X(void, DrawElements, GLenum, GLsizei, GLenum, const void*) \
@@ -171,6 +172,7 @@ constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;
X(void, RenderbufferStorage, GLenum, GLenum, GLsizei, GLsizei) \
X(void, RenderbufferStorageMultisample, GLenum, GLsizei, GLenum, GLsizei, GLsizei) \
X(void, BlitFramebuffer, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) \
+ X(void, FramebufferTexture2D, GLenum, GLenum, GLenum, GLuint, GLint) \
X(void, TexBuffer, GLenum, GLenum, GLuint) \
X(void, VertexAttribIPointer, GLuint, GLint, GLenum, GLsizei, const void*) \
X(void, VertexAttribDivisor, GLuint, GLuint) \
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index 083f4c58..f5fda87e 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -346,8 +346,11 @@ uniform vec2 uProjScale; // projection x and y scale
uniform vec3 uBaseColor;
uniform int uPaint; // 1: vertex colours replace the base colour
uniform int uShowMask; // 1: darken masked areas
-uniform int uGroups; // 0: off, 1: per-triangle ids from uGroupIds, 2: everything is group 0
+uniform int uGroups; // 0: off, 1: per-triangle ids from uGroupIds, 2: everything is group 0, 3: per-triangle
+ // colours (0xBBGGRR) from uGroupIds (the UV Editor's overlay)
uniform usamplerBuffer uGroupIds;
+uniform int uChecker; // 1: a checker on the UVs (TEXTURED), tinted per UDIM tile
+uniform float uCheckerScale; // checker squares per UV unit
uniform int uMatcap; // 1: shade with the matcap texture instead of the studio lights
uniform sampler2D uMatcapTex; // sRGB-encoded lit sphere (core/Matcap.h)
uniform vec2 uMatcapCavity; // crease darkening, ridge lift (sf::matcapCavity)
@@ -371,6 +374,19 @@ vec3 groupColor(uint id) {
vec3 rgb = clamp(abs(fract(hue + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0) - 1.0, 0.0, 1.0);
return val * mix(vec3(1.0), rgb, sat);
}
+vec3 faceColor(uint c) {
+ return pow(vec3(float(c & 255u), float((c >> 8) & 255u), float((c >> 16) & 255u)) / 255.0, vec3(2.2));
+}
+// The UV checker: light and dark squares, the whole tile tinted by its UDIM number so tiles tell apart.
+vec3 checkerColor(vec2 uv) {
+ vec2 cell = floor(uv * uCheckerScale);
+ float odd = mod(cell.x + cell.y, 2.0);
+ vec2 tile = floor(uv);
+ float hue = fract(0.13 + 0.37 * (tile.x + 10.0 * tile.y));
+ vec3 tint = clamp(abs(fract(hue + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0) - 1.0, 0.0, 1.0);
+ vec3 light = mix(vec3(0.86), tint, 0.18), dark = mix(vec3(0.16), tint * 0.45, 0.35);
+ return mix(light, dark, odd);
+}
// The unit vector from the pixel's point towards the eye, in view space.
vec3 viewRay() {
vec2 ndc = (gl_FragCoord.xy - uViewport.xy) / uViewport.zw * 2.0 - 1.0;
@@ -383,15 +399,18 @@ void main() {
vec3 albedo = uBaseColor;
vec3 tint = vec3(1.0); // multiplies a matcap: polypaint or polygroup colours
#ifdef PRIM
- if (uGroups == 1) albedo = tint = groupColor(texelFetch(uGroupIds, vPrimBase + gl_PrimitiveID).r);
+ if (uGroups == 3) albedo = tint = faceColor(texelFetch(uGroupIds, vPrimBase + gl_PrimitiveID).r);
+ else if (uGroups == 1) albedo = tint = groupColor(texelFetch(uGroupIds, vPrimBase + gl_PrimitiveID).r);
else
#endif
- if (uGroups != 0) albedo = tint = groupColor(0u);
+ if (uGroups == 2 || uGroups == 1) albedo = tint = groupColor(0u);
else if (uPaint == 1) albedo = tint = V_COLOR;
#if defined(NORMALMAP)
- if (uGroups == 0 && uHasPaint == 1) albedo = tint = (uPaint == 1 ? V_COLOR : vec3(1.0)) * texture(uPaintTex, vUv).rgb;
+ if (uChecker == 1) albedo = tint = (uGroups == 3 ? albedo : vec3(1.0)) * checkerColor(vUv);
+ else if (uGroups == 0 && uHasPaint == 1) albedo = tint = (uPaint == 1 ? V_COLOR : vec3(1.0)) * texture(uPaintTex, vUv).rgb;
#elif defined(TEXTURED)
- if (uGroups == 0) albedo = tint = (uPaint == 1 ? V_COLOR : vec3(1.0)) * texture(uPaintTex, vUv).rgb;
+ if (uChecker == 1) albedo = tint = (uGroups == 3 ? albedo : vec3(1.0)) * checkerColor(vUv);
+ else if (uGroups == 0) albedo = tint = (uPaint == 1 ? V_COLOR : vec3(1.0)) * texture(uPaintTex, vUv).rgb;
#endif
#ifdef FLAT
// The triangle's own normal, from its plane's screen-space slopes, turned towards the viewer: a back face (seen
@@ -722,6 +741,8 @@ const Renderer::MeshProgram* Renderer::meshProgram(int features) {
p.hasPaint = at("uHasPaint");
p.normalFlipY = at("uNormalFlipY");
p.twoSided = at("uTwoSided");
+ p.checker = at("uChecker");
+ p.checkerScale = at("uCheckerScale");
p.ghostGroups = at("uGhostGroups");
p.ghostRange = at("uGhostRange");
p.ghostEdge = at("uGhostEdge");
@@ -1143,7 +1164,9 @@ void Renderer::syncScene(const std::vector<SceneMesh>& scene) {
drawList_.clear();
for (const SceneMesh& m : scene) {
if (!m.visible || !m.mesh) continue; // hidden: keeps its dirty state until shown
- sync(slot(m.id), *m.mesh, m.normalMap, m.wireframe && m.active);
+ MeshSlot& ms = slot(m.id);
+ ms.overlay = m.active ? m.overlay : nullptr;
+ sync(ms, *m.mesh, m.normalMap, m.wireframe && m.active);
drawList_.push_back({m.id, m.active, m.flat});
}
}
@@ -1303,7 +1326,8 @@ void Renderer::uploadIndices(MeshSlot& s, const Mesh& mesh) {
void Renderer::uploadFaces(MeshSlot& s, const Mesh& mesh, bool wantUvs, bool indicesDone) {
const size_t nt = mesh.triangleCount();
const bool hidden = mesh.hidden.size() == nt && nt > 0;
- const bool groups = mesh.polygroups.size() == nt && nt > 0;
+ const bool overlay = s.overlay && s.overlay->colors.size() == nt && nt > 0;
+ const bool groups = (mesh.polygroups.size() == nt || overlay) && nt > 0;
const auto clusters = s.order.clusters();
const size_t nc = clusters.size();
s.primBase.assign(nc, 0);
@@ -1351,13 +1375,15 @@ void Renderer::uploadFaces(MeshSlot& s, const Mesh& mesh, bool wantUvs, bool ind
visibleGroups_.resize(groups ? drawn : 0);
if (groups)
poolFor(drawn, [&](size_t b, size_t e) {
- for (size_t i = b; i < e; ++i) visibleGroups_[i] = mesh.polygroups[drawnTris[i]];
+ for (size_t i = b; i < e; ++i) visibleGroups_[i] = overlay ? s.overlay->colors[drawnTris[i]] : mesh.polygroups[drawnTris[i]];
}, 1 << 16);
s.hasGroups = groups && !visibleGroups_.empty() && visibleGroups_.size() <= size_t(std::max(maxTexels, 0));
+ s.overlayColors = overlay && s.hasGroups;
+ s.overlaySerial = s.overlay ? s.overlay->serial : 0;
s.bytes[5] = 0;
if (s.hasGroups) {
// 16 bits per triangle when every id fits (nearly always).
- const bool small = *std::max_element(visibleGroups_.begin(), visibleGroups_.end()) <= 0xFFFFu;
+ const bool small = !overlay && *std::max_element(visibleGroups_.begin(), visibleGroups_.end()) <= 0xFFFFu;
gl::BindBuffer(GL_TEXTURE_BUFFER, s.groupData);
if (small) {
std::vector<uint16_t> ids(visibleGroups_.size());
@@ -1829,7 +1855,8 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo
if (normalMap && (!normalMap->rgb || !normalMap->tangents || normalMap->tangents->size() != mesh.uvs.size() ||
!mesh.hasUvs() || normalMap->rgb->size() != size_t(normalMap->width) * size_t(normalMap->height) * 3))
normalMap = nullptr; // made for another mesh
- const bool wantUvs = hasTexture(mesh) || normalMap;
+ const bool wantUvs = hasTexture(mesh) || normalMap || (s.overlay && s.overlay->checker);
+ const bool overlayChanged = (s.overlay ? s.overlay->serial : 0) != s.overlaySerial;
// Dynamic topology changes topology a little at a time: patches (notePatches) instead of a full upload,
// until there are too many of them.
const bool patched = !s.patches.empty() || !mesh.changedTriangles.empty();
@@ -1918,7 +1945,7 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo
s.bytes[0] = s.bytes[1] = 0;
}
}
- if (!full && (mesh.facesDirty || wantUvs != s.hasUvs)) uploadFaces(s, mesh, wantUvs);
+ if (!full && (mesh.facesDirty || wantUvs != s.hasUvs || overlayChanged)) uploadFaces(s, mesh, wantUvs);
if (wireframe && !s.linesValid && !s.outOfMemory) buildLines(s, mesh);
// Small meshes draw in full while the view moves too (their proxy would save little).
constexpr size_t kProxyMinTriangles = size_t(1) << 18;
@@ -2464,15 +2491,19 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS
drawMicro(s, active, flat, settings);
return;
}
+ // The UV Editor's checker on the model.
+ const bool checker = active && s.hasUvs && s.overlay && s.overlay->checker;
// A painted texture shows through the textured program (polypaint still multiplies it).
- const bool textured = s.hasUvs && s.paintTexture && settings.showPolypaint && settings.showTexture;
+ const bool textured = s.hasUvs && ((s.paintTexture && settings.showPolypaint && settings.showTexture) || checker);
// A baked normal map preview bends the shading normal (core/Bake.h).
const bool normalMapped = s.hasUvs && s.normalTexture && s.hasTangents;
- const int groups = active && settings.showPolygroups ? (s.hasGroups ? 1 : 2) : 0;
+ const int groups = active && s.overlayColors ? 3
+ : active && settings.showPolygroups && !s.overlayColors ? (s.hasGroups ? 1 : 2)
+ : 0;
// (Not through the textured program's geometry shader: those meshes are sculpted without the preview.)
const bool ghost = active && s.id == ghostId_ && !ghost_.empty() && !settings.motionProxy && !textured && !normalMapped;
- const int features = (s.hasColors || s.hasMask ? kPaint : 0) | (groups == 1 ? kPrim : 0) | (textured ? kTextured : 0) |
- (normalMapped ? kNormalMap : 0) | (flat ? kFlat : 0);
+ const int features = (s.hasColors || s.hasMask ? kPaint : 0) | (groups == 1 || groups == 3 ? kPrim : 0) |
+ (textured ? kTextured : 0) | (normalMapped ? kNormalMap : 0) | (flat ? kFlat : 0);
const MeshProgram* p = meshProgram(features);
if (!p) return;
const auto bind = [&](const MeshProgram* p) {
@@ -2515,6 +2546,8 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS
gl::Uniform1i(p->groups, groups);
gl::Uniform1i(p->dim, !active && settings.dimInactive ? 1 : 0);
gl::Uniform1i(p->twoSided, 1);
+ gl::Uniform1i(p->checker, checker ? 1 : 0);
+ gl::Uniform1f(p->checkerScale, checker ? s.overlay->checkerScale : 8.0f);
};
bind(p);
gl::BindVertexArray(s.vao);
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index 2ee0a7c0..31e1e888 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -54,6 +54,15 @@ struct NormalMapView {
bool flipGreen = false; // DirectX convention (green down)
};
+// What the UV Editor shows on the model (app/PanelUvEditor.cpp): a colour per triangle (stretch, texel density,
+// islands, the selection) and / or a checker on the UVs. `serial` changes whenever the colours or the checker do.
+struct MeshOverlay {
+ uint64_t serial = 0;
+ std::vector<uint32_t> colors; // per triangle, 0xBBGGRR (sRGB); empty = the usual colours
+ bool checker = false; // a UDIM-tinted checker on the UVs instead of the base colour
+ float checkerScale = 8.0f; // checker squares per UV unit
+};
+
// One mesh of the scene for Renderer::syncScene: a SubTool, keyed by its stable id.
struct SceneMesh {
uint32_t id = 0;
@@ -64,6 +73,7 @@ struct SceneMesh {
bool wireframe = false; // keep the wireframe's edges on the GPU (built on first need; draw() falls back to
// outlining the triangles, quad diagonals included, until they are)
bool flat = false; // flat shading: each triangle shows its own face normal (faceted)
+ const MeshOverlay* overlay = nullptr; // the UV Editor's view of the active mesh (must outlive the frame)
};
// Part of the target the 3D view is drawn into (framebuffer pixels, origin bottom-left); the rest is
@@ -222,6 +232,9 @@ private:
uint64_t normalSerial = 0;
bool hasTangents = false, tangentsStale = true, normalFlipGreen = false;
bool hasColors = false, hasMask = false, hasGroups = false, hasUvs = false;
+ const MeshOverlay* overlay = nullptr; // this frame's (SceneMesh::overlay)
+ uint64_t overlaySerial = 0; // the one uploaded
+ bool overlayColors = false; // the per-triangle data holds overlay colours, not polygroups
bool fresh = true; // nothing uploaded yet
bool regrid = false; // a stroke's vertex left the position grid (prepareStrokeUpload): the next sync re-sends everything
bool outOfMemory = false; // the last full upload ran out of GPU memory: not drawn
@@ -341,7 +354,7 @@ private:
GLuint id = 0;
GLint view = -1, proj = -1, gridOrigin = -1, gridStep = -1, viewport = -1, projScale = -1, baseColor = -1, paint = -1,
showMask = -1, groups = -1, matcap = -1, matcapCavity = -1, dim = -1, primBase = -1, hasPaint = -1,
- normalFlipY = -1, twoSided = -1;
+ normalFlipY = -1, twoSided = -1, checker = -1, checkerScale = -1;
GLint ghostGroups = -1, ghostRange = -1, ghostEdge = -1, ghostA = -1, ghostB = -1, ghostC = -1, ghostBound = -1, ghostKind = -1, ghostFocal = -1;
};
static constexpr int kPaint = 1, kPrim = 2, kTextured = 4, kNormalMap = 8, kFlat = 16, kMicro = 32, kGhost = 64;
diff --git a/src/render/UvView.cpp b/src/render/UvView.cpp
new file mode 100644
index 00000000..8228a7fb
--- /dev/null
+++ b/src/render/UvView.cpp
@@ -0,0 +1,315 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "render/UvView.h"
+
+#include <glm/gtc/type_ptr.hpp>
+
+#include <algorithm>
+
+namespace sf {
+
+namespace {
+
+constexpr GLenum kViewport = 0x0BA2; // GL_VIEWPORT
+constexpr GLenum kFramebufferBinding = 0x8CA6; // GL_FRAMEBUFFER_BINDING
+constexpr GLenum kRepeat = 0x2901; // GL_REPEAT
+
+// A full-view quad: the tile grid, the checker or the texture.
+const char* kBgVS = R"(#version 330 core
+uniform vec2 uMin, uMax;
+out vec2 vUv;
+void main() {
+ vec2 p = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
+ vUv = mix(uMin, uMax, p);
+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
+}
+)";
+const char* kBgFS = R"(#version 330 core
+in vec2 vUv;
+out vec4 fragColor;
+uniform int uMode; // 0 nothing, 1 checker, 2 texture
+uniform sampler2D uImage; // sRGB: samples come back linear
+uniform float uOpacity;
+uniform float uChecker; // squares per UV unit
+uniform vec2 uPixel; // UV units per pixel
+uniform ivec2 uTiles; // UDIM tiles in use (columns, rows)
+// Distance in pixels to the nearest line of a grid with `step` UV units.
+float gridDist(vec2 uv, float step) {
+ vec2 d = abs(fract(uv / step + 0.5) - 0.5) * step / uPixel;
+ return min(d.x, d.y);
+}
+void main() {
+ vec2 tile = floor(vUv);
+ bool used = tile.x >= 0.0 && tile.y >= 0.0 && tile.x < float(uTiles.x) && tile.y < float(uTiles.y);
+ bool home = tile.x == 0.0 && tile.y == 0.0;
+ vec3 c = vec3(0.098, 0.098, 0.106);
+ if (used) c = vec3(0.137, 0.137, 0.149);
+ if (home) c = vec3(0.157, 0.157, 0.172);
+ if (uMode == 1 && used) {
+ vec2 cell = floor(vUv * uChecker);
+ float odd = mod(cell.x + cell.y, 2.0);
+ c = mix(c, mix(vec3(0.62), vec3(0.30), odd), uOpacity);
+ } else if (uMode == 2 && home) {
+ c = mix(c, pow(texture(uImage, vUv).rgb, vec3(1.0 / 2.2)), uOpacity);
+ }
+ // Tenths inside tiles (fading out when they get too close), tile borders on top.
+ float tenthsPx = 0.1 / max(uPixel.x, 1e-9);
+ float fine = (1.0 - smoothstep(0.0, 1.0, gridDist(vUv, 0.1))) * smoothstep(6.0, 18.0, tenthsPx);
+ float border = 1.0 - smoothstep(0.5, 1.5, gridDist(vUv, 1.0));
+ c = mix(c, vec3(0.30, 0.30, 0.34), fine * (used ? 0.55 : 0.25));
+ c = mix(c, used ? vec3(0.50, 0.50, 0.56) : vec3(0.26, 0.26, 0.29), border);
+ fragColor = vec4(c, 1.0);
+}
+)";
+// Triangles (fill) and lines (edges) of the UV layout.
+const char* kMeshVS = R"(#version 330 core
+layout(location = 0) in vec2 aUv;
+layout(location = 1) in vec4 aFace;
+layout(location = 2) in vec4 aEdge;
+layout(location = 3) in float aMove;
+uniform vec2 uMin, uMax;
+uniform mat3 uMove;
+uniform int uLines;
+flat out vec4 vColor;
+void main() {
+ vec2 p = aUv;
+ if (aMove > 0.5) p = (uMove * vec3(p, 1.0)).xy;
+ gl_Position = vec4((p - uMin) / (uMax - uMin) * 2.0 - 1.0, 0.0, 1.0);
+ vColor = uLines == 1 ? aEdge : aFace;
+}
+)";
+const char* kMeshFS = R"(#version 330 core
+flat in vec4 vColor;
+out vec4 fragColor;
+void main() { fragColor = vColor; }
+)";
+
+GLuint compileShader(GLenum type, const char* src, std::string& error) {
+ GLuint s = gl::CreateShader(type);
+ gl::ShaderSource(s, 1, &src, nullptr);
+ gl::CompileShader(s);
+ GLint ok = 0;
+ gl::GetShaderiv(s, GL_COMPILE_STATUS, &ok);
+ if (!ok) {
+ char log[1024];
+ gl::GetShaderInfoLog(s, sizeof log, nullptr, log);
+ error = std::string("UV view shader: ") + log;
+ gl::DeleteShader(s);
+ return 0;
+ }
+ return s;
+}
+
+GLuint linkProgram(const char* vs, const char* fs, std::string& error) {
+ const GLuint v = compileShader(GL_VERTEX_SHADER, vs, error);
+ if (!v) return 0;
+ const GLuint f = compileShader(GL_FRAGMENT_SHADER, fs, error);
+ if (!f) {
+ gl::DeleteShader(v);
+ return 0;
+ }
+ GLuint p = gl::CreateProgram();
+ gl::AttachShader(p, v);
+ gl::AttachShader(p, f);
+ gl::LinkProgram(p);
+ gl::DeleteShader(v);
+ gl::DeleteShader(f);
+ GLint ok = 0;
+ gl::GetProgramiv(p, GL_LINK_STATUS, &ok);
+ if (!ok) {
+ error = "UV view shader: link failed";
+ gl::DeleteProgram(p);
+ return 0;
+ }
+ return p;
+}
+
+} // namespace
+
+bool UvViewRenderer::init(std::string& error) {
+ if (meshProgram_) return true;
+ bgProgram_ = linkProgram(kBgVS, kBgFS, error);
+ meshProgram_ = bgProgram_ ? linkProgram(kMeshVS, kMeshFS, error) : 0;
+ if (!meshProgram_) return false;
+ auto at = [](GLuint p, const char* n) { return gl::GetUniformLocation(p, n); };
+ bgMin_ = at(bgProgram_, "uMin"), bgMax_ = at(bgProgram_, "uMax"), bgMode_ = at(bgProgram_, "uMode");
+ bgImage_ = at(bgProgram_, "uImage"), bgOpacity_ = at(bgProgram_, "uOpacity"), bgChecker_ = at(bgProgram_, "uChecker");
+ bgPixel_ = at(bgProgram_, "uPixel"), bgTiles_ = at(bgProgram_, "uTiles");
+ mMin_ = at(meshProgram_, "uMin"), mMax_ = at(meshProgram_, "uMax"), mMove_ = at(meshProgram_, "uMove");
+ mLines_ = at(meshProgram_, "uLines");
+ gl::GenVertexArrays(1, &vao_);
+ gl::GenVertexArrays(1, &emptyVao_);
+ GLuint buffers[5];
+ gl::GenBuffers(5, buffers);
+ uvBuffer_ = buffers[0], faceBuffer_ = buffers[1], edgeBuffer_ = buffers[2], moveBuffer_ = buffers[3], indexBuffer_ = buffers[4];
+ gl::BindVertexArray(vao_);
+ gl::BindBuffer(GL_ARRAY_BUFFER, uvBuffer_);
+ gl::EnableVertexAttribArray(0);
+ gl::VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
+ gl::BindBuffer(GL_ARRAY_BUFFER, faceBuffer_);
+ gl::EnableVertexAttribArray(1);
+ gl::VertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, nullptr);
+ gl::BindBuffer(GL_ARRAY_BUFFER, edgeBuffer_);
+ gl::EnableVertexAttribArray(2);
+ gl::VertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, nullptr);
+ gl::BindBuffer(GL_ARRAY_BUFFER, moveBuffer_);
+ gl::EnableVertexAttribArray(3);
+ gl::VertexAttribPointer(3, 1, GL_UNSIGNED_BYTE, GL_FALSE, 0, nullptr);
+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer_);
+ gl::BindVertexArray(0);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+ return true;
+}
+
+void UvViewRenderer::shutdown() {
+ if (!meshProgram_) return;
+ gl::DeleteProgram(bgProgram_);
+ gl::DeleteProgram(meshProgram_);
+ const GLuint buffers[5] = {uvBuffer_, faceBuffer_, edgeBuffer_, moveBuffer_, indexBuffer_};
+ gl::DeleteBuffers(5, buffers);
+ gl::DeleteVertexArrays(1, &vao_);
+ gl::DeleteVertexArrays(1, &emptyVao_);
+ if (fbo_) gl::DeleteFramebuffers(1, &fbo_);
+ if (msFbo_) gl::DeleteFramebuffers(1, &msFbo_);
+ if (msColor_) gl::DeleteRenderbuffers(1, &msColor_);
+ if (texture_) gl::DeleteTextures(1, &texture_);
+ *this = UvViewRenderer();
+}
+
+void UvViewRenderer::setUvs(const std::vector<glm::vec2>& uvs) {
+ if (!meshProgram_) return;
+ if (uvs.size() != corners_) colorsValid_ = false;
+ corners_ = uvs.size();
+ gl::BindBuffer(GL_ARRAY_BUFFER, uvBuffer_);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(uvs.size() * sizeof(glm::vec2)), uvs.empty() ? nullptr : uvs.data(), GL_DYNAMIC_DRAW);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+}
+
+void UvViewRenderer::setColors(const std::vector<uint32_t>& face, const std::vector<uint32_t>& edge, const std::vector<uint8_t>& moving) {
+ if (!meshProgram_) return;
+ colorsValid_ = face.size() == corners_ && edge.size() == corners_ && moving.size() == corners_;
+ if (!colorsValid_) return;
+ gl::BindBuffer(GL_ARRAY_BUFFER, faceBuffer_);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(face.size() * 4), face.data(), GL_DYNAMIC_DRAW);
+ gl::BindBuffer(GL_ARRAY_BUFFER, edgeBuffer_);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(edge.size() * 4), edge.data(), GL_DYNAMIC_DRAW);
+ gl::BindBuffer(GL_ARRAY_BUFFER, moveBuffer_);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(moving.size()), moving.data(), GL_DYNAMIC_DRAW);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+}
+
+void UvViewRenderer::setEdges(const std::vector<uint32_t>& corners) {
+ if (!meshProgram_) return;
+ // Each line as (next corner, corner): the last vertex is the provoking one, so the edge takes the colour of
+ // the corner it starts at.
+ std::vector<uint32_t> idx(corners.size() * 2);
+ for (size_t i = 0; i < corners.size(); ++i) {
+ const uint32_t c = corners[i];
+ idx[i * 2] = c - c % 3 + (c % 3 + 1) % 3;
+ idx[i * 2 + 1] = c;
+ }
+ edgeCount_ = corners.size();
+ gl::BindVertexArray(vao_);
+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(idx.size() * sizeof(uint32_t)), idx.empty() ? nullptr : idx.data(), GL_DYNAMIC_DRAW);
+ gl::BindVertexArray(0);
+}
+
+bool UvViewRenderer::ensureTarget(int w, int h) {
+ if (w == width_ && h == height_ && fbo_) return true;
+ if (!fbo_) {
+ gl::GenFramebuffers(1, &fbo_);
+ gl::GenFramebuffers(1, &msFbo_);
+ gl::GenRenderbuffers(1, &msColor_);
+ gl::GenTextures(1, &texture_);
+ }
+ GLint maxSamples = 0;
+ gl::GetIntegerv(GL_MAX_SAMPLES, &maxSamples);
+ samples_ = std::clamp(maxSamples, 1, 4);
+ gl::BindRenderbuffer(GL_RENDERBUFFER, msColor_);
+ gl::RenderbufferStorageMultisample(GL_RENDERBUFFER, samples_, GL_RGBA8, w, h);
+ gl::BindRenderbuffer(GL_RENDERBUFFER, 0);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, msFbo_);
+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msColor_);
+ const bool msOk = gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ gl::BindTexture(GL_TEXTURE_2D, texture_);
+ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_RGBA8), w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ gl::BindTexture(GL_TEXTURE_2D, 0);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, fbo_);
+ gl::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_, 0);
+ const bool ok = gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ if (!msOk) samples_ = 0; // draw straight into the texture
+ width_ = w, height_ = h;
+ return ok;
+}
+
+GLuint UvViewRenderer::draw(int w, int h, const View& v) {
+ if (!meshProgram_ || w <= 0 || h <= 0) return 0;
+ GLint oldFbo = 0, oldViewport[4] = {0, 0, 0, 0};
+ gl::GetIntegerv(kFramebufferBinding, &oldFbo);
+ gl::GetIntegerv(kViewport, oldViewport);
+ if (!ensureTarget(w, h)) {
+ gl::BindFramebuffer(GL_FRAMEBUFFER, GLuint(oldFbo));
+ return 0;
+ }
+ gl::BindFramebuffer(GL_FRAMEBUFFER, samples_ > 0 ? msFbo_ : fbo_);
+ gl::Viewport(0, 0, w, h);
+ gl::Disable(GL_DEPTH_TEST);
+ gl::Disable(GL_CULL_FACE);
+ gl::Disable(GL_SCISSOR_TEST);
+ gl::ClearColor(0.098f, 0.098f, 0.106f, 1.0f);
+ gl::Clear(GL_COLOR_BUFFER_BIT);
+ // Background.
+ gl::UseProgram(bgProgram_);
+ gl::Uniform2f(bgMin_, v.min.x, v.min.y);
+ gl::Uniform2f(bgMax_, v.max.x, v.max.y);
+ gl::Uniform1i(bgMode_, v.imageMode == 2 && !v.image ? 0 : v.imageMode);
+ gl::Uniform1f(bgOpacity_, v.imageOpacity);
+ gl::Uniform1f(bgChecker_, v.checkerScale);
+ gl::Uniform2f(bgPixel_, (v.max.x - v.min.x) / float(w), (v.max.y - v.min.y) / float(h));
+ gl::Uniform2i(bgTiles_, std::max(v.tiles.x, 1), std::max(v.tiles.y, 1));
+ gl::Uniform1i(bgImage_, 0);
+ gl::ActiveTexture(GL_TEXTURE0);
+ gl::BindTexture(GL_TEXTURE_2D, v.image);
+ if (v.image) {
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GLint(kRepeat));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GLint(kRepeat));
+ }
+ gl::BindVertexArray(emptyVao_);
+ gl::DrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+ gl::BindTexture(GL_TEXTURE_2D, 0);
+ // The layout.
+ if (corners_ && colorsValid_) {
+ gl::Enable(GL_BLEND);
+ gl::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ gl::UseProgram(meshProgram_);
+ gl::Uniform2f(mMin_, v.min.x, v.min.y);
+ gl::Uniform2f(mMax_, v.max.x, v.max.y);
+ gl::UniformMatrix3fv(mMove_, 1, GL_FALSE, glm::value_ptr(v.move));
+ gl::BindVertexArray(vao_);
+ if (v.fill) {
+ gl::Uniform1i(mLines_, 0);
+ gl::DrawArrays(GL_TRIANGLES, 0, GLsizei(corners_));
+ }
+ if (v.edges && edgeCount_) {
+ gl::Uniform1i(mLines_, 1);
+ gl::DrawElements(GL_LINES, GLsizei(edgeCount_ * 2), GL_UNSIGNED_INT, nullptr);
+ }
+ gl::BindVertexArray(0);
+ gl::Disable(GL_BLEND);
+ }
+ gl::UseProgram(0);
+ if (samples_ > 0) {
+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, msFbo_);
+ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_);
+ gl::BlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+ }
+ gl::BindFramebuffer(GL_FRAMEBUFFER, GLuint(oldFbo));
+ gl::Viewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]);
+ return texture_;
+}
+
+} // namespace sf
diff --git a/src/render/UvView.h b/src/render/UvView.h
new file mode 100644
index 00000000..2a887a85
--- /dev/null
+++ b/src/render/UvView.h
@@ -0,0 +1,62 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The UV Editor's 2D view (app/PanelUvEditor.cpp), drawn on the GPU into an offscreen texture the window shows:
+// the UDIM tile grid with a checker or the painted texture behind, every UV triangle filled with its colour
+// (stretch, texel density, islands, the selection) and its edges on top, antialiased. The UVs, colours and edges
+// are uploaded only when they change; a drag moves the selection with a matrix in the vertex shader, so even a
+// million triangles move without re-sending anything.
+#pragma once
+
+#include "render/GL.h"
+
+#include <glm/glm.hpp>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class UvViewRenderer {
+public:
+ bool init(std::string& error);
+ void shutdown();
+
+ // Per triangle corner (Mesh::uvs layout).
+ void setUvs(const std::vector<glm::vec2>& uvs);
+ // Per corner, RGBA8 (0xAABBGGRR): the fill of the corner's triangle, the colour of the edge that starts at the
+ // corner, and whether the corner follows the drag matrix.
+ void setColors(const std::vector<uint32_t>& face, const std::vector<uint32_t>& edge, const std::vector<uint8_t>& moving);
+ // The edges to draw, as corners (each draws the edge from it to the next corner of its triangle).
+ void setEdges(const std::vector<uint32_t>& corners);
+
+ struct View {
+ glm::vec2 min{0.0f}, max{1.0f}; // the UV rectangle shown
+ int imageMode = 1; // 0 nothing, 1 checker, 2 the texture (`image`)
+ GLuint image = 0; // the painted texture (sRGB, rows bottom-up)
+ float imageOpacity = 0.6f;
+ float checkerScale = 8.0f; // squares per UV unit
+ glm::ivec2 tiles{1, 1}; // UDIM tiles in use, from 1001 (columns, rows)
+ glm::mat3 move{1.0f}; // applied to the moving corners
+ bool fill = true;
+ bool edges = true;
+ };
+ // Draws `view` into a `w` x `h` texture and returns it (0 when the GPU can't). The caller's framebuffer and
+ // viewport are restored.
+ GLuint draw(int w, int h, const View& view);
+ size_t triangles() const { return corners_ / 3; }
+
+private:
+ GLuint bgProgram_ = 0, meshProgram_ = 0;
+ GLuint vao_ = 0, emptyVao_ = 0, uvBuffer_ = 0, faceBuffer_ = 0, edgeBuffer_ = 0, moveBuffer_ = 0, indexBuffer_ = 0;
+ GLuint msFbo_ = 0, msColor_ = 0, fbo_ = 0, texture_ = 0;
+ int width_ = 0, height_ = 0, samples_ = 4;
+ size_t corners_ = 0, edgeCount_ = 0;
+ bool colorsValid_ = false;
+ GLint bgMin_ = -1, bgMax_ = -1, bgMode_ = -1, bgImage_ = -1, bgOpacity_ = -1, bgChecker_ = -1, bgPixel_ = -1, bgTiles_ = -1;
+ GLint mMin_ = -1, mMax_ = -1, mMove_ = -1, mLines_ = -1;
+ bool ensureTarget(int w, int h);
+};
+
+} // namespace sf
diff --git a/tests/test_uv_editor.cpp b/tests/test_uv_editor.cpp
index 18bf1a22..6f622332 100644
--- a/tests/test_uv_editor.cpp
+++ b/tests/test_uv_editor.cpp
@@ -236,6 +236,7 @@ TEST(uv_pack_one_tile_and_udim_tiles) {
// at twice the size one tile would give.
CommandResult r = run(doc, "uv_pack", {{"tiles", 4.0}, {"margin", 16.0}});
CHECK(r.ok);
+ }
CHECK(r.message.find("2 UDIM tiles") != std::string::npos);
CHECK(uvsWithin(doc.mesh, glm::vec2(0.0f), glm::vec2(4.0f, 1.0f)));
const UvTopology topo = buildUvTopology(doc.mesh);
@@ -538,3 +539,25 @@ TEST(uv_editor_million_triangles_stay_interactive) {
CHECK(unwrap < 60.0);
CHECK(flippedTriangles(m) < m.triangleCount() / 1000);
}
+
+TEST(uv_unwrap_lion_head_by_sharp_edges) {
+ // A real sculpt with holes and thin strands: the islands don't fold, overlap or leave the tile.
+ Document doc;
+ std::string lion = __FILE__;
+ lion = lion.substr(0, lion.rfind("tests")) + "assets/demo/lion-head.glb";
+ if (!run(doc, "open", {{"path", lion}}).ok) return;
+ CHECK(run(doc, "uv_seam", {{"op", std::string("angle")}, {"angle", 50.0}}).ok);
+ for (const char* method : {"isometric", "conformal", "polygroups"}) {
+ const CommandResult r = run(doc, "uv_unwrap", {{"method", std::string(method)}});
+ CHECK(r.ok);
+ const UvStretchStats st = uvStretchStats(doc.mesh);
+ const UvTopology topo = buildUvTopology(doc.mesh);
+ const size_t folded = flippedTriangles(doc.mesh);
+ std::printf(" lion %s: %s; %u islands, %zu folded, stretch %.3f, boxes disjoint %d\n", method, r.message.c_str(),
+ topo.islandCount, folded, double(st.mean), int(islandBoxesDisjoint(doc.mesh)));
+ CHECK(folded * 200 < doc.mesh.triangleCount());
+ CHECK(islandBoxesDisjoint(doc.mesh));
+ CHECK(uvsWithin(doc.mesh, glm::vec2(0.0f), glm::vec2(1.0f)));
+ CHECK(st.mean < 0.25f);
+ }
+}
diff --git a/tests/ui/uv_editor.sfui b/tests/ui/uv_editor.sfui
new file mode 100644
index 00000000..154e2635
--- /dev/null
+++ b/tests/ui/uv_editor.sfui
@@ -0,0 +1,101 @@
+# UV Editor (Tool > Texture Map > UV Editor, Shift+U): the 2D layout drawn on the GPU, seams drawn on the model,
+# unwrapping, the colours and checker on the model, packing across UDIM tiles, texel density, trim strips,
+# selecting and moving islands with undo.
+drop ../../assets/demo/lion-head.glb
+wait_idle 60
+key shift+u
+expect_value uv_editor_open == 1
+expect "UV Editor/Unwrap##uvunwrap"
+expect_value uv_islands == 0
+shot open
+
+# Seams on the model with the Seam tool: a drag across the mane marks the edges under it, red on the model.
+click "UV Editor/Seam Tool"
+expect_value uv_tool == 1
+stroke 0.2 0.45 0.8 0.45
+expect_value uv_seams > 10
+remember uv_seams drawn
+shot seam-tool
+key ctrl+z
+expect_value uv_seams == 0
+key ctrl+shift+z
+expect_value uv_seams == $drawn
+click "UV Editor/Seam Tool"
+expect_value uv_tool == 0
+
+# Sharp edges as seams, then Least Stretch: islands that neither fold nor stretch much, a view of them and the
+# same colours and a checker on the model.
+run uv_seam op=angle angle=50
+click "UV Editor/Unwrap##uvunwrap"
+wait_idle 120
+expect_value uv_unwraps == 1
+expect_value uv_islands > 20
+expect_value uv_stretch_x1000 < 60
+expect_value uv_flipped_x1000 < 5
+expect_value uv_view_triangles == 47214
+expect_value uv_overlay == 1
+expect_status "Unwrapped"
+shot unwrapped
+# One undo step: back to no UVs, and redo.
+key ctrl+z
+expect_value uv_islands == 0
+key ctrl+shift+z
+expect_value uv_islands > 20
+
+# Stretch on the model and in the view.
+click "UV Editor/##uvcolor"
+click "Stretch"
+shot stretch
+
+# Across two UDIM tiles.
+run uv_pack tiles=2 margin=6
+expect_value uv_tiles == 2
+hover_window 0.45 0.5
+key f
+shot udim
+run uv_pack tiles=1
+expect_value uv_tiles == 1
+
+# Texel density: every island to 400 texels per unit at 2K.
+run uv_density op=set value=400
+wait 0.2
+expect_value uv_density > 395
+expect_value uv_density < 405
+run uv_pack
+
+# Select an island and move it with G; undo puts it back.
+click "UV Editor/##uvcolor"
+click "Islands"
+run uv_select op=island face=20000 mode=island
+expect_value uv_selected > 10
+hover_window 0.45 0.5
+key home
+remember uv_max_u before_move
+shot selected
+hover_window 0.40 0.50
+key g
+hover_window 0.52 0.50
+key enter
+expect_value can_undo == 1
+shot moved
+key ctrl+z
+expect_value uv_max_u == $before_move
+
+# Trim sheet: the selected island laid into the second of four strips.
+click "UV Editor/Trim Sheet"
+run uv_trim strip=2 strips=4 fit_width=true
+expect_status "in Strip 2"
+shot trim
+
+# Select in 3D: a click on the model picks its island.
+run uv_select op=none
+click "UV Editor/Select in 3D"
+expect_value uv_tool == 2
+stroke 0.5 0.4 0.5 0.4
+expect_value uv_selected > 0
+click "UV Editor/Select in 3D"
+
+# The window closes with its key.
+hover_window 0.2 0.5
+key shift+u
+expect_value uv_editor_open == 0