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.

Linked Duplicates (#94): Parts sharing one mesh and history, each with its own transform

islandmed4764c4743f9d
diff --git a/changes/feat-linked-duplicate.md b/changes/feat-linked-duplicate.md
new file mode 100644
index 00000000..5f9950cf
--- /dev/null
+++ b/changes/feat-linked-duplicate.md
@@ -0,0 +1,25 @@
+---
+whats_new: **Linked Duplicates**: **Tool > Parts > Linked Duplicate** makes a copy that shares the Part's mesh but
+ sits in its own place. Sculpt, paint or mask any of them and all change; move, turn or scale each with the Gizmo.
+ **Make Unique** gives one its own mesh again. Hundreds of copies cost about one mesh.
+highlight: Linked Duplicates: sculpt one, every copy follows
+added: **Linked Duplicates** (#94, asked for by ebarranco; the idea of placing copies on their own by NicTanghe):
+ **Tool > Parts > Linked Duplicate** adds a Part sharing the active one's mesh, undo history and GPU buffers, with
+ its own transform. Strokes, masking and painting on any copy edit the shared mesh (symmetry about the copy's own
+ axes); the Gizmo and `transform` move a linked copy as a whole (a mask poses the shared mesh instead); **Make
+ Unique** breaks the link; deleting one keeps the others. The Parts list shows a link and the count. Projects keep
+ the links (project format 8); glTF reuses one mesh with a node per copy, USD writes instanceable prims referencing
+ the first copy (and reads them back), OBJ / STL / FBX / PLY write each copy where it is. Commands
+ `part_duplicate_linked` and `part_make_unique`. 500 linked copies use about the memory of one mesh.
+testers:
+ - Any OS: new sphere, Tool > Parts > Linked Duplicate three times. The rows show a link and 4; sculpt on the last
+ copy: all four change, Ctrl+Z on the first undoes it.
+ - Any OS: Gizmo (W / E / R) on a copy: only that copy moves, turns, scales; then sculpt on the turned copy, the
+ stroke lands under the cursor; with X symmetry the mirrored dab lands on the copy's own other side.
+ - Any OS: Make Unique on one copy, sculpt it: the others don't change. Delete the original: the copies stay.
+ - Any OS: save, reopen: the links and places are back. Export GLB and USD and open them in another app: every
+ copy is where it was.
+ - Windows (low-end GPU): 100 linked copies of a 50k-triangle Part: orbiting stays smooth, and Edit >
+ Preferences > Performance shows the GPU memory of about one Part.
+---
+Phase 2 (arrays of linked copies: linear, radial, along a curve) is planned in REPORT.md.
diff --git a/docs/guide/images/linked-duplicates.jpg b/docs/guide/images/linked-duplicates.jpg
new file mode 100644
index 00000000..af642883
Binary files /dev/null and b/docs/guide/images/linked-duplicates.jpg differ
diff --git a/docs/guide/index.md b/docs/guide/index.md
index 7f2a210d..2dae0028 100644
--- a/docs/guide/index.md
+++ b/docs/guide/index.md
@@ -43,6 +43,7 @@ Read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<kbd>F1</
11. [Face Groups and visibility](face-groups.md)
12. [Selection sets and morph targets](selection-sets.md)
13. [Parts](parts.md)
+ - [Linked Duplicates](linked-duplicates.md)
14. [Forge Spheres](forge-spheres.md)
15. [Vertex Paint and materials](vertex-paint.md)
16. [Texture painting](texture-painting.md)
diff --git a/docs/guide/linked-duplicates.md b/docs/guide/linked-duplicates.md
new file mode 100644
index 00000000..bfd25e57
--- /dev/null
+++ b/docs/guide/linked-duplicates.md
@@ -0,0 +1,76 @@
+# Linked Duplicates
+
+A **Linked Duplicate** is a Part that shares its mesh with another Part but sits in its own place: rivets on a
+belt, the four legs of a table, the teeth of a gear, a row of columns. Sculpt, paint or mask any one of them and
+every linked copy changes with it; move, turn or scale each one on its own. A hundred linked copies cost about as
+much memory as one mesh, on the graphics card too.
+
+![Three linked copies of one sphere, the last one scaled up: a stroke on it shows on all three; the Parts list shows a link and the count on each row](images/linked-duplicates.jpg)
+
+## Make a linked copy
+
+1. Select the Part in **Tool > Parts**.
+2. Click **Linked Duplicate** (or right-click its row > **Linked Duplicate**).
+
+The copy is named `<name> link`, goes right under the original in the list and appears beside it on +X. It becomes
+the active Part. Each linked Part shows a link and the number of Parts sharing the mesh at the end of its row; point
+at the row to see the count in the tooltip too.
+
+Making a linked copy is undoable: <kbd>Ctrl</kbd>+<kbd>Z</kbd> takes it away again.
+
+## Sculpt any of them
+
+- Brushes, masking, Vertex Paint, texture painting, face groups and whole-mesh tools (remesh, subdivide,
+ decimate, layers) work on the shared mesh: every linked copy shows the change at once.
+- Strokes land where you see them on whichever copy is active, even when it is turned or scaled. **Symmetry**
+ mirrors across the copy's own axes, so a turned copy still sculpts symmetrically.
+- Linked copies share one undo history: undo on any of them steps back the shared mesh.
+- The copies that aren't active are drawn slightly darker, like other Parts. The mask shows on the active one.
+
+## Move, turn and scale a copy
+
+Use the [Gizmo](gizmo.md) on the active linked Part: it moves, turns or scales that copy as a whole and leaves the
+others where they are. Each move is one undo step. Scaling a linked copy is always even (the same along every
+axis), so it stays a copy of the same shape; uneven scaling takes the mean.
+
+With a mask (and the Gizmo's **Mask** option on), the Gizmo poses the shared mesh instead: the unmasked part
+moves, in every copy, along the active copy's own axes.
+
+`transform` does the same from the [console](scripting.md): `transform translate=0,1,0 rotate=0,90,0`.
+
+## Make Unique
+
+**Make Unique** (in **Tool > Parts**, or right-click the row) gives the active linked Part its own copy of the
+mesh. It stays where it is and no longer changes with the others. Its undo history starts fresh.
+
+Deleting a linked Part never touches the others: the mesh stays as long as one Part uses it.
+
+## Linked copies in files
+
+| Format | What happens |
+|---|---|
+| Project (`.sfproj`) | The links and each copy's place are kept; the mesh is saved once |
+| glTF / GLB | One mesh, one node per copy with its own matrix |
+| USD (`.usda`, `.usdz`) | The first copy holds the mesh; each other copy is an `instanceable` prim that references it, with its own transform |
+| OBJ, STL, PLY, FBX, Bridge | Every copy is written as its own mesh, where it is |
+
+**Merge down** and **Merge visible** put every Part where it is in the scene, so merged linked copies end up as
+separate pieces of one mesh. Projects with linked copies need SculptForge 0.12 or later to open.
+
+## Scripting
+
+| Command | What it does |
+|---|---|
+| `part_duplicate_linked` | A linked copy of the active Part (or `index=` / `name=`); `offset=x,y,z` places it (default: beside it on +X) |
+| `part_make_unique` | Give a linked Part its own mesh |
+| `part_list` | Linked Parts show `linked xN` |
+
+```text
+part_duplicate_linked offset=0,0,2; part_duplicate_linked offset=0,0,2; part_duplicate_linked offset=0,0,2
+```
+
+## See also
+
+- [Parts](parts.md): the Parts list, merging and splitting
+- [Moving, rotating and posing (Gizmo)](gizmo.md)
+- [Exporting](exporting.md)
diff --git a/docs/guide/parts.md b/docs/guide/parts.md
index f2e8a653..c46e3873 100644
--- a/docs/guide/parts.md
+++ b/docs/guide/parts.md
@@ -34,6 +34,7 @@ and they catch up a moment after you stop changing a Part (not during a stroke).
| Rename it | Double-click the row (or right-click > **Rename**), type, press <kbd>Enter</kbd> |
| Hide or show it | Click the eye at the end of the row |
| Duplicate or delete it | Right-click the row > **Duplicate** (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>D</kbd>) or **Delete...** |
+| Make a copy that shares the mesh | Right-click the row > **Linked Duplicate**, or the **Linked Duplicate** button; see [Linked Duplicates](linked-duplicates.md) |
| See its vertex and triangle counts | Point at the row for a moment |
The list shows six rows and scrolls when there are more. Names are kept unique: renaming a Part to a name that
@@ -96,6 +97,8 @@ You can also add files as Parts from elsewhere:
> **Tip:** **Duplicate** (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>D</kbd>, also in the command palette as
> **Duplicate Part**) copies the active Part with its layers and attributes, names it `<name> copy` and puts it
> right under the original. Use it to keep a safe copy before a destructive step such as a remesh.
+> **Linked Duplicate** instead makes a copy that shares the mesh and changes with it (rivets, legs, columns); see
+> [Linked Duplicates](linked-duplicates.md).
## Show, hide and solo
@@ -201,7 +204,7 @@ delete can't be undone.
| Format | What happens to Parts |
|---|---|
-| Project (`.sfproj`) | Every Part is saved with its name, visibility, folder, attributes, layers and active layer |
+| Project (`.sfproj`) | Every Part is saved with its name, visibility, folder, attributes, layers and active layer; [linked copies](linked-duplicates.md) keep their link |
| OBJ | Each visible Part is an `o` object; on import, `o` objects become Parts and `g` groups become face groups |
| glTF / GLB | One node and mesh per visible Part, both ways |
| FBX | One model per visible Part (with LODs, an LOD group each), both ways |
@@ -224,6 +227,7 @@ used.
| `part_select index=1` | Make a Part active |
| `part_append type=cube` | Add a primitive (`sphere`, `cube`, `plane`); `path=` adds a file; `size=` (0.05-2, default 0.35) |
| `part_duplicate` | Copy a Part |
+| `part_duplicate_linked` / `part_make_unique` | A [linked copy](linked-duplicates.md) sharing the mesh / break the link |
| `part_delete name=Helmet` | Delete a Part |
| `part_rename to=Body` | Rename a Part |
| `part_visibility visible=false` | Show or hide (toggles when `visible` is left out) |
@@ -245,6 +249,7 @@ part_append type=sphere name=EyeL size=0.12; part_duplicate; part_rename to=EyeR
## See also
+- [Linked Duplicates](linked-duplicates.md): copies that share one mesh
- [Face Groups and visibility](face-groups.md): hide parts of one Part
- [Sculpt layers and blend shapes](layers.md): layers belong to each Part
- [Exporting](exporting.md): how Parts reach other applications
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 765f9f38..fd1a4def 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -1638,7 +1638,7 @@ void App::dispatchEvent(const SDL_Event& event) {
bool App::pick(float x, float y, RayHit& hit) const {
if (!doc_.activePartInfo().visible) return false; // you can't sculpt what you can't see
glm::vec3 origin, dir;
- canvasRay(x, y, origin, dir);
+ partRay(x, y, origin, dir);
return frontRaycast(origin, dir, hit);
}
@@ -2007,7 +2007,7 @@ void App::wheelZoom(float x, float y, float steps) {
RayHit hit;
glm::vec3 p;
if (canPick && pick(x, y, hit)) {
- p = hit.position;
+ p = glm::vec3(doc_.activePartInfo().transform * glm::vec4(hit.position, 1.0f)); // (a moved linked copy, #94)
} else {
const glm::vec3 fwd = camera_.forward();
const float along = glm::dot(dir, fwd);
@@ -2069,8 +2069,8 @@ void App::onMouseUp() {
if (drag_ == Drag::Insert) {
// The drag's length on screen, as a size at the surface point's depth (at least a small default).
const float px = std::max(insertPx_, 12.0f * uiScale_);
- const float dist = glm::length(camera_.position() - insertAt_);
- const float worldPerPx = 2.0f * dist * std::tan(camera_.fovY * 0.5f) / std::max(canvasRect().h, 1.0f);
+ const float dist = glm::length(partCamera().position() - insertAt_);
+ const float worldPerPx = 2.0f * dist * std::tan(partCamera().fovY * 0.5f) / std::max(canvasRect().h, 1.0f);
Args args{{"x", double(insertAt_.x)}, {"y", double(insertAt_.y)},
{"z", double(insertAt_.z)}, {"nx", double(insertNormal_.x)},
{"ny", double(insertNormal_.y)}, {"nz", double(insertNormal_.z)},
@@ -2170,7 +2170,7 @@ void App::beginAlongNormal(const RayHit& hit, float radius) {
glm::vec3 n = brushAreaNormal(doc_.mesh, doc_.bvh, hit.position, std::max(radius, 1e-6f), focalShift_);
if (glm::length(n) < 0.5f) n = hit.normal;
if (glm::length(n) < 0.5f) return;
- if (glm::dot(n, camera_.forward()) > 0.0f && glm::dot(hit.normal, camera_.forward()) < 0.0f) n = -n; // (outward, to the viewer)
+ if (glm::dot(n, partCamera().forward()) > 0.0f && glm::dot(hit.normal, partCamera().forward()) < 0.0f) n = -n; // (outward, to the viewer)
strokeAlongNormal_ = true;
alongNormalDir_ = glm::normalize(n);
alongNormalAnchor_ = hit.position;
@@ -2183,10 +2183,10 @@ void App::beginAlongNormal(const RayHit& hit, float radius) {
// viewer (the cursor can't say how far along it), by how far the cursor went up since the press.
glm::vec3 App::alongNormalTarget(float x, float y) const {
glm::vec3 origin, dir;
- canvasRay(x, y, origin, dir);
+ partRay(x, y, origin, dir);
float s = 0.0f;
if (!lineRayClosest(alongNormalAnchor_, alongNormalDir_, origin, dir, s))
- s = (alongNormalStartY_ - y) * camera_.worldPerPixel(alongNormalAnchor_, canvasHeight());
+ s = (alongNormalStartY_ - y) * partCamera().worldPerPixel(alongNormalAnchor_, canvasHeight());
return alongNormalAnchor_ + alongNormalDir_ * s;
}
@@ -2257,8 +2257,8 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
pointerLatestAt_ = double(SDL_GetTicksNS()) * 1e-9;
penPredictor_.reset(pointerLatest_, pointerLatestAt_);
{
- const glm::vec3 n = glm::dot(hit.normal, camera_.forward()) > 0.0f ? -hit.normal : hit.normal;
- ghostFrame_ = {hit.position, glm::length(n) > 0.0f ? glm::normalize(n) : -camera_.forward(), hit.position, true};
+ const glm::vec3 n = glm::dot(hit.normal, partCamera().forward()) > 0.0f ? -hit.normal : hit.normal;
+ ghostFrame_ = {hit.position, glm::length(n) > 0.0f ? glm::normalize(n) : -partCamera().forward(), hit.position, true};
const glm::uvec3 t = hit.triangle < doc_.mesh.triangles.size() ? doc_.mesh.triangles[hit.triangle] : glm::uvec3(0);
const auto& P = doc_.mesh.positions;
ghostCurvature_ = 0.0f;
@@ -2270,8 +2270,8 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
// few percent (#122), so Move grabs with the full brush size.
DabParams p;
p.center = hit.position;
- p.viewDir = camera_.forward();
- p.radius = radiusPx_ * camera_.worldPerPixel(hit.position, canvasHeight());
+ p.viewDir = partCamera().forward();
+ p.radius = radiusPx_ * partCamera().worldPerPixel(hit.position, canvasHeight());
p.strength = strength_;
p.focal = focalShift_;
p.connectedOnly = uiPrefs_.connectedOnly;
@@ -2295,7 +2295,7 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
lazyMouse_.reset(glm::vec2(x, y));
if ((strokeBrush_ == BrushType::SnakeHook || strokeBrush_ == BrushType::KelvinSnake) && !recipe && strokeSculpt_) {
grabLast_ = hit.position; // the pulled tip (see snakeHookTo)
- beginAlongNormal(hit, radiusPx_ * camera_.worldPerPixel(hit.position, canvasHeight()));
+ beginAlongNormal(hit, radiusPx_ * partCamera().worldPerPixel(hit.position, canvasHeight()));
return;
}
if (strokeType_ == StrokeType::DragRect || strokeType_ == StrokeType::DragDot) {
@@ -2353,8 +2353,8 @@ void App::strokeTo(float x, float y) {
}
if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_) {
glm::vec3 origin, dir;
- canvasRay(x, y, origin, dir);
- glm::vec3 n = camera_.forward();
+ partRay(x, y, origin, dir);
+ glm::vec3 n = partCamera().forward();
float denom = glm::dot(dir, n);
if (std::abs(denom) < 1e-6f) return;
float t = glm::dot(grabLast_ - origin, n) / denom; // (the plane through the grabbed point, facing the view)
@@ -2495,7 +2495,7 @@ void App::dabAt(float x, float y, float pressure) {
strokeProbe_->emplace_back(x, y);
if (strokeRadiusProbe_) strokeRadiusProbe_->push_back(st.radiusPx);
}
- const Camera& cam = dabView_ ? dabView_->camera : camera_;
+ const Camera cam = dabView_ ? dabView_->camera : partCamera(); // (a moved linked copy: its own space)
const glm::vec2 pathPoint(x, y); // (before any scatter: the rake follows the stroke itself)
const BrushRecipe* recipe = st.recipe;
if (recipe && recipe->jitter > 0.0f) {
@@ -2567,7 +2567,10 @@ void App::dabAt(float x, float y, float pressure) {
p.connectedOnly = st.connectedOnly;
p.viewFalloff = st.viewFalloff;
p.focal = st.focal;
- if (!dabView_) lastDabScreen_ = glm::vec2(x, y); // (the solver's: when its batch is committed)
+ if (!dabView_) { // (the solver's: when its batch is committed)
+ lastDabScreen_ = glm::vec2(x, y);
+ lastDabCentre_ = hit.position;
+ }
if (st.mask) {
p.strength = st.maskStrength;
doc_.sculptor.dabMask(doc_.mesh, doc_.bvh, p, st.symmetry);
@@ -2713,7 +2716,8 @@ void App::runCommand(const std::string& name, const Args& args) {
(name == "splat_transform" && args.contains("fit"))))
camera_.frame(sceneBounds());
// A new Part lands beside the model: bring it into view only if it isn't already.
- if (r.ok && (name == "part_append" || name == "part_duplicate") && !onScreen(doc_.mesh.bounds()))
+ if (r.ok && (name == "part_append" || name == "part_duplicate" || name == "part_duplicate_linked") &&
+ !onScreen(doc_.partBounds(doc_.activePart)))
camera_.frame(sceneBounds());
afterCommand(name, args, r);
afterVdmCommand(name, r); // the VDM brush after vdm_set / vdm_capture, the top view after vdm_new_plane
@@ -2848,7 +2852,7 @@ void App::updateFloorHeight() {
const Part& p = doc_.parts[size_t(i)];
mix(p.id);
mix(p.visible);
- mix(p.undo.revision());
+ mix(doc_.partUndo(i).revision());
mix(doc_.partMesh(i).vertexCount());
}
if (key == floorKey_) return;
@@ -2949,11 +2953,13 @@ void App::syncScene() {
for (int i = 0; i < doc_.partCount(); ++i) {
Part& s = doc_.parts[size_t(i)];
const bool active = i == doc_.activePart;
- Mesh* mesh = active ? &shown : &s.mesh;
+ Mesh* mesh = doc_.checkedOut(i) ? &shown : &s.data->mesh;
// Solo channel view (channel_view): the texture's shown texels follow before the renderer uploads them.
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});
+ const uint32_t key = doc_.meshKey(i); // (linked Parts, #94: one GPU mesh, drawn where each is)
+ scene.push_back({key, mesh, active, s.visible, bakeNormalMap(s.id, *mesh), renderSettings_.wireframe, flat});
+ scene.back().model = s.transform;
scene.back().pbr = renderSettings_.pbr();
if (active && &shown == &doc_.mesh) scene.back().overlay = uvEditorOverlay(s.id); // the UV Editor's colours
}
@@ -3696,8 +3702,8 @@ void App::projectImageFromView() {
o.depth = projectDepth_ * glm::length(b.extent());
o.invert = projectInvert_;
Mesh m = doc_.mesh;
- size_t n = projectImage(m, doc_.activeLayer, refImage_, camera_.projection() * camera_.view(),
- view.w / std::max(view.h, 1.0f), camera_.position(), o);
+ size_t n = projectImage(m, doc_.activeLayer, refImage_, partCamera().projection() * partCamera().view(),
+ view.w / std::max(view.h, 1.0f), partCamera().position(), o);
if (n == 0) {
status_ = "The image didn't land on the model - aim the view at it first";
return;
@@ -4211,7 +4217,7 @@ bool App::drawSurfaceCursor(ImDrawList* dl, float x, float y, float radiusPx, fl
RayHit hit;
if (!pick(x, y, hit)) return false; // one ray, as a press would cast
// The world radius a dab here gets (App::firstDab / the brushes: Size times world size of a pixel).
- const float radius = radiusPx * camera_.worldPerPixel(hit.position, canvasHeight());
+ const float radius = radiusPx * partCamera().worldPerPixel(hit.position, canvasHeight());
if (!(radius > 0.0f) || !std::isfinite(radius)) return false;
// A steady normal over the brush's area (32 rays), then the ring and the Falloff ring as true circles in
// that plane (#88): no per-point pressing, so bumps can't bend or break the ring. Never a pass over the mesh.
@@ -4219,8 +4225,8 @@ bool App::drawSurfaceCursor(ImDrawList* dl, float x, float y, float radiusPx, fl
surfaceCursorCircle(hit.position, n, radius, 64, cursorRing_);
surfaceCursorCircle(hit.position, n, radius * focalRingFraction(focal), 48, cursorInner_);
- const glm::vec3 eye = camera_.position(), forward = camera_.forward();
- const bool ortho = camera_.ortho;
+ const glm::vec3 eye = partCamera().position(), forward = partCamera().forward();
+ const bool ortho = partCamera().ortho;
auto facing = [&](const glm::vec3& p, const glm::vec3& pn) {
return glm::dot(pn, ortho ? -forward : eye - p) > 0.0f;
};
@@ -4228,7 +4234,7 @@ bool App::drawSurfaceCursor(ImDrawList* dl, float x, float y, float radiusPx, fl
ImVec2 sp[64];
const size_t count = std::min<size_t>(points.size(), 64);
for (size_t i = 0; i < count; ++i)
- if (!gizmoProject(points[i], sp[i])) return; // (behind the camera: a huge brush close up)
+ if (!partProject(points[i], sp[i])) return; // (behind the camera: a huge brush close up)
dl->AddPolyline(sp, int(count), colour, ImDrawFlags_Closed, width);
};
auto fade = [](ImU32 colour, float k) {
@@ -4246,7 +4252,7 @@ bool App::drawSurfaceCursor(ImDrawList* dl, float x, float y, float radiusPx, fl
const glm::vec3 q = m.point(hit.position);
if (glm::length(q - hit.position) < radius * 0.05f || !facing(q, m.dir(n))) continue;
ImVec2 at;
- if (!gizmoProject(q, at)) continue;
+ if (!partProject(q, at)) continue;
++symmetryCopiesDrawn_;
dl->AddCircleFilled(at, 3.0f * uiScale_, IM_COL32(0, 0, 0, 110));
dl->AddCircleFilled(at, 2.25f * uiScale_, fade(col, 0.8f));
@@ -4257,8 +4263,8 @@ bool App::drawSurfaceCursor(ImDrawList* dl, float x, float y, float radiusPx, fl
}
// The surface's direction: a short line out of the centre (with a dot where the brush touches).
ImVec2 c0, c1;
- if (gizmoProject(hit.position, c0)) {
- if (ring && gizmoProject(hit.position + n * (radius * 0.4f), c1)) dl->AddLine(c0, c1, fade(col, 0.85f), 1.5f);
+ if (partProject(hit.position, c0)) {
+ if (ring && partProject(hit.position + n * (radius * 0.4f), c1)) dl->AddLine(c0, c1, fade(col, 0.85f), 1.5f);
dl->AddCircleFilled(c0, 2.0f * uiScale_, col);
}
return true;
diff --git a/src/app/App.h b/src/app/App.h
index b4c35602..5c6354e7 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -1718,6 +1718,11 @@ private:
void updateCameraAspect(); // camera_.aspect from the canvas
// Ray through window point (x, y) of the canvas, and the canvas height for screen-size conversions.
void canvasRay(float x, float y, glm::vec3& origin, glm::vec3& dir) const;
+ // The view from inside the active Part (a moved linked copy, #94): camera_ with that Part's transform undone,
+ // so rays, brush sizes and projections line up with its mesh (and symmetry is about its own axes). The same
+ // as camera_ for a Part that isn't moved. partRay / partProject: canvasRay / gizmoProject in that space.
+ Camera partCamera() const { return camera_.inSpaceOf(doc_.activePartInfo().transform); }
+ void partRay(float x, float y, glm::vec3& origin, glm::vec3& dir) const;
float canvasHeight() const { return canvasRect().h; }
Renderer::Viewport canvasViewport(int fbWidth, int fbHeight) const; // the canvas in framebuffer pixels
void drawCanvasFrame();
@@ -2024,6 +2029,7 @@ private:
glm::mat3 gizmoFrame() const;
float gizmoWorldSize() const; // world length of an axis arrow (constant on screen)
bool gizmoProject(const glm::vec3& p, ImVec2& out) const; // false behind the camera
+ bool partProject(const glm::vec3& p, ImVec2& out) const; // a point of the active Part's mesh
GizmoHandle gizmoHandleAt(float x, float y) const;
bool gizmoHandleScreen(GizmoHandle h, ImVec2& out) const; // a point to grab handle h (UI tests)
std::vector<int> gizmoTargets() const; // Parts a drag transforms (the active one, or All)
@@ -2058,6 +2064,9 @@ private:
MeshTransform current;
std::vector<int> parts;
std::vector<TransformSession> sessions;
+ // Linked copies (#94) the drag moves as a whole (partMovesWhole), and their transforms when it began.
+ std::vector<int> wholeParts;
+ std::vector<glm::mat4> wholeStart;
std::string readout; // shown beside the gizmo while dragging ("Rotate 45")
// Where the gizmo was before and after each of its undo steps (active Part, by undo depth).
struct Step {
@@ -2438,6 +2447,7 @@ private:
void resetView(); // the view.reset action (Maya keys: Alt+H, #134)
float rollStartX_ = 0.0f, rollStartY_ = 0.0f;
glm::vec2 lastDabScreen_{0.0f}; // window pixels of the last dab (UI tests: last_dab_x / last_dab_y)
+ glm::vec3 lastDabCentre_{0.0f}; // ... and its centre on the active Part's mesh (UI tests: dab_scene_error_px)
bool maskClickPending_ = false; // Ctrl+press on the model: a click blurs (Alt: sharpens), a drag paints
float maskClickX_ = 0.0f, maskClickY_ = 0.0f;
// ---- end classic feel ----
diff --git a/src/app/AsyncStroke.cpp b/src/app/AsyncStroke.cpp
index dafccfe8..d8f3a5a2 100644
--- a/src/app/AsyncStroke.cpp
+++ b/src/app/AsyncStroke.cpp
@@ -302,12 +302,12 @@ void App::pumpStroke() {
s.batch.clear();
s.finalize = true;
s.catchUp = false;
- s.view.camera = camera_;
+ s.view.camera = partCamera();
s.view.canvas = canvasRect();
s.view.probe = nullptr;
s.view.radiusProbe = nullptr;
s.view.settings = dabSettings();
- s.uploadId = doc_.activePartInfo().id;
+ s.uploadId = doc_.meshKey(doc_.activePart);
renderer_.setPersistentUpload(uiPrefs_.fastUpload);
renderer_.bindStrokeUpload(s.uploadId, s.upload); // (the slot, found here: the thread doesn't walk the renderer's list)
s.prepare = &displayedMesh() == &doc_.mesh;
@@ -326,12 +326,12 @@ void App::pumpStroke() {
s.batch.clear();
s.finalize = false;
s.catchUp = true;
- s.view.camera = camera_;
+ s.view.camera = partCamera();
s.view.canvas = canvasRect();
s.view.probe = nullptr;
s.view.radiusProbe = nullptr;
s.view.settings = dabSettings();
- s.uploadId = doc_.activePartInfo().id;
+ s.uploadId = doc_.meshKey(doc_.activePart);
renderer_.bindStrokeUpload(s.uploadId, s.upload);
s.prepare = &displayedMesh() == &doc_.mesh;
s.start();
@@ -355,7 +355,7 @@ void App::pumpStroke() {
s.finalize = strokeFinishing_ && dabQueue_.empty();
s.catchUp = false; // (dabs are coming: the exact normals wait for a pause or the release)
lastDabsQueued_ = double(SDL_GetTicksNS()) * 1e-9;
- s.view.camera = camera_;
+ s.view.camera = partCamera();
s.view.canvas = canvasRect();
s.view.probe = strokeProbe_ ? &s.probe : nullptr;
s.view.radiusProbe = strokeProbe_ ? &s.radiusProbe : nullptr;
@@ -401,7 +401,7 @@ void App::finishStrokeNow() {
if (solver_) solver_->finalize = false;
doc_.sculptor.flushDraft(doc_.mesh, doc_.bvh); // (a draft stroke ended here rather than on the solver thread)
renderer_.setDraftNormals(0);
- if (asyncStroke_) renderer_.refineStrokeBounds(doc_.activePartInfo().id, displayedMesh()); // (the quick ones)
+ if (asyncStroke_) renderer_.refineStrokeBounds(doc_.meshKey(doc_.activePart), displayedMesh()); // (the quick ones)
strokeFinishing_ = false;
asyncStroke_ = false;
renderer_.setGhost(0, GhostStroke());
@@ -507,7 +507,7 @@ bool App::ghostSurface(const glm::vec3& origin, const glm::vec3& dir, glm::vec3&
void App::buildGhost() {
ghostHeadValid_ = false;
renderer_.setScreenStroke(GhostStroke()); // (set again below when this frame's dabs draw on the screen)
- const uint32_t id = doc_.activePartInfo().id;
+ const uint32_t id = doc_.meshKey(doc_.activePart); // (the renderer's slot: linked Parts share it)
if (liveMove_.active) { // Live Move: one "dab" per mirror, the whole move so far
GhostStroke g;
g.kind = GhostKind::Move;
@@ -579,13 +579,14 @@ void App::buildGhost() {
if (mirrors.size() > GhostStroke::kMaxMirrors) mirrors.resize(GhostStroke::kMaxMirrors); // (the shader's groups)
const size_t perMirror = GhostStroke::kMaxDabs / std::max<size_t>(1, mirrors.size());
std::vector<GhostDab> base;
+ const Camera cam = partCamera();
for (const Screen& sd : pending) {
if (base.size() >= perMirror) break;
glm::vec3 origin, dir, n;
- camera_.screenRay(sd.x - c.x, sd.y - c.y, c.w, c.h, origin, dir);
+ cam.screenRay(sd.x - c.x, sd.y - c.y, c.w, c.h, origin, dir);
GhostDab d;
if (!ghostSurface(origin, dir, d.center, n)) continue;
- d.radius = (worldSize_ && worldRadius_ > 0.0f ? worldRadius_ : radiusPx_ * camera_.worldPerPixel(d.center, c.h)) *
+ d.radius = (worldSize_ && worldRadius_ > 0.0f ? worldRadius_ : radiusPx_ * cam.worldPerPixel(d.center, c.h)) *
(pressureSizeOn() ? std::max(sd.pressure, 0.05f) : 1.0f);
d.normal = n;
d.strength = std::clamp((strokeBrush_ == BrushType::Smooth ? smoothStrength_ : strength_), 0.0f, 1.0f) *
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 973f378a..787e1957 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -471,6 +471,14 @@ void App::initActions() {
[this] { sculptPartUnderCursor(); }, ICON_LC_MOUSE_POINTER_CLICK, nullptr, nullptr, nullptr,
"Make the Part under the pointer the one you sculpt, without moving the view (each Part keeps its mask). "
"The same key as Blender's; Preferences > Hotkeys changes it.");
+ add("part.duplicate_linked", "Linked Duplicate", "Tool > Parts", nullptr, [this] { runCommand("part_duplicate_linked"); },
+ ICON_LC_LINK, "part_duplicate_linked", nullptr, [this] { return doc_.mesh.triangleCount() > 0; },
+ "A copy that shares the active Part's mesh, beside it: sculpt, paint or mask any of them and all change. Move "
+ "each with the Gizmo; Make Unique gives one its own mesh again. Hundreds of copies cost about one mesh.");
+ add("part.make_unique", "Make Unique", "Tool > Parts", nullptr, [this] { runCommand("part_make_unique"); },
+ ICON_LC_UNLINK, "part_make_unique", nullptr, [this] { return doc_.linkCount(doc_.activePart) > 1; },
+ "Give the active linked Part its own copy of the mesh: it stays where it is and no longer changes with the "
+ "others.");
// Tool > Part > Extract, Tool > Geometry > Modify Topology, Tool > Deformation (PanelExtract.cpp).
add("part.extract", "Extract", "Tool > Parts", nullptr, [this] { runExtract(); }, nullptr, "extract", nullptr,
[this] { return doc_.mesh.hasMask(); },
diff --git a/src/app/Demo.cpp b/src/app/Demo.cpp
index 4380eae0..26246f91 100644
--- a/src/app/Demo.cpp
+++ b/src/app/Demo.cpp
@@ -284,7 +284,7 @@ ImVec2 Demo::project(const glm::vec3& p) const {
}
ImVec2 Demo::onModel(float u, float v) const {
- const AABB b = app_.doc_.mesh.bounds();
+ const AABB b = app_.doc_.partBounds(app_.doc_.activePart); // (where it is: a moved linked copy, #94)
ImVec2 lo(1e9f, 1e9f), hi(-1e9f, -1e9f);
for (int i = 0; i < 8; ++i) {
const glm::vec3 c((i & 1) ? b.max.x : b.min.x, (i & 2) ? b.max.y : b.min.y, (i & 4) ? b.max.z : b.min.z);
diff --git a/src/app/FocusDetailApp.cpp b/src/app/FocusDetailApp.cpp
index c3780447..0f1fdeba 100644
--- a/src/app/FocusDetailApp.cpp
+++ b/src/app/FocusDetailApp.cpp
@@ -38,10 +38,10 @@ void App::updateFocusDetail() {
if (!(h > 0.0f)) return;
FocusView view;
view.valid = true;
- view.eye = camera_.position();
- view.viewProj = camera_.projection() * camera_.view();
+ view.eye = partCamera().position();
+ view.viewProj = partCamera().projection() * partCamera().view();
// pixels per world unit at distance 1 (ortho: as a perspective view would at the target's depth)
- view.focalPx = glm::distance(view.eye, camera_.target) / std::max(camera_.worldPerPixel(camera_.target, h), 1e-12f);
+ view.focalPx = glm::distance(view.eye, partCamera().target) / std::max(partCamera().worldPerPixel(partCamera().target, h), 1e-12f);
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
FocusBrush brush;
RayHit hit;
@@ -51,7 +51,7 @@ void App::updateFocusDetail() {
const glm::vec3 v = focusBrushValid_ && dt > 0.0f && dt < 0.25f ? (hit.position - focusBrushPos_) / dt : glm::vec3(0.0f);
focusBrushVel_ = glm::mix(focusBrushVel_, v, 0.5f); // smoothed over a couple of frames
focusBrushPos_ = hit.position;
- focusBrushRadius_ = radiusPx_ * camera_.worldPerPixel(hit.position, h);
+ focusBrushRadius_ = radiusPx_ * partCamera().worldPerPixel(hit.position, h);
focusBrushTime_ = now;
focusBrushValid_ = true;
} else if (!(drag_ == Drag::Stroke) || now - focusBrushTime_ > 1.0) {
diff --git a/src/app/Gizmo.cpp b/src/app/Gizmo.cpp
index 0a13b5a6..9ce95a5b 100644
--- a/src/app/Gizmo.cpp
+++ b/src/app/Gizmo.cpp
@@ -218,7 +218,8 @@ void App::updateGizmoPivot() {
(gizmo_.folder ? 8u + uint64_t(doc_.activePartInfo().folder) * 16u : 0u) ^
uint64_t(doc_.partCount()) << 48;
if (gizmo_.all || gizmo_.folder)
- for (const Part& s : doc_.parts) key = key * 1099511628211ull ^ s.undo.revision() ^ (s.visible ? 1u : 0u);
+ for (int i = 0; i < doc_.partCount(); ++i)
+ key = key * 1099511628211ull ^ doc_.partUndo(i).revision() ^ (doc_.parts[size_t(i)].visible ? 1u : 0u);
if (key == gizmo_.centreKey) return;
gizmo_.centreKey = key;
// A new mask (or another Part) means a new part to move: follow its centre again.
@@ -236,7 +237,11 @@ void App::updateGizmoPivot() {
for (int i : gizmoTargets()) {
const Mesh& m = doc_.partMesh(i);
if (m.vertexCount() == 0) continue;
- box.expand(transformBounds(m, transformWeights(m, gizmo_.useMask, 0.0f)));
+ const AABB local = transformBounds(m, transformWeights(m, gizmo_.useMask, 0.0f));
+ const glm::mat4& t = doc_.parts[size_t(i)].transform; // (a linked copy's place in the scene)
+ for (int c = 0; c < 8 && local.valid(); ++c)
+ box.expand(glm::vec3(t * glm::vec4(c & 1 ? local.max.x : local.min.x, c & 2 ? local.max.y : local.min.y,
+ c & 4 ? local.max.z : local.min.z, 1.0f)));
}
gizmo_.pivot = box.valid() ? box.center() : glm::vec3(0.0f);
}
@@ -278,6 +283,11 @@ bool App::gizmoProject(const glm::vec3& p, ImVec2& out) const {
return true;
}
+bool App::partProject(const glm::vec3& p, ImVec2& out) const {
+ const Part& s = doc_.activePartInfo();
+ return gizmoProject(s.moved() ? glm::vec3(s.transform * glm::vec4(p, 1.0f)) : p, out);
+}
+
// ---------------------------------------------------------------------------
// Handles: shapes, picking
// ---------------------------------------------------------------------------
@@ -484,23 +494,31 @@ bool App::gizmoMouseDown(float x, float y, SDL_Keymod mod) {
gizmo_.parts.clear();
gizmo_.sessions.clear();
+ gizmo_.wholeParts.clear();
+ gizmo_.wholeStart.clear();
if (!gizmo_.pivotOnly) {
+ std::vector<const PartData*> meshes; // a mesh linked Parts share is edited once
for (int i : gizmoTargets()) {
Mesh& m = doc_.partMesh(i);
- Part& s = doc_.parts[size_t(i)];
- if (i != doc_.activePart && s.bvhDirty) {
- s.bvh.build(s.mesh);
- s.bvhDirty = false;
+ const Part& s = doc_.parts[size_t(i)];
+ if (partMovesWhole(doc_, i, gizmo_.useMask)) { // a linked copy: its transform (#94)
+ if (m.vertexCount() == 0) continue;
+ gizmo_.wholeParts.push_back(i);
+ gizmo_.wholeStart.push_back(s.transform);
+ continue;
}
- // The active Part records into its active sculpt layer, as strokes do.
- const int layer = i == doc_.activePart ? doc_.activeLayer : -1;
+ if (std::find(meshes.begin(), meshes.end(), s.data.get()) != meshes.end()) continue;
+ meshes.push_back(s.data.get());
+ doc_.partBvh(i);
+ // The active Part's mesh records into its active sculpt layer, as strokes do.
+ const int layer = s.data == doc_.activePartInfo().data ? doc_.activeLayer : -1;
TransformSession session;
- if (!session.begin(m, transformWeights(m, gizmo_.useMask, gizmo_.falloff), symmetry_, gizmo_.pivot, layer))
- continue;
+ const glm::vec3 pivot = s.moved() ? glm::vec3(glm::inverse(s.transform) * glm::vec4(gizmo_.pivot, 1.0f)) : gizmo_.pivot;
+ if (!session.begin(m, transformWeights(m, gizmo_.useMask, gizmo_.falloff), symmetry_, pivot, layer)) continue;
gizmo_.parts.push_back(i);
gizmo_.sessions.push_back(std::move(session));
}
- if (gizmo_.sessions.empty()) {
+ if (gizmo_.sessions.empty() && gizmo_.wholeParts.empty()) {
status_ = TransformSession::layerWeightZero(doc_.mesh, doc_.activeLayer)
? "Active layer weight is 0 - raise it to transform into the layer"
: gizmo_.useMask && doc_.mesh.hasMask() ? "Nothing to move: everything is masked (Ctrl+click the "
@@ -525,8 +543,9 @@ void App::gizmoDragTo(float x, float y) {
const glm::vec3 c = gizmo_.startPivot;
const int axis = axisOf(h);
float size = 0.0f;
- for (int i : gizmo_.parts.empty() ? gizmoTargets() : gizmo_.parts)
- size = std::max(size, glm::length(doc_.partMesh(i).bounds().extent()));
+ for (int i : gizmo_.parts.empty() && gizmo_.wholeParts.empty() ? gizmoTargets() : gizmo_.parts)
+ size = std::max(size, glm::length(doc_.partBounds(i).extent()));
+ for (int i : gizmo_.wholeParts) size = std::max(size, glm::length(doc_.partBounds(i).extent()));
const float grid = gridStep(size);
MeshTransform t;
t.pivot = c;
@@ -604,7 +623,15 @@ void App::gizmoDragTo(float x, float y) {
return;
}
gizmo_.current = t;
- for (size_t i = 0; i < gizmo_.sessions.size(); ++i) gizmo_.sessions[i].apply(doc_.partMesh(gizmo_.parts[i]), t);
+ for (size_t i = 0; i < gizmo_.sessions.size(); ++i) {
+ const Part& s = doc_.parts[size_t(gizmo_.parts[i])];
+ gizmo_.sessions[i].apply(doc_.partMesh(gizmo_.parts[i]), s.moved() ? t.inSpaceOf(s.transform) : t);
+ }
+ if (!gizmo_.wholeParts.empty()) {
+ const glm::mat4 m = t.evenScale().matrix(); // (a linked copy scales evenly: it stays a similarity)
+ for (size_t i = 0; i < gizmo_.wholeParts.size(); ++i)
+ doc_.parts[size_t(gizmo_.wholeParts[i])].transform = m * gizmo_.wholeStart[i];
+ }
}
void App::gizmoRelease() {
@@ -618,21 +645,28 @@ void App::gizmoRelease() {
const std::string readout = std::move(gizmo_.readout);
gizmo_.handle = H::None;
gizmo_.readout.clear();
- if (gizmo_.pivotOnly || gizmo_.sessions.empty()) return;
+ if (gizmo_.pivotOnly || (gizmo_.sessions.empty() && gizmo_.wholeParts.empty())) return;
const char* label = isRotate(h) ? "Gizmo Rotate" : isScale(h) ? "Gizmo Scale" : "Gizmo Move";
size_t moved = 0;
for (size_t i = 0; i < gizmo_.sessions.size(); ++i) {
const int st = gizmo_.parts[i];
- const bool active = st == doc_.activePart;
- Part& s = doc_.parts[size_t(st)];
const size_t n = gizmo_.sessions[i].movingVertices();
- UndoRecord r = gizmo_.sessions[i].finish(active ? doc_.mesh : s.mesh, active ? doc_.bvh : s.bvh, label);
+ UndoRecord r = gizmo_.sessions[i].finish(doc_.partMesh(st), doc_.partBvh(st), label);
if (r.empty()) continue;
- (active ? doc_.undo : s.undo).push(std::move(r));
+ doc_.partUndo(st).push(std::move(r));
moved += n;
}
+ for (size_t i = 0; i < gizmo_.wholeParts.size(); ++i) { // linked copies: one transform step each
+ Part& s = doc_.parts[size_t(gizmo_.wholeParts[i])];
+ const glm::mat4 now = s.transform;
+ s.transform = gizmo_.wholeStart[i];
+ doc_.setPartTransform(gizmo_.wholeParts[i], now, label);
+ moved += now != gizmo_.wholeStart[i] ? doc_.partMesh(gizmo_.wholeParts[i]).vertexCount() : 0;
+ }
gizmo_.sessions.clear();
gizmo_.parts.clear();
+ gizmo_.wholeParts.clear();
+ gizmo_.wholeStart.clear();
if (moved == 0) return;
// The gizmo moves and turns with what it moved.
const MeshTransform& t = gizmo_.current;
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index eafaf004..b10eabe6 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -349,7 +349,17 @@ constexpr Entry kSimplifiedChinese[] = {
{"[ / ] previous / next Esc stops", "[ / ] 上一个 / 下一个 Esc 停止"},
{"Not enough GPU memory to show every Part: hide some or step down a subdivision level.",
"GPU 内存不足,无法显示所有部件:请隐藏部分部件或降低一级细分。"},
- {"%s\n%zu vertices, %zu triangles%s%s\nClick to select, double-click to rename", "%s\n%zu 个顶点,%zu 个三角形%s%s\n点击以选择,双击以重命名"},
+ {"%s\n%zu vertices, %zu triangles%s%s%s\nClick to select, double-click to rename", "%s\n%zu 个顶点,%zu 个三角形%s%s%s\n点击以选择,双击以重命名"},
+ {"\nLinked: %d Parts share this mesh",
+ "\n已链接:%d 个部件共享此网格"},
+ {"Linked Duplicate",
+ "链接复制"},
+ {"Make Unique",
+ "设为独立"},
+ {"A copy that shares the active Part's mesh, beside it: sculpt, paint or mask any of them and all change. Move each with the Gizmo; Make Unique gives one its own mesh again. Hundreds of copies cost about one mesh.",
+ "与当前部件共享网格的副本,放在它旁边:雕刻、绘制或遮罩其中任何一个,所有副本都会一起改变。用操纵器分别移动每个副本;“设为独立”让其中一个重新有自己的网格。数百个副本大约只占用一个网格的内存。"},
+ {"Give the active linked Part its own copy of the mesh: it stays where it is and no longer changes with the others.",
+ "让当前的链接部件有自己的网格副本:它留在原处,不再随其他副本改变。"},
{"Extract", "提取"},
{"Accept", "接受"},
{"Double", "双倍"},
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index 8a63ea2a..573d20b2 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -393,8 +393,15 @@ constexpr Entry kSpanish[] = {
{"Not enough GPU memory to show every Part: hide some or step down a subdivision level.",
"No hay memoria de GPU suficiente para mostrar todas las piezas: oculta alguna o baja un nivel de "
"subdivisión."},
- {"%s\n%zu vertices, %zu triangles%s%s\nClick to select, double-click to rename",
- "%s\n%zu vértices, %zu triángulos%s%s\nClic para seleccionar, doble clic para renombrar"},
+ {"%s\n%zu vertices, %zu triangles%s%s%s\nClick to select, double-click to rename",
+ "%s\n%zu vértices, %zu triángulos%s%s%s\nClic para seleccionar, doble clic para renombrar"},
+ {"\nLinked: %d Parts share this mesh", "\nEnlazada: %d piezas comparten esta malla"},
+ {"Linked Duplicate", "Duplicado enlazado"},
+ {"Make Unique", "Hacer única"},
+ {"A copy that shares the active Part's mesh, beside it: sculpt, paint or mask any of them and all change. Move each with the Gizmo; Make Unique gives one its own mesh again. Hundreds of copies cost about one mesh.",
+ "Una copia que comparte la malla de la pieza activa, a su lado: esculpe, pinta o enmascara cualquiera y cambian todas. Mueve cada una con el gizmo; Hacer única le devuelve a una su propia malla. Cientos de copias cuestan más o menos una malla."},
+ {"Give the active linked Part its own copy of the mesh: it stays where it is and no longer changes with the others.",
+ "Da a la pieza enlazada activa su propia copia de la malla: se queda donde está y ya no cambia con las demás."},
{"Extract", "Extraer"},
{"Accept", "Aceptar"},
{"Double", "Doble"},
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index 6fc3b2fa..2af3ec03 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -349,7 +349,17 @@ constexpr Entry kTraditionalChinese[] = {
{"[ / ] previous / next Esc stops", "[ / ] 上一個 / 下一個 Esc 停止"},
{"Not enough GPU memory to show every Part: hide some or step down a subdivision level.",
"GPU 記憶體不足,無法顯示所有部件:請隱藏部分部件或降低一級細分。"},
- {"%s\n%zu vertices, %zu triangles%s%s\nClick to select, double-click to rename", "%s\n%zu 個頂點,%zu 個三角形%s%s\n點選以選取,連按兩下以重新命名"},
+ {"%s\n%zu vertices, %zu triangles%s%s%s\nClick to select, double-click to rename", "%s\n%zu 個頂點,%zu 個三角形%s%s%s\n點選以選取,連按兩下以重新命名"},
+ {"\nLinked: %d Parts share this mesh",
+ "\n已連結:%d 個部件共用此網格"},
+ {"Linked Duplicate",
+ "連結複製"},
+ {"Make Unique",
+ "設為獨立"},
+ {"A copy that shares the active Part's mesh, beside it: sculpt, paint or mask any of them and all change. Move each with the Gizmo; Make Unique gives one its own mesh again. Hundreds of copies cost about one mesh.",
+ "與作用中部件共用網格的副本,放在它旁邊:雕刻、繪製或遮罩其中任何一個,所有副本都會一起改變。用操縱器分別移動每個副本;「設為獨立」讓其中一個重新擁有自己的網格。數百個副本大約只佔用一個網格的記憶體。"},
+ {"Give the active linked Part its own copy of the mesh: it stays where it is and no longer changes with the others.",
+ "讓作用中的連結部件擁有自己的網格副本:它留在原處,不再隨其他副本改變。"},
{"Extract", "擷取"},
{"Accept", "接受"},
{"Double", "雙倍"},
diff --git a/src/app/Input.cpp b/src/app/Input.cpp
index 9537fa2b..bb48e6df 100644
--- a/src/app/Input.cpp
+++ b/src/app/Input.cpp
@@ -458,7 +458,7 @@ void App::viewOrbitStep(float yawDegrees, float pitchDegrees) {
}
void App::frameActivePart() {
- const AABB b = doc_.mesh.bounds();
+ const AABB b = doc_.partBounds(doc_.activePart); // (where it is: a moved linked copy, #94)
if (b.valid()) camera_.frame(b);
else camera_.frame(sceneBounds());
}
diff --git a/src/app/LineGradient.cpp b/src/app/LineGradient.cpp
index 35113560..427baf91 100644
--- a/src/app/LineGradient.cpp
+++ b/src/app/LineGradient.cpp
@@ -122,7 +122,7 @@ void App::applyGradient() {
{"color", colorToHex(doc_.paintColor)},
{"to", gradient_.toClear ? std::string("clear") : colorToHex(gradient_.to)},
{"aspect", double(c.w / c.h)},
- {"view_proj", matrixText(camera_.projection() * camera_.view())}});
+ {"view_proj", matrixText(partCamera().projection() * partCamera().view())}}); // (#94)
if (!lastCommandOk_ || doc_.undo.revision() == before) return;
gradient_.placed = true;
gradient_.revision = doc_.undo.revision();
diff --git a/src/app/PanelAiLink.cpp b/src/app/PanelAiLink.cpp
index f908aa8e..456cc95e 100644
--- a/src/app/PanelAiLink.cpp
+++ b/src/app/PanelAiLink.cpp
@@ -671,12 +671,13 @@ Json App::aiLiveTool(const std::string& name, const Args& args, bool& ok) {
if (std::sscanf(token.c_str(), "%f,%f", &u, &v) != 2 || !std::isfinite(u) || !std::isfinite(v))
return fail("points must be \"u,v u,v ...\" in 0..1 (bad: " + token + ")");
glm::vec3 origin, dir;
- camera_.screenRay(u * c.w, v * c.h, c.w, c.h, origin, dir);
+ partCamera().screenRay(u * c.w, v * c.h, c.w, c.h, origin, dir); // (the active Part's space, #94)
RayHit hit;
if (!doc_.bvh.raycast(doc_.mesh, origin, dir, hit)) {
++misses;
continue;
}
+ hit.position = glm::vec3(doc_.activePartInfo().transform * glm::vec4(hit.position, 1.0f)); // stroke takes scene points
if (radius == 0.0f) radius = camera_.worldPerPixel(hit.position, c.h) * radiusFrac * c.h;
char buf[96];
std::snprintf(buf, sizeof buf, "%s%g,%g,%g", worldPoints.empty() ? "" : " ", double(hit.position.x),
diff --git a/src/app/PanelBrushes.cpp b/src/app/PanelBrushes.cpp
index 4bdf16d6..447c8970 100644
--- a/src/app/PanelBrushes.cpp
+++ b/src/app/PanelBrushes.cpp
@@ -25,7 +25,7 @@ void SDLCALL App::onAlphaChosen(void* userdata, const char* const* files, int) {
}
glm::vec3 App::screenUpVector(float angle) const {
- const glm::quat q = camera_.orientation();
+ const glm::quat q = partCamera().orientation();
return q * glm::vec3(-std::sin(angle), std::cos(angle), 0.0f);
}
@@ -131,8 +131,8 @@ void App::drawAlphaOptions(bool vdm) {
void App::snakeHookTo(float x, float y) {
const float h = canvasHeight();
glm::vec3 origin, dir;
- canvasRay(x, y, origin, dir);
- const glm::vec3 n = camera_.forward();
+ partRay(x, y, origin, dir);
+ const glm::vec3 n = partCamera().forward();
const float denom = glm::dot(dir, n);
if (std::abs(denom) < 1e-6f) return;
// Along the normal (App::beginAlongNormal): the tip slides out along the normal at the press.
@@ -141,7 +141,7 @@ void App::snakeHookTo(float x, float y) {
const float pressure = strokePressure();
DabParams p;
p.viewDir = n;
- p.radius = radiusPx_ * (pressureSizeOn() ? std::max(pressure, 0.05f) : 1.0f) * camera_.worldPerPixel(grabLast_, h);
+ p.radius = radiusPx_ * (pressureSizeOn() ? std::max(pressure, 0.05f) : 1.0f) * partCamera().worldPerPixel(grabLast_, h);
p.strength = strength_;
p.pressure = pressureStrengthOn() ? pressure : 1.0f;
p.invert = strokeInvert_;
@@ -168,13 +168,13 @@ void App::dragRectTo(float x, float y) {
const glm::vec2 drag = glm::vec2(x, y) - dragAnchor_;
const float len = glm::length(drag);
if (len < 2.0f) return;
- const glm::quat q = camera_.orientation();
+ const glm::quat q = partCamera().orientation();
const float pressure = stampPressure_.hold(strokePressure()); // (not the lift's falling pressure, #146)
DabParams p;
p.center = dragAnchorHit_;
- p.viewDir = camera_.forward();
- p.radius = len * camera_.worldPerPixel(dragAnchorHit_, canvasHeight());
+ p.viewDir = partCamera().forward();
+ p.radius = len * partCamera().worldPerPixel(dragAnchorHit_, canvasHeight());
p.strength = strength_;
p.pressure = pressureStrengthOn() ? pressure : 1.0f;
p.invert = strokeInvert_;
diff --git a/src/app/PanelCut.cpp b/src/app/PanelCut.cpp
index 54cba2a8..e7c73554 100644
--- a/src/app/PanelCut.cpp
+++ b/src/app/PanelCut.cpp
@@ -40,7 +40,7 @@ void App::runCut(const char* shape, const std::vector<ImVec2>& path, bool closed
double(1.0f - (p.y - c.y) / c.h * 2.0f));
points += buf;
}
- const glm::mat4 vp = camera_.projection() * camera_.view();
+ const glm::mat4 vp = partCamera().projection() * partCamera().view();
std::string matrix;
for (int i = 0; i < 16; ++i) {
std::snprintf(buf, sizeof buf, "%s%.9g", i ? " " : "", double(vp[i / 4][i % 4]));
diff --git a/src/app/PanelFace.cpp b/src/app/PanelFace.cpp
index 5e6f790e..021bef4e 100644
--- a/src/app/PanelFace.cpp
+++ b/src/app/PanelFace.cpp
@@ -225,7 +225,7 @@ bool App::faceMouseDown(float x, float y, SDL_Keymod mod) {
const float grab = 10.0f * uiScale_;
for (int i = 0; i < kFaceLandmarkCount; ++i) {
ImVec2 sp;
- if (faceLandmarks_.set[size_t(i)] && i != facePlaceIndex_ && gizmoProject(faceLandmarks_.position[size_t(i)], sp) &&
+ if (faceLandmarks_.set[size_t(i)] && i != facePlaceIndex_ && partProject(faceLandmarks_.position[size_t(i)], sp) &&
std::hypot(sp.x - x, sp.y - y) < grab) {
facePlaceIndex_ = i;
status_ = std::string("Click the new place for the ") + faceLandmarkLabel(i);
@@ -261,7 +261,7 @@ void App::drawFaceOverlay() {
for (int i = 0; i < kFaceLandmarkCount; ++i) {
if (!faceLandmarks_.set[size_t(i)]) continue;
ImVec2 p;
- if (!gizmoProject(faceLandmarks_.position[size_t(i)], p)) continue;
+ if (!partProject(faceLandmarks_.position[size_t(i)], p)) continue;
const bool current = facePlacing_ && i == facePlaceIndex_;
dl->AddCircleFilled(p, 5.0f * s, current ? IM_COL32(255, 196, 64, 255) : IM_COL32(80, 200, 255, 255));
dl->AddCircle(p, 5.0f * s, IM_COL32(0, 0, 0, 200), 0, 1.5f * s);
diff --git a/src/app/PanelForgeSpheres.cpp b/src/app/PanelForgeSpheres.cpp
index ff85ec71..429b7dfc 100644
--- a/src/app/PanelForgeSpheres.cpp
+++ b/src/app/PanelForgeSpheres.cpp
@@ -153,10 +153,10 @@ void App::drawForgeSpheresContents() {
float App::worldPerPixel(const glm::vec3& at) const {
ImVec2 sp;
- if (!gizmoProject(at, sp)) return 0.0f;
+ if (!partProject(at, sp)) return 0.0f;
glm::vec3 o0, d0, o1, d1;
- canvasRay(sp.x, sp.y, o0, d0);
- canvasRay(sp.x + 1.0f, sp.y, o1, d1);
+ partRay(sp.x, sp.y, o0, d0);
+ partRay(sp.x + 1.0f, sp.y, o1, d1);
const glm::vec3 n = glm::normalize(d0);
return glm::length(planeHit(o1, d1, at, n) - planeHit(o0, d0, at, n));
}
@@ -217,7 +217,7 @@ bool App::forgesphereMouseDown(float x, float y, SDL_Keymod mod) {
}
if (d.op == ForgeSphereMode::Move) {
glm::vec3 o, dir;
- canvasRay(x, y, o, dir);
+ partRay(x, y, o, dir);
const glm::vec3 c = d.start[size_t(d.sphere)].center;
d.grab = c - planeHit(o, dir, c, glm::normalize(dir));
}
@@ -236,7 +236,7 @@ void App::forgesphereDragTo(float x, float y) {
case ForgeSphereMode::Draw: {
// The new sphere sits on the parent's surface where the drag started, sized by the drag.
glm::vec3 o, dir;
- canvasRay(d.x, d.y, o, dir);
+ partRay(d.x, d.y, o, dir);
glm::vec3 n = -glm::normalize(dir);
const float tc = glm::dot(z.center - o, glm::normalize(dir));
const glm::vec3 closest = o + glm::normalize(dir) * tc;
@@ -248,7 +248,7 @@ void App::forgesphereDragTo(float x, float y) {
// Half the parent's size, starting on its surface and following the cursor in the plane through
// that point facing the camera.
glm::vec3 o2, dir2;
- canvasRay(x, y, o2, dir2);
+ partRay(x, y, o2, dir2);
const glm::vec3 at = planeHit(o2, dir2, c, glm::normalize(dir));
forgesphereAdd(s, d.sphere, at, 0.5f * z.radius, symmetry_, &d.added);
status_ = "Forge Spheres: new sphere, " + std::to_string(glm::distance(at, z.center) / z.radius).substr(0, 4) +
@@ -263,7 +263,7 @@ void App::forgesphereDragTo(float x, float y) {
}
case ForgeSphereMode::Move: {
glm::vec3 o, dir;
- canvasRay(x, y, o, dir);
+ partRay(x, y, o, dir);
const glm::vec3 c = planeHit(o, dir, z.center, glm::normalize(dir)) + d.grab;
forgesphereSet(s, d.sphere, c, z.radius, symmetry_);
break;
@@ -387,7 +387,7 @@ void App::drawForgeSphereOverlay() {
ImVec2 c;
const float wpp = worldPerPixel(z.center);
dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);
- if (gizmoProject(z.center, c) && wpp > 0.0f) dl->AddCircle(c, z.radius / wpp + 2.0f * s, IM_COL32(255, 170, 60, 220), 64, 2.0f * s);
+ if (partProject(z.center, c) && wpp > 0.0f) dl->AddCircle(c, z.radius / wpp + 2.0f * s, IM_COL32(255, 170, 60, 220), 64, 2.0f * s);
dl->PopClipRect();
}
bool link = false;
@@ -402,13 +402,13 @@ void App::drawForgeSphereOverlay() {
ImVec2 m;
const glm::vec3 mid = (c.center + p.center) * 0.5f;
const float wpp = worldPerPixel(mid);
- if (forgesphereMode_ == ForgeSphereMode::Draw && gizmoProject(mid, m) && wpp > 0.0f)
+ if (forgesphereMode_ == ForgeSphereMode::Draw && partProject(mid, m) && wpp > 0.0f)
dl->AddCircle(m, 0.5f * (c.radius + p.radius) / wpp, IM_COL32(120, 200, 255, 160), 48, 1.5f * s);
} else {
const ForgeSphere& z = doc_.mesh.forgespheres[size_t(i)];
ImVec2 c;
const float wpp = worldPerPixel(z.center);
- if (gizmoProject(z.center, c) && wpp > 0.0f) dl->AddCircle(c, z.radius / wpp, col, 64, 2.0f * s);
+ if (partProject(z.center, c) && wpp > 0.0f) dl->AddCircle(c, z.radius / wpp, col, 64, 2.0f * s);
}
dl->PopClipRect();
}
diff --git a/src/app/PanelKelvinlet.cpp b/src/app/PanelKelvinlet.cpp
index a3c681db..e7e31faf 100644
--- a/src/app/PanelKelvinlet.cpp
+++ b/src/app/PanelKelvinlet.cpp
@@ -54,7 +54,7 @@ bool App::kelvinStrokeBrush() const { return dragBrush(strokeBrush_) && !strokeR
void App::kelvinBegin(const RayHit& hit) {
// Full brush size, as Move: the press pressure of a pen is near zero, so Pressure > Size would shrink the grab (#122).
kelvinCenter_ = hit.position;
- kelvinRadius_ = radiusPx_ * camera_.worldPerPixel(hit.position, canvasHeight());
+ kelvinRadius_ = radiusPx_ * partCamera().worldPerPixel(hit.position, canvasHeight());
grabLast_ = kelvinTarget_ = hit.position;
kelvinPending_ = 0.0f;
kelvinLastX_ = lastX_;
@@ -69,8 +69,8 @@ void App::kelvinTo(float x, float y) {
// The grabbed point follows the cursor in the plane through it facing the camera (as Move), or along the
// normal (App::beginAlongNormal).
glm::vec3 origin, dir;
- canvasRay(x, y, origin, dir);
- const glm::vec3 n = camera_.forward();
+ partRay(x, y, origin, dir);
+ const glm::vec3 n = partCamera().forward();
const float denom = glm::dot(dir, n);
if (strokeAlongNormal_) kelvinTarget_ = alongNormalTarget(x, y);
else if (std::abs(denom) < 1e-6f) return;
@@ -91,8 +91,8 @@ void App::kelvinTo(float x, float y) {
bool App::kelvinNextStep(KelvinletStep& step) {
step = KelvinletStep{};
step.radius = kelvinRadius_;
- step.viewDir = camera_.forward();
- step.axis = -camera_.forward();
+ step.viewDir = partCamera().forward();
+ step.axis = -partCamera().forward();
step.frontFacesOnly = frontFacesOnly_;
const float share = doc_.sculptor.kelvinletOverBudget() ? 0.5f : 1.0f;
if (strokeBrush_ == BrushType::KelvinGrab) {
@@ -140,7 +140,7 @@ bool App::kelvinPump() {
s.view.probe = nullptr;
s.view.radiusProbe = nullptr;
s.view.settings = dabSettings();
- s.uploadId = doc_.activePartInfo().id;
+ s.uploadId = doc_.meshKey(doc_.activePart);
renderer_.setPersistentUpload(uiPrefs_.fastUpload);
renderer_.bindStrokeUpload(s.uploadId, s.upload);
s.prepare = &displayedMesh() == &doc_.mesh;
@@ -157,8 +157,8 @@ void App::kelvinAdvance() {
}
KelvinletStep step;
step.radius = kelvinRadius_;
- step.viewDir = camera_.forward();
- step.axis = -camera_.forward();
+ step.viewDir = partCamera().forward();
+ step.axis = -partCamera().forward();
step.frontFacesOnly = frontFacesOnly_;
static const bool log = std::getenv("SF_KELVIN_LOG") != nullptr;
const SculptTimings before = doc_.sculptor.timings;
@@ -350,12 +350,12 @@ void App::captureMouseUp() {
}
// Keep the square where it was drawn: the point on the plane through the hit under the centre.
glm::vec3 origin, dir;
- canvasRay(centre.x, centre.y, origin, dir);
- const glm::vec3 n = camera_.forward();
+ partRay(centre.x, centre.y, origin, dir);
+ const glm::vec3 n = partCamera().forward();
hit.position = origin + dir * (glm::dot(hit.position - origin, n) / glm::dot(dir, n));
}
- const float halfWorld = half * camera_.worldPerPixel(hit.position, canvasHeight());
- capture_.frame = makeCaptureFrame(hit.position, camera_.forward(), screenUpVector(0.0f), halfWorld, capture_.circle);
+ const float halfWorld = half * partCamera().worldPerPixel(hit.position, canvasHeight());
+ capture_.frame = makeCaptureFrame(hit.position, partCamera().forward(), screenUpVector(0.0f), halfWorld, capture_.circle);
capture_.haveFrame = true;
capture_.open = true;
recapture();
diff --git a/src/app/PanelMasking.cpp b/src/app/PanelMasking.cpp
index 546f1e00..b5c52b24 100644
--- a/src/app/PanelMasking.cpp
+++ b/src/app/PanelMasking.cpp
@@ -469,7 +469,7 @@ void App::drawMaskingSection() {
int(MaskArt::Facing), cell)) {
const glm::vec3 dir = maskFacingDir_ == 1 ? glm::vec3(0, 1, 0)
: maskFacingDir_ == 2 ? glm::vec3(0, -1, 0)
- : -camera_.forward();
+ : -partCamera().forward();
runCommand("mask_by_facing", {{"x", double(dir.x)},
{"y", double(dir.y)},
{"z", double(dir.z)},
diff --git a/src/app/PanelMaya.cpp b/src/app/PanelMaya.cpp
index d73ed280..58070f7b 100644
--- a/src/app/PanelMaya.cpp
+++ b/src/app/PanelMaya.cpp
@@ -76,7 +76,7 @@ void saveMayaPrefs(const std::string& configDir, const UiPrefs& p) {
}
uint64_t partUndoRevision(const Document& doc, int i) {
- return i == doc.activePart ? doc.undo.revision() : doc.parts[size_t(i)].undo.revision();
+ return doc.partUndo(i).revision();
}
// One number for every Part's id and undo revision: it moves with each stroke, undo, new or removed Part.
diff --git a/src/app/PanelParts.cpp b/src/app/PanelParts.cpp
index 959e34eb..9efafd75 100644
--- a/src/app/PanelParts.cpp
+++ b/src/app/PanelParts.cpp
@@ -10,6 +10,8 @@
#include "app/Demo.h"
#include "app/Theme.h"
#include "app/I18n.h"
+#include "app/Ui.h"
+#include <IconsLucide.h>
#include "core/Multires.h"
#include "render/GL.h"
@@ -91,15 +93,13 @@ int App::pickPart(float x, float y, RayHit* out) {
if (!s.visible) continue;
RayHit hit;
bool found = false;
- if (i == doc_.activePart) {
- doc_.syncBvh();
- found = doc_.bvh.raycast(doc_.mesh, origin, dir, hit);
- } else {
- if (s.bvhDirty || (s.bvh.nodeCount() == 0 && s.mesh.triangleCount())) {
- s.bvh.build(s.mesh);
- s.bvhDirty = false;
- }
- found = s.bvh.raycast(s.mesh, origin, dir, hit);
+ // In the Part's own space (a linked copy's transform): the ray goes there, the hit comes back.
+ const glm::mat4 inv = s.moved() ? glm::inverse(s.transform) : glm::mat4(1.0f);
+ const glm::vec3 o = glm::vec3(inv * glm::vec4(origin, 1.0f)), d = glm::mat3(inv) * dir;
+ found = doc_.partBvh(i).raycast(doc_.partMesh(i), o, d, hit);
+ if (found && s.moved()) {
+ hit.position = glm::vec3(s.transform * glm::vec4(hit.position, 1.0f));
+ hit.normal = glm::normalize(glm::mat3(s.transform) * hit.normal);
}
if (found && (best < 0 || hit.t < nearest.t)) {
best = i;
@@ -133,7 +133,7 @@ void App::partClickRelease() {
runCommand("part_select", {{"index", double(partClickTarget_)}});
partSelected("Alt+click");
}
- if (partClickFrame_) camera_.frame(doc_.mesh.bounds()); // Shift+Alt+click: frame it too
+ if (partClickFrame_) camera_.frame(doc_.partBounds(doc_.activePart)); // Shift+Alt+click: frame it too
}
partClickTarget_ = -1;
partClickFrame_ = false;
@@ -194,15 +194,22 @@ void App::updatePartThumbnails() {
ids.reserve(doc_.parts.size());
const double now = double(SDL_GetTicksNS()) * 1e-9; // (the main loop's clock, as redrawAt_)
for (int i = 0; i < doc_.partCount(); ++i) {
- const Part& s = doc_.parts[size_t(i)];
+ // By mesh (Document::meshKey): linked copies (#94) show their shared mesh's one thumbnail, kept by its
+ // first visible Part.
+ const uint32_t mk = doc_.meshKey(i);
+ if (std::find(ids.begin(), ids.end(), mk) != ids.end()) continue;
+ int first = i;
+ for (int k = i; k < doc_.partCount() && !doc_.parts[size_t(first)].visible; ++k)
+ if (doc_.meshKey(k) == mk && doc_.parts[size_t(k)].visible) first = k;
+ const Part& s = doc_.parts[size_t(first)];
const Mesh& m = doc_.partMesh(i);
- const UndoStack& undo = i == doc_.activePart ? doc_.undo : s.undo;
+ const UndoStack& undo = doc_.partUndo(i);
uint64_t key = undo.revision();
for (uint64_t part : {uint64_t(m.triangleCount()), uint64_t(m.vertexCount()), uint64_t(s.visible),
uint64_t(s.shading), uint64_t(renderSettings_.litsphere + 1), uint64_t(renderSettings_.showVertexPaint)})
key = key * 1099511628211ull ^ part;
- partThumbSchedule_.observe(s.id, key, now);
- ids.push_back(s.id);
+ partThumbSchedule_.observe(mk, key, now);
+ ids.push_back(mk);
}
for (uint32_t gone : partThumbSchedule_.keepOnly(ids))
if (auto it = partThumbs_.find(gone); it != partThumbs_.end()) {
@@ -250,6 +257,7 @@ void App::drawPartsContents() {
// The list: eye, name, triangles. Row actions run after the loop (they change the list).
int selectIndex = -1, toggleIndex = -1, deleteIndex = -1, duplicateIndex = -1, renameIndex = -1;
+ int linkIndex = -1, uniqueIndex = -1; // Linked Duplicate / Make Unique from the right-click menu
std::string renameTo;
// Folders (#96): pending actions on one, by name; a Part put into a folder ("" = out of its folder).
PartFolderActions fa;
@@ -371,11 +379,23 @@ void App::drawPartsContents() {
focusRename_ = true;
std::snprintf(renameBuffer_, sizeof renameBuffer_, "%s", s.name.c_str());
}
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))
- ImGui::SetTooltip(tr("%s\n%zu vertices, %zu triangles%s%s\nClick to select, double-click to rename"),
+ const int links = doc_.linkCount(i);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal)) {
+ char linked[96] = "";
+ if (links > 1) std::snprintf(linked, sizeof linked, tr("\nLinked: %d Parts share this mesh"), links);
+ ImGui::SetTooltip(tr("%s\n%zu vertices, %zu triangles%s%s%s\nClick to select, double-click to rename"),
s.name.c_str(), doc_.partMesh(i).vertexCount(), doc_.partMesh(i).triangleCount(),
subdivLevelCount(doc_.partMesh(i)) ? ", " : "",
- subdivLevelText(doc_.partMesh(i)).c_str());
+ subdivLevelText(doc_.partMesh(i)).c_str(), linked);
+ }
+ if (links > 1) { // a link and the count at the name's end (#94): these Parts share one mesh
+ const std::string badge = std::string(ICON_LC_LINK) + " " + std::to_string(links);
+ const ImVec2 r1 = ImGui::GetItemRectMax(), bs = ImGui::CalcTextSize(badge.c_str());
+ const float x = ImGui::TableGetCellBgRect(ImGui::GetCurrentTable(), 0).Max.x - bs.x - cellPad.x;
+ ImVec4 col = isActive ? theme::accent : style.Colors[ImGuiCol_TextDisabled];
+ ImGui::GetWindowDrawList()->AddText(ImVec2(x, r1.y - innerH * 0.5f - bs.y * 0.5f),
+ ImGui::ColorConvertFloat4ToU32(col), badge.c_str());
+ }
if (ImGui::BeginPopupContextItem("##row")) {
ImGui::TextDisabled("%s", s.name.c_str());
if (ImGui::MenuItem(tr("Rename"))) {
@@ -401,6 +421,8 @@ void App::drawPartsContents() {
}
ImGui::EndMenu();
}
+ if (ImGui::MenuItem(tr("Linked Duplicate"))) linkIndex = i;
+ if (ImGui::MenuItem(tr("Make Unique"), nullptr, false, links > 1)) uniqueIndex = i;
if (ImGui::MenuItem(tr("Delete..."), nullptr, false, count > 1)) deleteIndex = i;
ImGui::EndPopup();
}
@@ -414,7 +436,7 @@ void App::drawPartsContents() {
ImDrawList* dl = ImGui::GetWindowDrawList();
const ImVec2 t1(thumbAt.x + thumb, thumbAt.y + thumb);
dl->AddRectFilled(thumbAt, t1, ImGui::ColorConvertFloat4ToU32(kThumbWell), theme::rounding(3.0f * scale));
- const auto tex = partThumbs_.find(s.id);
+ const auto tex = partThumbs_.find(doc_.meshKey(i));
if (tex != partThumbs_.end() && tex->second)
dl->AddImageRounded(ImTextureID(uintptr_t(tex->second)), thumbAt, t1, ImVec2(0, 0), ImVec2(1, 1),
IM_COL32(255, 255, 255, s.visible ? 255 : 110), theme::rounding(3.0f * scale));
@@ -487,6 +509,8 @@ void App::drawPartsContents() {
setGizmoMode(GizmoMode::Move);
status_ = "Move " + fa.gizmo + ": drag the gizmo (its visible Parts move together; W again: back to Draw)";
}
+ if (linkIndex >= 0) runCommand("part_duplicate_linked", {{"index", double(linkIndex)}});
+ if (uniqueIndex >= 0) runCommand("part_make_unique", {{"index", double(uniqueIndex)}});
// Buttons act on the active Part.
const std::string activeName = doc_.activePartInfo().name;
@@ -582,6 +606,13 @@ void App::drawPartsContents() {
if (ImGui::Button(tr("Delete..."), ImVec2(third, 0)))
confirm("Delete Part?", "Delete \"" + activeName + "\"? This can't be undone.", "Delete", "part_delete");
ImGui::EndDisabled();
+ // Linked Duplicates (#94): copies sharing one mesh, each placed on its own.
+ {
+ const float half = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) / 2.0f;
+ ui::ActionButton(*this, "part.duplicate_linked", ImVec2(half, 0), ui::Look::IconLabel);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "part.make_unique", ImVec2(half, 0), ui::Look::IconLabel);
+ }
const float arrowW = ImGui::GetFrameHeight();
ImGui::BeginDisabled(active <= 0);
diff --git a/src/app/PanelPbr.cpp b/src/app/PanelPbr.cpp
index 7e0ed99c..5b325727 100644
--- a/src/app/PanelPbr.cpp
+++ b/src/app/PanelPbr.cpp
@@ -395,7 +395,7 @@ double App::pbrTestValue(const std::string& name) const {
if (name == "view_pbr") return renderSettings_.pbr() ? 1.0 : 0.0;
if (name == "environment") return double(renderSettings_.environment);
if (name == "environment_pending") return renderer_.environmentPending() ? 1.0 : 0.0;
- if (name == "pbr_planes") return double(renderer_.pbrPlanes(doc_.activePartInfo().id));
+ if (name == "pbr_planes") return double(renderer_.pbrPlanes(doc_.meshKey(doc_.activePart)));
if (name == "brush_channels") return double(doc_.paintMaterial.channels);
if (name == "roughness_painted") {
if (!tex || !channelEnabled(*m.texture, Channel::Roughness)) return 0.0;
diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cpp
index 94c1ffa7..313f1eb6 100644
--- a/src/app/PanelPerformance.cpp
+++ b/src/app/PanelPerformance.cpp
@@ -219,7 +219,7 @@ void App::notePerformanceFrame(double syncMs) {
}
// A Part too big for the GPU's memory isn't drawn: say so once.
bool oom = false;
- for (const Part& s : doc_.parts) oom = oom || (s.visible && renderer_.outOfMemory(s.id));
+ for (int i = 0; i < doc_.partCount(); ++i) oom = oom || (doc_.parts[size_t(i)].visible && renderer_.outOfMemory(doc_.meshKey(i)));
if (oom && !perf_.gpuOutOfMemory)
status_ = "Not enough GPU memory to show every Part: hide some, or step down a subdivision level "
"(Preferences > Performance)";
diff --git a/src/app/PanelRetopo.cpp b/src/app/PanelRetopo.cpp
index 429a37c3..7ceefa87 100644
--- a/src/app/PanelRetopo.cpp
+++ b/src/app/PanelRetopo.cpp
@@ -603,7 +603,7 @@ int App::guideAt(float x, float y) const {
for (size_t i = 0; i <= n; ++i) {
if (i == n && !guide.closed) break;
ImVec2 p;
- if (!gizmoProject(guide.points[i % n], p)) {
+ if (!partProject(guide.points[i % n], p)) {
havePrev = false;
continue;
}
@@ -712,7 +712,7 @@ void App::drawQRemeshGuides() {
// Which points the model hides: a ray from the eye to each one (refreshed when the view or the guides change;
// at most ~2000 rays a frame, the points between them follow their neighbours).
{
- const glm::mat4 vp = camera_.projection() * camera_.view();
+ const glm::mat4 vp = partCamera().projection() * partCamera().view();
uint64_t key = 1469598103934665603ull;
auto mix = [&](const void* data, size_t bytes) {
const auto* b = static_cast<const unsigned char*>(data);
@@ -741,12 +741,12 @@ void App::drawQRemeshGuides() {
vis.assign(pts.size(), 1);
for (size_t i = 0; i < pts.size(); i += stride) {
ImVec2 sp;
- if (!gizmoProject(pts[i], sp)) {
+ if (!partProject(pts[i], sp)) {
vis[i] = 0;
continue;
}
glm::vec3 origin, dir;
- canvasRay(sp.x, sp.y, origin, dir);
+ partRay(sp.x, sp.y, origin, dir);
const float t = glm::dot(pts[i] - origin, dir) / std::max(glm::dot(dir, dir), 1e-20f);
RayHit hit;
vis[i] = !doc_.bvh.raycast(doc_.mesh, origin, dir, hit) || hit.t > t - eps / std::sqrt(glm::dot(dir, dir));
@@ -781,7 +781,7 @@ void App::drawQRemeshGuides() {
bool whole = guide.closed;
for (size_t i = 0; i < n; ++i) {
ImVec2 p;
- const bool on = gizmoProject(guide.points[i], p);
+ const bool on = partProject(guide.points[i], p);
const bool vis = on && guideVisible_[g][i] != 0;
if (!on || (!run.empty() && vis != runVis)) {
whole = false;
@@ -799,7 +799,7 @@ void App::drawQRemeshGuides() {
}
if (guide.closed && !whole && !run.empty() && n > 0) { // close the loop back to the first point
ImVec2 p0;
- if (gizmoProject(guide.points[0], p0)) run.push_back(p0);
+ if (partProject(guide.points[0], p0)) run.push_back(p0);
}
flush(whole);
}
@@ -810,7 +810,7 @@ void App::drawQRemeshGuides() {
std::vector<ImVec2> pts;
for (const glm::vec3& q : guidePath_) {
ImVec2 a;
- if (gizmoProject(q * m, a)) pts.push_back(a);
+ if (partProject(q * m, a)) pts.push_back(a);
}
if (drag_ == Drag::Guide && own) pts.push_back(ImVec2(mouseX_, mouseY_)); // up to the pointer (the lazy lag)
guideLine(dl, pts, false, own ? IM_COL32(255, 230, 140, 255) : IM_COL32(255, 230, 140, 140), (own ? 2.5f : 1.5f) * s,
diff --git a/src/app/PanelSculptable.cpp b/src/app/PanelSculptable.cpp
index 5c94129b..a0f9d4e9 100644
--- a/src/app/PanelSculptable.cpp
+++ b/src/app/PanelSculptable.cpp
@@ -298,7 +298,7 @@ void App::pollSculptable() {
lastCommandOk_ = true;
clearLods();
playingLayer_ = -1;
- if (!onScreen(doc_.mesh.bounds())) camera_.frame(sceneBounds());
+ if (!onScreen(doc_.partBounds(doc_.activePart))) camera_.frame(sceneBounds());
updateTitle();
consoleEcho("splat_to_mesh", job->args, r);
}
diff --git a/src/app/PanelTexture.cpp b/src/app/PanelTexture.cpp
index ee3b8663..fce4e5c3 100644
--- a/src/app/PanelTexture.cpp
+++ b/src/app/PanelTexture.cpp
@@ -351,7 +351,7 @@ void App::drawTextureMapContents() {
const float side = ImGui::GetContentRegionAvail().x;
const ImVec2 p = ImGui::GetCursorScreenPos();
ImDrawList* dl = ImGui::GetWindowDrawList();
- const GLuint tex = hasTexture(m) ? renderer_.paintTexture(doc_.activePartInfo().id) : 0;
+ const GLuint tex = hasTexture(m) ? renderer_.paintTexture(doc_.meshKey(doc_.activePart)) : 0;
if (tex) dl->AddImage(ImTextureID(uintptr_t(tex)), p, ImVec2(p.x + side, p.y + side), ImVec2(0, 1), ImVec2(1, 0));
else dl->AddRectFilled(p, ImVec2(p.x + side, p.y + side), IM_COL32(40, 40, 46, 255));
const uint64_t key = (uint64_t(doc_.activePartInfo().id) << 40) ^ uint64_t(uintptr_t(m.uvs.data())) ^ m.uvs.size();
diff --git a/src/app/PanelUvEditor.cpp b/src/app/PanelUvEditor.cpp
index 200db15e..db562ede 100644
--- a/src/app/PanelUvEditor.cpp
+++ b/src/app/PanelUvEditor.cpp
@@ -1239,7 +1239,7 @@ void App::drawUvEditor() {
v.min = s.center - half;
v.max = s.center + half;
v.imageMode = s.image;
- v.image = s.image == 2 && hasTexture(m) ? renderer_.paintTexture(doc_.activePartInfo().id) : 0;
+ v.image = s.image == 2 && hasTexture(m) ? renderer_.paintTexture(doc_.meshKey(doc_.activePart)) : 0;
v.imageOpacity = s.image == 2 ? 1.0f : s.imageOpacity;
v.checkerScale = s.checkerScale;
v.tiles = s.tiles;
@@ -1677,7 +1677,7 @@ void App::drawUvEditorOverlay() {
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();
+ const glm::vec3 eye = partCamera().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);
@@ -1695,7 +1695,7 @@ void App::drawUvEditorOverlay() {
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;
+ if (!partProject(a, pa) || !partProject(b, pb)) continue;
dl->AddLine(pa, pb, IM_COL32(245, 78, 64, 225), 1.6f * uiScale_);
}
dl->PopClipRect();
@@ -1707,7 +1707,7 @@ void App::drawUvEditorOverlay() {
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)) {
+ if (partProject(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);
diff --git a/src/app/PanelVdm.cpp b/src/app/PanelVdm.cpp
index d46b2da1..04972af5 100644
--- a/src/app/PanelVdm.cpp
+++ b/src/app/PanelVdm.cpp
@@ -135,9 +135,9 @@ void App::dragDotTo(float x, float y) {
const float pressure = stampPressure_.hold(strokePressure()); // (not the lift's falling pressure, #146)
DabParams p;
p.center = hit.position;
- p.viewDir = camera_.forward();
+ p.viewDir = partCamera().forward();
p.radius = radiusPx_ * (pressureSizeOn() ? std::max(pressure, 0.05f) : 1.0f) *
- camera_.worldPerPixel(hit.position, canvasHeight());
+ partCamera().worldPerPixel(hit.position, canvasHeight());
p.strength = strokeBrush_ == BrushType::Smooth ? smoothStrength_ : strength_;
p.pressure = pressureStrengthOn() ? pressure : 1.0f;
p.invert = strokeInvert_;
diff --git a/src/app/Precision.cpp b/src/app/Precision.cpp
index eec7ecc3..4fdb8a18 100644
--- a/src/app/Precision.cpp
+++ b/src/app/Precision.cpp
@@ -51,7 +51,7 @@ void App::syncWorldSize() {
haveCursorSurface_ = true;
}
// Off the model: at the surface point last under the cursor (so zooming there keeps the size), else the pivot.
- cursorWorldPerPx_ = camera_.worldPerPixel(haveCursorSurface_ ? cursorSurface_ : camera_.target, canvasHeight());
+ cursorWorldPerPx_ = partCamera().worldPerPixel(haveCursorSurface_ ? cursorSurface_ : partCamera().target, canvasHeight());
const float wpp = cursorWorldPerPx_;
if (!(wpp > 0.0f)) return;
if (!worldSize_ || radiusPx_ != worldSyncedPx_ || worldRadius_ <= 0.0f) {
diff --git a/src/app/Selection.cpp b/src/app/Selection.cpp
index a5b900b2..e74aaa0e 100644
--- a/src/app/Selection.cpp
+++ b/src/app/Selection.cpp
@@ -87,7 +87,7 @@ bool App::runSelection(const char* rectCommand, const char* lassoCommand, Args a
if (c.w <= 0.0f || c.h <= 0.0f || selectPath_.empty()) return false;
// Window pixels -> normalised device coordinates (y up).
auto ndc = [&](ImVec2 p) { return glm::vec2((p.x - c.x) / c.w * 2.0f - 1.0f, 1.0f - (p.y - c.y) / c.h * 2.0f); };
- args["view_proj"] = matrixString(camera_.projection() * camera_.view());
+ args["view_proj"] = matrixString(partCamera().projection() * partCamera().view());
if (selectShape_ == SelectShape::Lasso) {
std::vector<ImVec2> path = selectPath_;
path.push_back(ImVec2(mouseX_, mouseY_));
diff --git a/src/app/Shell.cpp b/src/app/Shell.cpp
index 25724dc1..d9ec3ec4 100644
--- a/src/app/Shell.cpp
+++ b/src/app/Shell.cpp
@@ -853,6 +853,11 @@ void App::canvasRay(float x, float y, glm::vec3& origin, glm::vec3& dir) const {
camera_.screenRay(x - c.x, y - c.y, c.w, c.h, origin, dir);
}
+void App::partRay(float x, float y, glm::vec3& origin, glm::vec3& dir) const {
+ const CanvasRect c = canvasRect();
+ partCamera().screenRay(x - c.x, y - c.y, c.w, c.h, origin, dir);
+}
+
Renderer::Viewport App::canvasViewport(int fbWidth, int fbHeight) const {
if (hideUi_) return {};
int w = 0, h = 0;
diff --git a/src/app/SpaceMouse.cpp b/src/app/SpaceMouse.cpp
index c4c12702..36e20f0a 100644
--- a/src/app/SpaceMouse.cpp
+++ b/src/app/SpaceMouse.cpp
@@ -220,7 +220,7 @@ void App::regrabAfterViewMove() {
if (!grabStroke()) return;
// Where the grabbed point is on screen now: the pen's next motion moves it from there, by as much as the pen moves.
ImVec2 at;
- if (!gizmoProject(strokeBrush_ == BrushType::KelvinGrab ? kelvinTarget_ : grabLast_, at)) return;
+ if (!partProject(strokeBrush_ == BrushType::KelvinGrab ? kelvinTarget_ : grabLast_, at)) return;
grabScreenOffset_ = glm::vec2(at.x, at.y) - grabScreen_;
}
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 2f7da707..143d21c0 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -93,6 +93,8 @@
// welcome_open (the first-run welcome shown), new_look_card_open (the one-time
// "SculptForge has a new look" card),
// parts (count), part_thumbnails (Part panel thumbnails rendered), active_part (index, 0 = top), visible_parts,
+// linked_parts (Parts sharing the active one's mesh, #94; 1 = none), part_moved, part_x (its
+// centre's x in the scene),
// extract_preview (1 while an Extract preview waits for Accept), open_edges (edges of
// the active Part with one triangle: 0 = watertight), solid_volume (the active Part's
// volume with its open borders capped),
@@ -841,6 +843,11 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "saved_views") return double(app_.savedViews_.size());
if (name == "mask_darkness") return std::round(app_.renderSettings_.maskDarkness * 100.0f);
if (name == "brush_type") return app_.doc_.activeBrush >= 0 || app_.paintMode_ ? -1.0 : double(int(app_.brush_));
+ if (name == "dab_scene_error_px") { // the last dab's centre, placed in the scene and shown by the view, to the cursor
+ const Part& part = app_.doc_.activePartInfo(); // (a moved linked copy, #94: its own space and the scene's agree)
+ const ImVec2 p = project(glm::vec3(part.transform * glm::vec4(app_.lastDabCentre_, 1.0f)));
+ return double(glm::distance(glm::vec2(p.x, p.y), app_.lastDabScreen_));
+ }
if (name == "last_dab_x") return app_.lastDabScreen_.x;
if (name == "last_dab_y") return app_.lastDabScreen_.y;
if (name == "paint_r") return std::round(255.0f * linearToSrgb(app_.doc_.paintColor).x);
@@ -1005,12 +1012,15 @@ double Demo::query(const std::string& name, bool& known) const {
glm::cross(glm::dvec3(capped.positions[t.y]), glm::dvec3(capped.positions[t.z])));
return v / 6.0;
}
+ if (name == "linked_parts") return double(app_.doc_.linkCount(app_.doc_.activePart)); // (#94: 1 = not linked)
+ if (name == "part_moved") return app_.doc_.activePartInfo().moved() ? 1.0 : 0.0;
+ if (name == "part_x") return double(app_.doc_.partBounds(app_.doc_.activePart).center().x);
if (name == "visible_parts")
return double(std::count_if(doc.parts.begin(), doc.parts.end(), [](const Part& s) { return s.visible; }));
if (name == "edited_parts") { // Parts with undo history (the active one's lives in doc.undo)
int n = 0;
for (int i = 0; i < doc.partCount(); ++i)
- n += (i == doc.activePart ? doc.undo.canUndo() : doc.parts[size_t(i)].undo.canUndo()) ? 1 : 0;
+ n += doc.partUndo(i).canUndo() ? 1 : 0;
return double(n);
}
if (name == "user_brushes")
@@ -1545,7 +1555,7 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
return true;
}
// The point of its on-screen bounds nearest (U, V) where it's the front Part and no panel covers it.
- const AABB b = app_.doc_.partMesh(index).bounds();
+ const AABB b = app_.doc_.partBounds(index);
ImVec2 lo(1e9f, 1e9f), hi(-1e9f, -1e9f);
for (int i = 0; i < 8; ++i) {
const ImVec2 p = project(glm::vec3((i & 1) ? b.max.x : b.min.x, (i & 2) ? b.max.y : b.min.y,
@@ -1834,7 +1844,7 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
auto points = std::make_shared<std::vector<ImVec2>>();
steps_.push_back([this, uv, points](float t) {
// The model's on-screen bounds, without onModel's walk onto the surface: points may be on the background.
- const AABB b = app_.doc_.mesh.bounds();
+ const AABB b = app_.doc_.partBounds(app_.doc_.activePart);
ImVec2 lo(1e9f, 1e9f), hi(-1e9f, -1e9f);
for (int i = 0; i < 8; ++i) {
const ImVec2 p = project(glm::vec3((i & 1) ? b.max.x : b.min.x, (i & 2) ? b.max.y : b.min.y,
diff --git a/src/core/Benchmark.cpp b/src/core/Benchmark.cpp
index d8c32e50..bc44e3bc 100644
--- a/src/core/Benchmark.cpp
+++ b/src/core/Benchmark.cpp
@@ -115,18 +115,21 @@ size_t peakResidentBytes() {
MemoryUse documentMemory(const Document& doc) {
MemoryUse u;
std::vector<const PaintTexture*> seen; // textures shared between Parts count once
+ std::vector<const PartData*> meshes; // and meshes shared by linked Parts (#94): one mesh, one GPU slot
for (int i = 0; i < doc.partCount(); ++i) {
- const bool active = i == doc.activePart;
+ const bool active = doc.checkedOut(i);
const Part& st = doc.parts[size_t(i)];
+ if (std::find(meshes.begin(), meshes.end(), st.data.get()) != meshes.end()) continue;
+ meshes.push_back(st.data.get());
const Mesh& m = doc.partMesh(i);
u.mesh += m.memoryBytes();
if (m.texture && std::find(seen.begin(), seen.end(), m.texture.get()) == seen.end()) {
seen.push_back(m.texture.get());
u.textures += m.texture->colourBytes();
}
- u.bvh += (active ? doc.bvh : st.bvh).memoryBytes();
+ u.bvh += (active ? doc.bvh : st.data->bvh).memoryBytes();
u.levels += subdivBytes(m);
- u.undo += (active ? doc.undo : st.undo).undoBytes();
+ u.undo += (active ? doc.undo : st.data->undo).undoBytes();
u.triangles += m.triangleCount();
u.vertices += m.vertexCount();
if (st.visible) // the renderer's cluster layout (core/UploadOrder.h): packed vertices (12 bytes, + colour 4,
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index d7ec570c..6fbf4249 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -464,14 +464,15 @@ CommandRegistry::CommandRegistry() {
}});
add({"export_glb",
- "Export a game-ready binary glTF (.glb), one node and mesh per visible Part. Sculpt layers become "
+ "Export a game-ready binary glTF (.glb), one node and mesh per visible Part (linked copies: one mesh, a node "
+ "each). Sculpt layers become "
"morph targets (blend shapes). UVs are kept and Part textures are embedded. A baked face take "
"(face_take_bake) becomes an animation of the morph target weights.",
{{"path", T::String, "Output .glb path (UTF-8).", true}},
[](Document& doc, const Args& a) -> CommandResult {
std::string path = argString(a, "path");
std::string err;
- const auto objects = visiblePartObjects(doc);
+ const auto objects = visiblePartObjects(doc, true); // (linked copies, #94: one mesh, placed each)
if (objects.empty()) return {false, "Nothing visible to export"};
MorphAnimation take;
const bool animated = bakedFaceAnimation(doc, take);
@@ -481,7 +482,7 @@ CommandRegistry::CommandRegistry() {
add({"export_usd",
"Export OpenUSD (.usda text, or .usdz package for AR Quick Look / Vision Pro), one Mesh prim per visible "
- "Part. Sculpt layers become "
+ "Part (linked copies: instanceable prims referencing the first). Sculpt layers become "
"UsdSkel blend shapes with their current weights; loaded Gaussian splats are included as a "
"ParticleField3DGaussianSplat prim. UVs are kept; a Part's texture becomes a UsdPreviewSurface texture "
"(packed into .usdz, else a PNG beside the file). A baked face take (face_take_bake) becomes time samples "
@@ -492,7 +493,7 @@ CommandRegistry::CommandRegistry() {
std::string path = argString(a, "path");
std::string err;
const SplatCloud* splats = argBool(a, "splats", true) && !doc.splats.empty() ? &doc.splats : nullptr;
- const auto objects = visiblePartObjects(doc);
+ const auto objects = visiblePartObjects(doc, true); // (linked copies, #94: one mesh, placed each)
MorphAnimation take;
const bool animated = bakedFaceAnimation(doc, take);
if (!saveUsd(path, objects, splats, doc.assetName(), err, animated ? &take : nullptr)) return {false, err};
@@ -728,6 +729,14 @@ CommandRegistry::CommandRegistry() {
st.spacing = float(argNumber(a, "spacing", -1.0));
st.seed = uint32_t(std::max(argNumber(a, "seed", 1.0), 0.0));
if (!symmetryArg(a, doc.mesh, st.symmetry, err)) return {false, err};
+ if (const Part& part = doc.activePartInfo(); part.moved()) { // a moved linked copy (#94): into its space
+ const glm::mat4 inv = glm::inverse(part.transform);
+ const float scale = glm::length(glm::vec3(part.transform[0]));
+ for (auto& p : st.points) p = glm::vec3(inv * glm::vec4(p, 1.0f));
+ const glm::vec3 view = glm::mat3(inv) * st.view;
+ if (glm::length(view) > 0.0f) st.view = glm::normalize(view);
+ if (scale > 0.0f) st.radius /= scale;
+ }
// Resolve the brush: a library recipe (exact name, then any case), then a built-in type.
const std::string name = argString(a, "brush");
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index 91c23b88..782babd1 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -4,6 +4,8 @@
#include "core/Multires.h"
+#include <glm/gtc/matrix_transform.hpp>
+
#include <algorithm>
#include <cctype>
#include <filesystem>
@@ -14,9 +16,16 @@ namespace sf {
Document::Document() {
parts.emplace_back();
parts.back().id = 1;
+ parts.back().data->key = 1;
parts.back().name = "Sculpt";
}
+uint32_t Document::newPartId(Part& p) {
+ p.id = nextPartId_++;
+ if (!p.data->key) p.data->key = p.id;
+ return p.id;
+}
+
void Document::setMesh(Mesh m, std::string name, BVH* built) {
mesh = std::move(m);
mesh.topologyDirty = true;
@@ -32,7 +41,7 @@ void Document::setMesh(Mesh m, std::string name, BVH* built) {
partFolders.clear();
parts.clear();
parts.emplace_back();
- parts.back().id = nextPartId_++;
+ newPartId(parts.back());
parts.back().name = name.empty() ? "Sculpt" : std::move(name);
activePart = 0;
extractPreview = {};
@@ -42,7 +51,7 @@ void Document::setMesh(Mesh m, std::string name, BVH* built) {
bool Document::dirty() const {
if (modified || undo.revision() != cleanRevision_ || splatsVersion != cleanSplatsVersion_) return true;
for (int i = 0; i < partCount(); ++i)
- if (i != activePart && parts[size_t(i)].undo.revision() != parts[size_t(i)].cleanRevision) return true;
+ if (!checkedOut(i) && parts[size_t(i)].data->undo.revision() != parts[size_t(i)].data->cleanRevision) return true;
return false;
}
@@ -51,15 +60,32 @@ void Document::markClean() {
cleanRevision_ = undo.revision();
cleanSplatsVersion_ = splatsVersion;
for (int i = 0; i < partCount(); ++i)
- if (i != activePart) parts[size_t(i)].cleanRevision = parts[size_t(i)].undo.revision();
+ if (!checkedOut(i)) parts[size_t(i)].data->cleanRevision = parts[size_t(i)].data->undo.revision();
+}
+
+BVH& Document::partBvh(int i) {
+ if (checkedOut(i)) {
+ syncBvh();
+ return bvh;
+ }
+ PartData& d = *parts[size_t(i)].data;
+ if (d.bvhDirty || (d.bvh.nodeCount() == 0 && d.mesh.triangleCount())) {
+ d.bvh.build(d.mesh);
+ d.bvhDirty = false;
+ }
+ return d.bvh;
}
void Document::selectPart(int i) {
if (i < 0 || i >= partCount() || i == activePart) return;
+ if (checkedOut(i)) { // a linked copy of the active Part: its data is checked out already
+ activePart = i;
+ return;
+ }
uvSelection.clear();
// Check the active Part back in, then check `i` out. Swapping keeps each
// mesh's GPU dirty state, so the renderer doesn't re-upload anything.
- auto swapIn = [this](Part& s) {
+ auto swapIn = [this](PartData& s) {
std::swap(mesh, s.mesh);
std::swap(bvh, s.bvh);
std::swap(undo, s.undo);
@@ -69,22 +95,22 @@ void Document::selectPart(int i) {
std::swap(bvhDirty, s.bvhDirty);
std::swap(cleanRevision_, s.cleanRevision);
};
- swapIn(parts[size_t(activePart)]);
- subdivReleaseCache(parts[size_t(activePart)].mesh); // only the active Part keeps cached levels
+ swapIn(*parts[size_t(activePart)].data);
+ subdivReleaseCache(parts[size_t(activePart)].data->mesh); // only the active Part keeps cached levels
activePart = i;
- swapIn(parts[size_t(i)]);
+ swapIn(*parts[size_t(i)].data);
if (bvh.nodeCount() == 0 && mesh.triangleCount()) bvhDirty = true; // built on first use
syncBvh();
}
int Document::addPart(Mesh m, std::string name, bool select, int at, BVH* built) {
Part s;
- s.id = nextPartId_++;
+ newPartId(s);
s.name = uniquePartName(name.empty() ? "Part" : name);
- s.mesh = std::move(m);
- s.mesh.topologyDirty = true;
- if (built) s.bvh = std::move(*built);
- else s.bvh.build(s.mesh);
+ s.data->mesh = std::move(m);
+ s.data->mesh.topologyDirty = true;
+ if (built) s.data->bvh = std::move(*built);
+ else s.data->bvh.build(s.data->mesh);
const int index = at < 0 || at > partCount() ? partCount() : at;
parts.insert(parts.begin() + index, std::move(s));
if (index <= activePart) ++activePart;
@@ -129,17 +155,31 @@ int Document::partIndex(uint32_t id) const {
}
bool Document::applyPartStep(PartStep& step) {
+ if (step.isTransform) {
+ const int i = partIndex(step.id);
+ if (i < 0) return false;
+ std::swap(parts[size_t(i)].transform, step.transform);
+ modified = true;
+ return true;
+ }
if (step.stashed) { // redo: put it back where it was
const int at = std::clamp(step.at, 0, partCount());
parts.insert(parts.begin() + at, std::move(*step.stashed));
step.stashed.reset();
if (at <= activePart) ++activePart;
- parts[size_t(at)].mesh.topologyDirty = true;
+ partMesh(at).topologyDirty = true;
modified = true;
return true;
}
const int i = partIndex(step.id);
- if (i < 0 || i == activePart || partCount() <= 1) return false;
+ if (i < 0 || partCount() <= 1) return false;
+ if (i == activePart) { // a linked copy (its history is its group's): another Part of the group takes over
+ int other = -1;
+ for (int k = 0; k < partCount() && other < 0; ++k)
+ if (k != i && checkedOut(k)) other = k;
+ if (other < 0) return false;
+ selectPart(other);
+ }
step.at = i;
step.stashed = std::make_unique<Part>(std::move(parts[size_t(i)]));
parts.erase(parts.begin() + i);
@@ -231,13 +271,106 @@ std::string Document::uniqueFolderName(const std::string& wanted) const {
}
}
+AABB Document::partBounds(int i) const {
+ const AABB local = partMesh(i).bounds();
+ const glm::mat4& t = parts[size_t(i)].transform;
+ if (!local.valid() || !parts[size_t(i)].moved()) return local;
+ AABB b;
+ for (int c = 0; c < 8; ++c)
+ b.expand(glm::vec3(t * glm::vec4(c & 1 ? local.max.x : local.min.x, c & 2 ? local.max.y : local.min.y,
+ c & 4 ? local.max.z : local.min.z, 1.0f)));
+ return b;
+}
+
AABB Document::visibleBounds() const {
AABB b;
for (int i = 0; i < partCount(); ++i)
- if (parts[size_t(i)].visible && partMesh(i).vertexCount()) b.expand(partMesh(i).bounds());
+ if (parts[size_t(i)].visible && partMesh(i).vertexCount()) b.expand(partBounds(i));
return b;
}
+int Document::linkCount(int i) const {
+ int n = 0;
+ for (const Part& p : parts) n += p.data == parts[size_t(i)].data ? 1 : 0;
+ return n;
+}
+
+int Document::addLink(int i, std::string name, const glm::mat4& transform, int at) {
+ Part s;
+ s.data = parts[size_t(i)].data;
+ newPartId(s);
+ s.name = uniquePartName(name.empty() ? parts[size_t(i)].name : name);
+ s.transform = transform;
+ at = at < 0 || at > partCount() ? partCount() : at;
+ parts.insert(parts.begin() + at, std::move(s));
+ if (at <= activePart) ++activePart;
+ modified = true;
+ return at;
+}
+
+int Document::linkedDuplicate(int i, const glm::vec3& offset) {
+ int first = i; // named after the group's first Part: "Body link", "Body link 2", ...
+ for (int k = 0; k < partCount(); ++k)
+ if (parts[size_t(k)].data == parts[size_t(i)].data) {
+ first = k;
+ break;
+ }
+ const int at = addLink(i, parts[size_t(first)].name + " link",
+ glm::translate(glm::mat4(1.0f), offset) * parts[size_t(i)].transform, i + 1);
+ parts[size_t(at)].visible = parts[size_t(at - 1)].visible;
+ parts[size_t(at)].shading = parts[size_t(at - 1)].shading;
+ selectPart(at);
+ // One step in the shared history: undo takes the copy away again (applyPartStep).
+ UndoRecord r;
+ r.label = "Linked Duplicate";
+ r.part = std::make_shared<PartStep>();
+ r.part->id = parts[size_t(at)].id;
+ r.part->at = at;
+ undo.push(std::move(r));
+ modified = true;
+ return at;
+}
+
+bool Document::makeUnique(int i) {
+ if (i < 0 || i >= partCount() || linkCount(i) < 2) return false;
+ auto own = std::make_shared<PartData>();
+ own->key = nextPartId_++; // (a new GPU mesh: the group keeps its key)
+ const bool active = i == activePart;
+ const PartData& from = *parts[size_t(i)].data;
+ own->mesh = checkedOut(i) ? mesh : from.mesh;
+ own->mesh.topologyDirty = true;
+ own->activeLayer = checkedOut(i) ? activeLayer : from.activeLayer;
+ own->qremeshGuides = checkedOut(i) ? qremeshGuides : from.qremeshGuides;
+ own->bvh.build(own->mesh);
+ own->cleanRevision = ~uint64_t(0); // unsaved until the next save
+ if (active) {
+ // Check the group's data back in through another of its Parts, then this one's own copy out.
+ int other = -1;
+ for (int k = 0; k < partCount() && other < 0; ++k)
+ if (k != i && checkedOut(k)) other = k;
+ activePart = other;
+ parts[size_t(i)].data = std::move(own);
+ selectPart(i);
+ } else {
+ parts[size_t(i)].data = std::move(own);
+ }
+ modified = true;
+ return true;
+}
+
+void Document::setPartTransform(int i, const glm::mat4& transform, const std::string& label) {
+ if (i < 0 || i >= partCount() || parts[size_t(i)].transform == transform) return;
+ UndoRecord r;
+ r.label = label;
+ r.part = std::make_shared<PartStep>();
+ r.part->id = parts[size_t(i)].id;
+ r.part->isTransform = true;
+ r.part->transform = parts[size_t(i)].transform;
+ parts[size_t(i)].transform = transform;
+ partUndo(i).push(std::move(r));
+ modified = true;
+}
+
int Document::addBrush(BrushRecipe recipe) {
recipe.clamp();
for (size_t i = 0; i < brushes.size(); ++i) {
diff --git a/src/core/Document.h b/src/core/Document.h
index 7a4f562b..5aa5b893 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -28,18 +28,11 @@ enum class Shading : uint8_t { Default, Smooth, Flat };
const char* shadingName(Shading s); // "default", "smooth", "flat"
bool parseShading(const std::string& name, Shading& out);
-// One object in the scene, like a classic Part: a body, the eyes, the
-// teeth, a sword. Each keeps its own mesh, attributes, layers and undo
-// history. The active Part is "checked out" into Document::mesh / bvh /
-// undo, so every tool and command keeps working on the active one; its slot
-// here holds only the name and flags until another Part is selected.
-struct Part {
- uint32_t id = 0; // stable for the session (renderer slots, UI selection)
- std::string name;
- bool visible = true;
- Shading shading = Shading::Default; // per-Part override of the scene's shading
- uint32_t folder = 0; // the PartFolder it's in (its id), 0 = none
- // Inactive Parts only (empty while active).
+// What a Part is made of: its mesh, attributes, layers and undo history. Shared (reference counted) by the Parts
+// of one link group (Linked Duplicate, #94): sculpting, painting or masking any of them edits this one mesh, and
+// they share its history. `key` names it for the renderer (one GPU mesh per PartData): the id of the Part it
+// was made for.
+struct PartData {
Mesh mesh;
BVH bvh;
UndoStack undo;
@@ -48,6 +41,30 @@ struct Part {
bool bvhDirty = false;
uint64_t cleanRevision = 0;
std::vector<QRemeshGuide> qremeshGuides; // QRemesh Guides (core/QRemeshGuides.h)
+ uint32_t key = 0;
+};
+
+// One object in the scene, like a classic Part: a body, the eyes, the
+// teeth, a sword. Each keeps its own mesh, attributes, layers and undo
+// history (its PartData, shared with its linked copies). The active Part is "checked out" into Document::mesh /
+// bvh / undo, so every tool and command keeps working on the active one; its PartData holds only the key until
+// a Part with other data is selected.
+struct Part {
+ uint32_t id = 0; // stable for the session (renderer slots, UI selection)
+ std::string name;
+ bool visible = true;
+ Shading shading = Shading::Default; // per-Part override of the scene's shading
+ uint32_t folder = 0; // the PartFolder it's in (its id), 0 = none
+ // Where the mesh is in the scene: world = transform * mesh position. Identity unless the Part is a linked copy
+ // moved on its own (or was one: Make Unique keeps it). A similarity (rotation, translation, uniform scale).
+ glm::mat4 transform{1.0f};
+ std::shared_ptr<PartData> data = std::make_shared<PartData>();
+ Part() = default;
+ Part(Part&&) = default;
+ Part& operator=(Part&&) = default;
+ Part(const Part&) = delete; // (a copy would share the data: a link; Document::linkedDuplicate makes those)
+ Part& operator=(const Part&) = delete;
+ bool moved() const { return transform != glm::mat4(1.0f); }
};
// A folder in the Parts list (#96): a name the list groups its Parts under, so they hide, show and move
@@ -59,11 +76,14 @@ struct PartFolder {
};
// An undo step that added Part `id` at list position `at` (UndoRecord::part): `stashed` holds the Part
-// while it's undone.
+// while it's undone. With `isTransform` it instead moved Part `id` (a linked copy): `transform` holds the
+// other transform (undo and redo swap it with the Part's).
struct PartStep {
uint32_t id = 0;
int at = 0;
std::unique_ptr<Part> stashed;
+ bool isTransform = false;
+ glm::mat4 transform{1.0f};
};
// Extract's preview (core/ExtractMirror.h): Part `id`, made from the mask of Part `source` as it was at
@@ -156,9 +176,30 @@ struct Document {
int partCount() const { return int(parts.size()); }
Part& activePartInfo() { return parts[size_t(activePart)]; }
const Part& activePartInfo() const { return parts[size_t(activePart)]; }
- // The mesh of Part `i`, active or not.
- Mesh& partMesh(int i) { return i == activePart ? mesh : parts[size_t(i)].mesh; }
- const Mesh& partMesh(int i) const { return i == activePart ? mesh : parts[size_t(i)].mesh; }
+ // True when Part `i`'s data is the one checked out (the active Part, or a Part linked to it).
+ bool checkedOut(int i) const { return parts[size_t(i)].data == parts[size_t(activePart)].data; }
+ // The mesh, BVH (built if stale) and history of Part `i`, active or not (a linked copy's are its group's).
+ Mesh& partMesh(int i) { return checkedOut(i) ? mesh : parts[size_t(i)].data->mesh; }
+ const Mesh& partMesh(int i) const { return checkedOut(i) ? mesh : parts[size_t(i)].data->mesh; }
+ BVH& partBvh(int i);
+ UndoStack& partUndo(int i) { return checkedOut(i) ? undo : parts[size_t(i)].data->undo; }
+ const UndoStack& partUndo(int i) const { return checkedOut(i) ? undo : parts[size_t(i)].data->undo; }
+ // The renderer's key for Part `i`'s mesh (shared by linked copies: one GPU mesh).
+ uint32_t meshKey(int i) const { return parts[size_t(i)].data->key; }
+ // --- Linked Duplicates (#94): Parts sharing one mesh, each with its own transform.
+ // How many Parts share Part `i`'s mesh (1 = not linked).
+ int linkCount(int i) const;
+ // Adds a Part sharing Part `i`'s mesh and history at `at` (-1 = end), placed by `transform`; not undoable, not
+ // selected. Returns its index.
+ int addLink(int i, std::string name, const glm::mat4& transform, int at = -1);
+ // Adds a Part sharing Part `i`'s mesh and history, after it, offset by `offset` (world units), and makes it
+ // active; one undoable step in the shared history. Returns its index.
+ int linkedDuplicate(int i, const glm::vec3& offset);
+ // Gives Part `i` its own copy of the mesh (a fresh history), breaking its link; it keeps its transform.
+ // False when it isn't linked.
+ bool makeUnique(int i);
+ // Sets Part `i`'s transform as an undoable step in its history (`label`).
+ void setPartTransform(int i, const glm::mat4& transform, const std::string& label);
// Makes Part `i` the one tools and commands edit.
void selectPart(int i);
// Inserts a Part at `at` (-1 = end of the list), made active when `select`; returns its index. `built`:
@@ -202,8 +243,10 @@ struct Document {
// A name not used by any Part yet ("Eye", "Eye 2", ...).
std::string uniquePartName(const std::string& wanted) const;
- // Bounds of every visible Part.
+ // Bounds of every visible Part (in the scene: transforms applied).
AABB visibleBounds() const;
+ // Bounds of Part `i` in the scene (its transform applied).
+ AABB partBounds(int i) const;
// Replaces the whole scene with one Part holding `m` and clears the edit history (`built`: as addPart).
void setMesh(Mesh m, std::string name = "Sculpt", BVH* built = nullptr);
@@ -220,6 +263,7 @@ private:
uint64_t cleanRevision_ = 0, cleanSplatsVersion_ = 0;
uint32_t nextPartId_ = 2;
uint32_t nextFolderId_ = 1;
+ uint32_t newPartId(Part& p); // gives `p` the next id (and its data that key when it has none)
};
} // namespace sf
diff --git a/src/core/ExtractMirror.cpp b/src/core/ExtractMirror.cpp
index 902a8bee..514975c9 100644
--- a/src/core/ExtractMirror.cpp
+++ b/src/core/ExtractMirror.cpp
@@ -431,13 +431,14 @@ CommandResult runExtract(Document& doc, const Args& a) {
const size_t tris = shell.triangleCount();
doc.dropExtractPreview(true);
if (doc.extractPreview.id) { // Extract again (other settings): the preview is replaced
- Part& s = doc.parts[size_t(doc.partIndex(doc.extractPreview.id))];
+ PartData& s = *doc.parts[size_t(doc.partIndex(doc.extractPreview.id))].data;
s.mesh = std::move(shell);
s.mesh.topologyDirty = true;
s.bvh.build(s.mesh);
s.bvhDirty = false;
} else {
const int i = doc.addPart(std::move(shell), "Extract", false, doc.activePart + 1);
+ doc.parts[size_t(i)].transform = doc.activePartInfo().transform; // (made from the active mesh: where it is)
doc.extractPreview = {doc.parts[size_t(i)].id, doc.activePartInfo().id, doc.undo.revision()};
}
if (argBool(a, "accept", false)) return acceptPreview(doc);
diff --git a/src/core/Face.cpp b/src/core/Face.cpp
index 229a0b76..ea543c2b 100644
--- a/src/core/Face.cpp
+++ b/src/core/Face.cpp
@@ -880,11 +880,11 @@ glm::vec3 moveRigid(const Similarity& align, const glm::mat3& R, const glm::vec3
// Undoable mesh replacement for Part `i` (the active one through Document::replaceMeshUndoable).
void replacePartMesh(Document& doc, int i, Mesh m, const std::string& label) {
- if (i == doc.activePart) {
+ if (doc.checkedOut(i)) {
doc.replaceMeshUndoable(std::move(m), label);
return;
}
- Part& s = doc.parts[size_t(i)];
+ PartData& s = *doc.parts[size_t(i)].data;
UndoRecord r;
r.label = label;
r.mesh = std::make_unique<Mesh>(std::move(s.mesh));
@@ -1157,7 +1157,7 @@ FaceWeightsStats applyFaceWeights(Document& doc, const std::vector<std::pair<std
for (int si = 0; si < doc.partCount(); ++si) {
Mesh& m = doc.partMesh(si);
if (m.layers.empty() || m.base.size() != m.positions.size()) continue;
- const uint64_t revision = si == doc.activePart ? doc.undo.revision() : doc.parts[size_t(si)].undo.revision();
+ const uint64_t revision = doc.partUndo(si).revision();
std::vector<uint32_t> changed;
for (size_t w = 0; w < weights.size(); ++w)
for (size_t li = 0; li < m.layers.size(); ++li)
@@ -1210,8 +1210,8 @@ FaceWeightsStats applyFaceWeights(Document& doc, const std::vector<std::pair<std
if (verts.empty()) continue;
m.updateNormals(verts); // (also marks them, and their neighbours, for the GPU)
stats.vertices += verts.size();
- if (si == doc.activePart) doc.bvhDirty = true;
- else doc.parts[size_t(si)].bvhDirty = true;
+ if (doc.checkedOut(si)) doc.bvhDirty = true;
+ else doc.parts[size_t(si)].data->bvhDirty = true;
}
for (size_t w = 0; w < weights.size(); ++w) {
if (matched[w]) ++stats.matched;
diff --git a/src/core/ForgeSpheres.cpp b/src/core/ForgeSpheres.cpp
index 504be1cb..4d289369 100644
--- a/src/core/ForgeSpheres.cpp
+++ b/src/core/ForgeSpheres.cpp
@@ -517,7 +517,9 @@ void registerForgeSphereCommands(CommandRegistry& reg) {
const size_t faces = skin.triangleCount() - skin.quadCount();
const int from = doc.activePart;
const std::string name = doc.uniquePartName(doc.parts[size_t(from)].name + " Mesh");
+ const glm::mat4 place = doc.parts[size_t(from)].transform;
doc.addPart(std::move(skin), name, true, from + 1);
+ doc.activePartInfo().transform = place;
if (argBool(a, "keep", true)) doc.parts[size_t(from)].visible = false;
else doc.removePart(from);
return {true, "Made \"" + name + "\" from the Forge Spheres: " + std::to_string(faces) + " faces"};
diff --git a/src/core/MeshTransform.cpp b/src/core/MeshTransform.cpp
index 9edfce4b..b347f29a 100644
--- a/src/core/MeshTransform.cpp
+++ b/src/core/MeshTransform.cpp
@@ -66,6 +66,33 @@ glm::vec3 MeshTransform::apply(const glm::vec3& p) const {
return l * p + o;
}
+glm::mat4 MeshTransform::matrix() const {
+ glm::mat3 l;
+ glm::vec3 o;
+ at(1.0f, l, o);
+ glm::mat4 m(l);
+ m[3] = glm::vec4(o, 1.0f);
+ return m;
+}
+
+MeshTransform MeshTransform::inSpaceOf(const glm::mat4& place) const {
+ const float s = glm::length(glm::vec3(place[0]));
+ if (!(s > 0.0f)) return *this;
+ const glm::mat3 r = glm::mat3(place) / s, rt = glm::transpose(r);
+ MeshTransform out = *this;
+ out.pivot = glm::vec3(glm::inverse(place) * glm::vec4(pivot, 1.0f));
+ out.frame = rt * frame;
+ out.translate = rt * translate / s;
+ out.rotate = glm::normalize(glm::quat_cast(rt) * rotate * glm::quat_cast(r));
+ return out;
+}
+
+MeshTransform MeshTransform::evenScale() const {
+ MeshTransform out = *this;
+ out.scale = glm::vec3((scale.x + scale.y + scale.z) / 3.0f);
+ return out;
+}
+
glm::quat eulerRotation(const glm::vec3& degrees, const glm::mat3& axes) {
const glm::quat qx = glm::angleAxis(glm::radians(degrees.x), axes[0]);
const glm::quat qy = glm::angleAxis(glm::radians(degrees.y), axes[1]);
@@ -356,24 +383,31 @@ void TransformSession::cancel(Mesh& mesh, BVH& bvh) {
*this = TransformSession();
}
+bool partMovesWhole(const Document& doc, int index, bool useMask) {
+ const bool instance = doc.linkCount(index) > 1 || doc.parts[size_t(index)].moved();
+ return instance && !(useMask && doc.partMesh(index).hasMask());
+}
+
size_t transformPart(Document& doc, int index, const MeshTransform& t, bool useMask, float falloff, Symmetry mirror,
const std::string& label) {
if (index < 0 || index >= doc.partCount()) return 0;
- const bool active = index == doc.activePart;
- Part& info = doc.parts[size_t(index)];
- Mesh& mesh = active ? doc.mesh : info.mesh;
- BVH& bvh = active ? doc.bvh : info.bvh;
- UndoStack& undo = active ? doc.undo : info.undo;
- if (active) doc.syncBvh();
- else if (info.bvhDirty) {
- info.bvh.build(info.mesh);
- info.bvhDirty = false;
+ Mesh& mesh = doc.partMesh(index);
+ const Part& part = doc.parts[size_t(index)];
+ // A linked copy (or one moved as a whole before) moves as a whole: its transform, one undo step in its
+ // group's history. With a mask, what moves is the shared mesh, in the Part's own space.
+ if (partMovesWhole(doc, index, useMask)) {
+ if (!part.visible || mesh.vertexCount() == 0) return 0;
+ doc.setPartTransform(index, t.evenScale().matrix() * part.transform, label);
+ return mesh.vertexCount();
}
+ const MeshTransform local = part.moved() ? t.inSpaceOf(part.transform) : t;
+ BVH& bvh = doc.partBvh(index);
+ UndoStack& undo = doc.partUndo(index);
TransformSession s;
- const int layer = active ? doc.activeLayer : -1;
- if (!s.begin(mesh, transformWeights(mesh, useMask, falloff), mirror, t.pivot, layer)) return 0;
+ const int layer = part.data == doc.activePartInfo().data ? doc.activeLayer : -1; // (the checked-out mesh)
+ if (!s.begin(mesh, transformWeights(mesh, useMask, falloff), mirror, local.pivot, layer)) return 0;
const size_t n = s.movingVertices();
- s.apply(mesh, t);
+ s.apply(mesh, local);
UndoRecord r = s.finish(mesh, bvh, label);
if (r.empty()) return 0;
undo.push(std::move(r));
diff --git a/src/core/MeshTransform.h b/src/core/MeshTransform.h
index 3d38164f..60d9f65a 100644
--- a/src/core/MeshTransform.h
+++ b/src/core/MeshTransform.h
@@ -45,6 +45,12 @@ struct MeshTransform {
// The transform at weight `w` (0 = nothing, 1 = all of it) as p' = linear * p + offset.
void at(float w, glm::mat3& linear, glm::vec3& offset) const;
glm::vec3 apply(const glm::vec3& p) const; // full weight
+ glm::mat4 matrix() const; // full weight
+ // The same transform as seen in the space of a Part placed by `place` (Part::transform, a similarity): what it
+ // does to that Part's own mesh coordinates.
+ MeshTransform inSpaceOf(const glm::mat4& place) const;
+ // With one scale along every axis (the mean): a linked copy's transform stays a similarity.
+ MeshTransform evenScale() const;
};
// Rotation by Euler angles in degrees about axes[0], then axes[1], then axes[2] (the splat_rotate order).
@@ -114,8 +120,12 @@ public:
static constexpr int kLevels = 4096;
};
-// Transforms Part `index` of `doc` (active or not) as one undoable step on that Part; on the active Part it
-// records into the active sculpt layer (doc.activeLayer). Returns the number of vertices that moved.
+// True when a transform moves Part `index` as a whole, by its Part::transform: a linked copy (#94) or a Part
+// moved that way before, unless `useMask` and it has a mask (then the mask's part of its mesh moves).
+bool partMovesWhole(const Document& doc, int index, bool useMask);
+// Transforms Part `index` of `doc` (active or not) as one undoable step on that Part (a linked copy as a whole
+// unless masked: partMovesWhole); on the active Part's mesh it records into the active sculpt layer
+// (doc.activeLayer). Returns the number of vertices that moved.
size_t transformPart(Document& doc, int index, const MeshTransform& t, bool useMask, float falloff, Symmetry mirror,
const std::string& label);
diff --git a/src/core/MicroCommands.cpp b/src/core/MicroCommands.cpp
index c484cc19..ff2a5a66 100644
--- a/src/core/MicroCommands.cpp
+++ b/src/core/MicroCommands.cpp
@@ -139,7 +139,8 @@ void registerMicroCommands(CommandRegistry& reg) {
return {true, "Baked the micro level into this Part: " + tris + " triangles"};
}
const std::string name = doc.uniquePartName(doc.activePartInfo().name + " baked");
- doc.addPart(std::move(baked), name, false, doc.activePart + 1);
+ const int at = doc.addPart(std::move(baked), name, false, doc.activePart + 1);
+ doc.parts[size_t(at)].transform = doc.activePartInfo().transform; // (a linked copy's place)
return {true, "Baked the micro level into Part \"" + name + "\": " + tris + " triangles"};
}});
diff --git a/src/core/Parts.cpp b/src/core/Parts.cpp
index 0ebe9c27..b25436a6 100644
--- a/src/core/Parts.cpp
+++ b/src/core/Parts.cpp
@@ -7,6 +7,7 @@
#include "core/Dyntopo.h"
#include "core/Masking.h"
#include "core/Multires.h"
+#include "core/PathStroke.h"
#include "core/FaceGroups.h"
#include "core/Primitives.h"
#include "core/Sculpt.h"
@@ -18,6 +19,7 @@
#include <stb_image.h>
#include <cctype>
+#include <deque>
#include <algorithm>
#include <cstdlib>
#include <filesystem>
@@ -103,25 +105,62 @@ Mesh mergeMeshes(const std::vector<const Mesh*>& meshes) {
return out;
}
+Mesh placedMesh(const Mesh& mesh, const glm::mat4& transform) {
+ Mesh out = mesh;
+ if (transform == glm::mat4(1.0f)) return out;
+ const glm::mat3 linear(transform);
+ for (auto& p : out.positions) p = glm::vec3(transform * glm::vec4(p, 1.0f));
+ for (auto& p : out.base) p = glm::vec3(transform * glm::vec4(p, 1.0f));
+ for (auto& l : out.layers)
+ for (auto& d : l.delta) d = linear * d;
+ out.multires.reset();
+ out.topologyDirty = true;
+ out.recomputeAllNormals();
+ return out;
+}
+
+const Mesh& partPlacedMesh(const Document& doc, int i, Mesh& scratch) {
+ if (!doc.parts[size_t(i)].moved()) return doc.partMesh(i);
+ scratch = placedMesh(doc.partMesh(i), doc.parts[size_t(i)].transform);
+ return scratch;
+}
+
Mesh mergedVisibleMesh(const Document& doc) {
- if (doc.partCount() == 1) return doc.mesh;
+ if (doc.partCount() == 1) return placedMesh(doc.mesh, doc.parts[0].transform);
+ std::deque<Mesh> placed;
std::vector<const Mesh*> meshes;
for (int i = 0; i < doc.partCount(); ++i)
- if (doc.parts[size_t(i)].visible && doc.partMesh(i).triangleCount()) meshes.push_back(&doc.partMesh(i));
+ if (doc.parts[size_t(i)].visible && doc.partMesh(i).triangleCount())
+ meshes.push_back(&partPlacedMesh(doc, i, placed.emplace_back()));
if (meshes.empty()) return Mesh();
if (meshes.size() == 1) return *meshes.front();
return mergeMeshes(meshes);
}
-std::vector<MeshObjectRef> visiblePartObjects(const Document& doc) {
+std::vector<MeshObjectRef> visiblePartObjects(const Document& doc, bool instances) {
+ std::vector<MeshObjectRef> out;
+ std::vector<const PartData*> data; // by object, for instanceOf
+ auto add = [&](int i, const std::string& name) {
+ const Part& p = doc.parts[size_t(i)];
+ MeshObjectRef o{name, &doc.partMesh(i)};
+ if (instances) {
+ o.transform = p.transform;
+ const auto first = std::find(data.begin(), data.end(), p.data.get());
+ if (first != data.end()) o.instanceOf = int(first - data.begin());
+ } else if (p.moved()) {
+ o.owned = std::make_shared<const Mesh>(placedMesh(doc.partMesh(i), p.transform));
+ o.mesh = o.owned.get();
+ }
+ data.push_back(p.data.get());
+ out.push_back(std::move(o));
+ };
if (doc.partCount() == 1) {
if (doc.mesh.triangleCount() == 0) return {};
- return {{doc.assetName(), &doc.mesh}};
+ add(0, doc.assetName());
+ return out;
}
- std::vector<MeshObjectRef> out;
for (int i = 0; i < doc.partCount(); ++i)
- if (doc.parts[size_t(i)].visible && doc.partMesh(i).triangleCount())
- out.push_back({doc.parts[size_t(i)].name, &doc.partMesh(i)});
+ if (doc.parts[size_t(i)].visible && doc.partMesh(i).triangleCount()) add(i, doc.parts[size_t(i)].name);
return out;
}
@@ -212,10 +251,12 @@ void replaceWithPieces(Document& doc, int index, std::vector<Mesh> pieces) {
const std::string base = doc.parts[size_t(index)].name;
const bool visible = doc.parts[size_t(index)].visible;
const uint32_t folder = doc.parts[size_t(index)].folder;
+ const glm::mat4 place = doc.parts[size_t(index)].transform;
for (size_t k = 0; k < pieces.size(); ++k) {
const int at = doc.addPart(std::move(pieces[k]), base + " " + std::to_string(k + 1), false, index + 1 + int(k));
doc.parts[size_t(at)].visible = visible;
doc.parts[size_t(at)].folder = folder;
+ doc.parts[size_t(at)].transform = place;
}
doc.selectPart(index + 1);
doc.removePart(index);
@@ -489,6 +530,7 @@ void registerPartCommands(CommandRegistry& reg) {
const Part& s = doc.parts[size_t(i)];
out += "\n" + std::to_string(i) + ". " + s.name + " (" + countText(doc.partMesh(i).triangleCount());
if (subdivLevelCount(doc.partMesh(i))) out += ", " + subdivLevelText(doc.partMesh(i));
+ if (const int links = doc.linkCount(i); links > 1) out += ", linked x" + std::to_string(links);
if (i == doc.activePart) out += ", active";
if (!s.visible) out += ", hidden";
if (const int f = doc.partFolderIndex(s.folder); f >= 0) out += ", in " + doc.partFolders[size_t(f)].name;
@@ -678,12 +720,44 @@ void registerPartCommands(CommandRegistry& reg) {
Mesh copy = doc.partMesh(i);
const Shading shading = doc.parts[size_t(i)].shading;
const uint32_t folder = doc.parts[size_t(i)].folder;
+ const glm::mat4 place = doc.parts[size_t(i)].transform;
const int added = doc.addPart(std::move(copy), doc.parts[size_t(i)].name + " copy", true, i + 1);
doc.parts[size_t(added)].shading = shading;
doc.parts[size_t(added)].folder = folder; // (right below it: the folder stays together)
+ doc.parts[size_t(added)].transform = place;
return {true, "Duplicated as " + doc.parts[size_t(added)].name};
}});
+ reg.add({"part_duplicate_linked",
+ "Linked Duplicate: a new Part sharing the Part's mesh, with its own place in the scene (#94). "
+ "Sculpting, painting or masking any linked Part changes them all; move each with the Gizmo or "
+ "`transform`. One GPU mesh for all of them. Undoable.",
+ {indexParam, nameParam,
+ {"offset", T::String, "Where the copy goes relative to the Part, x,y,z in world units. Default: beside "
+ "it on +X.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int i = targetPart(doc, a);
+ if (i < 0) return notFound(a);
+ if (doc.partMesh(i).triangleCount() == 0) return {false, doc.parts[size_t(i)].name + " is empty"};
+ glm::vec3 offset(doc.partBounds(i).extent().x * 1.15f, 0.0f, 0.0f);
+ if (a.contains("offset") && !parseVec3(argString(a, "offset"), offset))
+ return {false, "Bad offset '" + argString(a, "offset") + "' (expected x,y,z)"};
+ const int added = doc.linkedDuplicate(i, offset);
+ return {true, "Linked duplicate " + doc.parts[size_t(added)].name + " (" +
+ std::to_string(doc.linkCount(added)) + " linked Parts share the mesh)"};
+ }});
+
+ reg.add({"part_make_unique",
+ "Make Unique: give a linked Part its own copy of the mesh, so it no longer changes with the others "
+ "(#94). It stays where it is; its edit history starts fresh.",
+ {indexParam, nameParam},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int i = targetPart(doc, a);
+ if (i < 0) return notFound(a);
+ if (!doc.makeUnique(i)) return {false, doc.parts[size_t(i)].name + " isn't linked"};
+ return {true, doc.parts[size_t(i)].name + " is unique now"};
+ }});
+
reg.add({"part_delete", "Delete a Part (not undoable). The last Part can't be deleted.",
{indexParam, nameParam},
[](Document& doc, const Args& a) -> CommandResult {
@@ -855,13 +929,18 @@ void registerPartCommands(CommandRegistry& reg) {
[](Document& doc, const Args& a) -> CommandResult {
const int i = doc.activePart;
if (i + 1 >= doc.partCount()) return {false, "There's no Part below " + doc.activePartInfo().name};
- Mesh merged = mergeMeshes({&doc.partMesh(i), &doc.partMesh(i + 1)});
- const std::string texture = carryMergedTexturesNote({&doc.partMesh(i), &doc.partMesh(i + 1)}, merged,
- argBool(a, "keep_texture", true));
+ doc.makeUnique(i); // (a linked Part: the merge is its own, the others stay as they are)
+ // Both where they are in the scene (linked copies, #94): the merged Part isn't moved.
+ Mesh placedA, placedB;
+ const Mesh& a0 = partPlacedMesh(doc, i, placedA);
+ const Mesh& b0 = partPlacedMesh(doc, i + 1, placedB);
+ Mesh merged = mergeMeshes({&a0, &b0});
+ const std::string texture = carryMergedTexturesNote({&a0, &b0}, merged, argBool(a, "keep_texture", true));
for (int k : {i, i + 1}) notePartLevelsDropped(doc, k); // merged at their current levels
const std::string name = doc.parts[size_t(i)].name, below = doc.parts[size_t(i + 1)].name;
doc.removePart(i + 1);
doc.replaceActiveMesh(std::move(merged));
+ doc.activePartInfo().transform = glm::mat4(1.0f);
return {true, "Merged " + below + " into " + name + " (" + countText(doc.mesh.triangleCount()) + ")" + texture};
}});
@@ -876,8 +955,9 @@ void registerPartCommands(CommandRegistry& reg) {
if (visible.size() < 2) return {false, "Show at least two Parts to merge"};
Mesh merged = mergedVisibleMesh(doc);
std::vector<const Mesh*> parts; // as mergedVisibleMesh gathers them
+ std::deque<Mesh> placed;
for (int i : visible)
- if (doc.partMesh(i).triangleCount()) parts.push_back(&doc.partMesh(i));
+ if (doc.partMesh(i).triangleCount()) parts.push_back(&partPlacedMesh(doc, i, placed.emplace_back()));
const std::string texture =
parts.size() > 1 ? carryMergedTexturesNote(parts, merged, argBool(a, "keep_texture", true)) : std::string();
for (int k : visible) notePartLevelsDropped(doc, k); // merged at their current levels
diff --git a/src/core/Parts.h b/src/core/Parts.h
index 488726cd..5168f32c 100644
--- a/src/core/Parts.h
+++ b/src/core/Parts.h
@@ -23,15 +23,23 @@ class CommandRegistry;
// layers are matched by name.
Mesh mergeMeshes(const std::vector<const Mesh*>& meshes);
+// A copy of `mesh` placed by `transform` (Part::transform): positions, the layers' base and offsets, normals.
+// Subdivision levels are left out (they'd be in the old place).
+Mesh placedMesh(const Mesh& mesh, const glm::mat4& transform);
+// Part `i`'s mesh where it is in the scene: the mesh itself when it isn't moved, else a placed copy in `scratch`.
+const Mesh& partPlacedMesh(const Document& doc, int i, Mesh& scratch);
+
// The visible Parts merged into one mesh (for exporters that write a single
-// mesh). With one Part this is a copy of it, whether shown or not.
+// mesh), where they are in the scene. With one Part this is a copy of it, whether shown or not.
Mesh mergedVisibleMesh(const Document& doc);
// The visible Parts that have triangles, in list order and named after
// them, for exporters that write one object per Part. With a single Part
// it is that one (shown or not) named doc.assetName(), so one-object exports
-// stay as they were.
-std::vector<MeshObjectRef> visiblePartObjects(const Document& doc);
+// stay as they were. Moved Parts (linked copies, #94) come as placed copies, unless `instances`: then each
+// object refers to its Part's mesh as is, with the Part's transform, and linked copies name the first object
+// with their mesh (MeshObjectRef::instanceOf).
+std::vector<MeshObjectRef> visiblePartObjects(const Document& doc, bool instances = false);
// Replaces the scene with one Part per object (the first one active), named
// after the objects. A single object, or an unnamed one, is named
@@ -68,7 +76,7 @@ inline constexpr const char* kBuiltinInsertSetPrefix = "builtin:";
// file is missing or differs (else the system temp folder); any other path is itself.
bool resolveInsertSetPath(const std::string& path, std::string& file, std::string& error);
-// part_list, part_select, part_append, part_duplicate, part_delete,
+// part_list, part_select, part_append, part_duplicate, part_duplicate_linked, part_make_unique, part_delete,
// part_rename, part_visibility, part_solo, part_show_all, part_move,
// part_merge_down, part_merge_visible, part_split_groups, part_split_parts.
void registerPartCommands(CommandRegistry& registry);
diff --git a/src/core/Project.cpp b/src/core/Project.cpp
index 05ef84c1..8aff1c17 100644
--- a/src/core/Project.cpp
+++ b/src/core/Project.cpp
@@ -853,6 +853,8 @@ struct LoadedPart {
Shading shading = Shading::Default;
int folder = -1; // index into the manifest's part_folders (#96)
int activeLayer = -1;
+ int link = -1; // a linked copy of this earlier Part (#94): no mesh of its own
+ glm::mat4 transform{1.0f}; // Part::transform
Mesh mesh;
// A big mesh's BVH is built on its own thread once the positions and triangles are read (they don't change
// after that), while the subdivision levels, topology and normals load.
@@ -896,14 +898,27 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erro
Json parts = Json::array();
for (int i = 0; i < doc.partCount(); ++i) {
const Part& s = doc.parts[size_t(i)];
- const bool active = i == doc.activePart;
+ const bool active = doc.checkedOut(i);
Json st = Json::object();
st.set("name", s.name);
st.set("visible", s.visible);
if (s.shading != Shading::Default) st.set("shading", shadingName(s.shading)); // (no format change: optional)
if (const int f = doc.partFolderIndex(s.folder); f >= 0) st.set("folder", f); // (#96: optional, as shading)
+ if (s.moved()) {
+ st.set("transform", matrixJson(s.transform));
+ version.need(8);
+ }
+ int link = -1; // a linked copy (#94): the first Part with its mesh holds it
+ for (int k = 0; k < i && link < 0; ++k)
+ if (doc.parts[size_t(k)].data == s.data) link = k;
+ if (link >= 0) {
+ st.set("link", link);
+ version.need(8);
+ parts.push(std::move(st));
+ continue;
+ }
writeMesh(w, "parts/" + std::to_string(i) + "/", doc.partMesh(i), st);
- st.set("active_layer", active ? doc.activeLayer : s.activeLayer);
+ st.set("active_layer", active ? doc.activeLayer : s.data->activeLayer);
if (hasPaintLayers(doc.partMesh(i)))
st.set("paint_layers", writePaintLayers(w, "parts/" + std::to_string(i) + "/", doc.partMesh(i)));
if (doc.partMesh(i).texture && doc.partMesh(i).texture->width > 0) {
@@ -927,9 +942,9 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erro
st.set("micro", std::move(mj));
version.need(7);
}
- const std::string& bridgeName = active ? doc.bridgeName : s.bridgeName;
+ const std::string& bridgeName = active ? doc.bridgeName : s.data->bridgeName;
if (!bridgeName.empty()) st.set("bridge_name", bridgeName);
- const std::vector<QRemeshGuide>& guides = active ? doc.qremeshGuides : s.qremeshGuides;
+ const std::vector<QRemeshGuide>& guides = active ? doc.qremeshGuides : s.data->qremeshGuides;
if (!guides.empty()) st.set("qremesh_guides", qremeshGuidesToJson(guides)); // (no format change: optional)
if (const Mesh& m = doc.partMesh(i); m.selectionSets && !m.selectionSets->sets.empty())
st.set("selection_sets", writeSelectionSets(w, "parts/" + std::to_string(i) + "/", *m.selectionSets));
@@ -1076,6 +1091,16 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {
s.folder = int(sj["folder"].asNumber(-1));
s.bridgeName = sj["bridge_name"].asString();
s.qremeshGuides = qremeshGuidesFromJson(sj["qremesh_guides"]);
+ if (sj["transform"].isArray()) s.transform = matrixFromJson(sj["transform"]);
+ if (const Json& lj = sj["link"]; lj.isNumber()) {
+ const double l = lj.asNumber(-1);
+ if (!(l >= 0 && l < double(parts.size() - 1)) || parts[size_t(l)].link >= 0) {
+ error = "Project Part link is invalid";
+ return false;
+ }
+ s.link = int(l);
+ continue;
+ }
if (!readMesh(r, sj["mesh"], sj["layers"], s.mesh, error, false, false)) return false;
s.mesh.forgespheres = forgespheresFromJson(sj["forgespheres"]);
s.mesh.forgespherePreview = !s.mesh.forgespheres.empty() && sj["forgesphere_preview"].asBool(false);
@@ -1170,15 +1195,23 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {
doc.qremeshGuides = std::move(parts[0].qremeshGuides);
doc.parts[0].visible = parts[0].visible;
doc.parts[0].shading = parts[0].shading;
+ doc.parts[0].transform = parts[0].transform;
for (size_t i = 1; i < parts.size(); ++i) {
+ if (parts[i].link >= 0) { // shares an earlier Part's mesh (Parts load in order: index i is i here too)
+ const int at = doc.addLink(parts[i].link, parts[i].name, parts[i].transform);
+ doc.parts[size_t(at)].visible = parts[i].visible;
+ doc.parts[size_t(at)].shading = parts[i].shading;
+ continue;
+ }
BVH* builtI = parts[i].finishBvh();
const int at = doc.addPart(std::move(parts[i].mesh), parts[i].name, false, -1, builtI);
Part& s = doc.parts[size_t(at)];
s.visible = parts[i].visible;
s.shading = parts[i].shading;
- s.activeLayer = validLayer(parts[i].activeLayer, s.mesh);
- s.bridgeName = parts[i].bridgeName;
- s.qremeshGuides = std::move(parts[i].qremeshGuides);
+ s.transform = parts[i].transform;
+ s.data->activeLayer = validLayer(parts[i].activeLayer, s.data->mesh);
+ s.data->bridgeName = parts[i].bridgeName;
+ s.data->qremeshGuides = std::move(parts[i].qremeshGuides);
}
// Folders (#96): a Part pointing at a folder that isn't there is simply outside any folder.
if (const Json& folders = manifest["part_folders"]; folders.isArray() && folders.size() <= kMaxProjectParts) {
diff --git a/src/core/Project.h b/src/core/Project.h
index ba15b00d..11ad999a 100644
--- a/src/core/Project.h
+++ b/src/core/Project.h
@@ -26,12 +26,14 @@ namespace sf {
// frames, not world space (format 4 files are converted when they load). 6: levels made by Divide keep no
// triangles, child maps or (where their positions say it) details; older files still load. 7: a Part texture
// may carry material channels (the texture's "pbr" key, core/LayerStackIO.h), and a Part a micro-displacement
-// level ("micro", core/Micro.h); both keys are optional in 7.
+// level ("micro", core/Micro.h); both keys are optional in 7. 8: Linked Duplicates (#94): a Part may share an
+// earlier Part's mesh ("link": that Part's index, no mesh of its own) and have a "transform" (16 numbers,
+// column-major) placing its mesh in the scene.
//
// kProjectVersion is the newest format this build reads. Saving writes the lowest version the content needs
// (ProjectVersionNeed): a project that uses nothing newer than format 6 is still written as 6, so older
// SculptForge versions keep opening it. A feature that needs a newer format calls need(N) while saving.
-constexpr int kProjectVersion = 7;
+constexpr int kProjectVersion = 8;
constexpr int kProjectBaseWriteVersion = 6;
struct ProjectVersionNeed {
int version = kProjectBaseWriteVersion;
diff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cpp
index 1c8ab00d..dff3f5a5 100644
--- a/src/core/RetopoCommands.cpp
+++ b/src/core/RetopoCommands.cpp
@@ -49,7 +49,8 @@ std::string applyQRemesh(Document& doc, Mesh result, bool keepOriginal, const QR
const int at = doc.activePart + 1;
doc.addPart(doc.mesh, active.name + " Original", false, at);
doc.parts[size_t(at)].visible = false;
- doc.parts[size_t(at)].qremeshGuides = doc.qremeshGuides; // to remesh it again with them
+ doc.parts[size_t(at)].data->qremeshGuides = doc.qremeshGuides; // to remesh it again with them
+ doc.parts[size_t(at)].transform = active.transform;
}
doc.replaceMeshUndoable(std::move(result), "Quad Remesh");
const size_t faces = st.quads + st.triangles;
diff --git a/src/core/Sculptable.cpp b/src/core/Sculptable.cpp
index 96a066a6..95fe416d 100644
--- a/src/core/Sculptable.cpp
+++ b/src/core/Sculptable.cpp
@@ -1428,7 +1428,7 @@ std::string applySculptable(Document& doc, SculptableResult& res, bool keepScan)
if (keepScan) {
const int s = doc.addPart(std::move(res.scan), doc.uniquePartName(base + " Scan"), false);
doc.parts[size_t(s)].visible = false;
- doc.parts[size_t(s)].qremeshGuides = res.guides;
+ doc.parts[size_t(s)].data->qremeshGuides = res.guides;
}
const std::string report = res.report();
doc.addPart(std::move(res.mesh), doc.uniquePartName(base), true);
diff --git a/src/core/Timeline.cpp b/src/core/Timeline.cpp
index 7ac98bb4..59bd67d2 100644
--- a/src/core/Timeline.cpp
+++ b/src/core/Timeline.cpp
@@ -951,7 +951,10 @@ bool saveHistorySidecar(Document& doc, const std::string& projectPath, std::stri
std::vector<uint8_t> body;
Writer wb{body};
for (int i = 0; i < doc.partCount(); ++i) {
- UndoStack& stack = i == doc.activePart ? doc.undo : doc.parts[size_t(i)].undo;
+ bool shared = false; // a linked copy: its history (the group's) is saved with the group's first Part
+ for (int k = 0; k < i; ++k) shared |= doc.parts[size_t(k)].data == doc.parts[size_t(i)].data;
+ if (shared) continue;
+ UndoStack& stack = doc.partUndo(i);
Timeline* t = Timeline::of(stack);
if (!t) continue;
t->bindStack(stack);
diff --git a/src/core/TransformCommands.cpp b/src/core/TransformCommands.cpp
index 58a027b2..16df8f58 100644
--- a/src/core/TransformCommands.cpp
+++ b/src/core/TransformCommands.cpp
@@ -3,6 +3,7 @@
//
// The `transform` command (core/MeshTransform.h): what a Transform gizmo drag does, for scripts, the console and AI.
#include "core/Commands.h"
+#include "core/Document.h"
#include "core/MeshTransform.h"
#include "core/PathStroke.h"
@@ -75,9 +76,15 @@ CommandResult runTransform(Document& doc, const Args& a) {
}
std::vector<int> targets;
- for (int i = 0; i < doc.partCount(); ++i)
- if (i == doc.activePart || (doc.parts[size_t(i)].visible && (all || (folder && doc.parts[size_t(i)].folder == folder))))
- targets.push_back(i);
+ for (int i = 0; i < doc.partCount(); ++i) {
+ const Part& s = doc.parts[size_t(i)];
+ if (!(i == doc.activePart || (s.visible && (all || (folder && s.folder == folder))))) continue;
+ // Linked copies (#94) share one mesh: a masked edit of it happens once.
+ const bool again = std::any_of(targets.begin(), targets.end(),
+ [&](int k) { return doc.parts[size_t(k)].data == s.data; });
+ if (again && !partMovesWhole(doc, i, useMask)) continue;
+ targets.push_back(i);
+ }
MeshTransform t;
t.translate = translate;
@@ -91,7 +98,10 @@ CommandResult runTransform(Document& doc, const Args& a) {
const Mesh& m = doc.partMesh(i);
if (m.vertexCount() == 0) continue;
const AABB b = transformBounds(m, transformWeights(m, useMask, falloff));
- if (b.valid()) box.expand(b);
+ const glm::mat4& place = doc.parts[size_t(i)].transform; // (where a linked copy is)
+ for (int c = 0; c < 8 && b.valid(); ++c)
+ box.expand(glm::vec3(place * glm::vec4(c & 1 ? b.max.x : b.min.x, c & 2 ? b.max.y : b.min.y,
+ c & 4 ? b.max.z : b.min.z, 1.0f)));
}
t.pivot = box.valid() ? box.center() : glm::vec3(0.0f);
} else if (pivot == "origin") {
diff --git a/src/io/BridgeCommands.cpp b/src/io/BridgeCommands.cpp
index c0d2f21a..efe22d28 100644
--- a/src/io/BridgeCommands.cpp
+++ b/src/io/BridgeCommands.cpp
@@ -41,7 +41,7 @@ std::string sendName(const Document& doc, const Args& a) {
} // namespace
std::string& partBridgeName(Document& doc, int i) {
- return i == doc.activePart ? doc.bridgeName : doc.parts[size_t(i)].bridgeName;
+ return doc.checkedOut(i) ? doc.bridgeName : doc.parts[size_t(i)].data->bridgeName;
}
std::vector<MeshObjectRef> bridgeObjects(Document& doc, std::vector<int>& indices) {
diff --git a/src/io/GltfIO.cpp b/src/io/GltfIO.cpp
index be1715a1..b668c394 100644
--- a/src/io/GltfIO.cpp
+++ b/src/io/GltfIO.cpp
@@ -154,8 +154,27 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
return accessorCount++;
};
- // One node and one mesh per object, each with its own morph targets.
+ // One node and one mesh per object, each with its own morph targets. A linked copy (#94, instanceOf) is a
+ // node of its own, placed by its matrix, reusing the first one's mesh.
+ std::vector<int> meshOf(objects.size(), -1);
+ int meshCount = 0;
+ auto addNode = [&](size_t oi) {
+ nodes << (oi ? "," : "") << "{\"mesh\":" << meshOf[oi] << ",\"name\":\"" << jsonEscape(objects[oi].name) << "\"";
+ if (objects[oi].transform != glm::mat4(1.0f)) {
+ std::ostringstream m;
+ m.precision(9);
+ for (int i = 0; i < 16; ++i) m << (i ? "," : "") << glm::value_ptr(objects[oi].transform)[i];
+ nodes << ",\"matrix\":[" << m.str() << "]";
+ }
+ nodes << "}";
+ };
for (size_t oi = 0; oi < objects.size(); ++oi) {
+ if (const int first = objects[oi].instanceOf; first >= 0 && size_t(first) < oi && meshOf[size_t(first)] >= 0) {
+ meshOf[oi] = meshOf[size_t(first)];
+ addNode(oi);
+ continue;
+ }
+ meshOf[oi] = meshCount++;
const Mesh& mesh = *objects[oi].mesh;
const std::string& name = objects[oi].name;
// Base shape and its normals.
@@ -252,9 +271,9 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
materials << "}";
}
- nodes << (oi ? "," : "") << "{\"mesh\":" << oi << ",\"name\":\"" << jsonEscape(name) << "\"}";
+ addNode(oi);
std::ostringstream& json = meshes; // this object's entry in "meshes"
- json << (oi ? "," : "") << "{\"name\":\"" << jsonEscape(name) << "\",\"primitives\":[{\"attributes\":{\"POSITION\":"
+ json << (meshOf[oi] ? "," : "") << "{\"name\":\"" << jsonEscape(name) << "\",\"primitives\":[{\"attributes\":{\"POSITION\":"
<< posAcc << ",\"NORMAL\":" << nrmAcc;
if (colors) json << ",\"COLOR_0\":" << colorAcc;
if (uvs) json << ",\"TEXCOORD_0\":" << uvAcc;
diff --git a/src/io/MayaCommands.cpp b/src/io/MayaCommands.cpp
index 4767e5df..431ef4db 100644
--- a/src/io/MayaCommands.cpp
+++ b/src/io/MayaCommands.cpp
@@ -10,7 +10,7 @@ namespace sf {
size_t mayaDropUnchanged(const Document& doc, std::vector<MeshObject>& objects) {
return std::erase_if(objects, [&](const MeshObject& o) {
for (int i = 0; i < doc.partCount(); ++i) {
- const std::string& bridge = i == doc.activePart ? doc.bridgeName : doc.parts[size_t(i)].bridgeName;
+ const std::string& bridge = doc.checkedOut(i) ? doc.bridgeName : doc.parts[size_t(i)].data->bridgeName;
if (bridge == o.name) return mayaMeshesMatch(doc.partMesh(i), o.mesh);
}
return false;
diff --git a/src/io/MeshObject.h b/src/io/MeshObject.h
index 2d8d62bf..86fc7d17 100644
--- a/src/io/MeshObject.h
+++ b/src/io/MeshObject.h
@@ -8,6 +8,7 @@
#include "core/Mesh.h"
+#include <memory>
#include <string>
#include <vector>
@@ -19,10 +20,16 @@ struct MeshObject {
Mesh mesh;
};
-// An object to write: its name and a mesh owned by the caller.
+// An object to write: its name and a mesh owned by the caller (or by `owned`, e.g. a copy placed in the scene).
+// Exporters that know instancing (glTF, USD) may get `transform` (where the mesh goes in the scene) and
+// `instanceOf` (the index of an earlier object with the same mesh: a linked copy, #94); the others always get
+// placed meshes (identity, -1).
struct MeshObjectRef {
std::string name;
const Mesh* mesh = nullptr;
+ glm::mat4 transform{1.0f};
+ int instanceOf = -1;
+ std::shared_ptr<const Mesh> owned{};
};
} // namespace sf
diff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cpp
index 66bf0084..35accb25 100644
--- a/src/io/UsdIO.cpp
+++ b/src/io/UsdIO.cpp
@@ -197,8 +197,25 @@ void writeSelectionSets(Writer& w, const Mesh& mesh, std::vector<uint32_t> triFa
}
// One mesh prim `prim` under the root (a SkelRoot holding the Mesh when it has blend shapes).
+// xformOp:transform and its order for a prim placed by `m` (nothing for the identity).
+void writeTransform(Writer& w, const glm::mat4& m, bool always = false) {
+ if (m == glm::mat4(1.0f) && !always) return;
+ w.indent();
+ w.s += "matrix4d xformOp:transform = (";
+ for (int col = 0; col < 4; ++col) { // USD rows are glm columns (row-vector convention)
+ w.s += col ? ", (" : "(";
+ for (int r = 0; r < 4; ++r) {
+ if (r) w.s += ", ";
+ w.num(m[col][r]);
+ }
+ w.s += ')';
+ }
+ w.s += ")\n";
+ w.line("uniform token[] xformOpOrder = [\"xformOp:transform\"]");
+}
+
void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::string& prim, const std::string& material,
- const MorphAnimation* animation) {
+ const MorphAnimation* animation, const glm::mat4& transform = glm::mat4(1.0f)) {
const bool skinned = !mesh.layers.empty();
const std::string meshPath = skinned ? "/" + root + "/" + prim + "/Mesh" : "/" + root + "/" + prim;
// Unique, valid names for the blend shapes.
@@ -217,13 +234,17 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::
base.rebuildTopology();
base.recomputeAllNormals();
- if (skinned) w.open("def SkelRoot \"" + prim + "\"");
+ if (skinned) {
+ w.open("def SkelRoot \"" + prim + "\"");
+ writeTransform(w, transform);
+ }
w.line("def Mesh \"" + (skinned ? std::string("Mesh") : prim) + "\" (");
w.line(skinned ? " prepend apiSchemas = [\"SkelBindingAPI\", \"MaterialBindingAPI\"]"
: " prepend apiSchemas = [\"MaterialBindingAPI\"]");
w.line(")");
w.line("{");
++w.depth;
+ if (!skinned) writeTransform(w, transform);
writeExtent(w, base.bounds());
// Quads where the mesh keeps them (Mesh::quadPartners), else triangles; UVs per face corner in the same
// order (a quad split by a UV seam along its diagonal is written as two triangles).
@@ -353,20 +374,7 @@ void writeSplats(Writer& w, const SplatCloud& c) {
w.line("uniform int radiance:sphericalHarmonicsDegree = " + std::to_string(c.shDegree));
w.array("float3[] scales", c.scales, [&](const glm::vec3& v) { w.vec3(v); });
w.line("uniform token sortingModeHint = \"zDepth\"");
- if (c.transform != glm::mat4(1.0f)) {
- w.indent();
- w.s += "matrix4d xformOp:transform = (";
- for (int col = 0; col < 4; ++col) { // USD rows are glm columns (row-vector convention)
- w.s += col ? ", (" : "(";
- for (int r = 0; r < 4; ++r) {
- if (r) w.s += ", ";
- w.num(c.transform[col][r]);
- }
- w.s += ')';
- }
- w.s += ")\n";
- w.line("uniform token[] xformOpOrder = [\"xformOp:transform\"]");
- }
+ writeTransform(w, c.transform);
w.close();
}
@@ -514,6 +522,7 @@ std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vecto
std::set<std::string> used = {"Materials", "Splats"};
std::vector<std::pair<std::string, std::string>> textured; // material name, texture
std::vector<size_t> texturedMesh; // which mesh each textured material is for
+ std::vector<std::string> prims; // by mesh
for (size_t i = 0; i < meshes.size(); ++i) {
const MeshObjectRef& m = meshes[i];
std::string prim = "Sculpt";
@@ -523,13 +532,28 @@ std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vecto
for (int k = 2; used.count(prim); ++k) prim = base + "_" + std::to_string(k);
}
used.insert(prim);
+ prims.push_back(prim);
+ // A linked copy (#94): an instanceable prim referencing the first one's (its mesh, material and
+ // blend shapes), placed by its own transform. Readers that instance load the mesh once.
+ if (m.instanceOf >= 0 && size_t(m.instanceOf) < i) {
+ w.line("def \"" + prim + "\" (");
+ w.line(" instanceable = true");
+ w.line(" prepend references = </" + root + "/" + prims[size_t(m.instanceOf)] + ">");
+ w.line(")");
+ w.line("{");
+ ++w.depth;
+ writeTransform(w, m.transform, true); // (always: else the referenced prim's own would apply)
+ w.close();
+ w.s += '\n';
+ continue;
+ }
std::string material = mixed && m.mesh->hasColors() ? paintedClay : clay;
if (!textures[i].empty()) {
textured.push_back({prim + "_Material", textures[i]});
texturedMesh.push_back(i);
material = "/" + root + "/Materials/" + textured.back().first;
}
- writeMesh(w, *m.mesh, root, prim, material, animation);
+ writeMesh(w, *m.mesh, root, prim, material, animation, m.transform);
w.s += '\n';
}
w.open("def Scope \"Materials\"");
@@ -649,6 +673,7 @@ struct Value {
struct Prim {
std::string type, path;
+ std::string reference; // an internal reference's target path (metadata `references = </path>`)
bool abstract = false;
int parent = -1;
std::map<std::string, Value> attrs;
@@ -703,6 +728,31 @@ private:
} while (level > 0);
}
+ // A prim's metadata: only an internal reference is kept (`[prepend] references = </path>` or `[</path>]`).
+ void parsePrimMetadata(Prim& prim) {
+ advance();
+ while (tok_.kind != Token::End && !isPunct(")")) {
+ if (isIdent("references")) {
+ advance();
+ if (isPunct("=")) advance();
+ if (isPunct("[")) {
+ advance();
+ if (tok_.kind == Token::Path) prim.reference = std::string(tok_.text);
+ while (tok_.kind != Token::End && !isPunct("]")) advance();
+ advance();
+ } else {
+ if (tok_.kind == Token::Path) prim.reference = std::string(tok_.text);
+ advance();
+ }
+ } else if (isPunct("(") || isPunct("[") || isPunct("{")) {
+ skipBalanced();
+ } else {
+ advance();
+ }
+ }
+ advance(); // ')'
+ }
+
void parseLayerMetadata() {
advance();
while (tok_.kind != Token::End && !isPunct(")")) {
@@ -790,7 +840,7 @@ private:
prim.parent = parent;
prim.abstract = abstract;
advance();
- if (isPunct("(")) skipBalanced();
+ if (isPunct("(")) parsePrimMetadata(prim);
if (!expect("{")) return false;
const int index = int(prims.size());
prims.push_back(std::move(prim));
@@ -1001,6 +1051,43 @@ const Prim* skelAnimation(const std::vector<Prim>& prims, const std::map<std::st
return nullptr;
}
+// Internal references (SculptForge writes linked copies, #94, as instanceable prims referencing the first one): a
+// referencing prim gets the referenced prim's type, properties (its own win) and children, with paths inside it
+// moved under the referencing prim. One level; a reference to itself, an ancestor or a descendant is ignored.
+void expandInternalReferences(std::vector<Prim>& prims, std::map<std::string, size_t>& byPath) {
+ const size_t original = prims.size();
+ for (size_t i = 0; i < original; ++i) {
+ if (prims[i].reference.empty()) continue;
+ const auto it = byPath.find(prims[i].reference);
+ if (it == byPath.end() || it->second >= original) continue;
+ const size_t r = it->second;
+ const std::string from = prims[r].path, to = prims[i].path;
+ if (from == to || to.rfind(from + "/", 0) == 0 || from.rfind(to + "/", 0) == 0) continue;
+ auto moved = [&](Value v) {
+ for (auto& s : v.strs)
+ if (s == from || s.rfind(from + "/", 0) == 0) s = to + s.substr(from.size());
+ return v;
+ };
+ if (prims[i].type.empty()) prims[i].type = prims[r].type;
+ for (const auto& [name, value] : prims[r].attrs) prims[i].attrs.try_emplace(name, moved(value));
+ std::map<size_t, size_t> cloneOf{{r, i}}; // referenced prim -> its copy
+ for (size_t q = r + 1; q < original && prims[q].path.rfind(from + "/", 0) == 0; ++q) {
+ const auto parent = cloneOf.find(size_t(prims[q].parent));
+ if (parent == cloneOf.end()) continue;
+ Prim c;
+ c.type = prims[q].type;
+ c.path = to + prims[q].path.substr(from.size());
+ c.abstract = prims[q].abstract || prims[i].abstract;
+ c.parent = int(parent->second);
+ for (const auto& [name, value] : prims[q].attrs) c.attrs.emplace(name, moved(value));
+ if (byPath.count(c.path)) continue; // (the referencing prim has a child of that name already)
+ cloneOf[q] = prims.size();
+ byPath[c.path] = prims.size();
+ prims.push_back(std::move(c));
+ }
+ }
+}
+
// Merges every Mesh prim into one object, or (split) makes one object per prim.
bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>& outMeshes, SplatCloud& outSplats,
std::string& error) {
@@ -1012,6 +1099,7 @@ bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>&
auto& prims = parser.prims;
std::map<std::string, size_t> byPath;
for (size_t i = 0; i < prims.size(); ++i) byPath[prims[i].path] = i;
+ expandInternalReferences(prims, byPath);
// World transforms (parents come first in `prims`), Y up, in the stage's unit. Mesh points go to metres through
// double (fromFileUnits), so 12.7 cm is the float nearest 0.127 m; splats take the unit in their transform.
@@ -1249,8 +1337,14 @@ bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splats
bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshesIn, const SplatCloud* splats,
const std::string& name, std::string& error, const MorphAnimation* animation) {
std::vector<MeshObjectRef> meshes;
- for (const auto& m : meshesIn)
- if (m.mesh && m.mesh->triangleCount() > 0) meshes.push_back(m);
+ std::vector<int> kept(meshesIn.size(), -1); // (instanceOf names an index of meshesIn)
+ for (size_t i = 0; i < meshesIn.size(); ++i) {
+ const auto& m = meshesIn[i];
+ if (!m.mesh || m.mesh->triangleCount() == 0) continue;
+ kept[i] = int(meshes.size());
+ meshes.push_back(m);
+ if (m.instanceOf >= 0) meshes.back().instanceOf = size_t(m.instanceOf) < i ? kept[size_t(m.instanceOf)] : -1;
+ }
const bool hasSplats = splats && !splats->empty();
if (meshes.empty() && !hasSplats) {
error = "Nothing to export";
@@ -1268,7 +1362,9 @@ bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshesIn
return false;
}
// Textures: PNGs inside a .usdz package, else beside the layer; asset paths are relative to the layer.
- const std::vector<std::string> pngs = textureFileNames(path, meshes);
+ std::vector<std::string> pngs = textureFileNames(path, meshes);
+ for (size_t i = 0; i < meshes.size(); ++i)
+ if (meshes[i].instanceOf >= 0) pngs[i].clear(); // (a linked copy uses the first one's material)
// Material channel maps (PBR slots) per textured mesh, named after its colour PNG.
std::vector<std::vector<PbrPng>> pbrPngs(meshes.size());
std::vector<std::vector<std::pair<std::string, std::string>>> pbr(meshes.size());
diff --git a/src/render/Camera.cpp b/src/render/Camera.cpp
index f41e2968..da2518c0 100644
--- a/src/render/Camera.cpp
+++ b/src/render/Camera.cpp
@@ -107,6 +107,18 @@ void Camera::screenRay(float x, float y, float width, float height, glm::vec3& o
dir = forward();
}
+Camera Camera::inSpaceOf(const glm::mat4& place) const {
+ if (place == glm::mat4(1.0f)) return *this;
+ const float s = glm::length(glm::vec3(place[0]));
+ if (!(s > 0.0f) || !std::isfinite(s)) return *this;
+ const glm::mat3 r = glm::mat3(place) / s;
+ Camera c = *this;
+ c.target = glm::vec3(glm::inverse(place) * glm::vec4(target, 1.0f));
+ c.distance = distance / s;
+ c.setOrientation(glm::quat_cast(glm::transpose(r)) * orientation());
+ return c;
+}
+
float Camera::worldPerPixel(const glm::vec3& point, float viewportHeight) const {
if (ortho) return 2.0f * distance * std::tan(fovY * 0.5f) / std::max(viewportHeight, 1.0f);
float depth = std::max(glm::dot(point - position(), forward()), nearPlane());
diff --git a/src/render/Camera.h b/src/render/Camera.h
index a249a162..daafea69 100644
--- a/src/render/Camera.h
+++ b/src/render/Camera.h
@@ -40,6 +40,10 @@ public:
// Ray through a window coordinate (origin top-left).
void screenRay(float x, float y, float width, float height, glm::vec3& origin, glm::vec3& dir) const;
+ // The same view as seen from a space placed by `place` (a similarity: rotation, translation, uniform scale;
+ // e.g. a linked Part's transform): view() becomes view() * place up to a uniform scale, which the projection
+ // ignores, so rays, projections and pixel sizes in that space match the view's.
+ Camera inSpaceOf(const glm::mat4& place) const;
// World units covered by one window pixel at the depth of `point`.
float worldPerPixel(const glm::vec3& point, float viewportHeight) const;
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index 6decf6bc..df65300f 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -1542,13 +1542,35 @@ void Renderer::syncScene(const std::vector<SceneMesh>& scene) {
}
drawList_.clear();
proxyPending_ = false;
+ std::vector<uint32_t> synced; // linked Parts (#94): one mesh, uploaded once (as the active one, if it's one of them)
for (const SceneMesh& m : scene) {
if (!m.visible || !m.mesh) continue; // hidden: keeps its dirty state until shown
- MeshSlot& ms = slot(m.id);
- ms.overlay = m.active ? m.overlay : nullptr;
- sync(ms, *m.mesh, m.normalMap, m.wireframe && m.active, m.pbr);
- drawList_.push_back({m.id, m.active, m.flat});
+ if (std::find(synced.begin(), synced.end(), m.id) == synced.end()) {
+ synced.push_back(m.id);
+ const SceneMesh* first = &m;
+ for (const SceneMesh& o : scene)
+ if (o.id == m.id && o.visible && o.active) first = &o;
+ MeshSlot& ms = slot(m.id);
+ ms.overlay = first->active ? first->overlay : nullptr;
+ sync(ms, *first->mesh, first->normalMap, first->wireframe && first->active, first->pbr);
+ }
+ drawList_.push_back({m.id, m.active, m.flat, m.model != glm::mat4(1.0f), m.model});
+ }
+}
+
+void Renderer::drawItem(const MeshSlot& s, const DrawItem& item, const RenderSettings& settings) {
+ if (!item.moved) {
+ drawSlot(s, item.active, item.flat, settings);
+ return;
}
+ const glm::mat4 view = frameView_;
+ const CullView cull = frameCull_;
+ frameView_ = view * item.model;
+ frameCull_ = CullView::from(frameView_, frameProj_);
+ frameCull_.backfaces = cull.backfaces;
+ drawSlot(s, item.active, item.flat, settings);
+ frameView_ = view;
+ frameCull_ = cull;
}
// The packed vertices of dirtyRuns_ (all of them when `full`, which also sizes the buffer). A vertex that left
@@ -3078,7 +3100,7 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
drawAlpha_ = 1.0f;
for (const DrawItem& item : drawList_)
if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0 && !seeThrough(item))
- drawSlot(*s, item.active, item.flat, settings);
+ drawItem(*s, item, settings);
drawMark(2);
if (xray) {
gl::Enable(GL_BLEND);
@@ -3090,13 +3112,13 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
gl::ColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
for (const DrawItem& item : drawList_)
if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0 && seeThrough(item))
- drawSlot(*s, item.active, item.flat, settings);
+ drawItem(*s, item, settings);
gl::ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
gl::DepthMask(GL_FALSE);
drawAlpha_ = opacity;
for (const DrawItem& item : drawList_)
if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0 && seeThrough(item))
- drawSlot(*s, item.active, item.flat, settings);
+ drawItem(*s, item, settings);
} else {
// The lone active Part: its back faces first, then its front faces over them, so its far side and
// insides show through in order (exact for a convex Part, close for the rest).
@@ -3107,7 +3129,7 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
xrayCull_ = cull;
for (const DrawItem& item : drawList_)
if (const MeshSlot* s = findSlot(item.id); s && s->drawnTriangles > 0)
- drawSlot(*s, item.active, item.flat, settings);
+ drawItem(*s, item, settings);
}
xrayCull_ = 0;
keepBackfaces_ = false;
@@ -3130,9 +3152,10 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
if (settings.wireframe) { // the active Part only
// Two programs: edge lists fade their sub-pixel edges (kWireLineGS); triangle outlines draw as before.
+ glm::mat4 wireView = view; // the item's (view * model for a moved linked copy)
auto use = [&](GLuint prog, const MeshSlot& slot) {
gl::UseProgram(prog);
- gl::UniformMatrix4fv(gl::GetUniformLocation(prog, "uView"), 1, GL_FALSE, glm::value_ptr(view));
+ gl::UniformMatrix4fv(gl::GetUniformLocation(prog, "uView"), 1, GL_FALSE, glm::value_ptr(wireView));
gl::UniformMatrix4fv(gl::GetUniformLocation(prog, "uProj"), 1, GL_FALSE, glm::value_ptr(proj));
gl::Uniform3fv(gl::GetUniformLocation(prog, "uGridOrigin"), 1, glm::value_ptr(slot.grid.origin));
gl::Uniform1f(gl::GetUniformLocation(prog, "uGridStep"), slot.grid.step);
@@ -3146,6 +3169,9 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
for (const DrawItem& item : drawList_) {
const MeshSlot* s = item.active ? findSlot(item.id) : nullptr;
if (!s || s->drawnTriangles == 0 || s->micro) continue; // (micro levels: drawMicro draws theirs)
+ wireView = item.moved ? view * item.model : view; // (a linked copy, #94)
+ const CullView frameCull = frameCull_;
+ if (item.moved) frameCull_ = CullView::from(wireView, proj);
cull(*s, frameCull_);
if (!s->patches.empty() && s->patchVao) { // dynamic topology's patches
const bool lines = s->patchLinesOn;
@@ -3167,6 +3193,7 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
drawClusters(*s, drawClusters_, GL_TRIANGLES, DrawPart::Triangles, -1);
gl::PolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
+ frameCull_ = frameCull;
}
gl::DepthMask(GL_TRUE);
gl::Disable(GL_BLEND);
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index 3b1d9145..8f1322cd 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -116,7 +116,9 @@ struct MeshOverlay {
float checkerScale = 8.0f; // checker squares per UV unit
};
-// One mesh of the scene for Renderer::syncScene: a Part, keyed by its stable id.
+// One mesh of the scene for Renderer::syncScene: a Part, keyed by its stable id. Linked Parts (#94) share one
+// mesh: they come with the same id (their PartData key) and their own `model` matrices, and are drawn from one
+// GPU slot, uploaded once.
struct SceneMesh {
uint32_t id = 0;
Mesh* mesh = nullptr;
@@ -128,6 +130,7 @@ struct SceneMesh {
bool flat = false; // flat shading: each triangle shows its own face normal (faceted)
bool pbr = false; // the view shades PBR: upload the texture's material channels and their tangents
const MeshOverlay* overlay = nullptr; // the UV Editor's view of the active mesh (must outlive the frame)
+ glm::mat4 model{1.0f}; // where the mesh is in the scene (Part::transform)
};
// Part of the target the 3D view is drawn into (framebuffer pixels, origin bottom-left); the rest is
@@ -572,7 +575,11 @@ private:
uint32_t id;
bool active;
bool flat;
+ bool moved = false; // drawn with `model` (a linked copy, #94)
+ glm::mat4 model{1.0f};
};
+ // drawSlot for `item`: with its model matrix in the frame's view and culling (restored after).
+ void drawItem(const MeshSlot& s, const DrawItem& item, const RenderSettings& settings);
std::vector<DrawItem> drawList_; // visible meshes, in scene order
std::vector<uint32_t> visibleGroups_; // scratch for uploadFaces
std::vector<glm::vec2> visibleUvs_; // scratch for uploadFaces
diff --git a/tests/test_blender_bridge.cpp b/tests/test_blender_bridge.cpp
index 6bd8a71d..05a93d2f 100644
--- a/tests/test_blender_bridge.cpp
+++ b/tests/test_blender_bridge.cpp
@@ -146,7 +146,7 @@ TEST(blender_bridge_round_trip) {
CHECK(r.ok && r.message.find("Received 2 objects") != std::string::npos);
CHECK(doc.partCount() == 2 && doc.activePart == 0);
CHECK(doc.parts[0].name == "Cube" && doc.bridgeName == "Cube");
- CHECK(doc.parts[1].name == "Ball ü" && doc.parts[1].bridgeName == "Ball ü");
+ CHECK(doc.parts[1].name == "Ball ü" && doc.parts[1].data->bridgeName == "Ball ü");
CHECK(doc.mesh.quadCount() == cube.quadCount() && doc.mesh.quadCount() > 0);
CHECK(doc.partMesh(1).facegroups.size() == ball.triangleCount() && doc.partMesh(1).hasUvs());
// Placed as in Blender's scene: p_sf = A * M_blender * A^-1 * p.
diff --git a/tests/test_bridge.cpp b/tests/test_bridge.cpp
index b64e3ce5..d7c16a34 100644
--- a/tests/test_bridge.cpp
+++ b/tests/test_bridge.cpp
@@ -315,7 +315,7 @@ TEST(bridge_bridge_send_and_receive) {
CHECK(r.ok && r.message.find("Sphere_1") != std::string::npos);
CHECK(back.partCount() == 2 && back.activePart == 0);
CHECK(back.parts[0].name == "Sphere_1" && back.bridgeName == "Sphere_1");
- CHECK(back.parts[1].name == "Other" && back.parts[1].bridgeName == "Other");
+ CHECK(back.parts[1].name == "Other" && back.parts[1].data->bridgeName == "Other");
CHECK(back.mesh.vertexCount() == m.vertexCount() && back.mesh.triangleCount() == m.triangleCount());
CHECK(back.partMesh(1).triangleCount() == second.triangleCount());
CHECK(back.mesh.mask.size() == back.mesh.vertexCount() && back.mesh.facegroups.size() == back.mesh.triangleCount());
diff --git a/tests/test_face.cpp b/tests/test_face.cpp
index f9cd75fb..ae186270 100644
--- a/tests/test_face.cpp
+++ b/tests/test_face.cpp
@@ -348,10 +348,10 @@ TEST(face_parts_eyes_and_teeth) {
teeth.recomputeAllNormals();
doc.addPart(teeth, "Teeth", false);
doc.addPart(makeIcosphere(2, 0.5f), "Far away ball", false);
- for (auto& p : doc.parts[3].mesh.positions) p += glm::vec3(3, 0, 0);
+ for (auto& p : doc.parts[3].data->mesh.positions) p += glm::vec3(3, 0, 0);
CHECK(run(doc, "face_shapes_generate").ok);
- const Mesh& em = doc.parts[1].mesh;
+ const Mesh& em = doc.parts[1].data->mesh;
const SculptLayer* up = findLayer(em, "eyeLookUpLeft");
const SculptLayer* out = findLayer(em, "eyeLookOutLeft");
CHECK(up && out && em.layers.size() == 8);
@@ -368,7 +368,7 @@ TEST(face_parts_eyes_and_teeth) {
CHECK(out->delta[front].x > 0.003f); // looking out = towards the character's left
CHECK(up->delta[rightFront] == glm::vec3(0.0f));
}
- const Mesh& tm = doc.parts[2].mesh;
+ const Mesh& tm = doc.parts[2].data->mesh;
const SculptLayer* jaw = findLayer(tm, "jawOpen");
CHECK(jaw != nullptr);
if (jaw) {
@@ -382,12 +382,12 @@ TEST(face_parts_eyes_and_teeth) {
CHECK(upperMove == 0.0f);
}
CHECK(findLayer(tm, "eyeBlinkLeft") == nullptr); // teeth only get the jaw shapes
- CHECK(doc.parts[3].mesh.layers.empty()); // not on the face: left alone
+ CHECK(doc.parts[3].data->mesh.layers.empty()); // not on the face: left alone
// face_weights drives every Part: the eyes turn with eyeLookUpLeft.
- const auto eyesBefore = doc.parts[1].mesh.positions;
+ const auto eyesBefore = doc.parts[1].data->mesh.positions;
CHECK(run(doc, "face_weights", {{"json", std::string("{\"eyeLookUpLeft\":1,\"jawOpen\":0.5}")}}).ok);
- CHECK(doc.parts[1].mesh.positions != eyesBefore);
+ CHECK(doc.parts[1].data->mesh.positions != eyesBefore);
}
TEST(face_weights_fast_path_is_exact_and_not_undoable) {
diff --git a/tests/test_linked_duplicate.cpp b/tests/test_linked_duplicate.cpp
new file mode 100644
index 00000000..ba32cb2c
--- /dev/null
+++ b/tests/test_linked_duplicate.cpp
@@ -0,0 +1,327 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Linked Duplicates (#94): Parts sharing one mesh (PartData), each placed by its own transform. Sculpting any of
+// them changes all, undo is shared, Make Unique breaks the link, deleting one keeps the others; the transform
+// command moves a linked copy as a whole; projects keep the links; exports instance (glTF, USD) or flatten (OBJ).
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Json.h"
+#include "core/Parts.h"
+#include "core/Project.h"
+#include "io/GltfIO.h"
+#include "io/ObjIO.h"
+#include "io/UsdIO.h"
+#include "io/Zip.h"
+#include "render/Camera.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <cmath>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+using namespace sf;
+
+namespace {
+
+bool near(const glm::vec3& a, const glm::vec3& b, float eps = 1e-4f) { return glm::length(a - b) < eps; }
+
+// A sphere "Body" and its linked copy "Body link" (active), 3 units along +X.
+Document linkedScene(CommandRegistry& reg) {
+ Document doc;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);
+ CHECK(reg.execute(doc, "part_rename", {{"to", std::string("Body")}}).ok);
+ const CommandResult r = reg.execute(doc, "part_duplicate_linked", {{"offset", std::string("3,0,0")}});
+ CHECK(r.ok);
+ return doc;
+}
+
+// A stroke on the active Part at the top of its sphere, in scene coordinates (looking down).
+CommandResult strokeTop(CommandRegistry& reg, Document& doc) {
+ const AABB b = doc.partBounds(doc.activePart);
+ const glm::vec3 c = b.center();
+ const float y = b.max.y + 0.5f;
+ char points[160];
+ std::snprintf(points, sizeof points, "%g,%g,%g %g,%g,%g", double(c.x - 0.2f), double(y), double(c.z),
+ double(c.x + 0.2f), double(y), double(c.z));
+ return reg.execute(doc, "stroke", {{"points", std::string(points)}, {"view", std::string("0,-1,0")},
+ {"brush", std::string("Clay")}, {"radius", 0.3}, {"strength", 1.0}});
+}
+
+std::string readText(const std::string& path) {
+ std::ifstream f(std::filesystem::path(path), std::ios::binary);
+ std::stringstream s;
+ s << f.rdbuf();
+ return s.str();
+}
+
+size_t countOf(const std::string& text, const std::string& what) {
+ size_t n = 0;
+ for (size_t at = text.find(what); at != std::string::npos; at = text.find(what, at + what.size())) ++n;
+ return n;
+}
+
+} // namespace
+
+TEST(linked_duplicate_shares_mesh_and_history) {
+ CommandRegistry reg;
+ Document doc = linkedScene(reg);
+ CHECK(doc.partCount() == 2 && doc.activePart == 1);
+ CHECK(doc.activePartInfo().name == "Body link");
+ CHECK(doc.linkCount(0) == 2 && doc.linkCount(1) == 2);
+ CHECK(doc.meshKey(0) == doc.meshKey(1)); // one GPU mesh
+ CHECK(&doc.partMesh(0) == &doc.partMesh(1)); // one mesh: the checked-out one
+ CHECK(near(glm::vec3(doc.parts[1].transform[3]), glm::vec3(3, 0, 0)));
+ CHECK(!doc.parts[0].moved() && doc.parts[1].moved());
+ CHECK(near(doc.partBounds(1).center(), doc.partBounds(0).center() + glm::vec3(3, 0, 0), 1e-3f));
+ CHECK(reg.execute(doc, "part_list").message.find("linked x2") != std::string::npos);
+
+ // A stroke on the copy (in scene space, where the copy is) changes the one mesh both show.
+ const std::vector<glm::vec3> before = doc.mesh.positions;
+ CHECK(strokeTop(reg, doc).ok);
+ CHECK(doc.mesh.positions != before);
+ const std::vector<glm::vec3> after = doc.mesh.positions;
+ // It landed on the top of the sphere in its own space (the scene point, moved back by the copy's transform).
+ size_t movedTop = 0, movedElsewhere = 0;
+ for (size_t v = 0; v < before.size(); ++v)
+ if (before[v] != after[v]) (before[v].y > 0.5f ? movedTop : movedElsewhere) += 1;
+ CHECK(movedTop > 0 && movedElsewhere == 0);
+
+ // Selecting the source keeps the same data checked out: no swap, the stroke is there, the history is shared.
+ doc.selectPart(0);
+ CHECK(doc.partMesh(0).positions == after && doc.partMesh(1).positions == after);
+ CHECK(doc.undo.canUndo());
+ CHECK(reg.execute(doc, "undo").ok); // undone from the source: both change back
+ CHECK(doc.partMesh(1).positions == before);
+ CHECK(reg.execute(doc, "redo").ok);
+ CHECK(doc.partMesh(1).positions == after);
+
+ // Another Part in between: the group's data goes back in and out intact.
+ CHECK(reg.execute(doc, "part_append", {{"type", std::string("cube")}}).ok);
+ CHECK(doc.partCount() == 3 && doc.linkCount(2) == 1);
+ CHECK(doc.partMesh(0).positions == after && doc.partMesh(1).positions == after);
+ doc.selectPart(1);
+ CHECK(doc.mesh.positions == after && doc.undo.canUndo());
+}
+
+TEST(linked_duplicate_undo_make_unique_delete) {
+ CommandRegistry reg;
+ Document doc = linkedScene(reg);
+ // Undo takes the copy away (from the copy itself: the source takes over), redo brings it back.
+ CHECK(reg.execute(doc, "undo").ok);
+ CHECK(doc.partCount() == 1 && doc.activePartInfo().name == "Body" && doc.linkCount(0) == 1);
+ CHECK(reg.execute(doc, "redo").ok);
+ CHECK(doc.partCount() == 2 && doc.linkCount(0) == 2 && doc.parts[1].moved());
+
+ // Make Unique: its own mesh (same shape), same place, fresh history; edits no longer reach the source.
+ doc.selectPart(1);
+ const std::vector<glm::vec3> shape = doc.mesh.positions;
+ const glm::mat4 place = doc.parts[1].transform;
+ CHECK(reg.execute(doc, "part_make_unique").ok);
+ CHECK(doc.linkCount(0) == 1 && doc.linkCount(1) == 1 && doc.meshKey(0) != doc.meshKey(1));
+ CHECK(doc.parts[1].transform == place && doc.mesh.positions == shape && !doc.undo.canUndo());
+ CHECK(!reg.execute(doc, "part_make_unique").ok); // not linked any more
+ CHECK(strokeTop(reg, doc).ok);
+ CHECK(doc.mesh.positions != shape && doc.partMesh(0).positions == shape);
+
+ // Delete keeps the others: link again, delete the source, the copy keeps the mesh.
+ doc.selectPart(0);
+ CHECK(reg.execute(doc, "part_duplicate_linked").ok);
+ CHECK(doc.partCount() == 3 && doc.linkCount(0) == 2);
+ CHECK(strokeTop(reg, doc).ok);
+ const std::vector<glm::vec3> sculpted = doc.mesh.positions;
+ CHECK(reg.execute(doc, "part_delete", {{"index", 0.0}}).ok);
+ CHECK(doc.partCount() == 2);
+ const int copy = doc.findPart("Body link 2");
+ CHECK(copy >= 0);
+ if (copy >= 0) {
+ CHECK(doc.linkCount(copy) == 1 && doc.partMesh(copy).positions == sculpted);
+ doc.selectPart(copy);
+ CHECK(doc.undo.canUndo()); // the group's history went with it
+ }
+}
+
+TEST(linked_duplicate_transform_moves_the_copy) {
+ CommandRegistry reg;
+ Document doc = linkedScene(reg);
+ const std::vector<glm::vec3> shape = doc.mesh.positions;
+ const glm::vec3 centre = doc.partBounds(1).center();
+ // Unmasked: the copy moves as a whole (its transform), the shared mesh stays.
+ CHECK(reg.execute(doc, "transform", {{"translate", std::string("0,2,0")}, {"rotate", std::string("0,90,0")}}).ok);
+ CHECK(doc.mesh.positions == shape);
+ CHECK(near(doc.partBounds(1).center(), centre + glm::vec3(0, 2, 0), 1e-3f));
+ CHECK(near(doc.partBounds(0).center(), centre - glm::vec3(3, 0, 0), 1e-3f)); // the source didn't move
+ // Uneven scale keeps a linked copy a similarity (one scale, the mean).
+ CHECK(reg.execute(doc, "transform", {{"scale", std::string("1,2,3")}}).ok);
+ const glm::mat3 l(doc.parts[1].transform);
+ CHECK(std::abs(glm::length(l[0]) - 2.0f) < 1e-4f && std::abs(glm::length(l[1]) - 2.0f) < 1e-4f &&
+ std::abs(glm::length(l[2]) - 2.0f) < 1e-4f);
+ // One undo step each, in the shared history.
+ CHECK(reg.execute(doc, "undo").ok && reg.execute(doc, "undo").ok);
+ CHECK(near(doc.partBounds(1).center(), centre, 1e-3f) && doc.mesh.positions == shape);
+ CHECK(reg.execute(doc, "redo").ok);
+ CHECK(near(doc.partBounds(1).center(), centre + glm::vec3(0, 2, 0), 1e-3f));
+
+ // Masked: the unmasked part of the shared mesh moves, in the copy's own space (turned 90 degrees about Y,
+ // its local +X is the scene's -Z... a scene +Y move is local +Y either way).
+ CHECK(reg.execute(doc, "mask_all").ok);
+ for (size_t v = 0; v < doc.mesh.vertexCount(); ++v)
+ if (doc.mesh.positions[v].y > 0.5f) doc.mesh.mask[v] = 0.0f; // the top is free
+ doc.mesh.markAllDirty();
+ const glm::mat4 place = doc.parts[1].transform;
+ CHECK(reg.execute(doc, "transform", {{"translate", std::string("0,0.5,0")}}).ok);
+ CHECK(doc.parts[1].transform == place);
+ bool topUp = true, restStill = true;
+ for (size_t v = 0; v < shape.size(); ++v) {
+ if (shape[v].y > 0.5f) topUp &= std::abs(doc.mesh.positions[v].y - (shape[v].y + 0.5f)) < 1e-3f;
+ else restStill &= doc.mesh.positions[v] == shape[v];
+ }
+ CHECK(topUp && restStill);
+}
+
+TEST(linked_duplicate_project_round_trip) {
+ CommandRegistry reg;
+ Document doc = linkedScene(reg);
+ CHECK(strokeTop(reg, doc).ok);
+ CHECK(reg.execute(doc, "part_duplicate_linked", {{"offset", std::string("0,0,3")}}).ok);
+ CHECK(reg.execute(doc, "part_append", {{"type", std::string("cube")}}).ok);
+ doc.selectPart(1);
+ doc.parts[2].folder = doc.addPartFolder("Copies"); // a linked copy in a folder (#96) keeps both
+ const std::string path = tempPath("sf_linked.sfproj");
+ std::string err;
+ CHECK(saveProject(path, doc, err));
+ Document back;
+ CHECK(loadProject(path, back, err));
+ CHECK(back.partCount() == 4 && back.activePart == 1);
+ CHECK(back.linkCount(0) == 3 && back.linkCount(3) == 1);
+ CHECK(back.meshKey(0) == back.meshKey(1) && back.meshKey(1) == back.meshKey(2));
+ for (int i = 0; i < 4; ++i) {
+ CHECK(back.parts[size_t(i)].name == doc.parts[size_t(i)].name);
+ CHECK(back.parts[size_t(i)].transform == doc.parts[size_t(i)].transform);
+ CHECK(back.partMesh(i).positions == doc.partMesh(i).positions);
+ CHECK((back.parts[size_t(i)].folder != 0) == (i == 2));
+ }
+ CHECK(back.partFolders.size() == 1 && back.partFolders[0].name == "Copies");
+ // A project with links needs format 8; an older reader says to update.
+ const std::string text = [&] {
+ std::vector<ZipEntry> entries;
+ std::string e;
+ readStoredZip(path, entries, e);
+ for (const auto& z : entries)
+ if (z.name == "manifest.json") return std::string(z.data.begin(), z.data.end());
+ return std::string();
+ }();
+ Json manifest;
+ std::string e;
+ CHECK(Json::parse(text, manifest, e));
+ CHECK(manifest["version"].asNumber(0) == 8);
+ CHECK(manifest["parts"][size_t(1)]["link"].asNumber(-1) == 0 && manifest["parts"][size_t(2)]["link"].asNumber(-1) == 0);
+ CHECK(manifest["parts"][size_t(3)]["link"].isNull());
+ std::filesystem::remove(path);
+}
+
+TEST(linked_duplicate_memory_500_copies) {
+ CommandRegistry reg;
+ Document doc;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}}).ok);
+ const size_t one = doc.mesh.memoryBytes();
+ for (int i = 0; i < 500; ++i) doc.linkedDuplicate(0, glm::vec3(float(i % 25) * 2.5f, float(i / 25) * 2.5f, 0.0f));
+ CHECK(doc.partCount() == 501 && doc.linkCount(0) == 501);
+ // 500 linked copies ~= 1 mesh: one PartData (one mesh, one BVH) for all of them, a transform each.
+ std::vector<const PartData*> distinct;
+ for (const Part& p : doc.parts)
+ if (std::find(distinct.begin(), distinct.end(), p.data.get()) == distinct.end()) distinct.push_back(p.data.get());
+ CHECK(distinct.size() == 1);
+ const size_t perCopy = sizeof(Part) + doc.parts.back().name.capacity();
+ CHECK(perCopy * 500 < one / 4);
+ // Bounds cover every copy where it is.
+ const AABB all = doc.visibleBounds();
+ CHECK(all.max.x > 24.0f * 2.5f && all.max.y > 19.0f * 2.5f);
+}
+
+TEST(linked_duplicate_exports) {
+ CommandRegistry reg;
+ Document doc = linkedScene(reg);
+ doc.path = tempPath("Linked.sfproj");
+ // glTF: two nodes, one mesh; the copy's node carries its matrix.
+ const std::string glb = tempPath("sf_linked.glb");
+ CHECK(reg.execute(doc, "export_glb", {{"path", glb}}).ok);
+ std::vector<MeshObject> objects;
+ std::string err;
+ CHECK(loadGltf(glb, objects, err) && objects.size() == 2);
+ if (objects.size() == 2) {
+ CHECK(objects[0].mesh.triangleCount() == objects[1].mesh.triangleCount());
+ CHECK(near(objects[1].mesh.bounds().center(), objects[0].mesh.bounds().center() + glm::vec3(3, 0, 0), 1e-3f));
+ }
+ const std::string bin = readText(glb);
+ CHECK(countOf(bin, "\"primitives\"") == 1 && bin.find("\"matrix\"") != std::string::npos);
+
+ // USD: the copy is an instanceable prim referencing the first; SculptForge reads both back.
+ const std::string usda = tempPath("sf_linked.usda");
+ CHECK(reg.execute(doc, "export_usd", {{"path", usda}}).ok);
+ const std::string text = readText(usda);
+ CHECK(countOf(text, "def Mesh ") == 1);
+ CHECK(text.find("instanceable = true") != std::string::npos);
+ CHECK(text.find("prepend references = </Linked/Body>") != std::string::npos);
+ CHECK(text.find("xformOp:transform") != std::string::npos);
+ CHECK(countOf(text, "{") == countOf(text, "}"));
+ SplatCloud splats;
+ objects.clear();
+ CHECK(loadUsd(usda, objects, splats, err) && objects.size() == 2);
+ if (objects.size() == 2) {
+ CHECK(objects[0].name == "Body" && objects[1].name == "Body_link");
+ CHECK(near(objects[1].mesh.bounds().center(), objects[0].mesh.bounds().center() + glm::vec3(3, 0, 0), 1e-3f));
+ }
+
+ // OBJ (no instancing): the copy written where it is.
+ const std::string obj = tempPath("sf_linked.obj");
+ CHECK(reg.execute(doc, "save_obj", {{"path", obj}}).ok);
+ Mesh merged;
+ CHECK(loadObj(obj, merged, err));
+ CHECK(merged.triangleCount() == 2 * doc.mesh.triangleCount());
+ CHECK(merged.bounds().max.x > doc.partBounds(1).max.x - 1e-3f);
+
+ // Merge Visible: the result is where the Parts were, not moved.
+ CHECK(reg.execute(doc, "part_merge_visible").ok);
+ CHECK(doc.partCount() == 1 && !doc.activePartInfo().moved());
+ CHECK(doc.mesh.bounds().max.x > 3.9f);
+ for (const std::string& p : {glb, usda, obj}) std::filesystem::remove(p);
+}
+
+TEST(camera_in_space_of_part) {
+ Camera cam;
+ cam.target = glm::vec3(1, 2, 3);
+ cam.distance = 7.0f;
+ cam.yaw = 0.4f;
+ cam.pitch = -0.3f;
+ cam.aspect = 1.5f;
+ // A linked copy's place: turned, moved and scaled evenly.
+ const glm::mat4 place = glm::translate(glm::mat4(1.0f), glm::vec3(3, -1, 2)) *
+ glm::rotate(glm::mat4(1.0f), 0.7f, glm::normalize(glm::vec3(1, 2, 0.5f))) *
+ glm::scale(glm::mat4(1.0f), glm::vec3(1.5f));
+ const Camera local = cam.inSpaceOf(place);
+ const glm::mat4 inv = glm::inverse(place);
+ for (float x : {10.0f, 300.0f, 590.0f})
+ for (float y : {20.0f, 200.0f, 390.0f}) {
+ glm::vec3 o, d, lo, ld;
+ cam.screenRay(x, y, 600.0f, 400.0f, o, d);
+ local.screenRay(x, y, 600.0f, 400.0f, lo, ld);
+ // The same ray, seen from the Part: the local ray's points map to the world ray's line.
+ const glm::vec3 wd = glm::normalize(glm::mat3(inv) * d);
+ CHECK(near(ld, wd, 1e-4f));
+ const glm::vec3 wo = glm::vec3(inv * glm::vec4(o, 1.0f));
+ const glm::vec3 off = lo - wo;
+ CHECK(glm::length(off - wd * glm::dot(off, wd)) < 1e-3f);
+ }
+ // A pixel covers 1/scale as many of the Part's units; projecting a local point lands where the world one does.
+ const glm::vec3 p(0.2f, 0.3f, -0.1f);
+ const glm::vec3 wp = glm::vec3(place * glm::vec4(p, 1.0f));
+ CHECK(std::abs(local.worldPerPixel(p, 400.0f) * 1.5f - cam.worldPerPixel(wp, 400.0f)) < 1e-4f);
+ const glm::vec4 a = cam.projection() * cam.view() * glm::vec4(wp, 1.0f);
+ const glm::vec4 b = local.projection() * local.view() * glm::vec4(p, 1.0f);
+ CHECK(near(glm::vec3(a) / a.w, glm::vec3(b) / b.w, 1e-4f));
+ CHECK(cam.inSpaceOf(glm::mat4(1.0f)).view() == cam.view());
+}
diff --git a/tests/test_maya_bridge.cpp b/tests/test_maya_bridge.cpp
index ffc55054..988a5ab7 100644
--- a/tests/test_maya_bridge.cpp
+++ b/tests/test_maya_bridge.cpp
@@ -166,7 +166,7 @@ TEST(maya_bridge_round_trip) {
CHECK(doc.partCount() == 2 && doc.activePart == 0 && doc.parts[0].name == "Body Hi");
CHECK(doc.mesh.quadCount() == quads && doc.mesh.hasUvs() && doc.undo.canUndo());
CHECK(std::abs(doc.mesh.positions[0].y - obj.positions[0].y) < 1e-5f);
- CHECK(doc.parts[1].name == "pSphere1" && doc.parts[1].bridgeName == "pSphere1");
+ CHECK(doc.parts[1].name == "pSphere1" && doc.parts[1].data->bridgeName == "pSphere1");
// A second send: the next revision, the first send's files removed, others in the folder left alone.
writeText(root / "sculptforge_to_maya" / "notes.txt", "mine");
diff --git a/tests/test_paint_layers.cpp b/tests/test_paint_layers.cpp
index 701a2a48..291a31a4 100644
--- a/tests/test_paint_layers.cpp
+++ b/tests/test_paint_layers.cpp
@@ -311,7 +311,7 @@ TEST(paint_layers_project_round_trip) {
CHECK(sameStack(back.mesh, doc.mesh));
CHECK(back.mesh.paintLayers[0].blend == BlendMode::Overlay && back.mesh.paintLayers[0].opacity == 0.75f);
CHECK(!back.mesh.paintLayers[1].visible && back.mesh.paintLayers[1].locked && back.mesh.activePaintLayer == 0);
- CHECK(back.parts[1].mesh.paintLayers.empty());
+ CHECK(back.parts[1].data->mesh.paintLayers.empty());
// Undo after loading has no history, but painting works on the loaded stack.
CHECK(reg.execute(back, "paint_fill", {{"color", std::string("#ffffff")}}).ok);
CHECK(reg.execute(back, "undo").ok && sameStack(back.mesh, doc.mesh));
diff --git a/tests/test_part_io.cpp b/tests/test_part_io.cpp
index d2295933..46d0918b 100644
--- a/tests/test_part_io.cpp
+++ b/tests/test_part_io.cpp
@@ -540,7 +540,7 @@ TEST(part_bridge_send_receive_and_export) {
CommandRegistry reg;
CommandResult r = reg.execute(doc, "bridge_send", {{"folder", root.string()}, {"launch", false}});
CHECK(r.ok && r.message.find("1 more Parts") != std::string::npos);
- CHECK(doc.bridgeName == "Body" && doc.parts[2].bridgeName == "Sword" && doc.parts[1].bridgeName == "Eye_ZB");
+ CHECK(doc.bridgeName == "Body" && doc.parts[2].data->bridgeName == "Sword" && doc.parts[1].data->bridgeName == "Eye_ZB");
const fs::path project = root / bridgefile::kProjectsFolder / "Default";
CHECK(fs::exists(project / (std::string("Body") + bridgefile::kExt)) && fs::exists(project / (std::string("Sword") + bridgefile::kExt)) && !fs::exists(project / (std::string("Eye_ZB") + bridgefile::kExt)));
@@ -549,7 +549,7 @@ TEST(part_bridge_send_receive_and_export) {
r = reg.execute(back, "bridge_receive", {{"folder", root.string()}});
CHECK(r.ok && back.partCount() == 2);
CHECK(back.parts[0].name == "Body" && back.parts[1].name == "Sword");
- CHECK(back.bridgeName == "Body" && back.parts[1].bridgeName == "Sword");
+ CHECK(back.bridgeName == "Body" && back.parts[1].data->bridgeName == "Sword");
CHECK(back.mesh.triangleCount() == doc.partMesh(0).triangleCount() && back.mesh.hasColors() && back.mesh.hasMask());
CHECK(groupCount(back.partMesh(1)) == 2);
diff --git a/tests/test_qremesh_guides.cpp b/tests/test_qremesh_guides.cpp
index 62ccc499..cb852b2b 100644
--- a/tests/test_qremesh_guides.cpp
+++ b/tests/test_qremesh_guides.cpp
@@ -454,7 +454,7 @@ TEST(qremesh_guide_command_parts_and_projects) {
std::printf(" %s\n", r.message.c_str());
CHECK(r.message.find("followed 1 guide") != std::string::npos);
CHECK(doc.qremeshGuides.size() == 1);
- CHECK(doc.parts[size_t(doc.activePart + 1)].qremeshGuides.size() == 1);
+ CHECK(doc.parts[size_t(doc.activePart + 1)].data->qremeshGuides.size() == 1);
r = reg.execute(doc, "qremesh", {{"target", 1500.0}, {"guides", false}});
CHECK(r.ok && r.message.find("guide") == std::string::npos);
// Guides left behind by a move are ignored, with a note.
diff --git a/tests/test_transform.cpp b/tests/test_transform.cpp
index 9e9252b3..5318bb0b 100644
--- a/tests/test_transform.cpp
+++ b/tests/test_transform.cpp
@@ -394,7 +394,7 @@ TEST(transform_all_parts) {
CHECK(d.partMesh(1).positions[0] == b[0] + glm::vec3(0, 2, 0));
// One undo step in each Part.
CHECK(d.undo.canUndo());
- CHECK(d.parts[1].undo.canUndo());
+ CHECK(d.parts[1].data->undo.canUndo());
d.selectPart(1);
CHECK(run(d, "undo").ok);
CHECK(sameBits(d.mesh.positions, b));
diff --git a/tests/ui/linked_duplicate.sfui b/tests/ui/linked_duplicate.sfui
new file mode 100644
index 00000000..466737eb
--- /dev/null
+++ b/tests/ui/linked_duplicate.sfui
@@ -0,0 +1,67 @@
+# Linked Duplicates (#94): Tool > Parts > Linked Duplicate and its link badge, the Gizmo moving one copy, a stroke
+# on a turned copy landing under the cursor (and changing every copy), shared undo, Make Unique, save and reopen.
+run new_sphere subdivisions=4 ; part_rename to=Body
+expect "Parts/Linked Duplicate##part.duplicate_linked"
+click "Parts/Linked Duplicate##part.duplicate_linked"
+expect_status Linked duplicate Body link
+expect_value parts == 2
+expect_value active_part == 1
+expect_value linked_parts == 2
+expect_value part_moved == 1
+click "Parts/Linked Duplicate##part.duplicate_linked"
+expect_value parts == 3
+expect_value linked_parts == 3
+key f
+wait 0.5
+shot three-linked
+
+# The Gizmo moves only the active copy: its place, not the shared mesh.
+remember part_x x0
+key w
+gizmo_drag move_y 0 -60
+expect_status Gizmo Move
+expect_value part_x == $x0
+expect_value part_moved == 1
+key q
+# Turn it a quarter about Z and scale it up (as a command, one undo step each).
+run transform rotate=0,0,90 scale=1.5
+key f
+wait 0.3
+shot moved-copy
+
+# A stroke on the turned, scaled copy lands under the cursor.
+click "Clay##brush.clay"
+stroke 0.35 0.4 0.65 0.6
+expect_value dabs > 3
+expect_value dab_scene_error_px < 0.5
+remember vertices v0
+shot sculpted-copy
+# Every copy shows it: the source has the same mesh, and its undo history takes the stroke back.
+click "Parts/Body"
+expect_value active_part == 0
+expect_value linked_parts == 3
+expect_value can_undo == 1
+key ctrl+z
+key ctrl+shift+z
+shot sculpted-source
+
+# Make Unique: the copy keeps its place, its own mesh, no history.
+click "Parts/Body link 2"
+expect_value active_part == 2
+expect_value linked_parts == 3
+click "Parts/Make Unique##part.make_unique"
+expect_status is unique now
+expect_value linked_parts == 1
+expect_value can_undo == 0
+expect_value part_moved == 1
+click "Parts/Body"
+expect_value linked_parts == 2
+
+# Save and reopen: the links and places come back.
+run save_project path=sf_ui_linked.sfproj
+run open path=sf_ui_linked.sfproj
+expect_value parts == 3
+expect_value active_part == 0
+expect_value linked_parts == 2
+wait 0.5
+shot reopened
diff --git a/tests/ui/parts.sfui b/tests/ui/parts.sfui
index b5c07c17..66154be2 100644
--- a/tests/ui/parts.sfui
+++ b/tests/ui/parts.sfui
@@ -156,6 +156,8 @@ expect "Parts/Append"
# Wireframe, face group colours and the LOD preview are for the active Part only.
key shift+f
expect_value wireframe == 1
+# (Parts closed first: open, it is tall enough that Face Groups is below the tray's fold)
+click "Parts##tool.part"
click "Face Groups"
click "Show face groups"
shot active-overlays