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
Real-world size (#148): exports keep the opened size, Units preference, USD metersPerUnit
islandmed0a26f513c874
diff --git a/CMakeLists.txt b/CMakeLists.txtindex a76585ab..f5ac85e9 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -63,6 +63,7 @@ add_library(sculptforge_core STATICsrc/core/SelectionSets.cppsrc/core/ScreenSelect.cppsrc/core/Parts.cpp+ src/core/Units.cppsrc/core/ExtractMirror.cppsrc/core/MeshTransform.cppsrc/core/Deform.cppdiff --git a/assets/fonts/NotoSansSC-UI.otf b/assets/fonts/NotoSansSC-UI.otfindex 2037e887..cb3ac7fd 100644Binary files a/assets/fonts/NotoSansSC-UI.otf and b/assets/fonts/NotoSansSC-UI.otf differdiff --git a/assets/fonts/NotoSansTC-UI.otf b/assets/fonts/NotoSansTC-UI.otfindex 6e85706e..859e5505 100644Binary files a/assets/fonts/NotoSansTC-UI.otf and b/assets/fonts/NotoSansTC-UI.otf differdiff --git a/changes/feat-real-world-units.md b/changes/feat-real-world-units.mdnew file mode 100644index 00000000..61b81a93--- /dev/null+++ b/changes/feat-real-world-units.md@@ -0,0 +1,24 @@+---+whats_new: **Real-world size**: parts for 3D printing keep their size through every export. Pick the unit sizes show in+ (mm, cm, m, in) in **Preferences > Interface > Units**; **Tool** shows the Part's size and **File** the size exports+ write. OBJ and PLY files can be read in mm, cm, m or in (**OBJ/PLY in**). Asked for by @Swar55.+highlight: Parts keep their real-world size, in mm, cm, m or in+added: **Units** (Preferences > Interface, #148, thanks @Swar55): sizes show in mm, cm, m or inches: the brush size,+ the active Part's width x height x depth under its name in Tool, and the size exports write in File > Import /+ Export. **OBJ/PLY in** reads the numbers in OBJ and PLY files (which have no units) as mm, cm, m (the default) or+ inches; `open`, `open_obj` and `part_append` take `unit=` for scripts, and STL files may be read as inches too.+fixed: Exports keep the size a part was opened with (#148, @Swar55): a scene opened from an STL, OBJ or PLY writes+ OBJ and PLY in that file's unit (an STL opened in millimetres used to come out of OBJ export 1000x smaller), an+ STL opened in another unit is written back in it, and decimal sizes round-trip exactly (12.7 mm stays 12.7, not+ 12.700001). Projects remember the unit.+fixed: USD files in centimetres (`metersPerUnit = 0.01`, as Maya and Houdini write) open at their real size instead+ of 100x too large.+testers:+ - Open an STL from your slicer (e.g. a 20 mm calibration cube): Tool shows 20 x 20 x 20 mm. File > Export OBJ and+ Export STL, open both in the slicer: both are 20 mm.+ - Preferences > Interface > Units > in: Tool and the brush size read in inches; restart, it is kept.+ - Preferences > Interface > OBJ/PLY in > mm, open an OBJ made for printing (numbers in mm): Tool shows its mm size;+ Export STL; the slicer shows the same size.+ - A .usda from Maya (centimetres): opens at its real size (a 180 cm figure is 1.8 m, not 180 m).+---+Step 3 of the brief (two-point Measure) is not in this branch: follow-up.diff --git a/docs/guide/exporting.md b/docs/guide/exporting.mdindex 590155c4..a003edef 100644--- a/docs/guide/exporting.md+++ b/docs/guide/exporting.md@@ -55,8 +55,23 @@ UV convention), checked colour by colour against SculptForge's own sampling. TheOpening an STL converts back, so a downloaded print model comes in upright and at its real size. STL filesfrom SculptForge 0.5 and earlier (metres, Y up) are recognised and open as they were saved.- PLY keeps positions as they are (no unit conversion).+- USD files in other units (`metersPerUnit`, e.g. centimetres from Maya or Houdini) open at their real size.- For Unreal, **Height** sets the real-world size directly (see below).+### Real-world size and units++A part keeps the size it was opened with through every export:++- OBJ, PLY and STL have no units. A scene opened from one of them remembers its unit: exporting OBJ or PLY writes+ that unit back (an STL opened in millimetres exports a 50 mm OBJ, not 0.05), and an STL written from an STL+ keeps its numbers. Decimal sizes come back exactly (12.7 stays 12.7). Projects remember the unit.+- **Preferences > Interface > OBJ/PLY in** says what OBJ and PLY numbers mean: **m** (the default; Blender and game+ tools), or **mm** for files made for 3D printing, **cm** or **in**. STL is always read as millimetres. From+ scripts: `open path=part.obj unit=mm` (`open_obj` and `part_append` take `unit=` too; `unit=in` reads an inch STL).+- **Preferences > Interface > Units** picks the unit sizes show in: mm, cm, m or in. The active Part's width x+ height x depth shows under its name in **Tool**, the size the exports write in **File** (Import / Export), and the+ brush size by the brush ring.+## Export a model1. Show the Parts you want to export and hide the others (the eye icon in **Tool > Parts**).diff --git a/src/app/App.cpp b/src/app/App.cppindex 6bddfecc..450bbca9 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -2588,7 +2588,18 @@ void App::runCommand(const std::string& name, const Args& args) {flushBrushEdits(); // commands may replace brushes: save edits first, then watch what's there afterwardscrashlog::action(name); // (failures reach the log through SDL_Log below)const auto commandStart = std::chrono::steady_clock::now();- CommandResult r = commands_.execute(doc_, name, args);+ // OBJ and PLY have no units: read them in the Preferences > Interface > Units file unit unless the call says.+ Args withUnit;+ if ((name == "open" || name == "open_obj" || name == "part_append") && !args.contains("unit")) {+ const std::string path = argString(args, "path");+ std::string ext = path.size() >= 4 ? path.substr(path.size() - 4) : "";+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ if (ext == ".obj" || ext == ".ply") {+ withUnit = args;+ withUnit["unit"] = uiPrefs_.fileUnit;+ }+ }+ CommandResult r = commands_.execute(doc_, name, withUnit.empty() ? args : withUnit);if (perftrace::on()) { // a command that held up the frames (remesh, Divide, micro, open...)const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - commandStart).count();if (ms > perf_.traceLongMs) {diff --git a/src/app/App.h b/src/app/App.hindex ce5edfe2..42dda0db 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -118,6 +118,7 @@ struct AppOptions {};class Demo;+struct LengthUnit; // core/Units.hstruct StudioSignInJob; // PanelAi.cpp: the studio sign-in on a worker (ai/Oidc.h)// Wakes the main loop from any thread (SDL_PushEvent): the app draws only when something changed (#14), so work@@ -788,7 +789,7 @@ private:float worldSyncedPx_ = 0.0f; // radiusPx_ as worldSize sync last set it (a different value: the user set it)float cursorWorldPerPx_ = 0.0f; // at the surface under the pointer (0: not seen yet)void syncWorldSize(); // every frame, outside strokes- std::string drawSizeLabel() const; // "Size %.1f px 0.42 mm" (an ImGui slider format)+ std::string drawSizeLabel() const; // "Size %.1f px 0.42 mm" (an ImGui slider format; the Units preference)std::string drawSizeStatus() const; // "Size 3.5 px (0.42 mm)"void drawPrecisionCursor(ImDrawList* dl, ImVec2 cursor, float radius, ImU32 col);void drawPrecisionOptions(); // the Stroke picker: Steady Stroke, its radius and catch-up, Precision Intensity@@ -1721,6 +1722,9 @@ private:// ---- Help/Console/Config (C): actions, help, command palette, console, config ----public:UiPrefs& uiPrefs() { return uiPrefs_; }+ // Preferences > Interface > Units (core/Units.h): the unit sizes show in.+ const LengthUnit& lengthUnit() const;+ void drawExportSizeLine(); // File > Import / Export: the size exports write (Palettes.cpp)const CommandRegistry& commands() const { return commands_; }ImFont* helpTitleFont() const { return fontHelpTitle_ ? fontHelpTitle_ : ImGui::GetFont(); }ImFont* consoleFont() const { return fontConsole_ ? fontConsole_ : ImGui::GetFont(); }diff --git a/src/app/Config.cpp b/src/app/Config.cppindex f4631743..feb1b87a 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -23,6 +23,7 @@#include "core/Micro.h"#include "core/Multires.h"#include "core/Script.h"+#include "core/Units.h"#include <IconsLucide.h>#include <imgui_internal.h>@@ -118,6 +119,8 @@ Json toJson(const UiPrefs& p) {j.set("alphabeticalPalettes", p.alphabeticalPalettes);lookToJson(p, j);j.set("language", p.language);+ j.set("lengthUnit", p.lengthUnit);+ j.set("fileUnit", p.fileUnit);j.set("tablet", toJson(p.tablet));j.set("spaceMouse", toJson(p.spaceMouse));j.set("antialiasing", double(p.antialiasing));@@ -206,6 +209,8 @@ void fromJson(const Json& j, UiPrefs& p) {p.shellLayout = 0;}if (j["language"].isString()) p.language = languageCode(languageFromCode(j["language"].asString()));+ if (const LengthUnit* u = findLengthUnit(j["lengthUnit"].asString())) p.lengthUnit = u->id;+ if (const LengthUnit* u = findLengthUnit(j["fileUnit"].asString())) p.fileUnit = u->id;fromJson(j["tablet"], p.tablet);fromJson(j["spaceMouse"], p.spaceMouse);const int aa = int(j["antialiasing"].asNumber(p.antialiasing));@@ -1492,6 +1497,23 @@ void drawInterfaceSection(App& app) {"Clay Block...) stay as they are.","Preferences > Interface");}+ // Units (#148): sizes show in this unit; OBJ and PLY files are read in the second (core/Units.h).+ auto unitRow = [&](const char* label, std::string& value, const char* id, const char* help) {+ ImGui::AlignTextToFramePadding();+ ImGui::TextUnformatted(tr(label));+ for (const LengthUnit& u : lengthUnits()) {+ ImGui::SameLine();+ if (ImGui::RadioButton((std::string(u.id) + "##" + id + "." + u.id).c_str(), value == u.id)) value = u.id;+ ui::HelpText(label, nullptr, help, "Preferences > Interface");+ }+ };+ unitRow("Units", p.lengthUnit, "units",+ "The unit sizes show in: the brush size, the Part size in Tool and the export size in File. "+ "SculptForge works in metres; this only changes how sizes read.");+ unitRow("OBJ/PLY in", p.fileUnit, "file_units",+ "OBJ and PLY files have no units. Their numbers are read in this unit (mm for most 3D printing files, m for "+ "Blender and game tools), and exporting OBJ or PLY writes them back in the unit they were opened with, so "+ "a part keeps its size. STL is always millimetres.");ImGui::Checkbox(tr("Ctrl+hover help"), &p.popupInfo);ui::HelpText("Ctrl+hover help", nullptr,"Hold Ctrl and point at any control to see what it does and its shortcut. Ctrl+Alt shows a command's "diff --git a/src/app/Config.h b/src/app/Config.hindex 15d308f7..5e27e962 100644--- a/src/app/Config.h+++ b/src/app/Config.h@@ -32,6 +32,9 @@ struct UiPrefs {bool libraryAtStartup = true;std::string libraryFolder; // "" = Documents/SculptForgebool alphabeticalPalettes = false; // strict A-Z palette bar (default: File, Edit first)+ // Preferences > Interface > Units (#148; core/Units.h ids): the unit sizes show in (brush ring, Part size, export+ // sizes, Measure), and the unit the numbers in OBJ and PLY files are read in (STL is millimetres by convention).+ std::string lengthUnit = "mm", fileUnit = "m";std::string language = "en"; // Preferences > Interface: the interface language, "en", "es" or "zh-TW" (app/I18n.h)int cameraNotch = 0; // keep the UI out of a laptop's camera notch: 0 automatic, 1 always, 2 neverbool turntable = false; // rotation: false = free, about the screen axes; true = turntable (Y up)diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cppindex 094a3375..fd785d4a 100644--- a/src/app/I18nSimplifiedChinese.cpp+++ b/src/app/I18nSimplifiedChinese.cpp@@ -463,6 +463,13 @@ constexpr Entry kSimplifiedChinese[] = {// --- Preferences > Config ---// --- Preferences > Interface ---{"Language", "语言"},+ {"Units", "单位"},+ {"OBJ/PLY in", "OBJ/PLY 单位"},+ {"Part size", "部件尺寸"},+ {"Export size", "导出尺寸"},+ {"The unit sizes show in: the brush size, the Part size in Tool and the export size in File. SculptForge works in metres; this only changes how sizes read.", "尺寸显示所用的单位:笔刷大小、Tool 中的部件尺寸,以及 File 中的导出尺寸。SculptForge 以米为单位工作;这只改变尺寸的显示方式。"},+ {"OBJ and PLY files have no units. Their numbers are read in this unit (mm for most 3D printing files, m for Blender and game tools), and exporting OBJ or PLY writes them back in the unit they were opened with, so a part keeps its size. STL is always millimetres.", "OBJ 和 PLY 文件没有单位。其数值按此单位读取(大多数 3D 打印文件用 mm,Blender 和游戏工具用 m),导出 OBJ 或 PLY 时会按打开时的单位写回,因此部件保持原尺寸。STL 始终为毫米。"},+ {"The active Part's width x height x depth (X, Y, Z). The unit is set in Preferences > Interface > Units; STL exports write it in millimetres.", "当前部件的宽 x 高 x 深(X、Y、Z)。单位在 Preferences > Interface > Units 中设置;STL 导出以毫米写入。"},{"Tooltip delay", "工具提示延迟"},{"One sub-palette open", "一次只打开一个子调色板"},{"Reduce motion", "减少动态效果"},diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 43f863c4..3474d6cc 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -554,6 +554,13 @@ constexpr Entry kSpanish[] = {// --- Preferences > Interface ---{"Language", "Idioma"},+ {"Units", "Unidades"},+ {"OBJ/PLY in", "OBJ/PLY en"},+ {"Part size", "Tamaño de la parte"},+ {"Export size", "Tamaño al exportar"},+ {"The unit sizes show in: the brush size, the Part size in Tool and the export size in File. SculptForge works in metres; this only changes how sizes read.", "La unidad en que se muestran los tamaños: el tamaño del pincel, el tamaño de la parte en Tool y el tamaño al exportar en File. SculptForge trabaja en metros; esto solo cambia cómo se leen los tamaños."},+ {"OBJ and PLY files have no units. Their numbers are read in this unit (mm for most 3D printing files, m for Blender and game tools), and exporting OBJ or PLY writes them back in the unit they were opened with, so a part keeps its size. STL is always millimetres.", "Los archivos OBJ y PLY no tienen unidades. Sus números se leen en esta unidad (mm para la mayoría de archivos de impresión 3D, m para Blender y herramientas de juegos), y al exportar OBJ o PLY se escriben en la unidad con la que se abrieron, así la parte conserva su tamaño. STL siempre está en milímetros."},+ {"The active Part's width x height x depth (X, Y, Z). The unit is set in Preferences > Interface > Units; STL exports write it in millimetres.", "Ancho x alto x profundidad de la parte activa (X, Y, Z). La unidad se elige en Preferences > Interface > Units; las exportaciones STL la escriben en milímetros."},{"The language of menus, palettes, shelves and messages. Brush and tool names (Quad Remesh, Forge Spheres, ""Clay Block...) stay as they are.","El idioma de los menús, las paletas, los estantes y los mensajes. Los nombres de pinceles y herramientas "diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cppindex b71f139a..3d050163 100644--- a/src/app/I18nTraditionalChinese.cpp+++ b/src/app/I18nTraditionalChinese.cpp@@ -463,6 +463,13 @@ constexpr Entry kTraditionalChinese[] = {// --- Preferences > Config ---// --- Preferences > Interface ---{"Language", "語言"},+ {"Units", "單位"},+ {"OBJ/PLY in", "OBJ/PLY 單位"},+ {"Part size", "部件尺寸"},+ {"Export size", "匯出尺寸"},+ {"The unit sizes show in: the brush size, the Part size in Tool and the export size in File. SculptForge works in metres; this only changes how sizes read.", "尺寸顯示所用的單位:筆刷大小、Tool 中的部件尺寸,以及 File 中的匯出尺寸。SculptForge 以公尺運作;這只改變尺寸的顯示方式。"},+ {"OBJ and PLY files have no units. Their numbers are read in this unit (mm for most 3D printing files, m for Blender and game tools), and exporting OBJ or PLY writes them back in the unit they were opened with, so a part keeps its size. STL is always millimetres.", "OBJ 和 PLY 檔案沒有單位。其數值以此單位讀取(大多數 3D 列印檔案用 mm,Blender 和遊戲工具用 m),匯出 OBJ 或 PLY 時會以開啟時的單位寫回,因此部件保持原尺寸。STL 一律為公釐。"},+ {"The active Part's width x height x depth (X, Y, Z). The unit is set in Preferences > Interface > Units; STL exports write it in millimetres.", "目前部件的寬 x 高 x 深(X、Y、Z)。單位在 Preferences > Interface > Units 設定;STL 匯出以公釐寫入。"},{"Tooltip delay", "工具提示延遲"},{"One sub-palette open", "一次只開啟一個子調色盤"},{"Reduce motion", "減少動態效果"},diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 542a065f..53d73d5f 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -17,6 +17,7 @@#include "app/I18n.h"#include "core/LitSphere.h"#include "core/StarterMeshes.h"+#include "core/Units.h"#include <IconsLucide.h>@@ -517,6 +518,23 @@ void App::drawPalette_Edit() {}}+// File > Import / Export (#148): the size the exports write, in the Units preference, and the unit STL, OBJ and PLY+// numbers are written in (the unit-less file the scene was opened from, else each format's convention).+void App::drawExportSizeLine() {+ const AABB b = doc_.visibleBounds();+ if (!b.valid()) return;+ ImGui::TextDisabled("%s", (std::string(tr("Export size")) + ": " + formatSize(b.extent(), lengthUnit())).c_str());+ const LengthUnit* stl = unitForScale(doc_.unitlessExportScale("stl"));+ const LengthUnit* obj = unitForScale(doc_.unitlessExportScale("obj"));+ const std::string from = doc_.unitlessFormat.empty() ? std::string()+ : " (as the " + doc_.unitlessFormat + " it was opened from)";+ const std::string help = "The visible Parts' width x height x depth. Every export keeps this size: STL writes " ++ std::string(stl ? stl->id : "custom units") + ", OBJ and PLY write " ++ std::string(obj ? obj->id : "custom units") + from ++ ", glTF and USD metres, FBX centimetres. Units: Preferences > Interface.";+ ui::HelpText("Export size", nullptr, help.c_str(), "File");+}+void App::drawPalette_File() {menuAction(*this, "file.new_sphere");menuAction(*this, "file.new_plane");@@ -536,6 +554,7 @@ void App::drawPalette_File() {menuAction(*this, "file.open");drawFileMenuProjectItems(); // Open Recent, Save, Save As, autosavetray::GroupLabel(*this, "Import / Export");+ drawExportSizeLine();menuAction(*this, "file.import");menuAction(*this, "file.export_obj");menuAction(*this, "file.export_stl");@@ -794,6 +813,14 @@ void App::drawPalette_Tool() {std::snprintf(tris, sizeof tris, "%zu tris", doc_.mesh.triangleCount());ImGui::SameLine(ImGui::GetContentRegionMax().x - ImGui::CalcTextSize(tris).x);ImGui::TextDisabled("%s", tris);+ // The Part's size, width x height x depth, in the Units preference (#148).+ if (const AABB b = doc_.mesh.bounds(); b.valid()) {+ ImGui::TextDisabled("%s", formatSize(b.extent(), lengthUnit()).c_str());+ ui::HelpText("Part size", nullptr,+ "The active Part's width x height x depth (X, Y, Z). The unit is set in Preferences > Interface > "+ "Units; STL exports write it in millimetres.",+ "Tool");+ }actionRow(*this, {"file.open", "file.save", "file.import"});ImGui::Dummy(ImVec2(0, 2.0f * s));}diff --git a/src/app/Precision.cpp b/src/app/Precision.cppindex f0bbfa81..eec7ecc3 100644--- a/src/app/Precision.cpp+++ b/src/app/Precision.cpp@@ -2,12 +2,13 @@// SPDX-License-Identifier: GPL-3.0-or-later//// Precision work, the app side of core/Precision.h: Steady Stroke with every stroke type (and its catch-up on-// release), World Size (Size kept in model units, shown in mm), the precision drag (Shift+Alt mid-stroke),+// release), World Size (Size kept in model units, shown in the Units preference), the precision drag (Shift+Alt mid-stroke),// the size readout by the brush, and each brush's own pressure curve (Brush Lab, Preferences > Tablet).#include "app/App.h"#include "app/Theme.h"#include "app/Ui.h"+#include "core/Units.h"#include <imgui_internal.h>@@ -65,21 +66,28 @@ namespace {std::filesystem::path utf8Path(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }-std::string mmText(float mm) {+// "0.42 mm", "12.5 mm", "289 mm" (or cm, m, in).+std::string sizeText(float metres, const LengthUnit& unit) {+ const double v = double(metres) * unit.perMetre;char buf[32];- std::snprintf(buf, sizeof buf, mm < 1.0f ? "%.2f mm" : mm < 100.0f ? "%.1f mm" : "%.0f mm", double(mm));+ std::snprintf(buf, sizeof buf, v < 1.0 ? "%.2f %s" : v < 100.0 ? "%.1f %s" : "%.0f %s", v, unit.id);return buf;}-float shownMm(float radiusPx, float worldRadius, bool worldSize, float wpp) {- return (worldSize && worldRadius > 0.0f ? worldRadius : radiusPx * wpp) * kMmPerUnit;+float shownRadius(float radiusPx, float worldRadius, bool worldSize, float wpp) {+ return worldSize && worldRadius > 0.0f ? worldRadius : radiusPx * wpp;}} // namespace+const LengthUnit& App::lengthUnit() const {+ const LengthUnit* u = findLengthUnit(uiPrefs_.lengthUnit);+ return u ? *u : millimetres();+}+std::string App::drawSizeLabel() const {std::string s = radiusPx_ < 10.0f ? "Size %.1f px" : "Size %.0f px";- if (cursorWorldPerPx_ > 0.0f) s += " " + mmText(shownMm(radiusPx_, worldRadius_, worldSize_, cursorWorldPerPx_));+ if (cursorWorldPerPx_ > 0.0f) s += " " + sizeText(shownRadius(radiusPx_, worldRadius_, worldSize_, cursorWorldPerPx_), lengthUnit());return s;}@@ -87,7 +95,7 @@ std::string App::drawSizeStatus() const {char buf[96];std::snprintf(buf, sizeof buf, radiusPx_ < 10.0f ? "Size %.1f px" : "Size %.0f px", double(radiusPx_));std::string s = buf;- if (cursorWorldPerPx_ > 0.0f) s += " (" + mmText(shownMm(radiusPx_, worldRadius_, worldSize_, cursorWorldPerPx_)) + ")";+ if (cursorWorldPerPx_ > 0.0f) s += " (" + sizeText(shownRadius(radiusPx_, worldRadius_, worldSize_, cursorWorldPerPx_), lengthUnit()) + ")";return s;}diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 878704fb..af1ef556 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -29,6 +29,7 @@#include "core/FaceGroups.h"#include "core/SelectionSets.h"#include "core/Parts.h"+#include "core/Units.h"#include "core/VertexPaint.h"#include "core/Primitives.h"#include "core/Project.h"@@ -118,6 +119,28 @@ std::string jsonEscape(const std::string& s) {return out;}+// The `unit` argument of open / open_obj (core/Units.h): numbers per metre in an STL, OBJ or PLY. Empty: the+// format's convention (STL millimetres, OBJ and PLY metres). Null with `err` set for an unknown unit.+const LengthUnit* fileUnitArg(const Args& a, const std::string& ext, std::string& err) {+ const std::string id = argString(a, "unit");+ if (id.empty()) return ext == ".stl" ? &millimetres() : &metres();+ const LengthUnit* u = findLengthUnit(id);+ if (!u) err = "Unknown unit '" + id + "' (mm, cm, m or in)";+ return u;+}++// File numbers to metres, rounded once from double (so writing them back at `perMetre` gives the numbers again).+void fileUnitsToMetres(Mesh& m, double perMetre) {+ if (perMetre == 1.0) return;+ for (glm::vec3& p : m.positions) p = glm::vec3(glm::dvec3(p) / perMetre);+ for (auto& layer : m.layers)+ for (glm::vec3& d : layer.delta) d = glm::vec3(glm::dvec3(d) / perMetre);+}++constexpr const char* kUnitArgHelp = "Unit of the numbers in a unit-less file (STL, OBJ, PLY): mm, cm, m or in. Default "+ "mm for STL, m for OBJ and PLY. Exports to the same kind of file write that unit "+ "back, so the part keeps its size.";+} // namespaceCommandRegistry::CommandRegistry() {@@ -158,15 +181,20 @@ CommandRegistry::CommandRegistry() {add({"open_obj","Load a Wavefront OBJ file, replacing the current scene.",- {{"path", T::String, "File path (UTF-8).", true}},+ {{"path", T::String, "File path (UTF-8).", true}, {"unit", T::String, kUnitArgHelp, false}},[](Document& doc, const Args& a) -> CommandResult {std::string path = argString(a, "path");std::vector<MeshObject> objects;std::string err;+ const LengthUnit* unit = fileUnitArg(a, ".obj", err);+ if (!unit) return {false, err};if (!loadObj(path, objects, err)) return {false, err};+ for (auto& o : objects) fileUnitsToMetres(o.mesh, unit->perMetre);const size_t count = objects.size();setSceneObjects(doc, std::move(objects), fileStem(path));doc.path = path;+ doc.unitlessScale = unit->perMetre;+ doc.unitlessFormat = "obj";return {true, "Loaded " + path + (count > 1 ? " (" + std::to_string(count) + " Parts)" : "")};}});@@ -176,7 +204,7 @@ CommandRegistry::CommandRegistry() {"glTF morph targets and FBX/USD blend shapes become sculpt layers. Files with several objects (OBJ `o`, ""glTF nodes, FBX models, USD meshes) open as one Part each. SculptForge projects (.sfproj) ""restore the whole scene.",- {{"path", T::String, "File path (UTF-8).", true}},+ {{"path", T::String, "File path (UTF-8).", true}, {"unit", T::String, kUnitArgHelp, false}},[](Document& doc, const Args& a) -> CommandResult {std::string path = argString(a, "path");if (isProjectPath(path)) return openProjectCommand(doc, path);@@ -186,19 +214,26 @@ CommandRegistry::CommandRegistry() {SplatCloud splats;std::string err;BridgeInfo bridge;+ const LengthUnit* unit = fileUnitArg(a, ext, err);+ if (!unit) return {false, err};+ const bool unitless = ext == ".stl" || ext == ".ply" || ext == ".obj";bool ok;if (ext == ".glb" || ext == ".gltf") ok = loadGltf(path, objects, err, &splats);else if (ext == ".usda" || ext == ".usd" || ext == ".usdz") ok = loadUsd(path, objects, splats, err);else if (ext == ".splat") ok = loadDotSplat(path, splats, err);else if (ext == ".fbx") ok = loadFbx(path, objects, err);else if (ext == bridgefile::kExtLower) ok = loadBridge(path, m, err, &bridge);- else if (ext == ".stl") ok = loadStl(path, m, err);+ else if (ext == ".stl") ok = loadStl(path, m, err, unit->perMetre);else if (ext == ".sculptforge") ok = loadBridgeFolder(path, objects, err); // numbered Bridge fileselse if (ext == ".ply") {PlyContent content;ok = loadPly(path, m, splats, content, err);} else ok = loadObj(path, objects, err);if (!ok) return {false, err};+ if (ext == ".obj" || ext == ".ply") {+ fileUnitsToMetres(m, unit->perMetre);+ for (auto& o : objects) fileUnitsToMetres(o.mesh, unit->perMetre);+ }if (m.triangleCount() > 0) objects.push_back({"", std::move(m)});std::erase_if(objects, [](const MeshObject& o) { return o.mesh.triangleCount() == 0; });std::string msg = "Opened " + std::filesystem::path(path).filename().string(); // file name only: status shows in screen recordings@@ -214,6 +249,10 @@ CommandRegistry::CommandRegistry() {setSceneObjects(doc, std::move(objects), ext == bridgefile::kExtLower && !bridge.name.empty() ? bridge.name : fileStem(path));doc.path = ext == ".obj" ? path : std::string(); // other formats are exported explicitlyif (ext == bridgefile::kExtLower) doc.bridgeName = bridge.name;+ if (unitless) { // exports write this unit back (Document::unitlessScale)+ doc.unitlessScale = unit->perMetre;+ doc.unitlessFormat = ext.substr(1);+ }msg += " (" + (count > 1 ? std::to_string(count) + " Parts, " : std::string()) + std::to_string(tris) +" triangles" + (quads == 0 ? "" : ", " + std::to_string(quads) + " quads") + (layers == 0 ? "" : ", " + std::to_string(layers) + " layers") + ")";}@@ -331,7 +370,8 @@ CommandRegistry::CommandRegistry() {"Export the visible Parts as a Wavefront OBJ file (one `o` object each, face groups as `g` groups). OBJ ""cannot hold the mask, visibility, sculpt layers or splats, so this is an export: the document keeps its ""path and unsaved-changes state. UVs are kept; a textured Part also writes <name>.mtl and its PNG beside "- "the file.",+ "the file. Positions are in metres, or in the units of the STL/OBJ/PLY the scene was opened from (an STL's "+ "millimetres stay millimetres).",{{"path", T::String, "File path (UTF-8). Defaults to the current document path unless that is a project.", false}},[](Document& doc, const Args& a) -> CommandResult {std::string path = argString(a, "path", isProjectPath(doc.path) ? std::string() : doc.path);@@ -340,7 +380,7 @@ CommandRegistry::CommandRegistry() {std::string err;const auto objects = visiblePartObjects(doc);if (objects.empty()) return {false, "Nothing visible to export"};- if (!saveObj(path, objects, err)) return {false, err};+ if (!saveObj(path, objects, err, doc.unitlessExportScale("obj"))) return {false, err};return {true, "Saved " + path + objectCountText(objects)};}});diff --git a/src/core/Document.cpp b/src/core/Document.cppindex 10cac296..4bb3381f 100644--- a/src/core/Document.cpp+++ b/src/core/Document.cpp@@ -26,6 +26,8 @@ void Document::setMesh(Mesh m, std::string name, BVH* built) {activeLayer = -1;bvhDirty = false;bridgeName.clear();+ unitlessScale = 0.0;+ unitlessFormat.clear();qremeshGuides.clear();parts.clear();parts.emplace_back();@@ -241,4 +243,9 @@ void Document::replaceMeshUndoable(Mesh m, std::string label) {if (activeLayer >= static_cast<int>(mesh.layers.size())) activeLayer = -1;}+double Document::unitlessExportScale(const std::string& format) const {+ if (format == "stl") return unitlessFormat == "stl" && unitlessScale > 0.0 ? unitlessScale : 1000.0;+ return unitlessScale > 0.0 ? unitlessScale : 1.0;+}+} // namespace sfdiff --git a/src/core/Document.h b/src/core/Document.hindex bc85db1d..ae081731 100644--- a/src/core/Document.h+++ b/src/core/Document.h@@ -100,6 +100,14 @@ struct Document {bool bvhDirty = false; // set after whole-mesh deformations (e.g. layer weights)// Part name of a mesh that came (Bridge), so sending it back updates that Part.std::string bridgeName;+ // The unit-less file (STL, OBJ, PLY; core/Units.h) the scene was opened from: numbers per metre in it (1000+ // for millimetres) and its format ("stl", "obj", "ply"). OBJ and PLY exports write in that unit, STL exports+ // too when it was an STL (else millimetres), so a part comes out at the size and numbers it went in with.+ // 0 / empty = no such file: each format's default (OBJ, PLY metres; STL millimetres).+ double unitlessScale = 0.0;+ std::string unitlessFormat;+ // File units per metre for an export to `format` ("stl", "obj", "ply") under the rules above.+ double unitlessExportScale(const std::string& format) const;// QRemesh Guides of the active Part: curves QRemesh's edge loops follow (core/QRemeshGuides.h). Not part// of undo (Delete Last / Clear remove them); editing them sets `modified`.std::vector<QRemeshGuide> qremeshGuides;diff --git a/src/core/Parts.cpp b/src/core/Parts.cppindex 59563684..bef37cad 100644--- a/src/core/Parts.cpp+++ b/src/core/Parts.cpp@@ -341,6 +341,7 @@ void registerPartCommands(CommandRegistry& reg) {"It becomes the active Part.",{{"type", T::String, "'sphere' (default), 'cube', 'plane', 'cylinder', 'cone', 'torus', 'capsule', 'icosphere' or 'quadsphere'.", false},{"path", T::String, "Model file to append instead of a primitive (.obj, .glb, .fbx, .ply, .stl, .usd...).", false},+ {"unit", T::String, "Unit of the numbers in an STL, OBJ or PLY file (mm, cm, m, in), as open's.", false},{"name", T::String, "Name for the new Part.", false},{"size", T::Number, "Primitive size relative to the largest visible Part (0.05-2). Default 0.35.", false}},[](Document& doc, const Args& a) -> CommandResult {@@ -351,7 +352,9 @@ void registerPartCommands(CommandRegistry& reg) {// each object in the file becomes its own Part.Document scratch;const std::string path = argString(a, "path");- CommandResult r = CommandRegistry().execute(scratch, "open", {{"path", path}});+ Args openArgs{{"path", path}};+ if (a.contains("unit")) openArgs["unit"] = argString(a, "unit");+ CommandResult r = CommandRegistry().execute(scratch, "open", openArgs);if (!r.ok) return r;if (scratch.partCount() == 1) {if (scratch.mesh.triangleCount() == 0) return {false, path + " has no mesh to append"};diff --git a/src/core/Project.cpp b/src/core/Project.cppindex 8cca7f0c..ba21918c 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -19,6 +19,7 @@#include <atomic>#include <bit>#include <cctype>+#include <cmath>#include <cstring>#include <deque>#include <filesystem>@@ -55,7 +56,8 @@ ProjectThumbnailProvider& thumbnailProvider() {// version 1); every other key belongs to// Document::projectSettings (camera, render, brush, symmetry, ...).const char* const kCoreKeys[] = {"format", "version", "app_version", "mesh", "layers", "active_layer",- "parts", "active_part", "brushes", "active_brush", "splats", "attachments"};+ "parts", "active_part", "brushes", "active_brush", "splats", "attachments",+ "unitless_scale", "unitless_format"};std::filesystem::path fsPath(const std::string& p) { return std::filesystem::path(std::u8string(p.begin(), p.end())); }@@ -981,6 +983,11 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erroif (doc.projectSettings.isObject())for (const auto& [key, value] : doc.projectSettings.members())if (!isCoreKey(key)) manifest.set(key, value);+ // The unit-less file the scene came from (Document::unitlessScale). Optional: older readers ignore it.+ if (doc.unitlessScale > 0.0) {+ manifest.set("unitless_scale", doc.unitlessScale);+ manifest.set("unitless_format", doc.unitlessFormat);+ }manifest.set("version", version.version);const std::string text = manifest.dump(true);@@ -1161,6 +1168,11 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {s.qremeshGuides = std::move(parts[i].qremeshGuides);}doc.selectPart(activePart);+ if (const double scale = manifest["unitless_scale"].asNumber(0.0); scale > 0.0 && std::isfinite(scale)) {+ doc.unitlessScale = scale;+ const std::string& format = manifest["unitless_format"].asString();+ doc.unitlessFormat = format == "stl" || format == "obj" || format == "ply" ? format : "";+ }doc.splats = std::move(splats);doc.splatsChanged();if (!skippedSets.empty())diff --git a/src/core/Units.cpp b/src/core/Units.cppnew file mode 100644index 00000000..258bfb66--- /dev/null+++ b/src/core/Units.cpp@@ -0,0 +1,87 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Units.h"++#include <algorithm>+#include <cctype>+#include <cmath>+#include <charconv>+#include <cstdio>++namespace sf {++namespace {++constexpr LengthUnit kUnits[] = {{"mm", 1000.0}, {"cm", 100.0}, {"m", 1.0}, {"in", 1.0 / 0.0254}};++// About four significant digits, no trailing zeros: 50, 12.5, 0.254, 1234.+std::string number(double v) {+ const double a = std::fabs(v);+ const int decimals = a >= 1000.0 ? 0 : a >= 100.0 ? 1 : a >= 10.0 ? 2 : a >= 1.0 ? 3 : 4;+ char buf[48];+ std::snprintf(buf, sizeof buf, "%.*f", decimals, v);+ std::string s = buf;+ if (s.find('.') != std::string::npos) {+ while (s.back() == '0') s.pop_back();+ if (s.back() == '.') s.pop_back();+ }+ return s == "-0" ? "0" : s;+}++// Characters in the shortest decimal form that reads back as `v`.+size_t shortestLength(float v) {+ char buf[32];+ const auto r = std::to_chars(buf, buf + sizeof buf, v);+ return size_t(r.ptr - buf);+}++} // namespace++float fromFileUnits(float value, double perMetre) { return float(double(value) / perMetre); }++float toFileUnits(float metres, double perMetre) {+ if (perMetre == 1.0) return metres;+ const float nearest = float(double(metres) * perMetre);+ if (!std::isfinite(nearest)) return nearest;+ float best = nearest;+ size_t bestLength = shortestLength(nearest);+ for (const float c : {std::nextafter(nearest, -INFINITY), std::nextafter(nearest, INFINITY)}) {+ if (fromFileUnits(c, perMetre) != metres) continue;+ const size_t length = shortestLength(c);+ if (length < bestLength) best = c, bestLength = length;+ }+ return best;+}++glm::vec3 toFileUnits(glm::vec3 metres, double perMetre) {+ return {toFileUnits(metres.x, perMetre), toFileUnits(metres.y, perMetre), toFileUnits(metres.z, perMetre)};+}++std::span<const LengthUnit> lengthUnits() { return kUnits; }++const LengthUnit* findLengthUnit(std::string_view id) {+ std::string lower(id);+ std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ if (lower == "inch" || lower == "inches") lower = "in";+ for (const LengthUnit& u : kUnits)+ if (lower == u.id) return &u;+ return nullptr;+}++const LengthUnit& millimetres() { return kUnits[0]; }+const LengthUnit& metres() { return kUnits[2]; }++const LengthUnit* unitForScale(double perMetre) {+ for (const LengthUnit& u : kUnits)+ if (std::fabs(u.perMetre - perMetre) <= 1e-9 * u.perMetre) return &u;+ return nullptr;+}++std::string formatLength(double metres, const LengthUnit& unit) { return number(metres * unit.perMetre) + " " + unit.id; }++std::string formatSize(glm::vec3 metres, const LengthUnit& unit) {+ return number(metres.x * unit.perMetre) + " x " + number(metres.y * unit.perMetre) + " x " ++ number(metres.z * unit.perMetre) + " " + unit.id;+}++} // namespace sfdiff --git a/src/core/Units.h b/src/core/Units.hnew file mode 100644index 00000000..9afad991--- /dev/null+++ b/src/core/Units.h@@ -0,0 +1,44 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Real-world lengths. A SculptForge unit is one metre; sizes show in the unit picked in Preferences (mm, cm, m,+// in), and unit-less files (OBJ, PLY; STL is millimetres by convention) are read in a unit too, which the scene+// remembers so exporting writes the numbers it was opened with (Document::unitlessScale).+#pragma once++#include <glm/glm.hpp>++#include <span>+#include <string>+#include <string_view>++namespace sf {++struct LengthUnit {+ const char* id; // "mm", "cm", "m", "in"+ double perMetre; // numbers in this unit per metre+};++// mm, cm, m, in.+std::span<const LengthUnit> lengthUnits();+// The unit called `id` (case-insensitive; "inch"/"inches" too), or null.+const LengthUnit* findLengthUnit(std::string_view id);+const LengthUnit& millimetres();+const LengthUnit& metres();+// The unit with this many numbers per metre (mm for 1000, ...), or null.+const LengthUnit* unitForScale(double perMetre);++// A file number in a unit to metres (`perMetre` numbers per metre), rounded once from double.+float fromFileUnits(float value, double perMetre);+// Metres to a number in the file unit: the float nearest metres * perMetre, or a neighbour that reads back as the+// same metres with a shorter decimal form, so a file value such as 12.7 that was read with fromFileUnits is+// written back exactly (any value with up to about 7 significant digits).+float toFileUnits(float metres, double perMetre);+glm::vec3 toFileUnits(glm::vec3 metres, double perMetre);++// "12.5 mm", "1.8 m", "2.36 in": `metres` in the unit, with about four significant digits.+std::string formatLength(double metres, const LengthUnit& unit);+// "50 x 20 x 12.5 mm": an extent (x, y, z) in the unit.+std::string formatSize(glm::vec3 metres, const LengthUnit& unit);++} // namespace sfdiff --git a/src/core/VertexPaint.cpp b/src/core/VertexPaint.cppindex 0b258660..55fff02e 100644--- a/src/core/VertexPaint.cpp+++ b/src/core/VertexPaint.cpp@@ -396,7 +396,8 @@ void registerPaintCommands(CommandRegistry& registry) {}});registry.add({"export_ply",- "Export the visible Parts as one binary PLY mesh with vertex colours (vertex paint), for scan tools, MeshLab, Blender.",+ "Export the visible Parts as one binary PLY mesh with vertex colours (vertex paint), for scan tools, MeshLab, Blender. "+ "In metres, or the units of the STL/OBJ/PLY the scene was opened from.",{{"path", T::String, "Output .ply path (UTF-8).", true}},[](Document& doc, const Args& a) -> CommandResult {const std::string path = argString(a, "path");@@ -404,7 +405,7 @@ void registerPaintCommands(CommandRegistry& registry) {Mesh merged; // no copy for a single Partconst Mesh& mesh = doc.partCount() == 1 ? doc.mesh : (merged = mergedVisibleMesh(doc));if (mesh.triangleCount() == 0) return {false, "Nothing visible to export"};- if (!savePlyMesh(path, mesh, err)) return {false, err};+ if (!savePlyMesh(path, mesh, err, doc.unitlessExportScale("ply"))) return {false, err};return {true, "Exported " + path + (mesh.hasColors() ? " (with vertex paint)" : "")};}});registerPaintLayerCommands(registry); // paint_layer_* (core/PaintLayer.cpp)diff --git a/src/io/BridgeCommands.cpp b/src/io/BridgeCommands.cppindex cf49076a..c0d2f21a 100644--- a/src/io/BridgeCommands.cpp+++ b/src/io/BridgeCommands.cpp@@ -190,10 +190,12 @@ void registerBridgeCommands(CommandRegistry& reg) {reg.add({"export_stl","Export the visible Parts as one binary STL mesh for 3D printing, in millimetres with Z up (what "- "slicers expect): 1 unit = 1 m in SculptForge becomes 1000 mm.",+ "slicers expect): 1 unit = 1 m in SculptForge becomes 1000 mm. A scene opened from an STL is written in "+ "that STL's unit (open's `unit`), so it comes back out with the numbers it went in with.",{{"path", T::String, "Output .stl path (UTF-8).", true},{"height_mm", T::Number, "Print height in millimetres: scales the model to this height (overrides scale).", false},- {"scale", T::Number, "File units per SculptForge unit. Default 1000 (metres to millimetres).", false},+ {"scale", T::Number, "File units per SculptForge unit. Default 1000 (metres to millimetres), or the "+ "unit of the STL the scene was opened from.", false},{"z_up", T::Bool, "Turn Y up into Z up, so the model stands upright on the print bed. Default true.", false}},[](Document& doc, const Args& a) -> CommandResult {const std::string path = argString(a, "path");@@ -202,14 +204,14 @@ void registerBridgeCommands(CommandRegistry& reg) {const Mesh& mesh = doc.partCount() == 1 ? doc.mesh : (merged = mergedVisibleMesh(doc));StlExportOptions o;o.heightMm = float(argNumber(a, "height_mm", 0.0));- o.scale = float(argNumber(a, "scale", 1000.0));+ o.scale = argNumber(a, "scale", doc.unitlessExportScale("stl"));o.zUp = argBool(a, "z_up", true);if (!saveStl(path, mesh, err, o)) return {false, err};- // In millimetres, the printed size as a slicer shows it: width x depth x height.+ // The size as a slicer shows it (width x depth x height): STL numbers are read as millimetres.std::string size;- if (o.zUp && (o.heightMm > 0.0f || o.scale == 1000.0f)) {+ if (o.zUp) {const glm::vec3 e = mesh.bounds().extent();- const float s = o.heightMm > 0.0f ? o.heightMm / e.y : o.scale;+ const double s = o.heightMm > 0.0f ? double(o.heightMm) / e.y : o.scale;char text[96];std::snprintf(text, sizeof(text), ", %.1f x %.1f x %.1f mm", e.x * s, e.z * s, e.y * s);size = text;diff --git a/src/io/FbxIO.cpp b/src/io/FbxIO.cppindex acebc6d2..81de34df 100644--- a/src/io/FbxIO.cpp+++ b/src/io/FbxIO.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/FbxIO.h"+#include "core/Units.h"+#include "io/TextureExport.h"#include "ufbx.h"@@ -207,7 +209,10 @@ Node makeGeometry(int64_t id, const std::string& name, const Mesh& mesh, float sconst auto& base = mesh.basePositions();std::vector<double> verts;verts.reserve(base.size() * 3);- for (const auto& p : base) verts.insert(verts.end(), {double(p.x * scale), double(p.y * scale), double(p.z * scale)});+ for (const auto& p : base) { // (core/Units.h: a centimetre file read in comes back with its numbers)+ const glm::vec3 f = toFileUnits(p, scale);+ verts.insert(verts.end(), {double(f.x), double(f.y), double(f.z)});+ }g.add("Vertices").f64s(verts);// Polygons: quads where the mesh keeps them (Mesh::quadPartners), else triangles; the last corner is negated.diff --git a/src/io/ObjIO.cpp b/src/io/ObjIO.cppindex 74c1d6bb..2f5990f2 100644--- a/src/io/ObjIO.cpp+++ b/src/io/ObjIO.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/ObjIO.h"+#include "core/Units.h"+#include "io/TextureExport.h"#include <algorithm>@@ -282,7 +284,7 @@ bool saveObj(const std::string& path, const Mesh& mesh, std::string& error) {return saveObj(path, std::vector<MeshObjectRef>{{"", &mesh}}, error);}-bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects, std::string& error) {+bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects, std::string& error, double scale) {if (objects.empty()) {error = "Nothing to export";return false;@@ -360,7 +362,7 @@ bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects,}const bool colors = mesh.colors.size() == mesh.positions.size() && mesh.hasColors();for (size_t i = 0; i < mesh.positions.size(); ++i) {- const glm::vec3& v = mesh.positions[i];+ const glm::vec3 v = toFileUnits(mesh.positions[i], scale); // (core/Units.h: 12.7 mm comes back as 12.7)int n;if (colors) {const glm::vec3 c = linearToSrgb(mesh.colors[i]);diff --git a/src/io/ObjIO.h b/src/io/ObjIO.hindex 2891224b..d20f401f 100644--- a/src/io/ObjIO.h+++ b/src/io/ObjIO.h@@ -27,7 +27,8 @@ bool loadObj(const std::string& path, std::vector<MeshObject>& out, std::string&bool saveObj(const std::string& path, const Mesh& mesh, std::string& error);// Several objects are written as `o name` blocks; a single one as a plain mesh.-// Face groups (two or more) are written as `g` groups.-bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects, std::string& error);+// Face groups (two or more) are written as `g` groups. `scale`: file units per SculptForge unit (metre); OBJ+// has no units, so 1 writes the numbers as they are and 1000 writes millimetres (Document::unitlessScale).+bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects, std::string& error, double scale = 1.0);} // namespace sfdiff --git a/src/io/PlyIO.cpp b/src/io/PlyIO.cppindex b26437c4..81509799 100644--- a/src/io/PlyIO.cpp+++ b/src/io/PlyIO.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/PlyIO.h"+#include "core/Units.h"+#include <algorithm>#include <bit>#include <cctype>@@ -471,7 +473,7 @@ bool saveDotSplat(const std::string& path, const SplatCloud& input, std::string&return true;}-bool savePlyMesh(const std::string& path, const Mesh& mesh, std::string& error) {+bool savePlyMesh(const std::string& path, const Mesh& mesh, std::string& error, double scale) {if (mesh.triangleCount() == 0) {error = "There is no mesh to save";return false;@@ -505,7 +507,7 @@ bool savePlyMesh(const std::string& path, const Mesh& mesh, std::string& error)auto putFloat = [&](float v) { put32(std::bit_cast<uint32_t>(v)); };for (size_t v = 0; v < mesh.vertexCount(); ++v) {- for (int c = 0; c < 3; ++c) putFloat(mesh.positions[v][c]);+ for (int c = 0; c < 3; ++c) putFloat(toFileUnits(mesh.positions[v][c], scale));if (normals)for (int c = 0; c < 3; ++c) putFloat(mesh.normals[v][c]);if (colors) {diff --git a/src/io/PlyIO.h b/src/io/PlyIO.hindex 7eebc136..b0f87131 100644--- a/src/io/PlyIO.h+++ b/src/io/PlyIO.h@@ -32,7 +32,7 @@ bool saveDotSplat(const std::string& path, const SplatCloud& splats, std::string// Writes a mesh (binary little-endian: positions, normals and, when the mesh// has vertex paint, uchar red/green/blue in sRGB; quads where Mesh::quadPartners-// keeps them, else triangles) that loadPly reads back.-bool savePlyMesh(const std::string& path, const Mesh& mesh, std::string& error);+// keeps them, else triangles) that loadPly reads back. `scale`: file units per SculptForge unit, as saveObj.+bool savePlyMesh(const std::string& path, const Mesh& mesh, std::string& error, double scale = 1.0);} // namespace sfdiff --git a/src/io/StlIO.cpp b/src/io/StlIO.cppindex 5c4c27f3..370ba8ca 100644--- a/src/io/StlIO.cpp+++ b/src/io/StlIO.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/StlIO.h"+#include "core/Units.h"+#include <cmath>#include <cstring>#include <filesystem>@@ -37,13 +39,20 @@ void putF32(std::vector<uint8_t>& out, float f) {constexpr char kLegacyHeader[] = "SculptForge binary STL";constexpr char kHeader[] = "SculptForge binary STL, millimetres, Z up";-// Millimetres with Z up (the file) to metres with Y up (the sculpt).-glm::vec3 fromPrintSpace(glm::vec3 p) { return glm::vec3(p.x, p.z, -p.y) * 0.001f; }+// Millimetres (or `perMetre`) with Z up (the file) to metres with Y up (the sculpt). Divided in double and rounded+// once, so writing it back (saveStl, or OBJ at Document::unitlessScale) gives the file's numbers.+glm::vec3 fromPrintSpace(glm::vec3 p, double perMetre) {+ return glm::vec3(fromFileUnits(p.x, perMetre), fromFileUnits(p.z, perMetre), fromFileUnits(-p.y, perMetre));+}// Turns a triangle soup into a welded mesh.-bool finish(Mesh& soup, Mesh& out, std::string& error, bool printSpace) {+bool finish(Mesh& soup, Mesh& out, std::string& error, bool printSpace, double perMetre) {+ if (!(perMetre > 0.0) || !std::isfinite(perMetre)) {+ error = "The unit scale must be a positive number";+ return false;+ }if (printSpace)- for (glm::vec3& p : soup.positions) p = fromPrintSpace(p);+ for (glm::vec3& p : soup.positions) p = fromPrintSpace(p, perMetre);for (uint32_t i = 0; i + 2 < soup.positions.size(); i += 3) soup.triangles.push_back({i, i + 1, i + 2});if (soup.triangles.empty()) {error = "STL file has no triangles";@@ -60,7 +69,7 @@ bool finish(Mesh& soup, Mesh& out, std::string& error, bool printSpace) {} // namespace-bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error) {+bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error, double perMetre) {Mesh soup;// Binary: 80-byte header, uint32 count, 50 bytes per triangle. Some// binary files also start with "solid", so the size decides.@@ -73,7 +82,7 @@ bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error) {const uint8_t* p = data.data() + 84 + t * 50 + 12; // skip the facet normalfor (int c = 0; c < 3; ++c, p += 12) soup.positions.push_back({readF32(p), readF32(p + 4), readF32(p + 8)});}- return finish(soup, out, error, !legacy);+ return finish(soup, out, error, !legacy, perMetre);}}const std::string text(reinterpret_cast<const char*>(data.data()), data.size());@@ -92,10 +101,10 @@ bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error) {}soup.positions.push_back(p);}- return finish(soup, out, error, true);+ return finish(soup, out, error, true, perMetre);}-bool loadStl(const std::string& path, Mesh& out, std::string& error) {+bool loadStl(const std::string& path, Mesh& out, std::string& error, double perMetre) {std::ifstream f(utf8Path(path), std::ios::binary);if (!f) {error = "Cannot open " + path;@@ -103,7 +112,7 @@ bool loadStl(const std::string& path, Mesh& out, std::string& error) {}std::vector<uint8_t> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());std::string err;- if (!parseStl(data, out, err)) {+ if (!parseStl(data, out, err, perMetre)) {error = err + ": " + path;return false;}@@ -115,24 +124,24 @@ bool saveStl(const std::string& path, const Mesh& mesh, std::string& error, conserror = "Nothing to export: the mesh is empty";return false;}- float scale = options.scale;+ double scale = options.scale;if (options.heightMm > 0.0f) {const float height = mesh.bounds().extent().y;if (!(height > 0.0f)) {error = "Cannot set a height: the mesh is flat";return false;}- scale = options.heightMm / height;+ scale = double(options.heightMm) / height;}if (!(scale > 0.0f) || !std::isfinite(scale)) {error = "The scale must be a positive number";return false;}- auto toFile = [&](glm::vec3 p) { return (options.zUp ? glm::vec3(p.x, -p.z, p.y) : p) * scale; };+ auto toFile = [&](glm::vec3 p) { return toFileUnits(options.zUp ? glm::vec3(p.x, -p.z, p.y) : p, scale); };std::vector<uint8_t> bytes;bytes.reserve(84 + mesh.triangleCount() * 50);// The header says millimetres only when the file is in millimetres with Z up.- const bool printSpace = options.zUp && (options.heightMm > 0.0f || options.scale == 1000.0f);+ const bool printSpace = options.zUp && (options.heightMm > 0.0f || options.scale == 1000.0);const std::string header = printSpace ? kHeader : "SculptForge binary STL, custom scale";bytes.insert(bytes.end(), header.begin(), header.end());bytes.resize(80, 0);diff --git a/src/io/StlIO.h b/src/io/StlIO.hindex 4134c79e..41bfc61c 100644--- a/src/io/StlIO.h+++ b/src/io/StlIO.h@@ -15,16 +15,16 @@namespace sf {struct StlExportOptions {- float scale = 1000.0f; // file units per metre (1000: millimetres)+ double scale = 1000.0; // file units per metre (1000: millimetres)float heightMm = 0.0f; // > 0: scale so the model is this tall (Y in SculptForge, Z in the file); overrides `scale`bool zUp = true; // turn Y up into the Z up that slicers and printers use};-// Files are read as millimetres with Z up, except binary files written by-// SculptForge 0.5 and earlier (in metres, Y up), which are recognised by their+// Files are read as millimetres with Z up (`perMetre`: file numbers per metre, 1000; 1 / 0.0254 for inches),+// except binary files written by SculptForge 0.5 and earlier (in metres, Y up), which are recognised by their// header and kept as stored. Coincident corners are welded into a connected mesh.-bool loadStl(const std::string& path, Mesh& out, std::string& error);-bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error);+bool loadStl(const std::string& path, Mesh& out, std::string& error, double perMetre = 1000.0);+bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error, double perMetre = 1000.0);// Writes binary STL (every triangle, including hidden ones). Paths are UTF-8.bool saveStl(const std::string& path, const Mesh& mesh, std::string& error, const StlExportOptions& options = {});diff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cppindex e045794a..3c1ffe85 100644--- a/src/io/UsdIO.cpp+++ b/src/io/UsdIO.cpp@@ -663,6 +663,7 @@ public:std::vector<Prim> prims;std::string upAxis = "Y";+ double metersPerUnit = 1.0; // the stage's unit (0.01: centimetres, as Maya and Houdini often write)std::string error;bool parse() {@@ -709,6 +710,11 @@ private:if (isPunct("=")) advance();if (tok_.kind == Token::String) upAxis = std::string(tok_.text);advance();+ } else if (isIdent("metersPerUnit")) {+ advance();+ if (isPunct("=")) advance();+ if (tok_.kind == Token::Number && tok_.number > 0.0 && std::isfinite(tok_.number)) metersPerUnit = tok_.number;+ advance();} else if (isPunct("(") || isPunct("[") || isPunct("{")) {skipBalanced();} else {@@ -1006,9 +1012,10 @@ bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>&std::map<std::string, size_t> byPath;for (size_t i = 0; i < prims.size(); ++i) byPath[prims[i].path] = i;- // World transforms (parents come first in `prims`).- const glm::mat4 up = parser.upAxis == "Z" ? glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1, 0, 0))- : glm::mat4(1.0f);+ // World transforms (parents come first in `prims`), in metres with Y up.+ const glm::mat4 up = glm::scale(parser.upAxis == "Z" ? glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1, 0, 0))+ : glm::mat4(1.0f),+ glm::vec3(float(parser.metersPerUnit)));std::vector<glm::mat4> world(prims.size());for (size_t i = 0; i < prims.size(); ++i) {bool reset = false;diff --git a/tests/data/print_part_50mm.stl b/tests/data/print_part_50mm.stlnew file mode 100644index 00000000..3697ccde--- /dev/null+++ b/tests/data/print_part_50mm.stl@@ -0,0 +1,86 @@+solid print_part_50mm+ facet normal 0 0 0+ outer loop+ vertex 0 0 0+ vertex 0 20 0+ vertex 50 20 0+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 0 0+ vertex 50 20 0+ vertex 50 0 0+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 0 12.5+ vertex 50 0 12.5+ vertex 50 20 12.5+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 0 12.5+ vertex 50 20 12.5+ vertex 0 20 12.5+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 0 0+ vertex 50 0 0+ vertex 50 0 12.5+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 0 0+ vertex 50 0 12.5+ vertex 0 0 12.5+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 20 0+ vertex 0 20 12.5+ vertex 50 20 12.5+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 20 0+ vertex 50 20 12.5+ vertex 50 20 0+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 0 0+ vertex 0 0 12.5+ vertex 0 20 12.5+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 0 0 0+ vertex 0 20 12.5+ vertex 0 20 0+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 50 0 0+ vertex 50 20 0+ vertex 50 20 12.5+ endloop+ endfacet+ facet normal 0 0 0+ outer loop+ vertex 50 0 0+ vertex 50 20 12.5+ vertex 50 0 12.5+ endloop+ endfacet+endsolid print_part_50mmdiff --git a/tests/test_units.cpp b/tests/test_units.cppnew file mode 100644index 00000000..566a231d--- /dev/null+++ b/tests/test_units.cpp@@ -0,0 +1,276 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Real-world size (#148): a part opened from a file comes back out at the size it went in, in every format, with+// the file's own numbers where the format has no units (STL millimetres, OBJ and PLY in the unit they were read+// in), USD stage units (metersPerUnit) read, projects keeping the unit, and the length formatting the UI shows.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Project.h"+#include "core/Units.h"+#include "io/GltfIO.h"+#include "io/ObjIO.h"+#include "io/PlyIO.h"+#include "io/UsdIO.h"++#include <cstring>+#include <filesystem>+#include <fstream>+#include <sstream>++using namespace sf;++namespace {++struct Box {+ glm::vec3 lo, hi;+};++// Decimal sizes a CAD tool or slicer writes: a 50 x 50 x 199.5 box off the origin, in the file's own numbers.+constexpr Box kBox{{-12.7f, 0.4f, 0.0f}, {37.3f, 50.4f, 199.5f}};++std::vector<glm::vec3> boxTriangles(const Box& b) {+ const glm::vec3 c[8] = {{b.lo.x, b.lo.y, b.lo.z}, {b.hi.x, b.lo.y, b.lo.z}, {b.hi.x, b.hi.y, b.lo.z},+ {b.lo.x, b.hi.y, b.lo.z}, {b.lo.x, b.lo.y, b.hi.z}, {b.hi.x, b.lo.y, b.hi.z},+ {b.hi.x, b.hi.y, b.hi.z}, {b.lo.x, b.hi.y, b.hi.z}};+ const int f[12][3] = {{0, 2, 1}, {0, 3, 2}, {4, 5, 6}, {4, 6, 7}, {0, 1, 5}, {0, 5, 4},+ {2, 3, 7}, {2, 7, 6}, {1, 2, 6}, {1, 6, 5}, {0, 4, 7}, {0, 7, 3}};+ std::vector<glm::vec3> out;+ for (const auto& t : f)+ for (int k : t) out.push_back(c[k]);+ return out;+}++void writeStl(const std::string& path, const Box& b) {+ const auto tris = boxTriangles(b);+ std::string bytes(80, '\0');+ const uint32_t n = uint32_t(tris.size() / 3);+ bytes.append(reinterpret_cast<const char*>(&n), 4);+ for (uint32_t t = 0; t < n; ++t) {+ const float normal[3] = {0, 0, 0};+ bytes.append(reinterpret_cast<const char*>(normal), 12);+ for (int k = 0; k < 3; ++k) bytes.append(reinterpret_cast<const char*>(&tris[t * 3 + k]), 12);+ bytes.append(2, '\0');+ }+ std::ofstream(std::filesystem::path(path), std::ios::binary) << bytes;+}++void writeObj(const std::string& path, const Box& b) {+ std::ostringstream s;+ const auto tris = boxTriangles(b);+ for (const auto& p : tris) s << "v " << p.x << " " << p.y << " " << p.z << "\n";+ for (size_t i = 0; i < tris.size(); i += 3) s << "f " << i + 1 << " " << i + 2 << " " << i + 3 << "\n";+ std::ofstream(std::filesystem::path(path), std::ios::binary) << s.str();+}++std::string readFile(const std::string& path) {+ std::ifstream f(std::filesystem::path(path), std::ios::binary);+ std::stringstream s;+ s << f.rdbuf();+ return s.str();+}++Box boundsOf(const std::vector<glm::vec3>& points) {+ Box b{glm::vec3(INFINITY), glm::vec3(-INFINITY)};+ for (const auto& p : points) b.lo = glm::min(b.lo, p), b.hi = glm::max(b.hi, p);+ return b;+}++// The numbers in the file, as a slicer reads them.+Box stlFileBounds(const std::string& path) {+ const std::string bytes = readFile(path);+ uint32_t n = 0;+ std::memcpy(&n, bytes.data() + 80, 4);+ std::vector<glm::vec3> pts;+ for (uint32_t t = 0; t < n; ++t)+ for (int k = 0; k < 3; ++k) {+ glm::vec3 p;+ std::memcpy(&p, bytes.data() + 84 + t * 50 + 12 + k * 12, 12);+ pts.push_back(p);+ }+ return boundsOf(pts);+}++Box objFileBounds(const std::string& path) {+ std::istringstream in(readFile(path));+ std::string line;+ std::vector<glm::vec3> pts;+ while (std::getline(in, line)) {+ if (line.rfind("v ", 0) != 0) continue;+ glm::vec3 p;+ std::istringstream(line.substr(2)) >> p.x >> p.y >> p.z;+ pts.push_back(p);+ }+ return boundsOf(pts);+}++Box meshBounds(const Mesh& m) { return boundsOf(m.positions); }++bool same(const Box& a, const Box& b) { return a.lo == b.lo && a.hi == b.hi; }+bool near(const Box& a, const Box& b, float rel = 1e-6f) {+ const float tol = rel * glm::length(b.hi - b.lo);+ return glm::length(a.lo - b.lo) <= tol && glm::length(a.hi - b.hi) <= tol;+}++// The box in the file, Z up, as SculptForge holds it (Y up): x, z, -y.+Box yUp(const Box& b) { return {{b.lo.x, b.lo.z, -b.hi.y}, {b.hi.x, b.hi.z, -b.lo.y}}; }+Box scaled(const Box& b, float s) { return {b.lo * s, b.hi * s}; }++} // namespace++TEST(units_stl_round_trip_exact) {+ const std::string in = tempPath("sf_units_in.stl"), out = tempPath("sf_units_out.stl");+ writeStl(in, kBox);+ CommandRegistry reg;+ Document doc;+ CHECK(reg.execute(doc, "open", {{"path", in}}).ok);+ CHECK(near(meshBounds(doc.mesh), scaled(yUp(kBox), 0.001f)));+ const CommandResult r = reg.execute(doc, "export_stl", {{"path", out}});+ CHECK(r.ok);+ CHECK(same(stlFileBounds(out), kBox)); // the slicer sees exactly the numbers that went in+ CHECK(r.message.find("50.0 x 50.0 x 199.5 mm") != std::string::npos);+ std::filesystem::remove(in);+ std::filesystem::remove(out);+}++TEST(units_stl_in_obj_and_ply_out_keep_millimetres) {+ const std::string in = tempPath("sf_units_mm.stl"), obj = tempPath("sf_units_mm.obj"), ply = tempPath("sf_units_mm.ply");+ writeStl(in, kBox);+ CommandRegistry reg;+ Document doc;+ CHECK(reg.execute(doc, "open", {{"path", in}}).ok);+ CHECK(reg.execute(doc, "save_obj", {{"path", obj}}).ok);+ CHECK(same(objFileBounds(obj), yUp(kBox))); // was 0.001x: millimetres in, metres out+ CHECK(reg.execute(doc, "export_ply", {{"path", ply}}).ok);+ Mesh m;+ SplatCloud splats;+ PlyContent content;+ std::string err;+ CHECK(loadPly(ply, m, splats, content, err));+ CHECK(same(meshBounds(m), yUp(kBox)));+ // A slicer reading that OBJ (millimetres) back into an STL-world: open the OBJ in mm, export STL.+ Document again;+ CHECK(reg.execute(again, "open", {{"path", obj}, {"unit", std::string("mm")}}).ok);+ const std::string stl = tempPath("sf_units_mm_again.stl");+ CHECK(reg.execute(again, "export_stl", {{"path", stl}}).ok);+ CHECK(same(stlFileBounds(stl), kBox));+ for (const auto& p : {in, obj, ply, stl}) std::filesystem::remove(p);+}++TEST(units_obj_units_round_trip_exact) {+ // An OBJ of a 50 mm part read in mm: exports to OBJ keep the numbers, STL writes the same millimetres.+ const std::string in = tempPath("sf_units_part.obj"), obj = tempPath("sf_units_part_out.obj"), stl = tempPath("sf_units_part.stl");+ writeObj(in, kBox);+ CommandRegistry reg;+ for (const char* unit : {"mm", "cm", "m", "in"}) {+ Document doc;+ CHECK(reg.execute(doc, "open", {{"path", in}, {"unit", std::string(unit)}}).ok);+ const double perMetre = findLengthUnit(unit)->perMetre;+ CHECK(near(meshBounds(doc.mesh), scaled(kBox, float(1.0 / perMetre))));+ CHECK(reg.execute(doc, "save_obj", {{"path", obj}}).ok);+ CHECK(same(objFileBounds(obj), kBox));+ CHECK(reg.execute(doc, "export_stl", {{"path", stl}}).ok);+ // STL is millimetres: the OBJ's unit converted, Y up turned into Z up.+ const Box zUp{{kBox.lo.x, -kBox.hi.z, kBox.lo.y}, {kBox.hi.x, -kBox.lo.z, kBox.hi.y}};+ CHECK(near(stlFileBounds(stl), scaled(zUp, float(1000.0 / perMetre))));+ if (std::string(unit) == "mm") CHECK(same(stlFileBounds(stl), zUp));+ }+ // open_obj takes the unit too.+ Document doc;+ CHECK(reg.execute(doc, "open_obj", {{"path", in}, {"unit", std::string("mm")}}).ok);+ CHECK(near(meshBounds(doc.mesh), scaled(kBox, 0.001f)));+ CHECK(!reg.execute(doc, "open", {{"path", in}, {"unit", std::string("furlong")}}).ok);+ for (const auto& p : {in, obj, stl}) std::filesystem::remove(p);+}++TEST(units_inch_stl_stays_inches) {+ const std::string in = tempPath("sf_units_in_in.stl"), out = tempPath("sf_units_in_out.stl");+ writeStl(in, kBox);+ CommandRegistry reg;+ Document doc;+ CHECK(reg.execute(doc, "open", {{"path", in}, {"unit", std::string("in")}}).ok);+ CHECK(near(meshBounds(doc.mesh), scaled(yUp(kBox), 0.0254f)));+ CHECK(reg.execute(doc, "export_stl", {{"path", out}}).ok);+ CHECK(same(stlFileBounds(out), kBox));+ std::filesystem::remove(in);+ std::filesystem::remove(out);+}++TEST(units_gltf_fbx_usd_keep_the_size) {+ // Unit-carrying formats: metres in glTF and USD, centimetres in FBX; reopening gives the same size.+ const std::string in = tempPath("sf_units_carry.stl");+ writeStl(in, kBox);+ CommandRegistry reg;+ Document doc;+ CHECK(reg.execute(doc, "open", {{"path", in}}).ok);+ const Box metres = meshBounds(doc.mesh);+ for (const char* ext : {".glb", ".usda", ".fbx"}) {+ const std::string out = tempPath((std::string("sf_units_carry") + ext).c_str());+ const char* cmd = std::string(ext) == ".glb" ? "export_glb" : std::string(ext) == ".usda" ? "export_usd" : "export_fbx";+ CHECK(reg.execute(doc, cmd, {{"path", out}}).ok);+ Document back;+ CHECK(reg.execute(back, "open", {{"path", out}}).ok);+ if (std::string(ext) == ".fbx") CHECK(near(meshBounds(back.mesh), metres));+ else CHECK(same(meshBounds(back.mesh), metres));+ std::filesystem::remove(out);+ }+ std::filesystem::remove(in);+}++TEST(units_usd_meters_per_unit) {+ // A centimetre stage (Maya, Houdini): 5 x 5 x 19.95 cm comes in as 0.05 x 0.05 x 0.1995 m, not 100x.+ const std::string path = tempPath("sf_units_cm.usda");+ std::ostringstream s;+ s << "#usda 1.0\n(\n metersPerUnit = 0.01\n upAxis = \"Y\"\n)\n\ndef Mesh \"Box\"\n{\n point3f[] points = [";+ const auto tris = boxTriangles(scaled(kBox, 0.1f));+ for (size_t i = 0; i < tris.size(); ++i) s << (i ? ", " : "") << "(" << tris[i].x << ", " << tris[i].y << ", " << tris[i].z << ")";+ s << "]\n int[] faceVertexCounts = [";+ for (size_t i = 0; i < tris.size() / 3; ++i) s << (i ? ", " : "") << 3;+ s << "]\n int[] faceVertexIndices = [";+ for (size_t i = 0; i < tris.size(); ++i) s << (i ? ", " : "") << i;+ s << "]\n}\n";+ std::ofstream(std::filesystem::path(path), std::ios::binary) << s.str();+ CommandRegistry reg;+ Document doc;+ CHECK(reg.execute(doc, "open", {{"path", path}}).ok);+ CHECK(near(meshBounds(doc.mesh), scaled(kBox, 0.001f)));+ std::filesystem::remove(path);+}++TEST(units_project_keeps_the_file_unit) {+ const std::string in = tempPath("sf_units_proj.stl"), proj = tempPath("sf_units_proj.sfproj"), obj = tempPath("sf_units_proj.obj");+ writeStl(in, kBox);+ CommandRegistry reg;+ Document doc;+ CHECK(reg.execute(doc, "open", {{"path", in}}).ok);+ CHECK(doc.unitlessScale == 1000.0 && doc.unitlessFormat == "stl");+ std::string err;+ CHECK(saveProject(proj, doc, err));+ Document back;+ CHECK(loadProject(proj, back, err));+ CHECK(back.unitlessScale == 1000.0 && back.unitlessFormat == "stl");+ CHECK(reg.execute(back, "save_obj", {{"path", obj}}).ok);+ CHECK(same(objFileBounds(obj), yUp(kBox)));+ // A new scene forgets it: OBJ is metres again.+ CHECK(reg.execute(back, "new_sphere", {}).ok);+ CHECK(back.unitlessScale == 0.0 && back.unitlessFormat.empty());+ CHECK(back.unitlessExportScale("obj") == 1.0 && back.unitlessExportScale("stl") == 1000.0);+ for (const auto& p : {in, proj, obj}) std::filesystem::remove(p);+}++TEST(units_format_and_parse) {+ CHECK(findLengthUnit("MM") == &millimetres());+ CHECK(findLengthUnit("inches") && std::string(findLengthUnit("inches")->id) == "in");+ CHECK(!findLengthUnit("ft"));+ CHECK(formatLength(0.05, millimetres()) == "50 mm");+ CHECK(formatLength(0.0254, *findLengthUnit("in")) == "1 in");+ CHECK(formatLength(1.8, metres()) == "1.8 m");+ CHECK(formatLength(0.0125, *findLengthUnit("cm")) == "1.25 cm");+ CHECK(formatSize(glm::vec3(0.05f, 0.02f, 0.0125f), millimetres()) == "50 x 20 x 12.5 mm");+ CHECK(unitForScale(1000.0) == &millimetres() && !unitForScale(7.0));+ // Writing back what was read: decimal file values come back exactly in every unit.+ for (const LengthUnit& u : lengthUnits())+ for (float v : {12.7f, 0.4f, 199.9f, -33.3f, 25.4f, 1234.567f, 0.001f})+ CHECK(toFileUnits(fromFileUnits(v, u.perMetre), u.perMetre) == v);+}diff --git a/tests/ui/units.sfui b/tests/ui/units.sfuinew file mode 100644index 00000000..d5796ca8--- /dev/null+++ b/tests/ui/units.sfui@@ -0,0 +1,33 @@+# Real-world size (#148): a 50 x 20 x 12.5 mm print part (STL, Z up) shows its size in Tool and File > Export size,+# in the unit picked in Preferences > Interface > Units; at 100% and 200% UI scale.+run ui_look look=classic layout=classic+run open path=$SCRIPT_DIR/../data/print_part_50mm.stl+ui_scale 100+wait_idle 30+click "Tool##palette.tool"+expect_text 50 x 12.5 x 20 mm+shot tool-size-1x+click "File##palette.file"+expect_text Export size: 50 x 12.5 x 20 mm+shot file-export-size-1x+click "Preferences##palette.preferences"+click "Interface##preferences.interface"+expect "mm##units.mm"+expect "m##file_units.m"+click "in##units.in"+shot units-prefs-1x+click "Tool##palette.tool"+expect_text 1.969 x 0.4921 x 0.7874 in+click "Preferences##palette.preferences"+click "cm##units.cm"+click "Tool##palette.tool"+expect_text 5 x 1.25 x 2 cm++ui_scale 200+wait_idle 30+shot tool-size-hidpi+click "File##palette.file"+expect_text Export size: 5 x 1.25 x 2 cm+shot file-export-size-hidpi+click "Preferences##palette.preferences"+shot units-prefs-hidpi