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.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Insert sets: a multi-object file or a folder of meshes to insert from, one item at a time
islandmed675fefbfd2da
diff --git a/changes/feat-insert-sets.md b/changes/feat-insert-sets.mdnew file mode 100644index 00000000..e688c9db--- /dev/null+++ b/changes/feat-insert-sets.md@@ -0,0 +1,16 @@+---+whats_new: **Insert sets**: **Parts > Append > Insert on the model > Insert set from file...** or **from folder...** loads a+ kitbash set (a file with several objects, or a folder of meshes); pick one in its thumbnail window and drag it onto the+ model, `[` and `]` step through the set.+highlight: Kitbash sets for Insert+added: **Insert sets** (Parts > Append > Insert on the model): a model file with several objects (`.obj`, `.glb`) or a+ folder of `.obj` / `.ply` / `.glb` files becomes a set to insert from, one item at a time, with a thumbnail picker;+ `[` and `]` step to the previous / next item while inserting. Symmetry, undo and the up axis work as with one mesh.+ Commands `insert_mesh set=<path> index=<n>` and `insert_set_items set=<path>`. Asked by a viewer on askNK's video.+testers:+ - Any OS: Parts > Append > Insert on the model > Insert set from folder..., pick a folder with a few .obj / .glb files;+ the Insert set window shows a thumbnail per file. Click one, drag on the model: that mesh is inserted. Press ] and+ drag again: the next one. Ctrl+Z takes one insert back at a time.+ - Windows: the same with a .glb holding several objects (Insert set from file...); names under the thumbnails are the objects'.+---+Saving sets in projects / .sfpack (brush packs shipping kitbash sets) and showing them in the Library are follow-ups.diff --git a/docs/guide/parts.md b/docs/guide/parts.mdindex a0351ab4..70c8c09e 100644--- a/docs/guide/parts.md+++ b/docs/guide/parts.md@@ -61,6 +61,12 @@ Click **Append** and choose:**From file...** and pick an `.obj`, `.ply` or `.glb` file; then drag as with the shapes. The mesh is centred,scaled so its largest side matches the drag, and stood on the surface along its own up (+Y) axis. Esc stopsinserting. (Command: `insert_mesh part=<name>` or `insert_mesh file=<path>`.)+ To insert from a **kitbash set**, choose **Insert set from file...** (one `.obj` or `.glb` with several objects)+ or **Insert set from folder...** (its `.obj`, `.ply` and `.glb` files, by name; not its subfolders). The **Insert set**+ window shows a thumbnail of each item: click one, then drag on the model as above. While inserting, `]` steps to+ the next item and `[` to the previous one (around the set; brush size keys come back once you stop). Esc or the+ window's close button stops. (Commands: `insert_set_items set=<path>` lists them;+ `insert_mesh set=<path> index=<n>` inserts item `n`, 0 being the first.)- **From file...**: a model (`.obj`, `.fbx`, `.glb`, `.gltf`, `.ply`, `.stl`, Bridge files, `.usda`, `.usd`, `.usdz`) ora project (`.sfproj`). A file with several objects adds one Part per object.diff --git a/src/app/App.cpp b/src/app/App.cppindex d07cbc89..566b30e7 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -2029,8 +2029,9 @@ void App::onMouseUp() {// the drag's direction on screen turns it about the normal{"twist", insertPx_ > 4.0f ? double(glm::degrees(std::atan2(mouseY_ - insertY_, mouseX_ - insertX_))) : 0.0}};args = withSymmetryArgs(std::move(args));- if (insertType_ == "mesh") { // your own mesh: a Part's copy or a file (insert_mesh)+ if (insertType_ == "mesh") { // your own mesh: a Part's copy, a file or a set's item (insert_mesh)args[insertMeshKey_] = insertMeshValue_;+ if (insertMeshKey_ == "set") args["index"] = double(insertSet_.index);runCommand("insert_mesh", args);} else {args["type"] = insertType_;@@ -2072,6 +2073,11 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {closeStrokePopup();return;}+ if ((key == SDLK_LEFTBRACKET || key == SDLK_RIGHTBRACKET) && !(mod & (SDL_KMOD_CTRL | SDL_KMOD_ALT | SDL_KMOD_GUI)) &&+ insertSetActive()) { // an insert set: [ and ] step through it (the drag sets the size, not the brush's)+ selectInsertSetItem(insertSet_.index + (key == SDLK_RIGHTBRACKET ? 1 : -1));+ return;+ }if (key == SDLK_ESCAPE && !insertType_.empty()) { // Append > Insert (#34) offinsertType_.clear();status_ = "Insert off";@@ -2655,6 +2661,7 @@ void App::queueFile(FileAction action, std::string path) {aiLinkPicked(path); // the user chose it: a connected AI tool may use it without asking (PanelAiLink.cpp)if (action != FileAction::OpenObj && action != FileAction::LoadBrush && action != FileAction::OpenImage &&action != FileAction::AppendPart && action != FileAction::ComfyWorkflow && action != FileAction::InsertMesh &&+ action != FileAction::InsertSet &&!path.empty() &&std::filesystem::path(std::u8string(path.begin(), path.end())).extension().empty())path += action == FileAction::SaveObj ? ".obj"@@ -2794,6 +2801,7 @@ void App::processPendingFiles() {status_ = "Insert " + std::filesystem::path(std::u8string(f.path.begin(), f.path.end())).filename().string() +": drag on the model (the drag sets its size). Esc stops.";break;+ case FileAction::InsertSet: chooseInsertSet(f.path); break; // Insert on the model > Set (PanelParts.cpp)case FileAction::Count: break;}}diff --git a/src/app/App.h b/src/app/App.hindex f4c643c6..e34a361d 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -27,6 +27,7 @@#include "link/AiLinkSession.h"#include "core/Macro.h"#include "core/Pack.h"+#include "core/Parts.h"#include "core/Document.h"#include "core/DiscordPresence.h"#include "core/Face.h"@@ -155,7 +156,7 @@ public:static void glWindowAttributes(); // OpenGL 3.3 core, before a window is madevoid requestUiScale(); // Preferences > Interface > UI scale changed: rebuilt live before the next frame (#87)- enum class FileAction { OpenObj, SaveObj, ExportGlb, ExportLods, SaveBrush, LoadBrush, OpenImage, ExportUsd, SaveSplats, ExportUnreal, SaveProject, AppendPart, ComfyWorkflow, LoadLitSphere, InsertMesh, Count };+ enum class FileAction { OpenObj, SaveObj, ExportGlb, ExportLods, SaveBrush, LoadBrush, OpenImage, ExportUsd, SaveSplats, ExportUnreal, SaveProject, AppendPart, ComfyWorkflow, LoadLitSphere, InsertMesh, InsertSet, Count };struct DialogRequest {App* app;FileAction action;@@ -1833,8 +1834,19 @@ private:// Insert on the model (#34): the primitive chosen in Append > Insert; a drag on the surface places it.// "mesh" inserts your own mesh instead: insertMeshKey_ is "part" (a Part's name) or "file" (a path// chosen in the file dialog), insertMeshValue_ the name or path (insert_mesh).+ // insertMeshKey_ "set": one item of an insert set (a folder or a multi-object file; core/Parts.h), chosen+ // in the picker window or stepped with [ and ] while inserting.std::string insertType_;std::string insertMeshKey_, insertMeshValue_;+ struct InsertSetState {+ std::string path;+ std::vector<InsertSetItem> items;+ int index = 0;+ } insertSet_;+ void chooseInsertSet(const std::string& path); // the file or folder dialog's answer+ void selectInsertSetItem(int index); // wraps around+ bool insertSetActive() const { return insertType_ == "mesh" && insertMeshKey_ == "set" && !insertSet_.items.empty(); }+ void drawInsertSetPicker();glm::vec3 insertAt_{0.0f}, insertNormal_{0.0f, 1.0f, 0.0f};float insertX_ = 0.0f, insertY_ = 0.0f, insertPx_ = 0.0f;// own: our ui.json (its layout becomes storedLayout_; it may have none), not a shared file.diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cppindex 16f5f687..d29ebb8e 100644--- a/src/app/I18nSimplifiedChinese.cpp+++ b/src/app/I18nSimplifiedChinese.cpp@@ -326,6 +326,12 @@ constexpr Entry kSimplifiedChinese[] = {{"Plane", "平面"},{"From file", "从文件"},{"Active Part's copy", "当前部件的副本"},+ {"Insert set from file...", "从文件载入插入集..."},+ {"Insert set from folder...", "从文件夹载入插入集..."},+ {"A model file with several objects: insert them one at a time", "包含多个对象的模型文件:逐个插入"},+ {"A folder of .obj, .ply or .glb files: insert them one at a time", "存放 .obj、.ply 或 .glb 文件的文件夹:逐个插入"},+ {"Insert set", "插入集"},+ {"[ / ] 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点击以选择,双击以重命名"},diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 2289a7f4..a0e0b8c4 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -369,6 +369,12 @@ constexpr Entry kSpanish[] = {{"Plane", "Plano"},{"From file", "Desde archivo"},{"Active Part's copy", "Copia de la pieza activa"},+ {"Insert set from file...", "Conjunto para insertar desde archivo..."},+ {"Insert set from folder...", "Conjunto para insertar desde carpeta..."},+ {"A model file with several objects: insert them one at a time", "Un archivo de modelo con varios objetos: insértalos de uno en uno"},+ {"A folder of .obj, .ply or .glb files: insert them one at a time", "Una carpeta de archivos .obj, .ply o .glb: insértalos de uno en uno"},+ {"Insert set", "Conjunto para insertar"},+ {"[ / ] previous / next Esc stops", "[ / ] anterior / siguiente Esc termina"},{"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."},diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cppindex 2c4a040c..532d342b 100644--- a/src/app/I18nTraditionalChinese.cpp+++ b/src/app/I18nTraditionalChinese.cpp@@ -326,6 +326,12 @@ constexpr Entry kTraditionalChinese[] = {{"Plane", "平面"},{"From file", "從檔案"},{"Active Part's copy", "作用中部件的副本"},+ {"Insert set from file...", "從檔案載入插入集..."},+ {"Insert set from folder...", "從資料夾載入插入集..."},+ {"A model file with several objects: insert them one at a time", "含有多個物件的模型檔案:逐一插入"},+ {"A folder of .obj, .ply or .glb files: insert them one at a time", "存放 .obj、.ply 或 .glb 檔案的資料夾:逐一插入"},+ {"Insert set", "插入集"},+ {"[ / ] 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點選以選取,連按兩下以重新命名"},diff --git a/src/app/PanelParts.cpp b/src/app/PanelParts.cppindex 18777c3e..1dd21fed 100644--- a/src/app/PanelParts.cpp+++ b/src/app/PanelParts.cpp@@ -22,6 +22,7 @@#include <cmath>#include <cstdint>#include <cstdio>+#include <filesystem>#include <string>#include <vector>@@ -527,6 +528,18 @@ void App::drawPartsContents() {if (ImGui::MenuItem(tr("From file...##insert")))SDL_ShowOpenFileDialog(onAppendChosen, &dialogRequests_[int(FileAction::InsertMesh)], window_,kInsertFilters, 2, nullptr, false);+ // Insert sets (kitbash sets): a file with several objects, or a folder of model files; a picker of+ // their thumbnails, [ and ] step through them.+ ImGui::Separator();+ if (ImGui::MenuItem(tr("Insert set from file...")))+ SDL_ShowOpenFileDialog(onAppendChosen, &dialogRequests_[int(FileAction::InsertSet)], window_,+ kInsertFilters, 2, nullptr, false);+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))+ ImGui::SetTooltip("%s", tr("A model file with several objects: insert them one at a time"));+ if (ImGui::MenuItem(tr("Insert set from folder...")))+ SDL_ShowOpenFolderDialog(onAppendChosen, &dialogRequests_[int(FileAction::InsertSet)], window_, nullptr, false);+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))+ ImGui::SetTooltip("%s", tr("A folder of .obj, .ply or .glb files: insert them one at a time"));ImGui::EndMenu();}if (ImGui::MenuItem(tr("From file...")))@@ -769,7 +782,66 @@ void App::drawPartFolderRow(int fi, float rowH, ImVec2 cellPad, PartFolderActionImGui::PopID();}+void App::chooseInsertSet(const std::string& path) {+ InsertSetState set;+ std::string error;+ if (!listInsertSet(path, set.items, error)) {+ status_ = error;+ return;+ }+ set.path = path;+ insertSet_ = std::move(set);+ insertType_ = "mesh";+ insertMeshKey_ = "set";+ insertMeshValue_ = path;+ selectInsertSetItem(0);+}++void App::selectInsertSetItem(int index) {+ const int n = int(insertSet_.items.size());+ if (!n) return;+ insertSet_.index = ((index % n) + n) % n;+ status_ = "Insert " + insertSet_.items[size_t(insertSet_.index)].name + " (" + std::to_string(insertSet_.index + 1) ++ " of " + std::to_string(n) + "): drag on the model; [ and ] step through the set. Esc stops.";+}++// The insert set's picker: a thumbnail per item, the one a drag inserts outlined; open while inserting from a set.+void App::drawInsertSetPicker() {+ if (!insertSetActive()) return;+ const float s = uiScale_, tile = 72.0f * s;+ const CanvasRect c = canvasRect();+ // Bottom left of the canvas: clear of the timeline strip and the view figure at the top.+ ImGui::SetNextWindowPos(ImVec2(c.x + 12.0f * s, c.y + c.h - 12.0f * s), ImGuiCond_Appearing, ImVec2(0.0f, 1.0f));+ ImGui::SetNextWindowSizeConstraints(ImVec2(tile * 2.5f, 0), ImVec2(tile * 5.6f, c.h * 0.7f));+ bool open = true;+ const std::string title = std::string(tr("Insert set")) + "###insertset";+ if (ImGui::Begin(title.c_str(), &open, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing)) {+ const auto set = std::filesystem::path(std::u8string(insertSet_.path.begin(), insertSet_.path.end())).lexically_normal();+ const std::string name = (set.has_filename() ? set.filename() : set.parent_path().filename()).string();+ ImGui::TextDisabled("%s (%d)", name.c_str(), int(insertSet_.items.size()));+ const float spacing = ImGui::GetStyle().ItemSpacing.x;+ const int perRow = std::clamp(int(insertSet_.items.size()), 1, 5);+ for (size_t i = 0; i < insertSet_.items.size(); ++i) {+ const InsertSetItem& it = insertSet_.items[i];+ if (i % size_t(perRow)) ImGui::SameLine(0, spacing);+ const std::string id = "##insertset" + std::to_string(i);+ if (AssetTile(id.c_str(), thumbs_.insertSetItem(it.file, it.object), ICON_LC_BOX, it.name, tile,+ int(i) == insertSet_.index))+ selectInsertSetItem(int(i));+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal)) ImGui::SetTooltip("%s", it.name.c_str());+ }+ AssetTileHoverGlow();+ ImGui::TextDisabled("%s", tr("[ / ] previous / next Esc stops"));+ }+ ImGui::End();+ if (!open) {+ insertType_.clear();+ status_ = "Insert off";+ }+}+void App::drawPartPopups() {+ drawInsertSetPicker();const std::string popup = partConfirm_.title + "###" + partConfirm_.command;if (openPartConfirm_) {ImGui::OpenPopup(popup.c_str());diff --git a/src/app/Thumbnails.cpp b/src/app/Thumbnails.cppindex fb633b1f..6d3f4cc3 100644--- a/src/app/Thumbnails.cpp+++ b/src/app/Thumbnails.cpp@@ -7,6 +7,7 @@#include "core/Commands.h"#include "core/Document.h"#include "core/LitSphere.h"+#include "core/Parts.h"#include "core/PathStroke.h"#include "core/Primitives.h"#include "core/Project.h"@@ -269,7 +270,7 @@ ImTextureID ThumbnailCache::primitive(int primitive) {true);}-ImTextureID ThumbnailCache::file(const std::string& path) {+ThumbnailCache::Stat& ThumbnailCache::stat(const std::string& path) {Stat& s = stats_[path];const double now = ImGui::GetTime();if (now - s.at > kStatSeconds) {@@ -279,6 +280,31 @@ ImTextureID ThumbnailCache::file(const std::string& path) {s.size = s.exists ? uint64_t(std::filesystem::file_size(fsPath(path), ec)) : 0;s.mtime = modifiedTime(path);}+ return s;+}++ImTextureID ThumbnailCache::insertSetItem(const std::string& file, int object) {+ if (object < 0) return this->file(file); // a folder set's file+ const Stat& s = stat(file);+ if (!s.exists) return ImTextureID(0);+ const std::string key = fileThumbnailKey("setobject" + std::to_string(object), file, s.size, s.mtime, kPixels);+ return request(+ key,+ [file, object] {+ Result r;+ Mesh m;+ std::string name, err;+ if (loadInsertSetItem(file, object, m, name, err)) {+ m.recomputeAllNormals();+ r.mesh = std::make_unique<Mesh>(std::move(m));+ }+ return r;+ },+ true);+}++ImTextureID ThumbnailCache::file(const std::string& path) {+ const Stat& s = stat(path);if (!s.exists) return ImTextureID(0);const bool image = isImageFile(path), project = isProjectFile(path);const std::string kind = project ? "project" : image ? "image" : "mesh";diff --git a/src/app/Thumbnails.h b/src/app/Thumbnails.hindex ba89ebc5..28ada6d9 100644--- a/src/app/Thumbnails.h+++ b/src/app/Thumbnails.h@@ -51,6 +51,8 @@ public:ImTextureID primitive(int primitive); // Primitive (AssetLibrary.h)// Projects (their embedded thumbnail.png, else rendered once), meshes and images.ImTextureID file(const std::string& path);+ // An insert set's item (core/Parts.h InsertSetItem): object `object` of a model file, or the whole file (-1).+ ImTextureID insertSetItem(const std::string& file, int object);// Every frame on the main thread with the GL context current.void pump(Renderer& renderer);@@ -100,6 +102,7 @@ private:bool exists = false;};std::unordered_map<std::string, Stat> stats_; // file stats, refreshed every 2 s+ Stat& stat(const std::string& path);};} // namespace sfdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex c1bc0541..f0e7d81c 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -1851,13 +1851,14 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& econst auto u8 = std::filesystem::absolute(std::filesystem::path(std::u8string(d.begin(), d.end()))).lexically_normal().u8string();app_.setMayaFolder(std::string(u8.begin(), u8.end()));});- } else if (verb == "choose_file") { // choose_file insert|append <path>: what a native file dialog would answer+ } else if (verb == "choose_file") { // choose_file insert|insert_set|append <path>: what a native dialog would answerif (!need(2)) return false;App::FileAction action;if (w[1] == "insert") action = App::FileAction::InsertMesh;+ else if (w[1] == "insert_set") action = App::FileAction::InsertSet;else if (w[1] == "append") action = App::FileAction::AppendPart;else {- error = "'choose_file' takes insert or append";+ error = "'choose_file' takes insert, insert_set or append";return false;}auto file = std::filesystem::path(std::u8string(w[2].begin(), w[2].end()));diff --git a/src/core/Parts.cpp b/src/core/Parts.cppindex 5b0a1f8e..4a067155 100644--- a/src/core/Parts.cpp+++ b/src/core/Parts.cpp@@ -231,6 +231,91 @@ bool loadInsertMesh(const std::string& path, Mesh& out, std::string& error) {return ok;}+std::string lowerExtension(const std::string& path) {+ std::string ext = std::filesystem::path(std::u8string(path.begin(), path.end())).extension().string();+ for (char& ch : ext) ch = char(std::tolower(static_cast<unsigned char>(ch)));+ return ext;+}+bool insertableExtension(const std::string& ext) { return ext == ".obj" || ext == ".ply" || ext == ".glb" || ext == ".gltf"; }++// A multi-object file's objects (OBJ `o` blocks, glTF nodes); a PLY is one object.+bool loadInsertObjects(const std::string& path, std::vector<MeshObject>& out, std::string& error) {+ const std::string ext = lowerExtension(path);+ out.clear();+ bool ok = false;+ if (ext == ".obj") ok = loadObj(path, out, error);+ else if (ext == ".glb" || ext == ".gltf") ok = loadGltf(path, out, error);+ else {+ MeshObject one;+ ok = loadInsertMesh(path, one.mesh, error);+ if (ok) out.push_back(std::move(one));+ }+ if (!ok && error.empty()) error = "Couldn't read " + path;+ out.erase(std::remove_if(out.begin(), out.end(), [](const MeshObject& o) { return o.mesh.triangleCount() == 0; }), out.end());+ return ok;+}++} // namespace++bool listInsertSet(const std::string& path, std::vector<InsertSetItem>& items, std::string& error) {+ items.clear();+ const std::filesystem::path dir(std::u8string(path.begin(), path.end()));+ std::error_code ec;+ if (std::filesystem::is_directory(dir, ec)) {+ std::vector<std::string> files;+ for (auto it = std::filesystem::directory_iterator(dir, ec); !ec && it != std::filesystem::directory_iterator();+ it.increment(ec)) {+ std::error_code e2;+ if (!it->is_regular_file(e2)) continue;+ const auto u8 = it->path().u8string();+ std::string file(u8.begin(), u8.end());+ if (insertableExtension(lowerExtension(file))) files.push_back(std::move(file));+ }+ std::sort(files.begin(), files.end());+ if (files.size() > size_t(kInsertSetMaxItems)) files.resize(size_t(kInsertSetMaxItems));+ for (const std::string& f : files) items.push_back({fileStem(f), f, -1});+ if (items.empty()) error = path + " has no .obj, .ply or .glb files";+ return !items.empty();+ }+ if (!insertableExtension(lowerExtension(path))) {+ error = "An insert set is a folder, or an .obj, .ply or .glb file";+ return false;+ }+ std::vector<MeshObject> objects;+ if (!loadInsertObjects(path, objects, error)) return false;+ const std::string stem = fileStem(path);+ for (size_t i = 0; i < objects.size() && i < size_t(kInsertSetMaxItems); ++i)+ items.push_back({objects[i].name.empty() ? stem + " " + std::to_string(i + 1) : objects[i].name, path, int(i)});+ if (items.empty()) error = path + " has no mesh to insert";+ return !items.empty();+}++bool loadInsertSetItem(const std::string& path, int index, Mesh& out, std::string& name, std::string& error) {+ std::vector<InsertSetItem> items;+ const std::filesystem::path dir(std::u8string(path.begin(), path.end()));+ std::error_code ec;+ if (std::filesystem::is_directory(dir, ec)) {+ if (!listInsertSet(path, items, error)) return false;+ if (index < 0 || index >= int(items.size()))+ return error = "The set has " + std::to_string(items.size()) + " items (index 0-" + std::to_string(items.size() - 1) + ")", false;+ name = items[size_t(index)].name;+ return loadInsertMesh(items[size_t(index)].file, out, error);+ }+ if (!insertableExtension(lowerExtension(path))) {+ error = "An insert set is a folder, or an .obj, .ply or .glb file";+ return false;+ }+ std::vector<MeshObject> objects; // (one read: listing it again would read the file twice)+ if (!loadInsertObjects(path, objects, error)) return false;+ if (index < 0 || index >= int(objects.size()) || index >= kInsertSetMaxItems)+ return error = "The set has " + std::to_string(objects.size()) + " items (index 0-" + std::to_string(int(objects.size()) - 1) + ")", false;+ name = objects[size_t(index)].name.empty() ? fileStem(path) + " " + std::to_string(index + 1) : objects[size_t(index)].name;+ out = std::move(objects[size_t(index)].mesh);+ return true;+}++namespace {+// The shape of `source` for inserting: its triangles and quads only (no mask, paint, UVs, layers or levels),// centred on its bounds and scaled so its largest side is `size`. False if it has no triangles.bool normalizedPiece(const Mesh& source, float size, Mesh& out) {@@ -454,17 +539,20 @@ void registerPartCommands(CommandRegistry& reg) {std::vector<ParamSpec> meshParams{{"part", T::String, "insert a copy of this Part (by name)", false},- {"file", T::String, "insert the mesh in this model file (.obj, .ply or .glb)", false}};+ {"file", T::String, "insert the mesh in this model file (.obj, .ply or .glb)", false},+ {"set", T::String, "insert one item of this insert set: a folder of model files, or a file with several objects", false},+ {"index", T::Number, "with set=: which item (0 = the first; insert_set_items lists them)", false}};meshParams.insert(meshParams.end(), placeParams.begin(), placeParams.end());reg.add({"insert_mesh","Insert your own mesh into the active Part where the surface is (#34), placed like insert_primitive: "- "a copy of another Part or a model file, scaled so its largest side is `size`, its up (+Y) axis "+ "a copy of another Part, a model file, or one item of an insert set (a folder or a multi-object file), scaled so its largest side is `size`, its up (+Y) axis ""along the surface normal, as one new face group; one undoable step.",meshParams,[](Document& doc, const Args& a) -> CommandResult {const std::string blocked = dyntopoBlocker(doc.mesh);if (!blocked.empty()) return {false, "Can't insert: " + blocked};- if (a.contains("part") == a.contains("file")) return {false, "Give part= or file="};+ if (int(a.contains("part")) + int(a.contains("file")) + int(a.contains("set")) != 1)+ return {false, "Give part=, file= or set="};Mesh source;std::string label;if (a.contains("part")) {@@ -472,6 +560,10 @@ void registerPartCommands(CommandRegistry& reg) {const int i = doc.findPart(label);if (i < 0) return {false, "No Part named '" + label + "'"};source = doc.partMesh(i);+ } else if (a.contains("set")) {+ std::string error;+ if (!loadInsertSetItem(argString(a, "set"), int(argNumber(a, "index", 0.0)), source, label, error))+ return {false, error};} else {const std::string path = argString(a, "file");std::string error;@@ -484,6 +576,19 @@ void registerPartCommands(CommandRegistry& reg) {return insertPiece(doc, std::move(piece), a, label);}});+ reg.add({"insert_set_items",+ "List the items of an insert set (a folder of .obj / .ply / .glb files, or one file with several "+ "objects), in the order insert_mesh set=<path> index=<n> numbers them.",+ {{"set", T::String, "the folder or file", true}},+ [](Document&, const Args& a) -> CommandResult {+ std::vector<InsertSetItem> items;+ std::string error;+ if (!listInsertSet(argString(a, "set"), items, error)) return {false, error};+ std::string out = std::to_string(items.size()) + " item" + (items.size() == 1 ? "" : "s") + ":";+ for (size_t i = 0; i < items.size(); ++i) out += "\n" + std::to_string(i) + ". " + items[i].name;+ return {true, out};+ }});+reg.add({"part_duplicate", "Copy a Part (with its layers and attributes) and make the copy active.",{indexParam, nameParam},[](Document& doc, const Args& a) -> CommandResult {diff --git a/src/core/Parts.h b/src/core/Parts.hindex 930156d2..6c1e7e31 100644--- a/src/core/Parts.h+++ b/src/core/Parts.h@@ -43,6 +43,20 @@ std::vector<Mesh> splitByFaceGroups(const Mesh& mesh);// One mesh per connected piece, largest first (empty if the mesh is one piece).std::vector<Mesh> splitIntoParts(const Mesh& mesh);+// Insert sets (kitbash sets): a folder of model files, or one model file with several objects, to insert+// from one mesh at a time (insert_mesh set=<path> index=<n>). Each item is a file in the folder (.obj, .ply,+// .glb, .gltf; not its subfolders; by name, at most kInsertSetMaxItems) or an object in the file.+struct InsertSetItem {+ std::string name; // the file's stem, or the object's name ("<stem> <n>" when it has none)+ std::string file; // the file it is in (the set itself for a multi-object file)+ int object = -1; // its object in that file; -1 = the whole file+};+constexpr int kInsertSetMaxItems = 512;+// The set's items, without loading folder items (a multi-object file is read once to count its objects).+bool listInsertSet(const std::string& path, std::vector<InsertSetItem>& items, std::string& error);+// One item's mesh, and its name.+bool loadInsertSetItem(const std::string& path, int index, Mesh& out, std::string& name, std::string& error);+// part_list, part_select, part_append, part_duplicate, 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.diff --git a/tests/test_primitives_insert.cpp b/tests/test_primitives_insert.cppindex dd87a43e..8bcf5f6e 100644--- a/tests/test_primitives_insert.cpp+++ b/tests/test_primitives_insert.cpp@@ -6,6 +6,7 @@#include "core/Commands.h"#include "core/Document.h"#include "core/Json.h"+#include "core/Parts.h"#include "core/Primitives.h"#include "io/GltfIO.h"#include "io/ObjIO.h"@@ -14,6 +15,7 @@#include <algorithm>#include <cmath>#include <cstdio>+#include <filesystem>#include <map>#include <algorithm>@@ -185,3 +187,62 @@ TEST(insert_mesh_from_file) {CHECK(doc.mesh.triangleCount() == before + 12);for (const std::string& p : {obj, ply, glb}) std::remove(p.c_str());}++// Insert sets: one item at a time from a multi-object file or a folder of files.+TEST(insert_mesh_from_set) {+ Document doc;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);+ const size_t before = doc.mesh.triangleCount();+ const Mesh tet = [] {+ Mesh m;+ m.positions = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}};+ m.triangles = {{0, 2, 1}, {0, 1, 3}, {0, 3, 2}, {1, 2, 3}};+ m.sanitizeAttributes();+ return m;+ }();+ const Mesh cube = makeCube(2, 1.0f);+ std::string err;+ const std::string glb = tempPath("sf_insert_set.glb");+ CHECK(saveGlb(glb, {{"Tet", &tet}, {"Box", &cube}}, "kit", err));+ std::vector<InsertSetItem> items;+ CHECK(listInsertSet(glb, items, err));+ CHECK(items.size() == 2 && items[0].name == "Tet" && items[1].name == "Box");+ const Args at{{"x", 0.0}, {"y", 1.0}, {"z", 0.0}, {"size", 0.3}};+ Args a = at;+ a["set"] = glb;+ CHECK(reg.execute(doc, "insert_mesh", a).ok);+ CHECK(doc.mesh.triangleCount() == before + 4);+ a["index"] = 1.0;+ CommandResult r = reg.execute(doc, "insert_mesh", a);+ CHECK(r.ok && r.message.find("Box") != std::string::npos);+ CHECK(doc.mesh.triangleCount() == before + 4 + cube.triangleCount());+ a["index"] = 2.0;+ CHECK(!reg.execute(doc, "insert_mesh", a).ok);+ CHECK(reg.execute(doc, "insert_set_items", {{"set", glb}}).message.find("1. Box") != std::string::npos);++ // A folder: its model files by name, not its other files or subfolders.+ const std::filesystem::path dir = std::filesystem::temp_directory_path() / "sf_insert_set_dir";+ std::filesystem::remove_all(dir);+ std::filesystem::create_directories(dir / "sub");+ std::filesystem::create_directories(dir / "empty");+ CHECK(saveObj((dir / "b_box.obj").string(), cube, err));+ CHECK(saveGlb((dir / "a_tet.glb").string(), tet, "tet", err));+ CHECK(saveObj((dir / "sub" / "c.obj").string(), cube, err));+ if (FILE* f = std::fopen((dir / "notes.txt").string().c_str(), "w")) std::fclose(f);+ CHECK(listInsertSet(dir.string(), items, err));+ CHECK(items.size() == 2 && items[0].name == "a_tet" && items[1].name == "b_box");+ const size_t now = doc.mesh.triangleCount();+ a["set"] = dir.string();+ a["index"] = 0.0;+ CHECK(reg.execute(doc, "insert_mesh", a).ok);+ CHECK(doc.mesh.triangleCount() == now + 4);+ CHECK(reg.execute(doc, "undo", {}).ok);+ CHECK(doc.mesh.triangleCount() == now);+ // Not a set: a file type Insert doesn't read, an empty folder, a missing file.+ CHECK(!listInsertSet((dir / "notes.txt").string(), items, err));+ CHECK(!listInsertSet((dir / "empty").string(), items, err));+ CHECK(!listInsertSet((dir / "missing.glb").string(), items, err));+ std::filesystem::remove_all(dir);+ std::remove(glb.c_str());+}diff --git a/tests/ui/data/kitbash_set.glb b/tests/ui/data/kitbash_set.glbnew file mode 100644index 00000000..c479558dBinary files /dev/null and b/tests/ui/data/kitbash_set.glb differdiff --git a/tests/ui/data/make_kitbash_set.py b/tests/ui/data/make_kitbash_set.pynew file mode 100644index 00000000..ac8d429a--- /dev/null+++ b/tests/ui/data/make_kitbash_set.py@@ -0,0 +1,33 @@+#!/usr/bin/env python3+# Writes kitbash_set.glb for insert_set.sfui: an insert set of two objects, "Stud" (an octahedron, 8 triangles)+# and "Wedge" (a tetrahedron, 4 triangles), so the test can tell which one a drag inserted.+import json, os, struct++objects = [+ ("Stud", [(0, 1, 0), (1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 0, -1), (0, -1, 0)],+ [(0, 2, 1), (0, 3, 2), (0, 4, 3), (0, 1, 4), (5, 1, 2), (5, 2, 3), (5, 3, 4), (5, 4, 1)]),+ ("Wedge", [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)], [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)]),+]+binary, views, accessors, meshes, nodes = b"", [], [], [], []+for i, (name, verts, tris) in enumerate(objects):+ pos = b"".join(struct.pack("<3f", *v) for v in verts)+ idx = b"".join(struct.pack("<3H", *t) for t in tris)+ idx += b"\0" * (-len(idx) % 4)+ for data, target in ((pos, 34962), (idx, 34963)):+ views.append({"buffer": 0, "byteOffset": len(binary), "byteLength": len(data), "target": target})+ binary += data+ lo = [min(v[k] for v in verts) for k in range(3)]+ hi = [max(v[k] for v in verts) for k in range(3)]+ accessors.append({"bufferView": 2 * i, "componentType": 5126, "count": len(verts), "type": "VEC3", "min": lo, "max": hi})+ accessors.append({"bufferView": 2 * i + 1, "componentType": 5123, "count": 3 * len(tris), "type": "SCALAR"})+ meshes.append({"name": name, "primitives": [{"attributes": {"POSITION": 2 * i}, "indices": 2 * i + 1}]})+ nodes.append({"name": name, "mesh": i, "translation": [3.0 * i, 0, 0]})+doc = {"asset": {"version": "2.0", "generator": "make_kitbash_set.py"}, "scene": 0,+ "scenes": [{"nodes": list(range(len(nodes)))}], "nodes": nodes, "meshes": meshes, "accessors": accessors,+ "bufferViews": views, "buffers": [{"byteLength": len(binary)}]}+js = json.dumps(doc, separators=(",", ":")).encode()+js += b" " * (-len(js) % 4)+out = struct.pack("<3I", 0x46546C67, 2, 12 + 8 + len(js) + 8 + len(binary))+out += struct.pack("<2I", len(js), 0x4E4F534A) + js + struct.pack("<2I", len(binary), 0x004E4942) + binary+with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "kitbash_set.glb"), "wb") as f:+ f.write(out)diff --git a/tests/ui/insert_set.sfui b/tests/ui/insert_set.sfuinew file mode 100644index 00000000..235d34be--- /dev/null+++ b/tests/ui/insert_set.sfui@@ -0,0 +1,35 @@+# Insert sets (a viewer on askNK's video): a file with several objects is a set; its picker shows a thumbnail per+# item; [ and ] step through it while inserting. kitbash_set.glb: Stud (8 triangles), Wedge (4); X symmetry is on.+run new_sphere subdivisions=4+key f+remember triangles base+choose_file insert_set data/kitbash_set.glb+wait 0.1+expect_status Insert Stud (1 of 2)+wait_idle+shot insert_set_picker++# Item 0, then ] to item 1: each drag inserts the item chosen (with its mirrored copy).+stroke 0.8 0.45 0.86 0.45+expect_status 2 Studs (mirrored)+expect_value triangles == $base+16+key ]+expect_status Insert Wedge (2 of 2)+stroke 0.8 0.55 0.86 0.55+expect_status 2 Wedges (mirrored)+expect_value triangles == $base+24+shot insert_set_items++# ] wraps around, [ steps back; a click on a tile picks it.+key ]+expect_status Insert Stud (1 of 2)+key [+expect_status Insert Wedge (2 of 2)+click "##insertset0"+expect_status Insert Stud (1 of 2)+key ]+expect_status Insert Wedge (2 of 2)+key ctrl+z+expect_value triangles == $base+16+key escape+expect_status Insert off