Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Convert 3D models between GLB, glTF, STL, OBJ, 3MF and PLY

KnifeLemon09d11bfda148
diff --git a/Directory.Packages.props b/Directory.Packages.props
index e08ef703..39f9b73a 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -47,6 +47,7 @@
<PackageVersion Include="MimeKitLite" Version="4.18.1" />
<PackageVersion Include="ACadSharp" Version="3.8.0" />
<PackageVersion Include="AngleSharp" Version="1.8.2" />
+ <PackageVersion Include="SharpGLTF.Core" Version="1.0.7" />
</ItemGroup>
<ItemGroup Label="Tests">
diff --git a/README.ko.md b/README.ko.md
index f6e5d109..233171f2 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -29,7 +29,7 @@
<table>
<tr>
<td width="33%" valign="top"><b>커서 바로 옆에서</b><br>앱 창을 열 필요가 없어요. 끌고 있는 파일에 맞는 형식만 지금 있는 자리에 나타나요.</td>
- <td width="33%" valign="top"><b>180가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD를 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>
+ <td width="33%" valign="top"><b>180가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>
<td width="33%" valign="top"><b>내 컴퓨터 안에서만</b><br>아무것도 업로드하지 않아요. 오프라인으로 동작하고 결과는 원본 옆에 저장해요.</td>
</tr>
</table>
@@ -95,6 +95,7 @@
| **압축 파일**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG 등 | 압축 풀기, ZIP, 7Z, TAR, TAR.GZ; 여러 파일 → ZIP 하나 |
| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |
| **글꼴**: TTF, OTF, WOFF, WOFF2, EOT | 서로 변환 |
+| **3D 모델**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY | 서로 변환, PNG 미리보기 |
표시가 없는 형식은 오피스·한컴오피스·LibreOffice 없이 바로 변환돼요.
표시가 있는 형식은 추가 엔진이 필요하고, 필요할 때만 내려받아요: ¹ Ghostscript, ² LibreOffice, ³ Pandoc,
diff --git a/README.md b/README.md
index c2f73df1..ec6611ac 100644
--- a/README.md
+++ b/README.md
@@ -29,7 +29,7 @@
<table>
<tr>
<td width="33%" valign="top"><b>Right at your cursor</b><br>No app window to open. The formats appear where you already are, only the ones that make sense for the files you drag.</td>
- <td width="33%" valign="top"><b>180 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts and CAD work without Office, Hancom Office or LibreOffice.</td>
+ <td width="33%" valign="top"><b>180 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td>
<td width="33%" valign="top"><b>Stays on your computer</b><br>Nothing is uploaded. Filee works offline and saves the result next to the original.</td>
</tr>
</table>
@@ -95,6 +95,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
| **Archives**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG, … | extract, ZIP, 7Z, TAR, TAR.GZ; any files → one ZIP |
| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |
| **Fonts**: TTF, OTF, WOFF, WOFF2, EOT | each other |
+| **3D models**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY | each other, PNG preview |
Unmarked formats work out of the box, without Office, Hancom Office or LibreOffice.
Marked ones need an optional engine, downloaded only when needed: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre,
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9ca8989c..a64a1e94 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -29,7 +29,7 @@
<table>
<tr>
<td width="33%" valign="top"><b>就在光标旁</b><br>无需打开应用窗口。只显示适合当前拖动文件的格式,就在你所在的位置。</td>
- <td width="33%" valign="top"><b>180 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体和 CAD,无需 Office、韩文办公软件或 LibreOffice。</td>
+ <td width="33%" valign="top"><b>180 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td>
<td width="33%" valign="top"><b>只在你的电脑上</b><br>不上传任何文件。Filee 离线工作,结果保存在原文件旁边。</td>
</tr>
</table>
@@ -94,6 +94,7 @@
| **压缩包**:ZIP、7Z、RAR、TAR、TAR.GZ、TAR.BZ2、TAR.XZ、GZ、ISO、CAB、DMG、ALZ、EGG 等 | 解压、ZIP、7Z、TAR、TAR.GZ;多个文件 → 一个 ZIP |
| **CAD**:DWG、DXF | PDF、SVG、PNG、DWG ↔ DXF |
| **字体**:TTF、OTF、WOFF、WOFF2、EOT | 互相转换 |
+| **3D 模型**:GLB、glTF、STL、OBJ(+ MTL)、3MF、PLY | 互相转换、PNG 预览 |
未标注的格式装好即用,无需 Office、韩文办公软件或 LibreOffice。
标注的格式需要可选引擎,只在需要时下载,分别是 ¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpeg
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index a8ca94ba..b3446e00 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -26,6 +26,7 @@ Each component remains under its own license.
| PdfPig (PDF text, layout and pictures) | Apache-2.0 | https://github.com/UglyToad/PdfPig |
| MimeKitLite (e-mail / MIME parsing) | MIT | https://github.com/jstedfast/MimeKit |
| ACadSharp (DWG/DXF reading and writing; includes CSMath and CSUtilities) | MIT, Copyright (c) Albert Domenech | https://github.com/DomCR/ACadSharp |
+| SharpGLTF.Core (glTF / GLB reading and writing) | MIT, Copyright (c) Vicente Penades | https://github.com/vpenades/SharpGLTF |
| AngleSharp | MIT | https://github.com/AngleSharp/AngleSharp |
| pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx |
| Microsoft.Extensions.* | MIT | https://github.com/dotnet/runtime |
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e1434f2f..cb6dc95f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -22,7 +22,7 @@
│ Built in: Magick (images, RAW) · PdfSharp · Pdfium · PdfPig · Svg.Skia · ICNS │
│ HwpxWriter + DocxWriter over DocumentReaders (DOCX, XLSX, XLS, ODS, PPTX, │
│ PDF, HTML, EPUB, MOBI, FB2, HWPX, Markdown) · Spreadsheets · OOXML variants │
- │ · E-mail · E-books · CAD · Fonts │
+ │ · E-mail · E-books · CAD · Fonts · 3D models │
│ Bundled: rhwp (HWP→PDF, HWP↔HWPX) · 7-Zip (archives) · Unhwp · Markdig │
│ Optional: FFmpeg · LibreOffice + H2Orestart · calibre · Ghostscript · Pandoc │
└────────────────────────────────────────────────────────────────────────────────────┘
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index da0fca5f..6ee27922 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -21,6 +21,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| E-mail | built in (MimeKit) | **EML → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments) |
| **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ → EPUB, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF |
| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
+| 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; → PNG, JPG, … (an isometric preview) |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
| Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files |
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats |
@@ -341,6 +342,57 @@ and writes the files; Filee's own renderer draws them with SkiaSharp (one drawin
segments in total; beyond that the drawing is cut short with a warning in the log. Damaged or truncated files fail
with "The file is not a valid DWG/DXF drawing or is damaged: …".
+## 3D models
+
+`Filee.Engines/Models3D` converts GLB, glTF, STL, OBJ, 3MF and PLY into each other in managed code: every reader
+fills one in-memory model (`Model3D`: parts with positions, normals, UVs, vertex colours and triangles; materials
+with a base colour and a base colour texture) and every writer takes it, so each pair is one step. glTF and GLB are
+read and written with [SharpGLTF](https://github.com/vpenades/SharpGLTF) (MIT); STL, OBJ/MTL, PLY and 3MF are Filee's
+own code. No native library (Assimp) and no download.
+
+- **Units**: STL, OBJ and PLY have none; they are read and written as **millimetres**, as slicers and CAD programs
+ treat them. 3MF has a `unit` attribute (micron to metre) and is written in millimetres. glTF is metres. So a 20 mm
+ STL cube is 0.02 m in GLB and 20 mm again in STL. There is no preset option for another unit.
+- **Axes** follow Blender's defaults: STL, 3MF and PLY are Z up, OBJ and glTF Y up, so a part standing on a printer's
+ bed stands upright in a glTF viewer and comes back on its base.
+- **Structure**: node hierarchies, 3MF components and build items are flattened: every mesh instance becomes a part in
+ world coordinates (one glTF node / OBJ object / 3MF object per part). Polygons are triangulated (ear clipping, so
+ concave faces are right). OBJ negative indices, `\` line continuations and 0–255 vertex colours are understood.
+- **Vertices**: binary STL is streamed in blocks and vertices are merged by position (a 1,000,000-triangle STL
+ converts to GLB in a few seconds with about 150 MB of memory). STL normals are not kept: GLB written from STL has
+ none, which glTF viewers must shade flat; STL output gets facet normals from the winding. 3MF output welds vertices
+ by position, so meshes split for normals or UVs stay closed for slicers.
+- **Colours**: vertex colours are kept as sRGB and converted to linear for glTF `COLOR_0`; material colours are glTF's
+ linear base colour, OBJ's `Kd` as it is and 3MF's sRGB `displaycolor`. glTF materials are written metallic-roughness,
+ not metallic, roughness 0.8.
+
+What each format keeps:
+
+| Format | Read | Written |
+|---|---|---|
+| GLB / glTF | default scene (else all root nodes), triangles, strips and fans, `POSITION`, `NORMAL`, `TEXCOORD_n` of the base colour texture, `COLOR_0`, base colour factor and texture (metallic-roughness or specular-glossiness), double-sided; `.gltf` with embedded (data URI) or separate `.bin` and picture files | one node and mesh per part, 16- or 32-bit indices, PNG/JPEG textures (others are converted to PNG); **`.gltf` is one self-contained file** (its buffer is a base64 data URI, about a third larger than GLB) |
+| STL | binary (also with a header starting with "solid") and ASCII (one part per `solid`) | binary, one solid |
+| OBJ + MTL | `o` / `g` / `usemtl` as parts, `v` (+ r g b), `vt`, `vn`, faces of any size; `mtllib` with `Kd`, `d` / `Tr`, `map_Kd` (options skipped) next to the file | **the `.mtl` and the textures are written next to the `.obj`** (`name.obj`, `name.mtl`, `name_texture.png`, named like the output); vertex colours as `v x y z r g b` |
+| 3MF | objects, components (also in other model parts, as Bambu Studio writes them), build transforms, base materials, colour groups (materials extension); `support` / `other` objects skipped | one object per part, base materials from material colours, a colour group from vertex colours |
+| PLY | ASCII, binary little / big endian; vertex position, normal, UV (`s`/`t`, `u`/`v`, `texture_u`/`texture_v`), colours of any type; face lists with per-corner `texcoord` and face colours; `comment TextureFile`; other elements skipped | binary little endian, one mesh; material colours become vertex colours |
+
+Lost on the way (no place in the target): **STL** keeps only the triangles (no colours, UVs, normals or materials);
+**PLY** has no materials (their colours become vertex colours, textures are dropped); **OBJ** has no standard vertex
+colours (the common `v x y z r g b` extension is written and read; alpha is lost); **3MF** output has no normals, UVs or
+textures; and every format drops what Filee's model has no place for: animations, skins, morph targets, cameras,
+lights, metallic / roughness / normal / emissive maps, and lines and points. Draco- and meshopt-compressed glTF fail with
+a clear message, as do damaged files ("cut short", an index that does not exist, no triangles).
+
+**3D → pictures**: a small software rasteriser (`MeshRenderer`) draws an isometric view from the front right, above,
+with one light and flat shading per triangle, vertex colours or the texture interpolated across it, and a z-buffer,
+at 2048 px and scaled down to 1024 px for smooth edges, on a transparent background. The preset's image options
+(resize, background for JPG, quality) apply as for other pictures.
+
+Tests (`tests/Filee.Engines.Tests/ModelTests.cs`) build a cube, a sphere and a fan of coloured triangles in code and
+convert each through every format pair, checking triangle counts, bounds, signed volume (winding), normals, UVs,
+colours and materials where both formats keep them; hand-written STL, OBJ, PLY, 3MF and glTF files cover the reading
+details, and a generated 1,000,000-triangle STL the speed.
+
## HWPX reader
`Hwp/Hwpx/HwpxReader*.cs` is the inverse of the writer: it reads an HWPX package into the same document model, so
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 2828fbba..35454c30 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -76,6 +76,7 @@
"engine.icns.description": "macOS app icons (ICNS) from and to images.",
"engine.font.description": "Fonts: TTF, OTF, WOFF, WOFF2 and EOT into each other.",
"engine.cad.description": "AutoCAD drawings: DWG ↔ DXF, and both to PDF, SVG and PNG.",
+ "engine.model3d.description": "3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other, and a PNG preview.",
"engine.archive.description": "Extracts ZIP, 7Z, RAR, TAR, ISO and more, and packs ZIP, 7Z or TAR.GZ (7-Zip).",
"engine.ebook.description": "EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) to PDF, EPUB, DOCX and text.\nAlso documents to EPUB and PDF to CBZ.",
"engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC and more.\nAlso extracts sound, makes GIFs and saves images as HEIC.",
@@ -98,6 +99,7 @@
"profile.archives": "Archives",
"profile.cad": "CAD drawings",
"profile.fonts": "Fonts",
+ "profile.models": "3D models",
"profile.mixed": "Mixed files",
"preset.half_size": "Half size",
@@ -124,6 +126,7 @@
"format.category.Vector": "Vector",
"format.category.Cad": "CAD",
"format.category.Font": "Font",
+ "format.category.Model3D": "3D model",
"general.title": "General",
"general.language": "Language",
@@ -500,7 +503,7 @@
"common.no": "No",
"setup.title": "Choose conversion engines",
- "setup.description": "Images, PDF, Office documents, HWP, e-books, archives, fonts and CAD already convert.\nDownload engines only for video and audio or rare formats.",
+ "setup.description": "Images, PDF, Office documents, HWP, e-books, archives, fonts, CAD and 3D models already convert.\nDownload engines only for video and audio or rare formats.",
"setup.note": "You can install or remove engines at any time in Settings → Engines.",
"setup.install": "Install selected",
"setup.later": "Later",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index c0074be4..f6010cd6 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -76,6 +76,7 @@
"engine.icns.description": "macOS 앱 아이콘(ICNS)을 이미지로, 이미지를 ICNS로.",
"engine.font.description": "글꼴: TTF, OTF, WOFF, WOFF2, EOT를 서로 변환해요.",
"engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.",
+ "engine.model3d.description": "3D 모델: GLB, glTF, STL, OBJ, 3MF, PLY를 서로 변환하고 PNG 미리보기도 만들어요.",
"engine.archive.description": "ZIP, 7Z, RAR, TAR, ISO 등을 풀고, ZIP·7Z·TAR.GZ로 묶어요(7-Zip).",
"engine.ebook.description": "EPUB, MOBI, AZW3, FB2, 만화책(CBZ, CBR)을 PDF, EPUB, DOCX, 텍스트로 바꿔요.\n문서는 EPUB으로, PDF는 CBZ로도 만들어요.",
"engine.ffmpeg.description": "MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC 등 동영상·오디오를 변환해요.\n소리 추출, GIF 만들기, 이미지 → HEIC도 해요.",
@@ -98,6 +99,7 @@
"profile.archives": "압축 파일",
"profile.cad": "CAD 도면",
"profile.fonts": "글꼴",
+ "profile.models": "3D 모델",
"profile.mixed": "혼합 파일",
"preset.half_size": "50% 축소",
@@ -124,6 +126,7 @@
"format.category.Vector": "벡터",
"format.category.Cad": "CAD",
"format.category.Font": "글꼴",
+ "format.category.Model3D": "3D 모델",
"general.title": "일반",
"general.language": "언어",
@@ -500,7 +503,7 @@
"common.no": "아니요",
"setup.title": "변환 엔진 선택",
- "setup.description": "이미지, PDF, 오피스 문서, HWP, 전자책, 압축 파일, 글꼴, CAD는 지금 바로 변환돼요.\n동영상·오디오나 드문 형식이 필요할 때만 엔진을 받으세요.",
+ "setup.description": "이미지, PDF, 오피스 문서, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델은 지금 바로 변환돼요.\n동영상·오디오나 드문 형식이 필요할 때만 엔진을 받으세요.",
"setup.note": "엔진은 언제든 설정 → 변환 엔진에서 설치하거나 제거할 수 있어요.",
"setup.install": "선택한 엔진 설치",
"setup.later": "나중에",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 8ec41bb7..4fa7f47f 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -76,6 +76,7 @@
"engine.icns.description": "macOS 应用图标(ICNS)与图片互转。",
"engine.font.description": "字体:TTF、OTF、WOFF、WOFF2 和 EOT 互相转换。",
"engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。",
+ "engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相转换,并可生成 PNG 预览。",
"engine.archive.description": "解压 ZIP、7Z、RAR、TAR、ISO 等,并打包为 ZIP、7Z 或 TAR.GZ(7-Zip)。",
"engine.ebook.description": "EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)转为 PDF、EPUB、DOCX 和文本。\n也能把文档转为 EPUB、把 PDF 转为 CBZ。",
"engine.ffmpeg.description": "MP4、MOV、MKV、WEBM、MP3、M4A、WAV、FLAC 等视频和音频。\n还能提取声音、制作 GIF、把图片保存为 HEIC。",
@@ -98,6 +99,7 @@
"profile.archives": "压缩文件",
"profile.cad": "CAD 图纸",
"profile.fonts": "字体",
+ "profile.models": "3D 模型",
"profile.mixed": "混合文件",
"preset.half_size": "缩小 50%",
@@ -124,6 +126,7 @@
"format.category.Vector": "矢量图",
"format.category.Cad": "CAD",
"format.category.Font": "字体",
+ "format.category.Model3D": "3D 模型",
"general.title": "常规",
"general.language": "语言",
@@ -500,7 +503,7 @@
"common.no": "否",
"setup.title": "选择转换引擎",
- "setup.description": "图片、PDF、Office 文档、HWP、电子书、压缩文件、字体和 CAD 现在就能转换。\n只有视频、音频或少见格式才需要下载引擎。",
+ "setup.description": "图片、PDF、Office 文档、HWP、电子书、压缩文件、字体、CAD 和 3D 模型现在就能转换。\n只有视频、音频或少见格式才需要下载引擎。",
"setup.note": "可随时在“设置 → 转换引擎”中安装或删除引擎。",
"setup.install": "安装所选引擎",
"setup.later": "稍后",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index b608376d..b41f4509 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -233,7 +233,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowMultiPageTiff => TargetId is "tiff";
public bool ShowIco => TargetId == "ico";
/// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive and font targets.</summary>
- public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font);
+ public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font or FormatCategory.Model3D);
public bool ShowPdfBuild => TargetId == "pdf";
public bool ShowPdfSplit => TargetId == "pdf";
diff --git a/src/Filee.Core/Formats/FileFormat.cs b/src/Filee.Core/Formats/FileFormat.cs
index c8049d3d..40a945f3 100644
--- a/src/Filee.Core/Formats/FileFormat.cs
+++ b/src/Filee.Core/Formats/FileFormat.cs
@@ -19,6 +19,7 @@ public enum FormatCategory
Vector,
Cad,
Font,
+ Model3D,
}
/// <summary>
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index 46c2be56..09542546 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -213,6 +213,14 @@ public static class FormatRegistry
new("woff", "WOFF", FormatCategory.Font, ["woff"]),
new("woff2", "WOFF2", FormatCategory.Font, ["woff2"]),
new("eot", "EOT", FormatCategory.Font, ["eot"]),
+
+ // 3D models
+ new("glb", "GLB", FormatCategory.Model3D, ["glb"]),
+ new("gltf", "glTF", FormatCategory.Model3D, ["gltf"]),
+ new("stl", "STL", FormatCategory.Model3D, ["stl"]),
+ new("obj", "OBJ", FormatCategory.Model3D, ["obj"]),
+ new("3mf", "3MF", FormatCategory.Model3D, ["3mf"]),
+ new("ply", "PLY", FormatCategory.Model3D, ["ply"]),
];
private static readonly Dictionary<string, FileFormat> ById =
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index 65fab5c3..57ee5d96 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -74,6 +74,7 @@ public static class BuiltInData
new() { Id = "to-html", Name = "HTML", TargetFormat = "html" },
.. SpreadsheetPresets(),
.. CatalogPresets(),
+ .. ModelPresets(),
];
/// <summary>HWP as a target, through HWPX (added in settings schema 7, see SettingsMigrations).</summary>
@@ -89,6 +90,17 @@ public static class BuiltInData
new() { Id = "to-csv", Name = "CSV", TargetFormat = "csv" },
];
+ /// <summary>3D model targets (added in settings schema 11, see SettingsMigrations). glTF is on no donut: GLB is the same in one file.</summary>
+ public static List<Preset> ModelPresets() =>
+ [
+ new() { Id = "to-glb", Name = "GLB", TargetFormat = "glb" },
+ new() { Id = "to-stl", Name = "STL", TargetFormat = "stl" },
+ new() { Id = "to-obj", Name = "OBJ", TargetFormat = "obj" },
+ new() { Id = "to-3mf", Name = "3MF", TargetFormat = "3mf" },
+ new() { Id = "to-ply", Name = "PLY", TargetFormat = "ply" },
+ new() { Id = "to-gltf", Name = "glTF", TargetFormat = "gltf" },
+ ];
+
/// <summary>
/// Targets of the formats added in settings schema 6: images, vector, office, e-books, video, audio, archives,
/// CAD and fonts (see SettingsMigrations).
@@ -196,6 +208,7 @@ public static class BuiltInData
},
TextProfile(),
.. CatalogProfiles(),
+ ModelProfile(),
new()
{
Id = "mixed", NameKey = "profile.mixed", IsFallback = true,
@@ -277,6 +290,15 @@ public static class BuiltInData
},
];
+ /// <summary>3D models: GLB, glTF, STL, OBJ, 3MF, PLY (added in settings schema 11, after "fonts").</summary>
+ public static ToolbarProfile ModelProfile() => new()
+ {
+ Id = "models",
+ NameKey = "profile.models",
+ Extensions = ExtensionsOf(FormatCategory.Model3D),
+ PresetIds = ["to-glb", "to-stl", "to-obj", "to-3mf", "to-ply", "to-png"],
+ };
+
/// <summary>Every file extension of the formats in <paramref name="category"/>.</summary>
public static List<string> ExtensionsOf(FormatCategory category) =>
FormatRegistry.Known.Where(f => f.Category == category)
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 7e4f98ea..ce93770b 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -50,7 +50,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 10;
+ public const int CurrentSchemaVersion = 11;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
@@ -89,7 +89,7 @@ public sealed class AppSettings
public List<string> EnginePriority { get; set; } =
[
"magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer",
- "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre",
+ "pdf-text", "email", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre",
"libreoffice",
];
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index ae92ef14..0204fead 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -252,6 +252,10 @@ internal static class SettingsMigrations
InsertBefore(settings.EnginePriority, id, "libreoffice");
}
+ // v11: built-in "model3d" engine (3D models: GLB, glTF, STL, OBJ, 3MF, PLY), next to the CAD engine.
+ if (settings.SchemaVersion < 11)
+ InsertBefore(settings.EnginePriority, "model3d", "archive");
+
if (settings.Triggers.Count == 0)
settings.Triggers = TriggerGesture.Defaults();
@@ -360,9 +364,38 @@ internal static class SettingsMigrations
presets.Add(BuiltInData.CreatePresets().Single(p => p.Id == "remove-background"));
changed = true;
}
+
+ // v11: 3D models (GLB, glTF, STL, OBJ, 3MF, PLY) get presets and their own donut after "fonts" (else before the
+ // mixed-files one), with the extensions no donut of the user takes yet.
+ if (from < 11)
+ changed |= AddModels(presets, profiles);
return changed;
}
+ private static bool AddModels(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ foreach (var preset in BuiltInData.ModelPresets().Where(p => presets.All(existing => existing.Id != p.Id)))
+ {
+ presets.Add(preset);
+ changed = true;
+ }
+ if (profiles.Any(p => p.Id == "models"))
+ return changed;
+
+ var claimed = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var models = BuiltInData.ModelProfile();
+ models.Extensions = models.Extensions.Where(claimed.Add).ToList();
+ if (models.Extensions.Count == 0)
+ return changed;
+ var ids = presets.Select(p => p.Id).ToHashSet();
+ models.PresetIds = models.PresetIds.Where(ids.Contains).ToList();
+ var fonts = profiles.FindIndex(p => p.Id == "fonts");
+ var insertAt = fonts >= 0 ? fonts + 1 : profiles.FindIndex(p => p.IsFallback);
+ profiles.Insert(insertAt < 0 ? profiles.Count : insertAt, models);
+ return true;
+ }
+
private static bool AddCatalog(List<Preset> presets, List<ToolbarProfile> profiles)
{
var changed = false;
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 731e3bf3..f3683bbb 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -12,6 +12,7 @@ using Filee.Engines.Icns;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
using Filee.Engines.Media;
+using Filee.Engines.Models3D;
using Filee.Engines.Office;
using Filee.Engines.Pdf;
using Filee.Engines.Text;
@@ -47,6 +48,7 @@ public static class EngineRegistry
new EmlConverter(),
new FfmpegConverter(),
new CadConverter(),
+ new ModelConverter(),
new EbookConverter(),
new PandocConverter(),
new GhostscriptConverter(),
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index 923aab6e..98ccb89e 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -28,6 +28,7 @@
<PackageReference Include="MimeKitLite" />
<PackageReference Include="ACadSharp" />
<PackageReference Include="AngleSharp" />
+ <PackageReference Include="SharpGLTF.Core" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
diff --git a/src/Filee.Engines/Models3D/GltfFormat.cs b/src/Filee.Engines/Models3D/GltfFormat.cs
new file mode 100644
index 00000000..d9db5624
--- /dev/null
+++ b/src/Filee.Engines/Models3D/GltfFormat.cs
@@ -0,0 +1,333 @@
+// glTF 2.0 (.gltf with embedded or separate buffers, and binary .glb) through SharpGLTF (MIT). Metres, Y up.
+// Read: the default scene's nodes flattened to world coordinates, triangle primitives (strips and fans too) with
+// POSITION, NORMAL, TEXCOORD_n, COLOR_0, and the base colour factor and texture of metallic-roughness or
+// specular-glossiness materials. Points, lines, skins, morph targets, animations and cameras are ignored.
+// Written: one node and mesh per part, metallic-roughness materials (not metallic, as OBJ / 3MF colours are meant),
+// textures as PNG or JPEG. A .gltf is written as one self-contained file: the buffer is a base64 data URI.
+
+using System.Numerics;
+using System.Text.Json.Nodes;
+using ImageMagick;
+using SharpGLTF.Memory;
+using SharpGLTF.Schema2;
+using SharpGLTF.Validation;
+
+namespace Filee.Engines.Models3D;
+
+internal static class GltfFormat
+{
+ private const float MillimetresPerMetre = 1000;
+
+ public static Model3D Read(string path, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ ModelRoot root;
+ try
+ {
+ root = ModelRoot.Load(path, new ReadSettings { Validation = ValidationMode.Skip });
+ }
+ catch (FileNotFoundException ex)
+ {
+ throw new InvalidDataException($"A file the glTF model refers to is missing: {Path.GetFileName(ex.FileName ?? ex.Message)}", ex);
+ }
+ catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException or IOException or UnauthorizedAccessException))
+ {
+ throw new InvalidDataException(Describe(ex), ex);
+ }
+ progress?.Report(0.4);
+ if (root.ExtensionsUsed.FirstOrDefault(e => e is "KHR_draco_mesh_compression" or "EXT_meshopt_compression" or "KHR_meshopt_compression") is { } compression)
+ throw new InvalidDataException(Describe(new NotSupportedException(compression)));
+
+ try
+ {
+ return ReadScene(root, cancellationToken);
+ }
+ catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException or InvalidDataException))
+ {
+ throw new InvalidDataException($"The glTF model could not be read: {ex.Message}", ex);
+ }
+ }
+
+ private static Model3D ReadScene(ModelRoot root, CancellationToken cancellationToken)
+ {
+ var model = new Model3D();
+ var materials = new Dictionary<Material, int>();
+ var scene = root.DefaultScene ?? root.LogicalScenes.FirstOrDefault();
+ var nodes = scene is not null
+ ? Node.Flatten(scene)
+ : root.LogicalNodes.Where(n => n.VisualParent is null).SelectMany(n => Node.Flatten(n));
+ var scale = Matrix4x4.CreateScale(MillimetresPerMetre);
+ foreach (var node in nodes)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (node.Mesh is not { } mesh)
+ continue;
+ var world = node.WorldMatrix * scale;
+ foreach (var primitive in mesh.Primitives)
+ {
+ if (primitive.DrawPrimitiveType is not (PrimitiveType.TRIANGLES or PrimitiveType.TRIANGLE_STRIP or PrimitiveType.TRIANGLE_FAN))
+ continue;
+ if (ReadPrimitive(primitive, model, materials) is { } part)
+ {
+ part.Name = mesh.Name ?? node.Name ?? $"Mesh {mesh.LogicalIndex + 1}";
+ part.Transform(world);
+ model.Parts.Add(part);
+ }
+ }
+ }
+ return model;
+ }
+
+ private static string Describe(Exception ex) =>
+ ex.Message.Contains("KHR_draco_mesh_compression", StringComparison.Ordinal)
+ ? "The glTF model is Draco-compressed (KHR_draco_mesh_compression), which Filee cannot decode."
+ : ex.Message.Contains("meshopt_compression", StringComparison.Ordinal)
+ ? "The glTF model is meshopt-compressed (EXT_meshopt_compression), which Filee cannot decode."
+ : $"The file is not a valid glTF model: {ex.Message}";
+
+ private static MeshPart? ReadPrimitive(MeshPrimitive primitive, Model3D model, Dictionary<Material, int> materials)
+ {
+ if (primitive.GetVertexAccessor("POSITION") is not { } positionAccessor)
+ return null;
+ var part = new MeshPart();
+ var positions = positionAccessor.AsVector3Array();
+ part.Positions.Capacity = positions.Count * 3;
+ foreach (var p in positions)
+ {
+ part.Positions.Add(p.X);
+ part.Positions.Add(p.Y);
+ part.Positions.Add(p.Z);
+ }
+
+ if (primitive.GetVertexAccessor("NORMAL") is { } normalAccessor && normalAccessor.Count == positions.Count)
+ {
+ part.Normals = new List<float>(positions.Count * 3);
+ foreach (var n in normalAccessor.AsVector3Array())
+ {
+ part.Normals.Add(n.X);
+ part.Normals.Add(n.Y);
+ part.Normals.Add(n.Z);
+ }
+ }
+
+ var texCoordSet = 0;
+ if (primitive.Material is { } source)
+ {
+ if (!materials.TryGetValue(source, out var index))
+ {
+ index = model.Materials.Count;
+ model.Materials.Add(ReadMaterial(source, model.Materials.Count));
+ materials[source] = index;
+ }
+ part.Material = index;
+ texCoordSet = BaseColorChannel(source)?.TextureCoordinate ?? 0;
+ }
+
+ if ((primitive.GetVertexAccessor($"TEXCOORD_{texCoordSet}") ?? primitive.GetVertexAccessor("TEXCOORD_0")) is { } uvAccessor && uvAccessor.Count == positions.Count)
+ {
+ part.TexCoords = new List<float>(positions.Count * 2);
+ foreach (var uv in uvAccessor.AsVector2Array())
+ {
+ part.TexCoords.Add(uv.X);
+ part.TexCoords.Add(1 - uv.Y);
+ }
+ }
+
+ if (primitive.GetVertexAccessor("COLOR_0") is { } colorAccessor && colorAccessor.Count == positions.Count)
+ {
+ part.Colors = new List<float>(positions.Count * 4);
+ foreach (var c in colorAccessor.AsColorArray(1))
+ {
+ var srgb = MeshMath.LinearToSrgb(c);
+ part.Colors.Add(srgb.X);
+ part.Colors.Add(srgb.Y);
+ part.Colors.Add(srgb.Z);
+ part.Colors.Add(srgb.W);
+ }
+ }
+
+ foreach (var (a, b, c) in primitive.GetTriangleIndices())
+ part.AddTriangle(a, b, c);
+ return part;
+ }
+
+ private static MaterialChannel? BaseColorChannel(Material material) =>
+ material.FindChannel("BaseColor") ?? material.FindChannel("Diffuse");
+
+ private static Material3D ReadMaterial(Material source, int index)
+ {
+ var result = new Material3D
+ {
+ Name = string.IsNullOrEmpty(source.Name) ? $"Material {index + 1}" : source.Name,
+ DoubleSided = source.DoubleSided,
+ };
+ if (BaseColorChannel(source) is { } channel)
+ {
+ result.BaseColor = channel.Color;
+ if (channel.Texture?.PrimaryImage?.Content is { IsEmpty: false } image)
+ {
+ var data = image.Content.ToArray();
+ var name = channel.Texture.PrimaryImage.Name is { Length: > 0 } imageName ? Path.GetFileNameWithoutExtension(imageName) : $"texture{index + 1}";
+ result.BaseColorTexture = new Texture3D(data, Texture3D.Sniff(data, image.FileExtension ?? "png"), name);
+ }
+ }
+ return result;
+ }
+
+ /// <summary>Writes a GLB, or a self-contained .gltf when <paramref name="binary"/> is false.</summary>
+ public static void Write(Model3D model, Stream output, bool binary, CancellationToken cancellationToken)
+ {
+ var root = ModelRoot.CreateModel();
+ root.Asset.Generator = "Filee";
+ var scene = root.UseScene("Scene");
+
+ var images = new Dictionary<Texture3D, Image>();
+ var materials = new Material[model.Materials.Count];
+ for (var m = 0; m < model.Materials.Count; m++)
+ materials[m] = WriteMaterial(root, model.Materials[m], images);
+
+ foreach (var part in model.Parts)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var mesh = root.CreateMesh(part.Name.Length > 0 ? part.Name : null);
+ var primitive = mesh.CreatePrimitive();
+ var count = part.VertexCount;
+
+ var positions = new Vector3[count];
+ for (var v = 0; v < count; v++)
+ positions[v] = part.Position(v) / MillimetresPerMetre;
+ primitive.SetVertexAccessor("POSITION", Accessor(root, positions, DimensionType.VEC3, updateBounds: true));
+
+ if (part.Normals is not null)
+ {
+ var normals = new Vector3[count];
+ for (var v = 0; v < count; v++)
+ {
+ var n = part.Normal(v);
+ normals[v] = n.LengthSquared() > 0 ? Vector3.Normalize(n) : Vector3.UnitY;
+ }
+ primitive.SetVertexAccessor("NORMAL", Accessor(root, normals, DimensionType.VEC3));
+ }
+ if (part.TexCoords is not null)
+ {
+ var uvs = new Vector2[count];
+ for (var v = 0; v < count; v++)
+ {
+ var uv = part.TexCoord(v);
+ uvs[v] = new Vector2(uv.X, 1 - uv.Y);
+ }
+ primitive.SetVertexAccessor("TEXCOORD_0", Accessor(root, uvs, DimensionType.VEC2));
+ }
+ if (part.Colors is not null)
+ {
+ var colors = new Vector4[count];
+ for (var v = 0; v < count; v++)
+ colors[v] = Vector4.Clamp(MeshMath.SrgbToLinear(part.Color(v)), Vector4.Zero, Vector4.One);
+ primitive.SetVertexAccessor("COLOR_0", Accessor(root, colors, DimensionType.VEC4));
+ }
+
+ var indices = part.IndexSpan;
+ var wide = count > ushort.MaxValue;
+ var indexBytes = new byte[indices.Length * (wide ? 4 : 2)];
+ for (var i = 0; i < indices.Length; i++)
+ {
+ if (wide)
+ BitConverter.TryWriteBytes(indexBytes.AsSpan(i * 4), (uint)indices[i]);
+ else
+ BitConverter.TryWriteBytes(indexBytes.AsSpan(i * 2), (ushort)indices[i]);
+ }
+ var indexView = root.UseBufferView(indexBytes, 0, null, 0, BufferMode.ELEMENT_ARRAY_BUFFER);
+ var indexAccessor = root.CreateAccessor();
+ indexAccessor.SetIndexData(indexView, 0, indices.Length, wide ? IndexEncodingType.UNSIGNED_INT : IndexEncodingType.UNSIGNED_SHORT);
+ primitive.SetIndexAccessor(indexAccessor);
+ primitive.DrawPrimitiveType = PrimitiveType.TRIANGLES;
+ if (part.Material >= 0 && part.Material < materials.Length)
+ primitive.Material = materials[part.Material];
+
+ scene.CreateNode(mesh.Name).Mesh = mesh;
+ }
+
+ var settings = new WriteSettings { MergeBuffers = true, Validation = ValidationMode.Strict };
+ if (binary)
+ {
+ root.WriteGLB(output, settings);
+ return;
+ }
+
+ // A .gltf in one file: the GLB's JSON with its binary chunk as a data URI.
+ var glb = root.WriteGLB(settings);
+ WriteEmbeddedGltf(glb, output);
+ }
+
+ private static Accessor Accessor<T>(ModelRoot root, T[] values, DimensionType dimensions, bool updateBounds = false) where T : unmanaged
+ {
+ var bytes = System.Runtime.InteropServices.MemoryMarshal.AsBytes(values.AsSpan()).ToArray();
+ var view = root.UseBufferView(bytes, 0, null, 0, BufferMode.ARRAY_BUFFER);
+ var accessor = root.CreateAccessor();
+ accessor.SetVertexData(view, 0, values.Length, new AttributeFormat(dimensions, EncodingType.FLOAT, false));
+ if (updateBounds)
+ accessor.UpdateBounds();
+ return accessor;
+ }
+
+ private static Material WriteMaterial(ModelRoot root, Material3D source, Dictionary<Texture3D, Image> images)
+ {
+ var material = root.CreateMaterial(source.Name.Length > 0 ? source.Name : null);
+ material.InitializePBRMetallicRoughness();
+ material.DoubleSided = source.DoubleSided;
+ var color = Vector4.Clamp(source.BaseColor, Vector4.Zero, Vector4.One);
+ if (color.W < 1)
+ material.Alpha = AlphaMode.BLEND;
+ var baseColor = material.FindChannel("BaseColor")!.Value;
+ baseColor.Color = color;
+ if (source.BaseColorTexture is { } texture)
+ {
+ if (!images.TryGetValue(texture, out var image))
+ {
+ image = root.UseImage(new MemoryImage(TextureForGltf(texture)));
+ image.Name = texture.Name;
+ images[texture] = image;
+ }
+ baseColor.SetTexture(0, image, null, TextureWrapMode.REPEAT, TextureWrapMode.REPEAT,
+ TextureMipMapFilter.DEFAULT, TextureInterpolationFilter.DEFAULT);
+ }
+ // OBJ, 3MF and PLY colours describe plastic-like surfaces; glTF's default would make them fully metallic.
+ var metallic = material.FindChannel("MetallicRoughness")!.Value;
+ metallic.SetFactor("MetallicFactor", 0);
+ metallic.SetFactor("RoughnessFactor", 0.8f);
+ return material;
+ }
+
+ /// <summary>glTF viewers read PNG and JPEG: other pictures (BMP, TGA, TIFF, ...) are converted to PNG.</summary>
+ private static byte[] TextureForGltf(Texture3D texture)
+ {
+ if (texture.Extension is "png" or "jpg")
+ return texture.Data;
+ try
+ {
+ using var image = new MagickImage(texture.Data);
+ return image.ToByteArray(MagickFormat.Png);
+ }
+ catch (MagickException ex)
+ {
+ throw new InvalidDataException($"The texture \"{texture.Name}.{texture.Extension}\" cannot be read: {ex.Message}", ex);
+ }
+ }
+
+ /// <summary>Turns a GLB into a .gltf whose buffer is a base64 data URI (images stay in buffer views).</summary>
+ private static void WriteEmbeddedGltf(ArraySegment<byte> glb, Stream output)
+ {
+ var data = glb.AsSpan();
+ var jsonLength = BitConverter.ToInt32(data[12..]);
+ var json = JsonNode.Parse(data.Slice(20, jsonLength))!.AsObject();
+ var binStart = 20 + jsonLength;
+ if (binStart + 8 <= data.Length && json["buffers"] is JsonArray { Count: > 0 } buffers)
+ {
+ var binLength = BitConverter.ToInt32(data[binStart..]);
+ var bin = data.Slice(binStart + 8, binLength);
+ var declared = buffers[0]!["byteLength"]?.GetValue<int>() ?? binLength;
+ buffers[0]!["uri"] = "data:application/octet-stream;base64," + Convert.ToBase64String(bin[..Math.Min(declared, binLength)]);
+ }
+ using var writer = new System.Text.Json.Utf8JsonWriter(output, new System.Text.Json.JsonWriterOptions { Indented = true });
+ json.WriteTo(writer);
+ }
+}
diff --git a/src/Filee.Engines/Models3D/MeshRenderer.cs b/src/Filee.Engines/Models3D/MeshRenderer.cs
new file mode 100644
index 00000000..a0c30761
--- /dev/null
+++ b/src/Filee.Engines/Models3D/MeshRenderer.cs
@@ -0,0 +1,175 @@
+// A small software rasteriser for 3D → picture: an isometric view from the front right, above, with flat shading
+// (one light, faces lit by their geometric normal turned towards the viewer) and a z-buffer, rendered at twice the
+// size and scaled down for smooth edges. Colours come from the vertex colours, else the material (its texture
+// times its base colour), else grey; both are interpolated across each triangle, which is exact for a parallel
+// projection.
+
+using System.Numerics;
+using System.Runtime.InteropServices;
+using SkiaSharp;
+
+namespace Filee.Engines.Models3D;
+
+internal static class MeshRenderer
+{
+ private static readonly Vector4 DefaultColor = new(0.72f, 0.74f, 0.78f, 1);
+
+ private sealed record Picture(SKColor[] Pixels, int Width, int Height);
+
+ /// <summary>What one triangle is painted with: three corner colours, or a texture at three UVs times a tint.</summary>
+ private readonly record struct Paint(Vector3 A, Vector3 B, Vector3 C, Picture? Texture, Vector2 UvA, Vector2 UvB, Vector2 UvC);
+
+ /// <summary>Renders <paramref name="model"/> into a square PNG of <paramref name="size"/> pixels with a transparent background.</summary>
+ public static byte[] RenderPng(Model3D model, int size, CancellationToken cancellationToken)
+ {
+ const int scale = 2;
+ var full = size * scale;
+ var pixels = new uint[full * full];
+ var depth = new float[full * full];
+ Array.Fill(depth, float.NegativeInfinity);
+
+ // Camera at (1, 1, 1) looking at the origin, Y up: the classic isometric view. The light comes from the
+ // upper left, a little from the front, so the top, left and right faces of a box differ.
+ var forward = Vector3.Normalize(new Vector3(-1, -1, -1));
+ var right = Vector3.Normalize(Vector3.Cross(forward, Vector3.UnitY));
+ var up = Vector3.Cross(right, forward);
+ var light = Vector3.Normalize(-0.5f * right + 0.8f * up - 0.6f * forward);
+
+ // Fit the projected bounds into the picture with a margin.
+ float minX = float.MaxValue, maxX = float.MinValue, minY = float.MaxValue, maxY = float.MinValue;
+ foreach (var part in model.Parts)
+ {
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var p = part.Position(v);
+ var x = Vector3.Dot(p, right);
+ var y = Vector3.Dot(p, up);
+ minX = MathF.Min(minX, x);
+ maxX = MathF.Max(maxX, x);
+ minY = MathF.Min(minY, y);
+ maxY = MathF.Max(maxY, y);
+ }
+ }
+ var extent = MathF.Max(maxX - minX, maxY - minY);
+ var pixelsPerUnit = extent > 0 && float.IsFinite(extent) ? full * 0.9f / extent : 1;
+ var centerX = (minX + maxX) / 2;
+ var centerY = (minY + maxY) / 2;
+
+ var textures = new Dictionary<Texture3D, Picture?>();
+ foreach (var part in model.Parts)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var material = model.MaterialOf(part);
+ var texture = material?.BaseColorTexture is { } t && part.TexCoords is not null ? Decode(textures, t) : null;
+ var tint = Rgb(material is null ? DefaultColor : MeshMath.LinearToSrgb(material.BaseColor));
+ var indices = part.IndexSpan;
+ for (var i = 0; i + 2 < indices.Length; i += 3)
+ {
+ int ia = indices[i], ib = indices[i + 1], ic = indices[i + 2];
+ Vector3 a = part.Position(ia), b = part.Position(ib), c = part.Position(ic);
+ var normal = Vector3.Cross(b - a, c - a);
+ if (normal.LengthSquared() == 0 || !float.IsFinite(normal.X))
+ continue;
+ normal = Vector3.Normalize(normal);
+ // Seen from behind (an open surface, or a mesh wound the other way): light the side we see.
+ if (Vector3.Dot(normal, forward) > 0)
+ normal = -normal;
+ var shade = 0.45f + 0.55f * MathF.Max(0, Vector3.Dot(normal, light));
+
+ var paint = part.Colors is not null
+ ? new Paint(Rgb(part.Color(ia)) * shade, Rgb(part.Color(ib)) * shade, Rgb(part.Color(ic)) * shade, null, default, default, default)
+ : new Paint(tint * shade, tint * shade, tint * shade, texture, part.TexCoord(ia), part.TexCoord(ib), part.TexCoord(ic));
+ Fill(pixels, depth, full, Project(a), Project(b), Project(c), paint);
+ }
+ }
+
+ var info = new SKImageInfo(full, full, SKColorType.Rgba8888, SKAlphaType.Premul);
+ using var image = SKImage.FromPixelCopy(info, MemoryMarshal.AsBytes(pixels.AsSpan()), full * 4);
+ using var surface = SKSurface.Create(new SKImageInfo(size, size, SKColorType.Rgba8888, SKAlphaType.Premul));
+ surface.Canvas.Clear(SKColors.Transparent);
+ surface.Canvas.DrawImage(image, new SKRect(0, 0, size, size), new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear));
+ using var snapshot = surface.Snapshot();
+ using var data = snapshot.Encode(SKEncodedImageFormat.Png, 100);
+ return data.ToArray();
+
+ Vector3 Project(Vector3 p) => new(
+ full / 2f + (Vector3.Dot(p, right) - centerX) * pixelsPerUnit,
+ full / 2f - (Vector3.Dot(p, up) - centerY) * pixelsPerUnit,
+ -Vector3.Dot(p, forward));
+ }
+
+ private static Vector3 Rgb(Vector4 color) => new(color.X, color.Y, color.Z);
+
+ /// <summary>Fills one triangle into the z-buffered picture (larger depth = nearer).</summary>
+ private static void Fill(uint[] pixels, float[] depth, int size, Vector3 a, Vector3 b, Vector3 c, in Paint paint)
+ {
+ var area = Edge(a, b, c.X, c.Y);
+ if (MathF.Abs(area) < 1e-6f || !float.IsFinite(area))
+ return;
+ var x0 = Math.Max(0, (int)MathF.Floor(MathF.Min(a.X, MathF.Min(b.X, c.X))));
+ var x1 = Math.Min(size - 1, (int)MathF.Ceiling(MathF.Max(a.X, MathF.Max(b.X, c.X))));
+ var y0 = Math.Max(0, (int)MathF.Floor(MathF.Min(a.Y, MathF.Min(b.Y, c.Y))));
+ var y1 = Math.Min(size - 1, (int)MathF.Ceiling(MathF.Max(a.Y, MathF.Max(b.Y, c.Y))));
+ var inverse = 1 / area;
+ var flat = paint.Texture is null && paint.A == paint.B && paint.B == paint.C;
+ var flatColor = Pack(paint.A);
+ for (var y = y0; y <= y1; y++)
+ {
+ var py = y + 0.5f;
+ var row = y * size;
+ for (var x = x0; x <= x1; x++)
+ {
+ var px = x + 0.5f;
+ var w0 = Edge(b, c, px, py) * inverse;
+ var w1 = Edge(c, a, px, py) * inverse;
+ var w2 = Edge(a, b, px, py) * inverse;
+ if (w0 < 0 || w1 < 0 || w2 < 0)
+ continue;
+ var z = w0 * a.Z + w1 * b.Z + w2 * c.Z;
+ if (z <= depth[row + x])
+ continue;
+ depth[row + x] = z;
+ if (flat)
+ {
+ pixels[row + x] = flatColor;
+ continue;
+ }
+ var color = w0 * paint.A + w1 * paint.B + w2 * paint.C;
+ if (paint.Texture is { } texture)
+ color *= Sample(texture, w0 * paint.UvA + w1 * paint.UvB + w2 * paint.UvC);
+ pixels[row + x] = Pack(color);
+ }
+ }
+ }
+
+ private static uint Pack(Vector3 rgb)
+ {
+ rgb = Vector3.Clamp(rgb, Vector3.Zero, Vector3.One);
+ return (uint)(rgb.X * 255 + 0.5f) | (uint)(rgb.Y * 255 + 0.5f) << 8 | (uint)(rgb.Z * 255 + 0.5f) << 16 | 0xFF000000u;
+ }
+
+ private static float Edge(Vector3 a, Vector3 b, float x, float y) => (b.X - a.X) * (y - a.Y) - (b.Y - a.Y) * (x - a.X);
+
+ private static Picture? Decode(Dictionary<Texture3D, Picture?> cache, Texture3D texture)
+ {
+ if (cache.TryGetValue(texture, out var decoded))
+ return decoded;
+ using var bitmap = SKBitmap.Decode(texture.Data);
+ decoded = bitmap is null || bitmap.Width == 0 || bitmap.Height == 0 ? null : new Picture(bitmap.Pixels, bitmap.Width, bitmap.Height);
+ cache[texture] = decoded;
+ return decoded;
+ }
+
+ /// <summary>The texture's colour at <paramref name="uv"/> (origin bottom left, repeating), nearest pixel.</summary>
+ private static Vector3 Sample(Picture texture, Vector2 uv)
+ {
+ if (!float.IsFinite(uv.X) || !float.IsFinite(uv.Y))
+ return Vector3.One;
+ var u = uv.X - MathF.Floor(uv.X);
+ var v = uv.Y - MathF.Floor(uv.Y);
+ var x = Math.Clamp((int)(u * texture.Width), 0, texture.Width - 1);
+ var y = Math.Clamp((int)((1 - v) * texture.Height), 0, texture.Height - 1);
+ var pixel = texture.Pixels[y * texture.Width + x];
+ return new Vector3(pixel.Red / 255f, pixel.Green / 255f, pixel.Blue / 255f);
+ }
+}
diff --git a/src/Filee.Engines/Models3D/Model3D.cs b/src/Filee.Engines/Models3D/Model3D.cs
new file mode 100644
index 00000000..6cb91c77
--- /dev/null
+++ b/src/Filee.Engines/Models3D/Model3D.cs
@@ -0,0 +1,315 @@
+// The in-memory 3D model every reader produces and every writer takes (see docs/ENGINES.md, "3D models").
+//
+// Conventions, chosen once so every reader and writer agrees:
+// - positions are millimetres, Y up (glTF's axes). Unitless files (STL, OBJ, PLY) are read as millimetres; STL, 3MF
+// and PLY are Z up like Blender treats them, OBJ and glTF Y up;
+// - triangles only (polygons are triangulated on reading), counter-clockwise front faces;
+// - UVs have their origin at the bottom left (OBJ, PLY); glTF's top-left origin is flipped on the way in and out;
+// - vertex colours are sRGB 0–1 (as PLY, 3MF and OBJ store them), material colours linear (as glTF stores them);
+// - node hierarchies are flattened: every mesh instance becomes a part in world coordinates.
+
+using System.Numerics;
+using System.Runtime.InteropServices;
+
+namespace Filee.Engines.Models3D;
+
+/// <summary>A whole model: parts (meshes) and the materials they use.</summary>
+internal sealed class Model3D
+{
+ public List<MeshPart> Parts { get; } = [];
+ public List<Material3D> Materials { get; } = [];
+
+ public int TriangleCount => Parts.Sum(p => p.TriangleCount);
+ public int VertexCount => Parts.Sum(p => p.VertexCount);
+
+ /// <summary>The material of <paramref name="part"/>, or null.</summary>
+ public Material3D? MaterialOf(MeshPart part) =>
+ part.Material >= 0 && part.Material < Materials.Count ? Materials[part.Material] : null;
+
+ /// <summary>Axis-aligned bounds of every position, or (0, 0) for an empty model.</summary>
+ public (Vector3 Min, Vector3 Max) Bounds()
+ {
+ var min = new Vector3(float.MaxValue);
+ var max = new Vector3(float.MinValue);
+ foreach (var part in Parts)
+ {
+ var p = part.PositionSpan;
+ for (var i = 0; i + 2 < p.Length; i += 3)
+ {
+ var v = new Vector3(p[i], p[i + 1], p[i + 2]);
+ min = Vector3.Min(min, v);
+ max = Vector3.Max(max, v);
+ }
+ }
+ return min.X > max.X ? (Vector3.Zero, Vector3.Zero) : (min, max);
+ }
+
+ /// <summary>Drops parts without triangles and checks every index, so writers can trust the data.</summary>
+ public void Validate()
+ {
+ Parts.RemoveAll(p => p.TriangleCount == 0);
+ foreach (var part in Parts)
+ part.Validate();
+ if (Parts.Count == 0)
+ throw new InvalidDataException("The file contains no triangles (only points, lines or nothing at all).");
+ }
+}
+
+/// <summary>One mesh with per-vertex attributes and a triangle list.</summary>
+internal sealed class MeshPart
+{
+ public string Name { get; set; } = "";
+
+ /// <summary>Index into <see cref="Model3D.Materials"/>, or -1.</summary>
+ public int Material { get; set; } = -1;
+
+ /// <summary>x, y, z per vertex (millimetres, Y up).</summary>
+ public List<float> Positions { get; } = [];
+
+ /// <summary>x, y, z per vertex, or null.</summary>
+ public List<float>? Normals { get; set; }
+
+ /// <summary>u, v per vertex (origin bottom left), or null.</summary>
+ public List<float>? TexCoords { get; set; }
+
+ /// <summary>r, g, b, a per vertex (sRGB, 0–1), or null.</summary>
+ public List<float>? Colors { get; set; }
+
+ /// <summary>Three vertex indices per triangle.</summary>
+ public List<int> Indices { get; } = [];
+
+ public int VertexCount => Positions.Count / 3;
+ public int TriangleCount => Indices.Count / 3;
+
+ public Span<float> PositionSpan => CollectionsMarshal.AsSpan(Positions);
+ public Span<int> IndexSpan => CollectionsMarshal.AsSpan(Indices);
+
+ public Vector3 Position(int vertex) => new(Positions[vertex * 3], Positions[vertex * 3 + 1], Positions[vertex * 3 + 2]);
+
+ public Vector3 Normal(int vertex) => Normals is null ? Vector3.Zero : new(Normals[vertex * 3], Normals[vertex * 3 + 1], Normals[vertex * 3 + 2]);
+
+ public Vector2 TexCoord(int vertex) => TexCoords is null ? Vector2.Zero : new(TexCoords[vertex * 2], TexCoords[vertex * 2 + 1]);
+
+ public Vector4 Color(int vertex) => Colors is null ? Vector4.One : new(Colors[vertex * 4], Colors[vertex * 4 + 1], Colors[vertex * 4 + 2], Colors[vertex * 4 + 3]);
+
+ /// <summary>Appends a vertex; attributes the part does not have are ignored.</summary>
+ public int AddVertex(Vector3 position, Vector3? normal = null, Vector2? uv = null, Vector4? color = null)
+ {
+ var index = VertexCount;
+ Positions.Add(position.X);
+ Positions.Add(position.Y);
+ Positions.Add(position.Z);
+ if (Normals is not null)
+ {
+ var n = normal ?? Vector3.Zero;
+ Normals.Add(n.X);
+ Normals.Add(n.Y);
+ Normals.Add(n.Z);
+ }
+ if (TexCoords is not null)
+ {
+ var t = uv ?? Vector2.Zero;
+ TexCoords.Add(t.X);
+ TexCoords.Add(t.Y);
+ }
+ if (Colors is not null)
+ {
+ var c = color ?? Vector4.One;
+ Colors.Add(c.X);
+ Colors.Add(c.Y);
+ Colors.Add(c.Z);
+ Colors.Add(c.W);
+ }
+ return index;
+ }
+
+ public void AddTriangle(int a, int b, int c)
+ {
+ Indices.Add(a);
+ Indices.Add(b);
+ Indices.Add(c);
+ }
+
+ /// <summary>The geometric normal of triangle <paramref name="triangle"/> (from its winding), or zero when degenerate.</summary>
+ public Vector3 FaceNormal(int triangle)
+ {
+ var a = Position(Indices[triangle * 3]);
+ var b = Position(Indices[triangle * 3 + 1]);
+ var c = Position(Indices[triangle * 3 + 2]);
+ var n = Vector3.Cross(b - a, c - a);
+ var length = n.Length();
+ return length > 0 && float.IsFinite(length) ? n / length : Vector3.Zero;
+ }
+
+ /// <summary>
+ /// Smooth vertex normals: the area-weighted sum of the faces around each vertex (vertices that are split at hard
+ /// edges stay hard).
+ /// </summary>
+ public void ComputeNormals()
+ {
+ var normals = new float[Positions.Count];
+ var indices = IndexSpan;
+ for (var t = 0; t + 2 < indices.Length; t += 3)
+ {
+ var a = Position(indices[t]);
+ var n = Vector3.Cross(Position(indices[t + 1]) - a, Position(indices[t + 2]) - a);
+ for (var k = 0; k < 3; k++)
+ {
+ var v = indices[t + k] * 3;
+ normals[v] += n.X;
+ normals[v + 1] += n.Y;
+ normals[v + 2] += n.Z;
+ }
+ }
+ for (var v = 0; v < normals.Length; v += 3)
+ {
+ var n = Vector3.Normalize(new Vector3(normals[v], normals[v + 1], normals[v + 2]));
+ if (!float.IsFinite(n.X))
+ n = Vector3.UnitY;
+ normals[v] = n.X;
+ normals[v + 1] = n.Y;
+ normals[v + 2] = n.Z;
+ }
+ Normals = [.. normals];
+ }
+
+ /// <summary>Applies a transform to positions and normals; a mirroring transform also flips the winding.</summary>
+ public void Transform(Matrix4x4 matrix)
+ {
+ if (matrix.IsIdentity)
+ return;
+ var p = PositionSpan;
+ for (var i = 0; i + 2 < p.Length; i += 3)
+ {
+ var v = Vector3.Transform(new Vector3(p[i], p[i + 1], p[i + 2]), matrix);
+ p[i] = v.X;
+ p[i + 1] = v.Y;
+ p[i + 2] = v.Z;
+ }
+ if (Normals is not null)
+ {
+ var normalMatrix = Matrix4x4.Invert(matrix, out var inverse) ? Matrix4x4.Transpose(inverse) : matrix;
+ var n = CollectionsMarshal.AsSpan(Normals);
+ for (var i = 0; i + 2 < n.Length; i += 3)
+ {
+ var v = Vector3.TransformNormal(new Vector3(n[i], n[i + 1], n[i + 2]), normalMatrix);
+ var length = v.Length();
+ if (length > 0)
+ v /= length;
+ n[i] = v.X;
+ n[i + 1] = v.Y;
+ n[i + 2] = v.Z;
+ }
+ }
+ if (matrix.GetDeterminant() < 0)
+ {
+ var indices = IndexSpan;
+ for (var t = 0; t + 2 < indices.Length; t += 3)
+ (indices[t + 1], indices[t + 2]) = (indices[t + 2], indices[t + 1]);
+ }
+ }
+
+ /// <summary>Checks that every index points at a vertex and every attribute list has the vertex count.</summary>
+ public void Validate()
+ {
+ if (Indices.Count % 3 != 0)
+ throw new InvalidDataException("A mesh has an incomplete triangle.");
+ var count = VertexCount;
+ foreach (var index in IndexSpan)
+ {
+ if ((uint)index >= (uint)count)
+ throw new InvalidDataException($"A triangle refers to vertex {index + 1}, but the mesh has only {count} vertices.");
+ }
+ if (Normals is not null && Normals.Count != count * 3)
+ Normals = null;
+ if (TexCoords is not null && TexCoords.Count != count * 2)
+ TexCoords = null;
+ if (Colors is not null && Colors.Count != count * 4)
+ Colors = null;
+ }
+}
+
+/// <summary>A simple material: base colour (linear RGBA, as glTF) and an optional base colour texture.</summary>
+internal sealed class Material3D
+{
+ public string Name { get; set; } = "";
+ public Vector4 BaseColor { get; set; } = Vector4.One;
+ public Texture3D? BaseColorTexture { get; set; }
+ public bool DoubleSided { get; set; }
+}
+
+/// <summary>An encoded picture (PNG, JPEG, ...) used as a texture.</summary>
+/// <param name="Data">The file's bytes.</param>
+/// <param name="Extension">Lower-case extension without the dot ("png", "jpg").</param>
+/// <param name="Name">Original file name without extension, used for written texture files.</param>
+internal sealed record Texture3D(byte[] Data, string Extension, string Name)
+{
+ /// <summary>Recognises PNG, JPEG, WebP, BMP, GIF and TGA-less pictures by their signature, else the given extension.</summary>
+ public static string Sniff(ReadOnlySpan<byte> data, string fallback)
+ {
+ if (data.StartsWith((ReadOnlySpan<byte>)[0x89, (byte)'P', (byte)'N', (byte)'G']))
+ return "png";
+ if (data.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xD8, 0xFF]))
+ return "jpg";
+ if (data.Length > 12 && data[..4].SequenceEqual("RIFF"u8) && data[8..12].SequenceEqual("WEBP"u8))
+ return "webp";
+ if (data.StartsWith("BM"u8))
+ return "bmp";
+ if (data.StartsWith("GIF8"u8))
+ return "gif";
+ var ext = fallback.TrimStart('.').ToLowerInvariant();
+ return ext is "jpeg" ? "jpg" : ext;
+ }
+}
+
+/// <summary>Colour space and axis helpers shared by the readers and writers.</summary>
+internal static class MeshMath
+{
+ /// <summary>Z up (STL, 3MF, PLY) → Y up: (x, y, z) → (x, z, −y).</summary>
+ public static readonly Matrix4x4 ZUpToYUp = new(
+ 1, 0, 0, 0,
+ 0, 0, -1, 0,
+ 0, 1, 0, 0,
+ 0, 0, 0, 1);
+
+ /// <summary>Y up → Z up: (x, y, z) → (x, −z, y).</summary>
+ public static Vector3 ToZUp(Vector3 v) => new(v.X, -v.Z, v.Y);
+
+ /// <summary>Z up → Y up: (x, y, z) → (x, z, −y).</summary>
+ public static Vector3 ToYUp(Vector3 v) => new(v.X, v.Z, -v.Y);
+
+ public static float SrgbToLinear(float c) =>
+ c <= 0.04045f ? c / 12.92f : MathF.Pow((c + 0.055f) / 1.055f, 2.4f);
+
+ public static float LinearToSrgb(float c) =>
+ c <= 0.0031308f ? c * 12.92f : 1.055f * MathF.Pow(c, 1 / 2.4f) - 0.055f;
+
+ public static Vector4 SrgbToLinear(Vector4 c) => new(SrgbToLinear(c.X), SrgbToLinear(c.Y), SrgbToLinear(c.Z), c.W);
+
+ public static Vector4 LinearToSrgb(Vector4 c) => new(LinearToSrgb(c.X), LinearToSrgb(c.Y), LinearToSrgb(c.Z), c.W);
+
+ /// <summary>0–1 → 0–255, rounded and clamped.</summary>
+ public static byte ToByte(float value) => (byte)Math.Clamp((int)MathF.Round(value * 255), 0, 255);
+
+ /// <summary>The 0–1 colour as #RRGGBB, or #RRGGBBAA when not opaque (3MF).</summary>
+ public static string ToHex(Vector4 srgb)
+ {
+ var hex = $"#{ToByte(srgb.X):X2}{ToByte(srgb.Y):X2}{ToByte(srgb.Z):X2}";
+ return ToByte(srgb.W) == 255 ? hex : hex + ToByte(srgb.W).ToString("X2", System.Globalization.CultureInfo.InvariantCulture);
+ }
+
+ /// <summary>Parses #RGB, #RRGGBB or #RRGGBBAA (3MF colours), or null.</summary>
+ public static Vector4? ParseHex(string? text)
+ {
+ if (text is null || !text.StartsWith('#'))
+ return null;
+ var hex = text[1..];
+ if (hex.Length == 3)
+ hex = string.Concat(hex.Select(c => $"{c}{c}"));
+ if (hex.Length is not (6 or 8) || !uint.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out var value))
+ return null;
+ if (hex.Length == 6)
+ value = (value << 8) | 0xFF;
+ return new Vector4((value >> 24) / 255f, ((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f);
+ }
+}
diff --git a/src/Filee.Engines/Models3D/ModelConverter.cs b/src/Filee.Engines/Models3D/ModelConverter.cs
new file mode 100644
index 00000000..2a923e25
--- /dev/null
+++ b/src/Filee.Engines/Models3D/ModelConverter.cs
@@ -0,0 +1,177 @@
+// 3D models in managed code only (SharpGLTF for glTF, Filee's own readers and writers for the rest): GLB, glTF, STL,
+// OBJ, 3MF and PLY into each other through one in-memory model (Model3D), and an isometric preview picture.
+// See docs/ENGINES.md, "3D models", for units, axes and what each format keeps.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Magick;
+using ImageMagick;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Filee.Engines.Models3D;
+
+/// <summary>Converts 3D models between GLB, glTF, STL, OBJ, 3MF and PLY, and renders them to pictures.</summary>
+public sealed class ModelConverter(ILogger? logger = null) : IConverter
+{
+ /// <summary>The 3D formats, each readable and writable.</summary>
+ public static readonly string[] Formats = ["glb", "gltf", "stl", "obj", "3mf", "ply"];
+
+ /// <summary>Long edge of the preview picture before the preset's resize.</summary>
+ internal const int PreviewSize = 1024;
+
+ private readonly ILogger _logger = logger ?? NullLogger.Instance;
+
+ public string Id => "model3d";
+ public string DisplayName => "3D models (built-in)";
+
+ /// <summary>A large mesh takes a few hundred MB while it is converted, so only a few run at once.</summary>
+ public int MaxParallelism => Math.Clamp(Environment.ProcessorCount / 2, 1, 4);
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ .. from source in Formats from target in Formats where source != target select new ConversionEdge(source, target),
+ .. from source in Formats from target in ImageEncoder.Writable select ImageEncoder.Edge(source, target),
+ ];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("GLB, glTF, STL, OBJ, 3MF, PLY",
+ $"{EngineVersions.BuiltIn} · {EngineVersions.Library("SharpGLTF", typeof(SharpGLTF.Schema2.ModelRoot))}");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ var reading = progress is null ? null : new SubProgress(progress, 0, 0.6);
+ var model = Read(step.InputPath, step.From, reading, cancellationToken);
+ _logger.LogDebug("{File}: {Parts} parts, {Vertices} vertices, {Triangles} triangles, {Materials} materials",
+ step.InputPath, model.Parts.Count, model.VertexCount, model.TriangleCount, model.Materials.Count);
+ progress?.Report(0.6);
+
+ var outputs = new List<string>();
+ try
+ {
+ Write(model, step.To, step.Output, step.Preset.Image, outputs, cancellationToken);
+ }
+ catch
+ {
+ foreach (var output in outputs)
+ TryDelete(output);
+ throw;
+ }
+ progress?.Report(1);
+ return outputs;
+ }, cancellationToken);
+
+ /// <summary>Reads a model of format <paramref name="format"/> and checks it.</summary>
+ internal static Model3D Read(string path, string format, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var model = format switch
+ {
+ "stl" => StlFormat.Read(path, progress, cancellationToken),
+ "obj" => ObjFormat.Read(path, progress, cancellationToken),
+ "ply" => PlyFormat.Read(path, progress, cancellationToken),
+ "3mf" => ThreeMfFormat.Read(path, progress, cancellationToken),
+ "glb" or "gltf" => GltfFormat.Read(path, progress, cancellationToken),
+ _ => throw new NotSupportedException($"Unknown 3D format '{format}'."),
+ };
+ model.Validate();
+ return model;
+ }
+
+ /// <summary>Writes <paramref name="model"/> as <paramref name="format"/>; every file written is added to <paramref name="outputs"/>.</summary>
+ internal static void Write(Model3D model, string format, IOutputAllocator output, ImageOptions imageOptions, List<string> outputs, CancellationToken cancellationToken)
+ {
+ if (format == "obj")
+ {
+ WriteObj(model, output, outputs, cancellationToken);
+ return;
+ }
+ if (output.Allocate(format) is not { } path)
+ return;
+ outputs.Add(path);
+ if (!Formats.Contains(format))
+ {
+ WriteImage(model, format, imageOptions, path, cancellationToken);
+ return;
+ }
+ using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16);
+ switch (format)
+ {
+ case "stl":
+ StlFormat.Write(model, stream, cancellationToken);
+ break;
+ case "ply":
+ PlyFormat.Write(model, stream, cancellationToken);
+ break;
+ case "3mf":
+ ThreeMfFormat.Write(model, stream, cancellationToken);
+ break;
+ case "glb":
+ case "gltf":
+ GltfFormat.Write(model, stream, binary: format == "glb", cancellationToken);
+ break;
+ }
+ }
+
+ /// <summary>The .obj, the .mtl next to it (when the model has materials) and the textures next to that.</summary>
+ private static void WriteObj(Model3D model, IOutputAllocator output, List<string> outputs, CancellationToken cancellationToken)
+ {
+ if (output.Allocate("obj") is not { } obj)
+ return;
+ outputs.Add(obj);
+ string? mtl = null;
+ var textures = new Dictionary<Texture3D, string>();
+ if (model.Materials.Count > 0)
+ {
+ mtl = output.Allocate("mtl");
+ if (mtl is not null)
+ {
+ outputs.Add(mtl);
+ var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ foreach (var texture in model.Materials.Select(m => m.BaseColorTexture).OfType<Texture3D>().Distinct())
+ {
+ var name = SafeName(texture.Name);
+ for (var i = 2; !names.Add(name); i++)
+ name = $"{SafeName(texture.Name)}_{i}";
+ if (output.Allocate(texture.Extension.Length > 0 ? texture.Extension : "png", "_" + name) is not { } file)
+ continue;
+ outputs.Add(file);
+ File.WriteAllBytes(file, texture.Data);
+ textures[texture] = file;
+ }
+ }
+ }
+ ObjFormat.Write(model, obj, mtl, textures, cancellationToken);
+ }
+
+ private static string SafeName(string name)
+ {
+ var invalid = Path.GetInvalidFileNameChars();
+ var clean = new string([.. name.Where(c => !invalid.Contains(c) && !char.IsWhiteSpace(c))]);
+ return clean.Length == 0 ? "texture" : clean.Length > 40 ? clean[..40] : clean;
+ }
+
+ /// <summary>An isometric preview, then the preset's image options (resize, background, quality) as for other pictures.</summary>
+ private static void WriteImage(Model3D model, string format, ImageOptions options, string path, CancellationToken cancellationToken)
+ {
+ var png = MeshRenderer.RenderPng(model, PreviewSize, cancellationToken);
+ using var image = new MagickImage(png);
+ ImageEncoder.ApplyOptions(image, options, format);
+ image.Write(path, ImageEncoder.ToMagickFormat(format));
+ }
+
+ private static void TryDelete(string path)
+ {
+ try
+ {
+ File.Delete(path);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+
+ /// <summary>Maps 0–1 progress of one phase onto a slice of the step's progress, synchronously.</summary>
+ private sealed class SubProgress(IProgress<double> parent, double start, double length) : IProgress<double>
+ {
+ public void Report(double value) => parent.Report(start + length * value);
+ }
+}
diff --git a/src/Filee.Engines/Models3D/ObjFormat.cs b/src/Filee.Engines/Models3D/ObjFormat.cs
new file mode 100644
index 00000000..1ef01220
--- /dev/null
+++ b/src/Filee.Engines/Models3D/ObjFormat.cs
@@ -0,0 +1,544 @@
+// Wavefront OBJ with its MTL material library. Unitless (read as millimetres), Y up. Read: v (with the common
+// "v x y z r g b" vertex colour extension), vt, vn, f with negative (relative) indices and polygons, o / g / usemtl
+// as parts, mtllib with Kd, d / Tr and map_Kd textures next to the file. Written: one "o" per part, an .mtl next
+// to the .obj and the textures next to that.
+
+using System.Globalization;
+using System.Numerics;
+using System.Text;
+
+namespace Filee.Engines.Models3D;
+
+internal static class ObjFormat
+{
+ public static Model3D Read(string path, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var model = new Model3D();
+ var positions = new List<float>();
+ List<float>? colors = null;
+ var uvs = new List<float>();
+ var normals = new List<float>();
+ // Materials of the libraries by name; only those a face uses become materials of the model.
+ var library = new Dictionary<string, Material3D>(StringComparer.Ordinal);
+ var materials = new Dictionary<string, int>(StringComparer.Ordinal);
+ var parts = new Dictionary<(string, string?), PartBuilder>();
+ var directory = Path.GetDirectoryName(Path.GetFullPath(path))!;
+
+ string objectName = "", groupName = "";
+ string? material = null;
+ PartBuilder? current = null;
+ Span<int> corners = stackalloc int[256];
+ Span<float> numbers = stackalloc float[7];
+
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan);
+ var length = Math.Max(1, stream.Length);
+ using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, 1 << 16);
+ var lineNumber = 0;
+ while (reader.ReadLine() is { } raw)
+ {
+ lineNumber++;
+ if ((lineNumber & 0xFFFF) == 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report((double)stream.Position / length);
+ }
+ var line = raw;
+ // A trailing backslash continues the statement on the next line.
+ while (line.EndsWith('\\') && reader.ReadLine() is { } next)
+ {
+ line = line[..^1] + " " + next;
+ lineNumber++;
+ }
+ var text = line.AsSpan().Trim();
+ if (text.IsEmpty || text[0] == '#')
+ continue;
+ var space = text.IndexOfAny(' ', '\t');
+ var keyword = space < 0 ? text : text[..space];
+ var rest = space < 0 ? [] : text[(space + 1)..].Trim();
+
+ switch (keyword)
+ {
+ case "v":
+ {
+ var values = numbers;
+ var n = ParseFloats(rest, values, lineNumber);
+ if (n < 3)
+ throw new InvalidDataException($"Line {lineNumber} of the OBJ file has a vertex with fewer than three coordinates.");
+ positions.Add(values[0]);
+ positions.Add(values[1]);
+ positions.Add(values[2]);
+ if (n >= 6)
+ {
+ colors ??= [.. Enumerable.Repeat(1f, (positions.Count / 3 - 1) * 3)];
+ var scale = values[3] > 1 || values[4] > 1 || values[5] > 1 ? 1 / 255f : 1;
+ colors.Add(Math.Clamp(values[3] * scale, 0, 1));
+ colors.Add(Math.Clamp(values[4] * scale, 0, 1));
+ colors.Add(Math.Clamp(values[5] * scale, 0, 1));
+ }
+ else if (colors is not null)
+ {
+ colors.Add(1);
+ colors.Add(1);
+ colors.Add(1);
+ }
+ break;
+ }
+ case "vt":
+ {
+ var values = numbers[..3];
+ var n = ParseFloats(rest, values, lineNumber);
+ uvs.Add(n > 0 ? values[0] : 0);
+ uvs.Add(n > 1 ? values[1] : 0);
+ break;
+ }
+ case "vn":
+ {
+ var values = numbers[..3];
+ if (ParseFloats(rest, values, lineNumber) < 3)
+ throw new InvalidDataException($"Line {lineNumber} of the OBJ file has a normal with fewer than three values.");
+ normals.Add(values[0]);
+ normals.Add(values[1]);
+ normals.Add(values[2]);
+ break;
+ }
+ case "f" or "fo":
+ {
+ current ??= Part(groupName.Length > 0 ? groupName : objectName, material);
+ var count = 0;
+ foreach (var range in rest.SplitAny(' ', '\t'))
+ {
+ var token = rest[range];
+ if (token.IsEmpty)
+ continue;
+ if (count == corners.Length)
+ throw new InvalidDataException($"Line {lineNumber} of the OBJ file has a face with more than {corners.Length} corners.");
+ corners[count++] = current.Corner(token, positions, colors, uvs, normals, lineNumber);
+ }
+ Triangulator.AddPolygon(current.Part, corners[..count]);
+ break;
+ }
+ case "o":
+ objectName = rest.ToString();
+ groupName = "";
+ current = null;
+ break;
+ case "g":
+ groupName = rest.ToString();
+ current = null;
+ break;
+ case "usemtl":
+ material = rest.ToString();
+ current = null;
+ break;
+ case "mtllib":
+ foreach (var file in LibraryNames(rest.ToString(), directory))
+ MtlFormat.Read(file, library);
+ break;
+ }
+ }
+
+ foreach (var builder in parts.Values)
+ {
+ var part = builder.Part;
+ if (part.Normals is not null && HasZeroNormal(part.Normals))
+ part.ComputeNormals();
+ model.Parts.Add(part);
+ }
+ return model;
+
+ PartBuilder Part(string name, string? materialName)
+ {
+ if (parts.TryGetValue((name, materialName), out var existing))
+ return existing;
+ var index = -1;
+ if (materialName is not null && !materials.TryGetValue(materialName, out index))
+ {
+ // usemtl without a definition (missing .mtl) keeps the name, white.
+ index = model.Materials.Count;
+ model.Materials.Add(library.GetValueOrDefault(materialName) ?? new Material3D { Name = materialName });
+ materials[materialName] = index;
+ }
+ var builder = new PartBuilder(new MeshPart
+ {
+ Name = name.Length > 0 ? name : materialName ?? "OBJ",
+ Material = index,
+ });
+ parts[(name, materialName)] = builder;
+ return builder;
+ }
+ }
+
+ private static bool HasZeroNormal(List<float> normals)
+ {
+ for (var i = 0; i + 2 < normals.Count; i += 3)
+ {
+ if (normals[i] == 0 && normals[i + 1] == 0 && normals[i + 2] == 0)
+ return true;
+ }
+ return false;
+ }
+
+ /// <summary>The .mtl files of an mtllib statement: the whole text as one name first (names may have spaces), else each word.</summary>
+ private static IEnumerable<string> LibraryNames(string text, string directory)
+ {
+ var whole = Resolve(directory, text);
+ if (whole is not null)
+ return [whole];
+ return text.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries).Select(n => Resolve(directory, n)).OfType<string>();
+ }
+
+ /// <summary>Finds a file referenced from an OBJ / MTL: relative to <paramref name="directory"/>, else by name only.</summary>
+ internal static string? Resolve(string directory, string reference)
+ {
+ reference = reference.Trim().Trim('"').Replace('\\', '/');
+ if (reference.Length == 0)
+ return null;
+ try
+ {
+ var candidate = Path.GetFullPath(Path.Combine(directory, reference));
+ if (File.Exists(candidate))
+ return candidate;
+ candidate = Path.Combine(directory, Path.GetFileName(reference));
+ return File.Exists(candidate) ? candidate : null;
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ return null;
+ }
+ }
+
+ private static int ParseFloats(ReadOnlySpan<char> text, Span<float> values, int lineNumber)
+ {
+ var n = 0;
+ foreach (var range in text.SplitAny(' ', '\t'))
+ {
+ var token = text[range];
+ if (token.IsEmpty)
+ continue;
+ if (n == values.Length)
+ break;
+ if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out values[n++]))
+ throw new InvalidDataException($"Line {lineNumber} of the OBJ file has an invalid number: \"{token}\".");
+ }
+ return n;
+ }
+
+ /// <summary>Collects the vertices of one part, one per distinct (position, uv, normal) corner.</summary>
+ private sealed class PartBuilder(MeshPart part)
+ {
+ private readonly Dictionary<(int, int, int), int> _corners = [];
+
+ public MeshPart Part { get; } = part;
+
+ public int Corner(ReadOnlySpan<char> token, List<float> positions, List<float>? colors, List<float> uvs, List<float> normals, int lineNumber)
+ {
+ int v = -1, t = -1, n = -1, slot = 0;
+ foreach (var range in token.Split('/'))
+ {
+ var field = token[range];
+ if (slot > 2)
+ break;
+ if (!field.IsEmpty)
+ {
+ if (!int.TryParse(field, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var value) || value == 0)
+ throw new InvalidDataException($"Line {lineNumber} of the OBJ file has an invalid face index: \"{token}\".");
+ var count = slot switch { 0 => positions.Count / 3, 1 => uvs.Count / 2, _ => normals.Count / 3 };
+ var index = value > 0 ? value - 1 : count + value;
+ if ((uint)index >= (uint)count)
+ throw new InvalidDataException($"Line {lineNumber} of the OBJ file refers to {(slot switch { 0 => "vertex", 1 => "texture coordinate", _ => "normal" })} {value}, which does not exist (there are {count}).");
+ if (slot == 0) v = index;
+ else if (slot == 1) t = index;
+ else n = index;
+ }
+ slot++;
+ }
+ if (v < 0)
+ throw new InvalidDataException($"Line {lineNumber} of the OBJ file has a face corner without a vertex: \"{token}\".");
+
+ if (_corners.TryGetValue((v, t, n), out var existing))
+ return existing;
+ if (t >= 0 && Part.TexCoords is null)
+ Part.TexCoords = [.. new float[Part.VertexCount * 2]];
+ if (n >= 0 && Part.Normals is null)
+ Part.Normals = [.. new float[Part.VertexCount * 3]];
+ if (colors is not null && Part.Colors is null)
+ Part.Colors = [.. Enumerable.Repeat(1f, Part.VertexCount * 4)];
+ var vertex = Part.AddVertex(
+ new Vector3(positions[v * 3], positions[v * 3 + 1], positions[v * 3 + 2]),
+ n >= 0 ? new Vector3(normals[n * 3], normals[n * 3 + 1], normals[n * 3 + 2]) : null,
+ t >= 0 ? new Vector2(uvs[t * 2], uvs[t * 2 + 1]) : null,
+ colors is not null ? new Vector4(colors[v * 3], colors[v * 3 + 1], colors[v * 3 + 2], 1) : null);
+ _corners[(v, t, n)] = vertex;
+ return vertex;
+ }
+ }
+
+ /// <summary>
+ /// Writes <paramref name="model"/> as OBJ. <paramref name="mtlPath"/> (null: no material library) gets the
+ /// materials; <paramref name="texturePaths"/> maps each texture to the file it was written to.
+ /// </summary>
+ public static void Write(Model3D model, string objPath, string? mtlPath, IReadOnlyDictionary<Texture3D, string> texturePaths, CancellationToken cancellationToken)
+ {
+ var anyColors = model.Parts.Any(p => p.Colors is not null);
+ var materialNames = UniqueNames(model.Materials.Select(m => m.Name), "Material");
+ using (var writer = new StreamWriter(objPath, false, new UTF8Encoding(false), 1 << 16))
+ {
+ writer.NewLine = "\n";
+ writer.WriteLine("# Written by Filee");
+ if (mtlPath is not null)
+ writer.WriteLine($"mtllib {RelativeReference(objPath, mtlPath)}");
+
+ var partNames = UniqueNames(model.Parts.Select(p => p.Name), "Part");
+ int vBase = 1, tBase = 1, nBase = 1;
+ Span<char> buffer = stackalloc char[256];
+ for (var p = 0; p < model.Parts.Count; p++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var part = model.Parts[p];
+ writer.WriteLine($"o {partNames[p]}");
+
+ // Without vertex colours, a material's colour becomes the vertex colour, so parts look the same.
+ var fallback = MeshMath.LinearToSrgb(model.MaterialOf(part)?.BaseColor ?? Vector4.One);
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var position = part.Position(v);
+ var line = new LineBuilder(buffer);
+ line.Append("v");
+ line.Append(position.X);
+ line.Append(position.Y);
+ line.Append(position.Z);
+ if (anyColors)
+ {
+ var color = part.Colors is null ? fallback : part.Color(v);
+ line.Append(color.X);
+ line.Append(color.Y);
+ line.Append(color.Z);
+ }
+ writer.WriteLine(line.Text);
+ }
+ if (part.TexCoords is not null)
+ {
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var uv = part.TexCoord(v);
+ var line = new LineBuilder(buffer);
+ line.Append("vt");
+ line.Append(uv.X);
+ line.Append(uv.Y);
+ writer.WriteLine(line.Text);
+ }
+ }
+ if (part.Normals is not null)
+ {
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var n = part.Normal(v);
+ var line = new LineBuilder(buffer);
+ line.Append("vn");
+ line.Append(n.X);
+ line.Append(n.Y);
+ line.Append(n.Z);
+ writer.WriteLine(line.Text);
+ }
+ }
+
+ if (mtlPath is not null)
+ writer.WriteLine($"usemtl {(part.Material >= 0 && part.Material < model.Materials.Count ? materialNames[part.Material] : DefaultMaterial)}");
+ var indices = part.IndexSpan;
+ for (var i = 0; i + 2 < indices.Length; i += 3)
+ {
+ var line = new LineBuilder(buffer);
+ line.Append("f");
+ for (var k = 0; k < 3; k++)
+ line.AppendCorner(indices[i + k], vBase, part.TexCoords is null ? -1 : tBase, part.Normals is null ? -1 : nBase);
+ writer.WriteLine(line.Text);
+ }
+ vBase += part.VertexCount;
+ if (part.TexCoords is not null)
+ tBase += part.VertexCount;
+ if (part.Normals is not null)
+ nBase += part.VertexCount;
+ }
+ }
+
+ if (mtlPath is not null)
+ MtlFormat.Write(model, materialNames, mtlPath, texturePaths);
+ }
+
+ /// <summary>Name of the white material parts without one use when the file has a material library.</summary>
+ internal const string DefaultMaterial = "Default";
+
+ /// <summary>OBJ / MTL names without spaces, unique, never empty.</summary>
+ internal static List<string> UniqueNames(IEnumerable<string> names, string fallback)
+ {
+ var used = new HashSet<string>(StringComparer.Ordinal) { DefaultMaterial };
+ var result = new List<string>();
+ foreach (var name in names)
+ {
+ var clean = new string([.. name.Select(c => char.IsWhiteSpace(c) || char.IsControl(c) ? '_' : c)]);
+ if (clean.Length == 0)
+ clean = fallback;
+ var unique = clean;
+ for (var i = 2; !used.Add(unique); i++)
+ unique = $"{clean}_{i}";
+ result.Add(unique);
+ }
+ return result;
+ }
+
+ /// <summary>The path of <paramref name="target"/> as written in a file next to <paramref name="from"/> (forward slashes).</summary>
+ internal static string RelativeReference(string from, string target) =>
+ Path.GetRelativePath(Path.GetDirectoryName(Path.GetFullPath(from))!, Path.GetFullPath(target)).Replace('\\', '/');
+
+ /// <summary>Formats one OBJ statement into a stack buffer without allocating per number.</summary>
+ private ref struct LineBuilder(Span<char> buffer)
+ {
+ private readonly Span<char> _buffer = buffer;
+ private int _length;
+
+ public readonly ReadOnlySpan<char> Text => _buffer[.._length];
+
+ public void Append(string keyword)
+ {
+ keyword.AsSpan().CopyTo(_buffer[_length..]);
+ _length += keyword.Length;
+ }
+
+ public void Append(float value)
+ {
+ _buffer[_length++] = ' ';
+ if (!float.IsFinite(value))
+ value = 0;
+ value.TryFormat(_buffer[_length..], out var written, default, CultureInfo.InvariantCulture);
+ _length += written;
+ }
+
+ public void AppendCorner(int index, int vBase, int tBase, int nBase)
+ {
+ _buffer[_length++] = ' ';
+ AppendInt(index + vBase);
+ if (tBase < 0 && nBase < 0)
+ return;
+ _buffer[_length++] = '/';
+ if (tBase >= 0)
+ AppendInt(index + tBase);
+ if (nBase >= 0)
+ {
+ _buffer[_length++] = '/';
+ AppendInt(index + nBase);
+ }
+ }
+
+ private void AppendInt(int value)
+ {
+ value.TryFormat(_buffer[_length..], out var written, default, CultureInfo.InvariantCulture);
+ _length += written;
+ }
+ }
+}
+
+/// <summary>MTL material libraries: Kd (diffuse colour), d / Tr (opacity) and map_Kd (diffuse texture).</summary>
+internal static class MtlFormat
+{
+ /// <summary>Adds the materials of <paramref name="path"/> to <paramref name="library"/> (a later definition of a name wins).</summary>
+ public static void Read(string path, Dictionary<string, Material3D> library)
+ {
+ var directory = Path.GetDirectoryName(path)!;
+ Material3D? current = null;
+ foreach (var raw in File.ReadLines(path))
+ {
+ var text = raw.AsSpan().Trim();
+ if (text.IsEmpty || text[0] == '#')
+ continue;
+ var space = text.IndexOfAny(' ', '\t');
+ var keyword = (space < 0 ? text : text[..space]).ToString();
+ var rest = space < 0 ? "" : text[(space + 1)..].Trim().ToString();
+ if (keyword == "newmtl")
+ {
+ current = new Material3D { Name = rest };
+ library[rest] = current;
+ continue;
+ }
+ if (current is null)
+ continue;
+ var values = rest.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
+ switch (keyword.ToLowerInvariant())
+ {
+ case "kd" when values.Length >= 3 && Floats(values, 3) is { } kd:
+ current.BaseColor = new Vector4(kd[0], kd[1], kd[2], current.BaseColor.W);
+ break;
+ case "d" when values.Length >= 1 && Floats(values[^1..], 1) is { } d:
+ current.BaseColor = current.BaseColor with { W = Math.Clamp(d[0], 0, 1) };
+ break;
+ case "tr" when values.Length >= 1 && Floats(values[^1..], 1) is { } tr:
+ current.BaseColor = current.BaseColor with { W = Math.Clamp(1 - tr[0], 0, 1) };
+ break;
+ case "map_kd" when TextureFile(values) is { } file && ObjFormat.Resolve(directory, file) is { } texture:
+ var data = File.ReadAllBytes(texture);
+ current.BaseColorTexture = new Texture3D(data, Texture3D.Sniff(data, Path.GetExtension(texture)), Path.GetFileNameWithoutExtension(texture));
+ break;
+ }
+ }
+ }
+
+ private static float[]? Floats(string[] values, int count)
+ {
+ var result = new float[count];
+ for (var i = 0; i < count; i++)
+ {
+ if (!float.TryParse(values[i], NumberStyles.Float, CultureInfo.InvariantCulture, out result[i]))
+ return null;
+ }
+ return result;
+ }
+
+ /// <summary>The file name of a map_Kd statement after its options (-s 1 1 1, -bm 0.5, -clamp on, ...).</summary>
+ private static string? TextureFile(string[] values)
+ {
+ var i = 0;
+ while (i < values.Length && values[i].StartsWith('-'))
+ {
+ var option = values[i++].ToLowerInvariant();
+ var arguments = option switch
+ {
+ "-o" or "-s" or "-t" => 3,
+ "-mm" => 2,
+ "-blendu" or "-blendv" or "-boost" or "-cc" or "-clamp" or "-texres" or "-bm" or "-imfchan" or "-type" => 1,
+ _ => 0,
+ };
+ // -o, -s and -t take one to three numbers.
+ for (var a = 0; a < arguments && i < values.Length; a++)
+ {
+ if (arguments == 3 && a > 0 && !float.TryParse(values[i], NumberStyles.Float, CultureInfo.InvariantCulture, out _))
+ break;
+ i++;
+ }
+ }
+ return i < values.Length ? string.Join(' ', values[i..]) : null;
+ }
+
+ public static void Write(Model3D model, IReadOnlyList<string> names, string path, IReadOnlyDictionary<Texture3D, string> texturePaths)
+ {
+ using var writer = new StreamWriter(path, false, new UTF8Encoding(false));
+ writer.NewLine = "\n";
+ writer.WriteLine("# Written by Filee");
+ WriteMaterial(writer, ObjFormat.DefaultMaterial, new Material3D());
+ for (var m = 0; m < model.Materials.Count; m++)
+ WriteMaterial(writer, names[m], model.Materials[m]);
+
+ void WriteMaterial(StreamWriter w, string name, Material3D material)
+ {
+ var c = material.BaseColor;
+ w.WriteLine();
+ w.WriteLine($"newmtl {name}");
+ w.WriteLine(string.Create(CultureInfo.InvariantCulture, $"Kd {c.X} {c.Y} {c.Z}"));
+ w.WriteLine("Ka 0 0 0");
+ w.WriteLine("Ks 0 0 0");
+ if (c.W < 1)
+ w.WriteLine(string.Create(CultureInfo.InvariantCulture, $"d {c.W}"));
+ w.WriteLine("illum 1");
+ if (material.BaseColorTexture is { } texture && texturePaths.TryGetValue(texture, out var file))
+ w.WriteLine($"map_Kd {ObjFormat.RelativeReference(path, file)}");
+ }
+ }
+}
diff --git a/src/Filee.Engines/Models3D/PlyFormat.cs b/src/Filee.Engines/Models3D/PlyFormat.cs
new file mode 100644
index 00000000..dd8023dc
--- /dev/null
+++ b/src/Filee.Engines/Models3D/PlyFormat.cs
@@ -0,0 +1,489 @@
+// Stanford PLY: ASCII, binary little endian and binary big endian. Unitless (read as millimetres), Z up like Blender
+// treats it. Read: vertex x/y/z, normals, texture coordinates (s/t, u/v, texture_u/texture_v), colours (red/green/
+// blue/alpha in any type), faces as index lists (polygons are triangulated) with optional per-corner texture
+// coordinates and face colours, and a "comment TextureFile" picture next to the file; other elements are skipped.
+// Written: binary little endian, one mesh; PLY has no materials, so material colours become vertex colours.
+
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Numerics;
+using System.Text;
+
+namespace Filee.Engines.Models3D;
+
+internal static class PlyFormat
+{
+ private enum Encoding3 { Ascii, LittleEndian, BigEndian }
+
+ private enum PlyType { Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32, Float64 }
+
+ private sealed record Property(string Name, PlyType Type, PlyType? CountType);
+
+ private sealed class Element(string name, long count)
+ {
+ public string Name { get; } = name;
+ public long Count { get; } = count;
+ public List<Property> Properties { get; } = [];
+ }
+
+ public static Model3D Read(string path, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan);
+ var (encoding, elements, textureFile) = ReadHeader(stream);
+ IValueReader values = encoding == Encoding3.Ascii
+ ? new AsciiReader(stream)
+ : new BinaryReader(stream, encoding == Encoding3.BigEndian);
+
+ var part = new MeshPart { Name = Path.GetFileNameWithoutExtension(path) };
+ var model = new Model3D { Parts = { part } };
+ // Vertices as read; faces with their own texture coordinates or colours get split copies.
+ var vertexCount = 0;
+ var split = new Dictionary<(int, Vector2, Vector4), int>();
+ var claimed = new HashSet<int>();
+ var total = Math.Max(1, elements.Sum(e => e.Count));
+ long done = 0;
+ Span<int> corners = stackalloc int[256];
+ Span<double> color = stackalloc double[4];
+ var cornerValues = new List<double>();
+ var cornerUvs = new List<double>();
+
+ foreach (var element in elements)
+ {
+ if (element.Name == "vertex")
+ {
+ vertexCount = (int)Math.Min(element.Count, int.MaxValue / 4);
+ ReadVertices(element, values, part, progress, done, total, cancellationToken);
+ }
+ else if (element.Name == "face")
+ {
+ var indexProperty = element.Properties.FindIndex(p => p.CountType is not null && p.Name is "vertex_indices" or "vertex_index");
+ if (indexProperty < 0)
+ throw new InvalidDataException("The PLY file's faces have no vertex_indices list.");
+ var uvProperty = element.Properties.FindIndex(p => p.CountType is not null && p.Name == "texcoord");
+ var colorRoles = element.Properties.Select(p => ColorChannel(p.Name)).ToArray();
+ var hasFaceColor = colorRoles.Any(r => r >= 0);
+ for (long f = 0; f < element.Count; f++)
+ {
+ if ((f & 0xFFFF) == 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report((double)(done + f) / total);
+ }
+ cornerValues.Clear();
+ cornerUvs.Clear();
+ color[0] = color[1] = color[2] = color[3] = 1;
+ for (var p = 0; p < element.Properties.Count; p++)
+ {
+ var property = element.Properties[p];
+ if (property.CountType is { } countType)
+ {
+ var count = (long)values.Read(countType);
+ if (count < 0 || count > 1 << 20)
+ throw new InvalidDataException("The PLY file has a face with an invalid number of corners.");
+ var target = p == indexProperty ? cornerValues : p == uvProperty ? cornerUvs : null;
+ for (var i = 0; i < count; i++)
+ {
+ var value = values.Read(property.Type);
+ target?.Add(value);
+ }
+ }
+ else
+ {
+ var value = values.Read(property.Type);
+ if (colorRoles[p] >= 0)
+ color[colorRoles[p]] = ColorValue(value, property.Type);
+ }
+ }
+
+ var n = Math.Min(cornerValues.Count, corners.Length);
+ var wedgeUvs = cornerUvs.Count >= n * 2 && n > 0;
+ for (var i = 0; i < n; i++)
+ {
+ var index = (long)cornerValues[i];
+ if (index < 0 || index >= vertexCount)
+ throw new InvalidDataException($"A face of the PLY file refers to vertex {index}, but there are only {vertexCount} vertices.");
+ corners[i] = (int)index;
+ if (!wedgeUvs && !hasFaceColor)
+ continue;
+ var uv = wedgeUvs ? new Vector2((float)cornerUvs[i * 2], (float)cornerUvs[i * 2 + 1]) : part.TexCoord((int)index);
+ var rgba = hasFaceColor ? new Vector4((float)color[0], (float)color[1], (float)color[2], (float)color[3]) : part.Color((int)index);
+ corners[i] = Split(part, split, claimed, (int)index, uv, rgba, wedgeUvs, hasFaceColor);
+ }
+ Triangulator.AddPolygon(part, corners[..n]);
+ }
+ }
+ else
+ {
+ // Edges, materials, ...: read past them.
+ for (long i = 0; i < element.Count; i++)
+ {
+ foreach (var property in element.Properties)
+ {
+ if (property.CountType is { } countType)
+ {
+ var count = (long)values.Read(countType);
+ for (var k = 0; k < count; k++)
+ values.Read(property.Type);
+ }
+ else
+ {
+ values.Read(property.Type);
+ }
+ }
+ }
+ }
+ done += element.Count;
+ }
+
+ if (textureFile is not null && ObjFormat.Resolve(Path.GetDirectoryName(Path.GetFullPath(path))!, textureFile) is { } texture)
+ {
+ var data = File.ReadAllBytes(texture);
+ model.Materials.Add(new Material3D
+ {
+ Name = Path.GetFileNameWithoutExtension(texture),
+ BaseColorTexture = new Texture3D(data, Texture3D.Sniff(data, Path.GetExtension(texture)), Path.GetFileNameWithoutExtension(texture)),
+ });
+ part.Material = 0;
+ }
+ part.Transform(MeshMath.ZUpToYUp);
+ return model;
+ }
+
+ /// <summary>A copy of <paramref name="vertex"/> with the corner's own texture coordinate and/or colour.</summary>
+ private static int Split(MeshPart part, Dictionary<(int, Vector2, Vector4), int> split, HashSet<int> claimed, int vertex, Vector2 uv, Vector4 color, bool setUv, bool setColor)
+ {
+ if (setUv && part.TexCoords is null)
+ part.TexCoords = [.. new float[part.VertexCount * 2]];
+ if (setColor && part.Colors is null)
+ part.Colors = [.. Enumerable.Repeat(1f, part.VertexCount * 4)];
+ if (claimed.Add(vertex))
+ {
+ // The first face to use a vertex gives it its texture coordinate and colour.
+ if (part.TexCoords is not null)
+ {
+ part.TexCoords[vertex * 2] = uv.X;
+ part.TexCoords[vertex * 2 + 1] = uv.Y;
+ }
+ if (part.Colors is not null)
+ {
+ for (var k = 0; k < 4; k++)
+ part.Colors[vertex * 4 + k] = color[k];
+ }
+ return vertex;
+ }
+ if (part.TexCoord(vertex) == uv && part.Color(vertex) == color)
+ return vertex;
+ if (split.TryGetValue((vertex, uv, color), out var copy))
+ return copy;
+ copy = part.AddVertex(part.Position(vertex), part.Normals is null ? null : part.Normal(vertex), uv, color);
+ split[(vertex, uv, color)] = copy;
+ return copy;
+ }
+
+ private static void ReadVertices(Element element, IValueReader values, MeshPart part, IProgress<double>? progress, long done, long total, CancellationToken cancellationToken)
+ {
+ var names = element.Properties.Select(p => p.Name).ToList();
+ int[] position = [names.IndexOf("x"), names.IndexOf("y"), names.IndexOf("z")];
+ if (position.Any(i => i < 0))
+ throw new InvalidDataException("The PLY file's vertices have no x, y and z.");
+ int[] normal = [names.IndexOf("nx"), names.IndexOf("ny"), names.IndexOf("nz")];
+ int[] uv = [IndexOfAny(names, "s", "u", "texture_u", "texture_s"), IndexOfAny(names, "t", "v", "texture_v", "texture_t")];
+ var colorRoles = element.Properties.Select(p => ColorChannel(p.Name)).ToArray();
+ var hasNormals = normal.All(i => i >= 0);
+ var hasUvs = uv.All(i => i >= 0);
+ var hasColors = colorRoles.Any(r => r >= 0);
+ if (hasNormals)
+ part.Normals = [];
+ if (hasUvs)
+ part.TexCoords = [];
+ if (hasColors)
+ part.Colors = [];
+
+ var count = (int)Math.Min(element.Count, int.MaxValue / 4);
+ part.Positions.Capacity = count * 3;
+ var row = new double[element.Properties.Count];
+ for (var v = 0; v < count; v++)
+ {
+ if ((v & 0xFFFF) == 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report((double)(done + v) / total);
+ }
+ Vector4 color = Vector4.One;
+ for (var p = 0; p < row.Length; p++)
+ {
+ var property = element.Properties[p];
+ if (property.CountType is { } countType)
+ {
+ var n = (long)values.Read(countType);
+ for (var k = 0; k < n; k++)
+ values.Read(property.Type);
+ continue;
+ }
+ row[p] = values.Read(property.Type);
+ if (colorRoles[p] >= 0)
+ color[colorRoles[p]] = (float)ColorValue(row[p], property.Type);
+ }
+ part.AddVertex(
+ new Vector3((float)row[position[0]], (float)row[position[1]], (float)row[position[2]]),
+ hasNormals ? new Vector3((float)row[normal[0]], (float)row[normal[1]], (float)row[normal[2]]) : null,
+ hasUvs ? new Vector2((float)row[uv[0]], (float)row[uv[1]]) : null,
+ color);
+ }
+ }
+
+ private static int IndexOfAny(List<string> names, params string[] candidates) =>
+ candidates.Select(c => names.IndexOf(c)).FirstOrDefault(i => i >= 0, -1);
+
+ /// <summary>0–3 for red, green, blue, alpha (also "diffuse_red" ...), else -1.</summary>
+ private static int ColorChannel(string name) => name switch
+ {
+ "red" or "diffuse_red" or "r" => 0,
+ "green" or "diffuse_green" or "g" => 1,
+ "blue" or "diffuse_blue" or "b" => 2,
+ "alpha" or "diffuse_alpha" or "a" => 3,
+ _ => -1,
+ };
+
+ /// <summary>A colour channel as 0–1: integers are scaled by their range, floats are taken as they are.</summary>
+ private static double ColorValue(double value, PlyType type) => type switch
+ {
+ PlyType.UInt8 or PlyType.Int8 => value / 255,
+ PlyType.UInt16 or PlyType.Int16 => value / 65535,
+ PlyType.UInt32 or PlyType.Int32 => value > 255 ? value / uint.MaxValue : value / 255,
+ _ => Math.Clamp(value > 1 ? value / 255 : value, 0, 1),
+ };
+
+ private static (Encoding3, List<Element>, string?) ReadHeader(Stream stream)
+ {
+ var magic = ReadHeaderLine(stream);
+ if (magic != "ply")
+ throw new InvalidDataException("The file is not a PLY file (it does not start with \"ply\").");
+ Encoding3? encoding = null;
+ string? texture = null;
+ var elements = new List<Element>();
+ while (true)
+ {
+ var line = ReadHeaderLine(stream) ?? throw new InvalidDataException("The PLY header has no end_header line.");
+ var words = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
+ if (words.Length == 0)
+ continue;
+ switch (words[0])
+ {
+ case "end_header":
+ return (encoding ?? throw new InvalidDataException("The PLY header has no format line."), elements, texture);
+ case "format" when words.Length >= 2:
+ encoding = words[1] switch
+ {
+ "ascii" => Encoding3.Ascii,
+ "binary_little_endian" => Encoding3.LittleEndian,
+ "binary_big_endian" => Encoding3.BigEndian,
+ _ => throw new InvalidDataException($"Unknown PLY format \"{words[1]}\"."),
+ };
+ break;
+ case "comment" when words.Length >= 3 && words[1].Equals("TextureFile", StringComparison.OrdinalIgnoreCase):
+ texture = line[(line.IndexOf(words[1], StringComparison.Ordinal) + words[1].Length)..].Trim();
+ break;
+ case "element" when words.Length >= 3:
+ if (!long.TryParse(words[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var count) || count < 0)
+ throw new InvalidDataException($"The PLY element \"{words[1]}\" has an invalid count.");
+ elements.Add(new Element(words[1], count));
+ break;
+ case "property" when elements.Count > 0:
+ var element = elements[^1];
+ if (words.Length >= 5 && words[1] == "list")
+ element.Properties.Add(new Property(words[4], Type(words[3]), Type(words[2])));
+ else if (words.Length >= 3)
+ element.Properties.Add(new Property(words[2], Type(words[1]), null));
+ else
+ throw new InvalidDataException($"Invalid PLY property line: \"{line}\".");
+ break;
+ }
+ }
+ }
+
+ private static PlyType Type(string name) => name switch
+ {
+ "char" or "int8" => PlyType.Int8,
+ "uchar" or "uint8" => PlyType.UInt8,
+ "short" or "int16" => PlyType.Int16,
+ "ushort" or "uint16" => PlyType.UInt16,
+ "int" or "int32" => PlyType.Int32,
+ "uint" or "uint32" => PlyType.UInt32,
+ "float" or "float32" => PlyType.Float32,
+ "double" or "float64" => PlyType.Float64,
+ _ => throw new InvalidDataException($"Unknown PLY property type \"{name}\"."),
+ };
+
+ /// <summary>Reads one header line byte by byte, so the stream stops exactly where the body starts.</summary>
+ private static string? ReadHeaderLine(Stream stream)
+ {
+ var bytes = new List<byte>();
+ while (true)
+ {
+ var b = stream.ReadByte();
+ if (b < 0)
+ return bytes.Count == 0 ? null : System.Text.Encoding.ASCII.GetString([.. bytes]);
+ if (b == '\n')
+ return System.Text.Encoding.ASCII.GetString([.. bytes]).TrimEnd('\r');
+ if (bytes.Count > 4096)
+ throw new InvalidDataException("The file is not a PLY file (its header has an endless line).");
+ bytes.Add((byte)b);
+ }
+ }
+
+ private interface IValueReader
+ {
+ double Read(PlyType type);
+ }
+
+ private sealed class BinaryReader(Stream stream, bool bigEndian) : IValueReader
+ {
+ private readonly byte[] _buffer = new byte[1 << 16];
+ private int _position;
+ private int _length;
+
+ public double Read(PlyType type)
+ {
+ var size = type switch
+ {
+ PlyType.Int8 or PlyType.UInt8 => 1,
+ PlyType.Int16 or PlyType.UInt16 => 2,
+ PlyType.Float64 => 8,
+ _ => 4,
+ };
+ if (_length - _position < size)
+ Fill(size);
+ var data = _buffer.AsSpan(_position, size);
+ _position += size;
+ return type switch
+ {
+ PlyType.Int8 => (sbyte)data[0],
+ PlyType.UInt8 => data[0],
+ PlyType.Int16 => bigEndian ? BinaryPrimitives.ReadInt16BigEndian(data) : BinaryPrimitives.ReadInt16LittleEndian(data),
+ PlyType.UInt16 => bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(data) : BinaryPrimitives.ReadUInt16LittleEndian(data),
+ PlyType.Int32 => bigEndian ? BinaryPrimitives.ReadInt32BigEndian(data) : BinaryPrimitives.ReadInt32LittleEndian(data),
+ PlyType.UInt32 => bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(data) : BinaryPrimitives.ReadUInt32LittleEndian(data),
+ PlyType.Float32 => bigEndian ? BinaryPrimitives.ReadSingleBigEndian(data) : BinaryPrimitives.ReadSingleLittleEndian(data),
+ _ => bigEndian ? BinaryPrimitives.ReadDoubleBigEndian(data) : BinaryPrimitives.ReadDoubleLittleEndian(data),
+ };
+ }
+
+ private void Fill(int size)
+ {
+ var left = _length - _position;
+ Array.Copy(_buffer, _position, _buffer, 0, left);
+ _position = 0;
+ _length = left + stream.ReadAtLeast(_buffer.AsSpan(left), size - left, throwOnEndOfStream: false);
+ if (_length < size)
+ throw new InvalidDataException("The PLY file is cut short: it ends before all vertices and faces were read.");
+ }
+ }
+
+ private sealed class AsciiReader(Stream stream) : IValueReader
+ {
+ private readonly StreamReader _reader = new(stream, System.Text.Encoding.ASCII, false, 1 << 16);
+ private string _line = "";
+ private int _position;
+
+ public double Read(PlyType type)
+ {
+ while (true)
+ {
+ while (_position < _line.Length && char.IsWhiteSpace(_line[_position]))
+ _position++;
+ if (_position < _line.Length)
+ break;
+ _line = _reader.ReadLine() ?? throw new InvalidDataException("The PLY file is cut short: it ends before all vertices and faces were read.");
+ _position = 0;
+ }
+ var start = _position;
+ while (_position < _line.Length && !char.IsWhiteSpace(_line[_position]))
+ _position++;
+ var token = _line.AsSpan(start, _position - start);
+ return double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out var value)
+ ? value
+ : throw new InvalidDataException($"The PLY file has an invalid number: \"{token}\".");
+ }
+ }
+
+ /// <summary>Writes one binary little-endian mesh (Z up, millimetres).</summary>
+ public static void Write(Model3D model, Stream output, CancellationToken cancellationToken)
+ {
+ var hasNormals = model.Parts.Any(p => p.Normals is not null);
+ var hasUvs = model.Parts.Any(p => p.TexCoords is not null);
+ var hasColors = model.Parts.Any(p => p.Colors is not null || (model.MaterialOf(p) is { } m && m.BaseColor != Vector4.One));
+ foreach (var part in model.Parts.Where(p => hasNormals && p.Normals is null))
+ part.ComputeNormals();
+
+ var header = new StringBuilder();
+ header.Append("ply\nformat binary_little_endian 1.0\ncomment Written by Filee\n");
+ header.Append(CultureInfo.InvariantCulture, $"element vertex {model.VertexCount}\n");
+ header.Append("property float x\nproperty float y\nproperty float z\n");
+ if (hasNormals)
+ header.Append("property float nx\nproperty float ny\nproperty float nz\n");
+ if (hasUvs)
+ header.Append("property float s\nproperty float t\n");
+ if (hasColors)
+ header.Append("property uchar red\nproperty uchar green\nproperty uchar blue\nproperty uchar alpha\n");
+ header.Append(CultureInfo.InvariantCulture, $"element face {model.TriangleCount}\n");
+ header.Append("property list uchar int vertex_indices\nend_header\n");
+
+ using var stream = new BufferedStream(output, 1 << 20);
+ stream.Write(System.Text.Encoding.ASCII.GetBytes(header.ToString()));
+ Span<byte> record = stackalloc byte[36];
+ foreach (var part in model.Parts)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var fallback = MeshMath.LinearToSrgb(model.MaterialOf(part)?.BaseColor ?? Vector4.One);
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var length = 0;
+ Put(record, ref length, MeshMath.ToZUp(part.Position(v)));
+ if (hasNormals)
+ Put(record, ref length, MeshMath.ToZUp(part.Normal(v)));
+ if (hasUvs)
+ {
+ var uv = part.TexCoord(v);
+ BinaryPrimitives.WriteSingleLittleEndian(record[length..], uv.X);
+ BinaryPrimitives.WriteSingleLittleEndian(record[(length + 4)..], uv.Y);
+ length += 8;
+ }
+ if (hasColors)
+ {
+ var c = part.Colors is null ? fallback : part.Color(v);
+ record[length++] = MeshMath.ToByte(c.X);
+ record[length++] = MeshMath.ToByte(c.Y);
+ record[length++] = MeshMath.ToByte(c.Z);
+ record[length++] = MeshMath.ToByte(c.W);
+ }
+ stream.Write(record[..length]);
+ }
+ }
+
+ var offset = 0;
+ Span<byte> face = stackalloc byte[13];
+ face[0] = 3;
+ foreach (var part in model.Parts)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var indices = part.IndexSpan;
+ for (var i = 0; i + 2 < indices.Length; i += 3)
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(face[1..], indices[i] + offset);
+ BinaryPrimitives.WriteInt32LittleEndian(face[5..], indices[i + 1] + offset);
+ BinaryPrimitives.WriteInt32LittleEndian(face[9..], indices[i + 2] + offset);
+ stream.Write(face);
+ }
+ offset += part.VertexCount;
+ }
+
+ static void Put(Span<byte> record, ref int length, Vector3 v)
+ {
+ BinaryPrimitives.WriteSingleLittleEndian(record[length..], v.X);
+ BinaryPrimitives.WriteSingleLittleEndian(record[(length + 4)..], v.Y);
+ BinaryPrimitives.WriteSingleLittleEndian(record[(length + 8)..], v.Z);
+ length += 12;
+ }
+ }
+}
diff --git a/src/Filee.Engines/Models3D/StlFormat.cs b/src/Filee.Engines/Models3D/StlFormat.cs
new file mode 100644
index 00000000..38c9b0cc
--- /dev/null
+++ b/src/Filee.Engines/Models3D/StlFormat.cs
@@ -0,0 +1,219 @@
+// STL (stereolithography): binary and ASCII. Triangles only, no units (read as millimetres), Z up, no colours,
+// UVs or materials. Binary files are streamed in blocks and vertices merged by position, so a 1,000,000-triangle
+// file needs about 40 MB.
+
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Numerics;
+using System.Text;
+
+namespace Filee.Engines.Models3D;
+
+internal static class StlFormat
+{
+ private const int HeaderSize = 84;
+ private const int RecordSize = 50;
+
+ /// <summary>Bytes of an ASCII STL: printable ASCII, tab, CR and LF.</summary>
+ private static readonly System.Buffers.SearchValues<byte> TextBytes =
+ System.Buffers.SearchValues.Create([9, 10, 13, .. Enumerable.Range(32, 95).Select(b => (byte)b)]);
+
+ public static Model3D Read(string path, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan);
+ var length = stream.Length;
+ Span<byte> header = stackalloc byte[HeaderSize];
+ var headerRead = stream.ReadAtLeast(header, HeaderSize, throwOnEndOfStream: false);
+ var count = headerRead == HeaderSize ? BinaryPrimitives.ReadUInt32LittleEndian(header[80..]) : 0;
+ var exactBinary = headerRead == HeaderSize && HeaderSize + (long)RecordSize * count == length;
+ var startsWithSolid = Encoding.ASCII.GetString(header[..headerRead]).TrimStart().StartsWith("solid", StringComparison.OrdinalIgnoreCase);
+ var fitsBinary = headerRead == HeaderSize && count > 0 && HeaderSize + (long)RecordSize * count <= length;
+ if (startsWithSolid && fitsBinary && !exactBinary)
+ {
+ // Some exporters start a binary header with "solid" and add bytes at the end: text has no control bytes.
+ Span<byte> sample = stackalloc byte[512];
+ var read = stream.ReadAtLeast(sample, sample.Length, throwOnEndOfStream: false);
+ startsWithSolid = !sample[..read].ContainsAnyExcept(TextBytes);
+ stream.Position = HeaderSize;
+ }
+
+ Model3D model;
+ if (exactBinary || (!startsWithSolid && fitsBinary))
+ {
+ model = ReadBinary(stream, (int)Math.Min(count, int.MaxValue / 3), progress, cancellationToken);
+ }
+ else if (startsWithSolid)
+ {
+ stream.Position = 0;
+ model = ReadAscii(stream, progress, cancellationToken);
+ }
+ else
+ {
+ throw new InvalidDataException(headerRead < HeaderSize
+ ? "The file is too short to be an STL file."
+ : $"The binary STL file is cut short: it announces {count:N0} triangles but holds only {(length - HeaderSize) / RecordSize:N0}.");
+ }
+
+ foreach (var part in model.Parts)
+ part.Transform(MeshMath.ZUpToYUp);
+ return model;
+ }
+
+ private static Model3D ReadBinary(Stream stream, int count, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var part = new MeshPart { Name = "STL" };
+ part.Indices.Capacity = count * 3;
+ var merger = new PositionMerger(part, count / 2);
+ var buffer = new byte[RecordSize * 4096];
+ var done = 0;
+ while (done < count)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var batch = Math.Min(4096, count - done);
+ stream.ReadExactly(buffer, 0, batch * RecordSize);
+ for (var r = 0; r < batch; r++)
+ {
+ var record = buffer.AsSpan(r * RecordSize, RecordSize);
+ var a = ReadVector(record[12..]);
+ var b = ReadVector(record[24..]);
+ var c = ReadVector(record[36..]);
+ if (!Finite(a) || !Finite(b) || !Finite(c))
+ continue;
+ part.AddTriangle(merger.Add(a), merger.Add(b), merger.Add(c));
+ }
+ done += batch;
+ progress?.Report((double)done / count);
+ }
+ return new Model3D { Parts = { part } };
+
+ static Vector3 ReadVector(ReadOnlySpan<byte> data) => new(
+ BinaryPrimitives.ReadSingleLittleEndian(data),
+ BinaryPrimitives.ReadSingleLittleEndian(data[4..]),
+ BinaryPrimitives.ReadSingleLittleEndian(data[8..]));
+ }
+
+ private static Model3D ReadAscii(Stream stream, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var model = new Model3D();
+ MeshPart? part = null;
+ PositionMerger? merger = null;
+ Span<int> corners = stackalloc int[3];
+ var cornerCount = 0;
+ var length = Math.Max(1, stream.Length);
+ using var reader = new StreamReader(stream, Encoding.ASCII, detectEncodingFromByteOrderMarks: true, 1 << 16);
+ var lineNumber = 0;
+ while (reader.ReadLine() is { } line)
+ {
+ lineNumber++;
+ var text = line.AsSpan().Trim();
+ if (text.StartsWith("vertex", StringComparison.OrdinalIgnoreCase))
+ {
+ if (part is null)
+ {
+ part = new MeshPart { Name = "STL" };
+ merger = new PositionMerger(part, 1024);
+ model.Parts.Add(part);
+ }
+ var v = ParseVector(text[6..], lineNumber);
+ if (cornerCount < 3)
+ corners[cornerCount++] = merger!.Add(v);
+ }
+ else if (text.StartsWith("endloop", StringComparison.OrdinalIgnoreCase))
+ {
+ if (cornerCount == 3)
+ part!.AddTriangle(corners[0], corners[1], corners[2]);
+ cornerCount = 0;
+ }
+ else if (text.StartsWith("solid", StringComparison.OrdinalIgnoreCase))
+ {
+ part = new MeshPart { Name = text[5..].Trim().ToString() is { Length: > 0 } name ? name : "STL" };
+ merger = new PositionMerger(part, 1024);
+ model.Parts.Add(part);
+ }
+ if ((lineNumber & 0xFFFF) == 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report((double)stream.Position / length);
+ }
+ }
+ return model;
+ }
+
+ private static Vector3 ParseVector(ReadOnlySpan<char> text, int lineNumber)
+ {
+ Span<float> values = stackalloc float[3];
+ var found = 0;
+ foreach (var range in text.Split(' '))
+ {
+ var token = text[range].Trim();
+ if (token.IsEmpty)
+ continue;
+ if (found == 3 || !float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out values[found++]))
+ throw new InvalidDataException($"Line {lineNumber} of the STL file has an invalid vertex.");
+ }
+ if (found != 3)
+ throw new InvalidDataException($"Line {lineNumber} of the STL file has an invalid vertex.");
+ return new Vector3(values[0], values[1], values[2]);
+ }
+
+ private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z);
+
+ /// <summary>Writes a binary STL (Z up, millimetres) with every part in one solid and facet normals from the winding.</summary>
+ public static void Write(Model3D model, Stream output, CancellationToken cancellationToken)
+ {
+ using var stream = new BufferedStream(output, 1 << 20);
+ var header = new byte[HeaderSize];
+ Encoding.ASCII.GetBytes("Binary STL written by Filee").CopyTo(header, 0);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(80), (uint)model.TriangleCount);
+ stream.Write(header);
+
+ Span<byte> record = stackalloc byte[RecordSize];
+ foreach (var part in model.Parts)
+ {
+ var indices = part.IndexSpan;
+ for (var t = 0; t + 2 < indices.Length; t += 3)
+ {
+ if ((t & 0xFFFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ var a = MeshMath.ToZUp(part.Position(indices[t]));
+ var b = MeshMath.ToZUp(part.Position(indices[t + 1]));
+ var c = MeshMath.ToZUp(part.Position(indices[t + 2]));
+ var n = Vector3.Cross(b - a, c - a);
+ n = n.LengthSquared() > 0 ? Vector3.Normalize(n) : Vector3.Zero;
+ if (!float.IsFinite(n.X))
+ n = Vector3.Zero;
+ WriteVector(record, n);
+ WriteVector(record[12..], a);
+ WriteVector(record[24..], b);
+ WriteVector(record[36..], c);
+ record[48] = 0;
+ record[49] = 0;
+ stream.Write(record);
+ }
+ }
+
+ static void WriteVector(Span<byte> data, Vector3 v)
+ {
+ BinaryPrimitives.WriteSingleLittleEndian(data, v.X);
+ BinaryPrimitives.WriteSingleLittleEndian(data[4..], v.Y);
+ BinaryPrimitives.WriteSingleLittleEndian(data[8..], v.Z);
+ }
+ }
+}
+
+/// <summary>Adds positions to a part, reusing the vertex of an identical position.</summary>
+internal sealed class PositionMerger(MeshPart part, int capacity)
+{
+ private readonly Dictionary<Vector3, int> _seen = new(Math.Clamp(capacity, 16, 1 << 24));
+
+ public int Add(Vector3 position)
+ {
+ // -0 and 0 are the same point.
+ position += Vector3.Zero;
+ if (_seen.TryGetValue(position, out var index))
+ return index;
+ index = part.AddVertex(position);
+ _seen.Add(position, index);
+ return index;
+ }
+}
diff --git a/src/Filee.Engines/Models3D/ThreeMfFormat.cs b/src/Filee.Engines/Models3D/ThreeMfFormat.cs
new file mode 100644
index 00000000..56bed9ff
--- /dev/null
+++ b/src/Filee.Engines/Models3D/ThreeMfFormat.cs
@@ -0,0 +1,508 @@
+// 3MF (3D Manufacturing Format): a ZIP package with XML models (core specification 1.3). Z up, unit from the model's
+// "unit" attribute. Read: objects with meshes and components (also in other model files of the package, as slicers
+// such as Bambu Studio write them), build items with transforms, base materials (one part per material) and the
+// materials extension's colour groups (per-corner colours). Objects of type "support" and "other" are skipped.
+// Written: millimetres, one object per part with its vertices welded by position (slicers need closed meshes),
+// base materials from the material colours and colour groups from the vertex colours. UVs, normals and textures
+// are not written.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Numerics;
+using System.Xml;
+
+namespace Filee.Engines.Models3D;
+
+internal static class ThreeMfFormat
+{
+ private const string CoreNs = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02";
+ private const string MaterialNs = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02";
+ private const string ProductionNs = "http://schemas.microsoft.com/3dmanufacturing/production/2015/06";
+ private const string ModelRelationship = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
+ private const int MaxDepth = 32;
+
+ /// <summary>Millimetres per 3MF unit.</summary>
+ private static double UnitScale(string? unit) => unit switch
+ {
+ null or "" or "millimeter" => 1,
+ "micron" => 0.001,
+ "centimeter" => 10,
+ "inch" => 25.4,
+ "foot" => 304.8,
+ "meter" => 1000,
+ _ => throw new InvalidDataException($"The 3MF model has an unknown unit \"{unit}\"."),
+ };
+
+ private sealed class ModelFile
+ {
+ public double Scale = 1;
+ public Dictionary<int, ObjectDef> Objects { get; } = [];
+ public Dictionary<int, List<(string Name, Vector4 Color)>> BaseMaterials { get; } = [];
+ public Dictionary<int, List<Vector4>> ColorGroups { get; } = [];
+ public List<(int ObjectId, string? Path, Matrix4x4 Transform)> Build { get; } = [];
+ }
+
+ private sealed class ObjectDef
+ {
+ public string Name = "";
+ public string Type = "model";
+ public int? Pid;
+ public int? PIndex;
+ public List<float> Vertices { get; } = [];
+ /// <summary>v1, v2, v3, pid, p1, p2, p3 per triangle (-1 when not given).</summary>
+ public List<int> Triangles { get; } = [];
+ public List<(int ObjectId, string? Path, Matrix4x4 Transform)> Components { get; } = [];
+ }
+
+ public static Model3D Read(string path, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ ZipArchive zip;
+ try
+ {
+ zip = ZipFile.OpenRead(path);
+ }
+ catch (InvalidDataException ex)
+ {
+ throw new InvalidDataException("The file is not a 3MF package (it is not a valid ZIP file).", ex);
+ }
+ using (zip)
+ {
+ var rootPath = FindRootModel(zip);
+ var files = new Dictionary<string, ModelFile>(StringComparer.OrdinalIgnoreCase);
+ var root = Load(zip, rootPath, files, cancellationToken);
+ progress?.Report(0.6);
+
+ var model = new Model3D();
+ var materials = new Dictionary<(ModelFile, int, int), int>();
+ foreach (var (objectId, itemPath, transform) in root.Build)
+ {
+ var file = itemPath is null ? root : Load(zip, itemPath, files, cancellationToken);
+ Instantiate(model, zip, files, file, objectId, transform, materials, 0, cancellationToken);
+ }
+ var toYUp = Matrix4x4.CreateScale((float)root.Scale) * MeshMath.ZUpToYUp;
+ foreach (var part in model.Parts)
+ part.Transform(toYUp);
+ return model;
+ }
+ }
+
+ private static string FindRootModel(ZipArchive zip)
+ {
+ if (zip.GetEntry("_rels/.rels") is { } rels)
+ {
+ using var stream = rels.Open();
+ using var reader = XmlReader.Create(stream, Settings);
+ while (reader.Read())
+ {
+ if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Relationship"
+ && reader.GetAttribute("Type") == ModelRelationship && reader.GetAttribute("Target") is { } target)
+ return target.TrimStart('/');
+ }
+ }
+ return zip.Entries.FirstOrDefault(e => e.FullName.EndsWith(".model", StringComparison.OrdinalIgnoreCase))?.FullName
+ ?? throw new InvalidDataException("The 3MF package has no 3D model part.");
+ }
+
+ private static readonly XmlReaderSettings Settings = new()
+ {
+ DtdProcessing = DtdProcessing.Prohibit,
+ XmlResolver = null,
+ IgnoreComments = true,
+ IgnoreWhitespace = true,
+ };
+
+ private static ModelFile Load(ZipArchive zip, string path, Dictionary<string, ModelFile> files, CancellationToken cancellationToken)
+ {
+ path = path.TrimStart('/');
+ if (files.TryGetValue(path, out var loaded))
+ return loaded;
+ var entry = zip.GetEntry(path) ?? throw new InvalidDataException($"The 3MF package has no part \"{path}\".");
+ var file = new ModelFile();
+ files[path] = file;
+ using var stream = entry.Open();
+ try
+ {
+ Parse(stream, file, cancellationToken);
+ }
+ catch (XmlException ex)
+ {
+ throw new InvalidDataException($"The 3MF model \"{path}\" is not valid XML: {ex.Message}", ex);
+ }
+ return file;
+ }
+
+ private static void Parse(Stream stream, ModelFile file, CancellationToken cancellationToken)
+ {
+ using var reader = XmlReader.Create(stream, Settings);
+ ObjectDef? current = null;
+ List<(string, Vector4)>? baseMaterials = null;
+ List<Vector4>? colors = null;
+ var count = 0;
+ while (reader.Read())
+ {
+ if (reader.NodeType == XmlNodeType.EndElement)
+ {
+ switch (reader.LocalName)
+ {
+ case "object":
+ current = null;
+ break;
+ case "basematerials":
+ baseMaterials = null;
+ break;
+ case "colorgroup":
+ colors = null;
+ break;
+ }
+ continue;
+ }
+ if (reader.NodeType != XmlNodeType.Element)
+ continue;
+ if ((++count & 0xFFFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var ns = reader.NamespaceURI;
+ switch (reader.LocalName)
+ {
+ case "model":
+ file.Scale = UnitScale(reader.GetAttribute("unit"));
+ break;
+ case "vertex" when current is not null:
+ current.Vertices.Add(Float(reader, "x"));
+ current.Vertices.Add(Float(reader, "y"));
+ current.Vertices.Add(Float(reader, "z"));
+ break;
+ case "triangle" when current is not null:
+ current.Triangles.Add(Int(reader, "v1"));
+ current.Triangles.Add(Int(reader, "v2"));
+ current.Triangles.Add(Int(reader, "v3"));
+ current.Triangles.Add(OptionalInt(reader, "pid") ?? -1);
+ current.Triangles.Add(OptionalInt(reader, "p1") ?? -1);
+ current.Triangles.Add(OptionalInt(reader, "p2") ?? -1);
+ current.Triangles.Add(OptionalInt(reader, "p3") ?? -1);
+ break;
+ case "object":
+ current = new ObjectDef
+ {
+ Name = reader.GetAttribute("name") ?? "",
+ Type = reader.GetAttribute("type") ?? "model",
+ Pid = OptionalInt(reader, "pid"),
+ PIndex = OptionalInt(reader, "pindex"),
+ };
+ file.Objects[Int(reader, "id")] = current;
+ if (reader.IsEmptyElement)
+ current = null;
+ break;
+ case "component" when current is not null:
+ current.Components.Add((Int(reader, "objectid"), reader.GetAttribute("path", ProductionNs), Transform(reader)));
+ break;
+ case "item":
+ file.Build.Add((Int(reader, "objectid"), reader.GetAttribute("path", ProductionNs), Transform(reader)));
+ break;
+ case "basematerials":
+ baseMaterials = [];
+ file.BaseMaterials[Int(reader, "id")] = baseMaterials;
+ break;
+ case "base" when baseMaterials is not null:
+ baseMaterials.Add((reader.GetAttribute("name") ?? "", MeshMath.ParseHex(reader.GetAttribute("displaycolor")) ?? Vector4.One));
+ break;
+ case "colorgroup" when ns == MaterialNs || ns.Length == 0:
+ colors = [];
+ file.ColorGroups[Int(reader, "id")] = colors;
+ break;
+ case "color" when colors is not null:
+ colors.Add(MeshMath.ParseHex(reader.GetAttribute("color")) ?? Vector4.One);
+ break;
+ }
+ }
+ }
+
+ private static void Instantiate(Model3D model, ZipArchive zip, Dictionary<string, ModelFile> files, ModelFile file, int objectId,
+ Matrix4x4 transform, Dictionary<(ModelFile, int, int), int> materials, int depth, CancellationToken cancellationToken)
+ {
+ if (depth > MaxDepth)
+ throw new InvalidDataException("The 3MF model's components are nested too deeply (or refer to themselves).");
+ if (!file.Objects.TryGetValue(objectId, out var definition))
+ throw new InvalidDataException($"The 3MF model refers to object {objectId}, which does not exist.");
+ if (definition.Type is "support" or "other")
+ return;
+
+ if (definition.Triangles.Count > 0)
+ AddMesh(model, file, definition, transform, materials, cancellationToken);
+ foreach (var (childId, childPath, childTransform) in definition.Components)
+ {
+ var childFile = childPath is null ? file : Load(zip, childPath, files, cancellationToken);
+ Instantiate(model, zip, files, childFile, childId, childTransform * transform, materials, depth + 1, cancellationToken);
+ }
+ }
+
+ private static void AddMesh(Model3D model, ModelFile file, ObjectDef definition, Matrix4x4 transform,
+ Dictionary<(ModelFile, int, int), int> materials, CancellationToken cancellationToken)
+ {
+ var vertexCount = definition.Vertices.Count / 3;
+ // One part per base material; per-corner colours split vertices by colour.
+ var groups = new Dictionary<int, (MeshPart Part, Dictionary<(int, int), int> Map)>();
+ var triangles = definition.Triangles;
+ Span<int> corners = stackalloc int[3];
+ for (var t = 0; t + 6 < triangles.Count; t += 7)
+ {
+ if ((t & 0xFFFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ var pid = triangles[t + 3] >= 0 ? triangles[t + 3] : definition.Pid ?? -1;
+ var p1 = triangles[t + 4] >= 0 ? triangles[t + 4] : definition.PIndex ?? 0;
+ var key = -1;
+ List<Vector4>? colorGroup = null;
+ if (file.BaseMaterials.TryGetValue(pid, out var bases) && p1 < bases.Count)
+ key = MaterialIndex(model, file, pid, p1, bases[p1], materials);
+ else if (file.ColorGroups.TryGetValue(pid, out colorGroup))
+ key = -2;
+
+ if (!groups.TryGetValue(key, out var group))
+ {
+ var name = definition.Name.Length > 0 ? definition.Name : "Object";
+ var part = new MeshPart { Name = name, Material = key >= 0 ? key : -1 };
+ if (key == -2)
+ part.Colors = [];
+ group = (part, []);
+ groups[key] = group;
+ model.Parts.Add(part);
+ }
+
+ for (var k = 0; k < 3; k++)
+ {
+ var v = triangles[t + k];
+ if ((uint)v >= (uint)vertexCount)
+ throw new InvalidDataException($"A triangle of 3MF object \"{definition.Name}\" refers to vertex {v}, but it has only {vertexCount}.");
+ var colorIndex = -1;
+ if (colorGroup is not null)
+ {
+ var p = k == 0 ? p1 : triangles[t + 4 + k] >= 0 ? triangles[t + 4 + k] : p1;
+ colorIndex = p < colorGroup.Count ? p : -1;
+ }
+ if (!group.Map.TryGetValue((v, colorIndex), out var index))
+ {
+ var position = Vector3.Transform(new Vector3(definition.Vertices[v * 3], definition.Vertices[v * 3 + 1], definition.Vertices[v * 3 + 2]), transform);
+ index = group.Part.AddVertex(position, color: colorIndex >= 0 ? colorGroup![colorIndex] : Vector4.One);
+ group.Map[(v, colorIndex)] = index;
+ }
+ corners[k] = index;
+ }
+ if (transform.GetDeterminant() < 0)
+ group.Part.AddTriangle(corners[0], corners[2], corners[1]);
+ else
+ group.Part.AddTriangle(corners[0], corners[1], corners[2]);
+ }
+ }
+
+ private static int MaterialIndex(Model3D model, ModelFile file, int pid, int index, (string Name, Vector4 Color) material,
+ Dictionary<(ModelFile, int, int), int> materials)
+ {
+ if (materials.TryGetValue((file, pid, index), out var existing))
+ return existing;
+ existing = model.Materials.Count;
+ model.Materials.Add(new Material3D
+ {
+ Name = material.Name.Length > 0 ? material.Name : $"Material {existing + 1}",
+ BaseColor = MeshMath.SrgbToLinear(material.Color),
+ });
+ materials[(file, pid, index)] = existing;
+ return existing;
+ }
+
+ private static Matrix4x4 Transform(XmlReader reader)
+ {
+ var text = reader.GetAttribute("transform");
+ if (string.IsNullOrWhiteSpace(text))
+ return Matrix4x4.Identity;
+ var values = text.Split([' ', '\t', '\n', '\r'], StringSplitOptions.RemoveEmptyEntries)
+ .Select(v => float.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out var f) ? f : float.NaN)
+ .ToArray();
+ if (values.Length != 12 || values.Any(v => !float.IsFinite(v)))
+ throw new InvalidDataException($"The 3MF model has an invalid transform \"{text}\".");
+ return new Matrix4x4(
+ values[0], values[1], values[2], 0,
+ values[3], values[4], values[5], 0,
+ values[6], values[7], values[8], 0,
+ values[9], values[10], values[11], 1);
+ }
+
+ private static float Float(XmlReader reader, string name) =>
+ float.TryParse(reader.GetAttribute(name), NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && float.IsFinite(value)
+ ? value
+ : throw new InvalidDataException($"The 3MF model has a {reader.LocalName} with an invalid \"{name}\".");
+
+ private static int Int(XmlReader reader, string name) =>
+ OptionalInt(reader, name) ?? throw new InvalidDataException($"The 3MF model has a {reader.LocalName} without a valid \"{name}\".");
+
+ private static int? OptionalInt(XmlReader reader, string name) =>
+ int.TryParse(reader.GetAttribute(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null;
+
+ /// <summary>Writes a 3MF package (millimetres, Z up) with one object per part.</summary>
+ public static void Write(Model3D model, Stream output, CancellationToken cancellationToken)
+ {
+ using var zip = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true);
+ WriteText(zip, "[Content_Types].xml", """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>
+ """);
+ WriteText(zip, "_rels/.rels", $"""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Target="/3D/3dmodel.model" Id="rel0" Type="{ModelRelationship}"/></Relationships>
+ """);
+
+ var entry = zip.CreateEntry("3D/3dmodel.model", CompressionLevel.Optimal);
+ using var stream = entry.Open();
+ using var writer = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true, Encoding = new System.Text.UTF8Encoding(false) });
+ writer.WriteStartDocument();
+ writer.WriteStartElement("model", CoreNs);
+ writer.WriteAttributeString("unit", "millimeter");
+ writer.WriteAttributeString("xml", "lang", null, "en-US");
+ var anyColors = model.Parts.Any(p => p.Colors is not null);
+ if (anyColors)
+ writer.WriteAttributeString("xmlns", "m", null, MaterialNs);
+ writer.WriteStartElement("metadata", CoreNs);
+ writer.WriteAttributeString("name", "Application");
+ writer.WriteString("Filee");
+ writer.WriteEndElement();
+
+ writer.WriteStartElement("resources", CoreNs);
+ var nextId = 1;
+ var baseMaterialsId = 0;
+ if (model.Materials.Count > 0)
+ {
+ baseMaterialsId = nextId++;
+ writer.WriteStartElement("basematerials", CoreNs);
+ writer.WriteAttributeString("id", Text(baseMaterialsId));
+ for (var m = 0; m < model.Materials.Count; m++)
+ {
+ writer.WriteStartElement("base", CoreNs);
+ writer.WriteAttributeString("name", model.Materials[m].Name.Length > 0 ? model.Materials[m].Name : $"Material {m + 1}");
+ writer.WriteAttributeString("displaycolor", MeshMath.ToHex(MeshMath.LinearToSrgb(model.Materials[m].BaseColor)));
+ writer.WriteEndElement();
+ }
+ writer.WriteEndElement();
+ }
+
+ var objectIds = new List<int>();
+ foreach (var part in model.Parts)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ // Welded by position: split vertices (for normals or UVs) would leave the mesh open.
+ var weld = new Dictionary<Vector3, int>();
+ var vertexOf = new int[part.VertexCount];
+ var positions = new List<Vector3>();
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var p = MeshMath.ToZUp(part.Position(v)) + Vector3.Zero;
+ if (!weld.TryGetValue(p, out var index))
+ {
+ index = positions.Count;
+ positions.Add(p);
+ weld[p] = index;
+ }
+ vertexOf[v] = index;
+ }
+
+ var colorGroupId = 0;
+ int[]? colorOf = null;
+ if (part.Colors is not null)
+ {
+ colorGroupId = nextId++;
+ var unique = new Dictionary<uint, int>();
+ colorOf = new int[part.VertexCount];
+ writer.WriteStartElement("m", "colorgroup", MaterialNs);
+ writer.WriteAttributeString("id", Text(colorGroupId));
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var c = part.Color(v);
+ var key = (uint)MeshMath.ToByte(c.X) << 24 | (uint)MeshMath.ToByte(c.Y) << 16 | (uint)MeshMath.ToByte(c.Z) << 8 | MeshMath.ToByte(c.W);
+ if (!unique.TryGetValue(key, out var index))
+ {
+ index = unique.Count;
+ unique[key] = index;
+ writer.WriteStartElement("m", "color", MaterialNs);
+ writer.WriteAttributeString("color", MeshMath.ToHex(c));
+ writer.WriteEndElement();
+ }
+ colorOf[v] = index;
+ }
+ writer.WriteEndElement();
+ }
+
+ var objectId = nextId++;
+ objectIds.Add(objectId);
+ writer.WriteStartElement("object", CoreNs);
+ writer.WriteAttributeString("id", Text(objectId));
+ writer.WriteAttributeString("type", "model");
+ if (part.Name.Length > 0)
+ writer.WriteAttributeString("name", part.Name);
+ if (colorGroupId > 0)
+ {
+ writer.WriteAttributeString("pid", Text(colorGroupId));
+ writer.WriteAttributeString("pindex", "0");
+ }
+ else if (part.Material >= 0 && part.Material < model.Materials.Count)
+ {
+ writer.WriteAttributeString("pid", Text(baseMaterialsId));
+ writer.WriteAttributeString("pindex", Text(part.Material));
+ }
+ writer.WriteStartElement("mesh", CoreNs);
+ writer.WriteStartElement("vertices", CoreNs);
+ foreach (var p in positions)
+ {
+ writer.WriteStartElement("vertex", CoreNs);
+ writer.WriteAttributeString("x", Text(p.X));
+ writer.WriteAttributeString("y", Text(p.Y));
+ writer.WriteAttributeString("z", Text(p.Z));
+ writer.WriteEndElement();
+ }
+ writer.WriteEndElement();
+ writer.WriteStartElement("triangles", CoreNs);
+ var indices = part.IndexSpan;
+ for (var i = 0; i + 2 < indices.Length; i += 3)
+ {
+ int a = vertexOf[indices[i]], b = vertexOf[indices[i + 1]], c = vertexOf[indices[i + 2]];
+ if (a == b || b == c || a == c)
+ continue; // collapsed by welding
+ writer.WriteStartElement("triangle", CoreNs);
+ writer.WriteAttributeString("v1", Text(a));
+ writer.WriteAttributeString("v2", Text(b));
+ writer.WriteAttributeString("v3", Text(c));
+ if (colorOf is not null)
+ {
+ writer.WriteAttributeString("pid", Text(colorGroupId));
+ writer.WriteAttributeString("p1", Text(colorOf[indices[i]]));
+ writer.WriteAttributeString("p2", Text(colorOf[indices[i + 1]]));
+ writer.WriteAttributeString("p3", Text(colorOf[indices[i + 2]]));
+ }
+ writer.WriteEndElement();
+ }
+ writer.WriteEndElement();
+ writer.WriteEndElement();
+ writer.WriteEndElement();
+ }
+ writer.WriteEndElement();
+
+ writer.WriteStartElement("build", CoreNs);
+ foreach (var id in objectIds)
+ {
+ writer.WriteStartElement("item", CoreNs);
+ writer.WriteAttributeString("objectid", Text(id));
+ writer.WriteEndElement();
+ }
+ writer.WriteEndElement();
+ writer.WriteEndElement();
+ writer.WriteEndDocument();
+ }
+
+ private static string Text(int value) => value.ToString(CultureInfo.InvariantCulture);
+
+ private static string Text(float value) => (float.IsFinite(value) ? value : 0).ToString(CultureInfo.InvariantCulture);
+
+ private static void WriteText(ZipArchive zip, string name, string text)
+ {
+ var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
+ using var writer = new StreamWriter(entry.Open(), new System.Text.UTF8Encoding(false));
+ writer.Write(text);
+ }
+}
diff --git a/src/Filee.Engines/Models3D/Triangulator.cs b/src/Filee.Engines/Models3D/Triangulator.cs
new file mode 100644
index 00000000..3442dd69
--- /dev/null
+++ b/src/Filee.Engines/Models3D/Triangulator.cs
@@ -0,0 +1,98 @@
+// Splits a polygon (OBJ and PLY faces with more than three corners) into triangles by ear clipping in the plane of
+// the polygon, so concave faces come out right; a fan is the fallback for faces that are not simple polygons.
+
+using System.Numerics;
+
+namespace Filee.Engines.Models3D;
+
+internal static class Triangulator
+{
+ /// <summary>Adds the triangles of the polygon <paramref name="corners"/> (vertex indices of <paramref name="part"/>).</summary>
+ public static void AddPolygon(MeshPart part, ReadOnlySpan<int> corners)
+ {
+ switch (corners.Length)
+ {
+ case < 3:
+ return;
+ case 3:
+ part.AddTriangle(corners[0], corners[1], corners[2]);
+ return;
+ }
+ if (corners.Length > 64 || !EarClip(part, corners))
+ {
+ for (var i = 1; i + 1 < corners.Length; i++)
+ part.AddTriangle(corners[0], corners[i], corners[i + 1]);
+ }
+ }
+
+ private static bool EarClip(MeshPart part, ReadOnlySpan<int> corners)
+ {
+ var n = corners.Length;
+ // Newell's normal gives the polygon's plane and winding even for concave polygons.
+ var normal = Vector3.Zero;
+ for (var i = 0; i < n; i++)
+ {
+ var a = part.Position(corners[i]);
+ var b = part.Position(corners[(i + 1) % n]);
+ normal += new Vector3((a.Y - b.Y) * (a.Z + b.Z), (a.Z - b.Z) * (a.X + b.X), (a.X - b.X) * (a.Y + b.Y));
+ }
+ if (normal.LengthSquared() == 0 || !float.IsFinite(normal.X))
+ return false;
+
+ // Project onto the plane: drop the dominant axis, keeping the polygon counter-clockwise.
+ var abs = Vector3.Abs(normal);
+ Span<Vector2> points = stackalloc Vector2[n];
+ for (var i = 0; i < n; i++)
+ {
+ var p = part.Position(corners[i]);
+ points[i] = abs.X >= abs.Y && abs.X >= abs.Z ? (normal.X >= 0 ? new Vector2(p.Y, p.Z) : new Vector2(p.Z, p.Y))
+ : abs.Y >= abs.Z ? (normal.Y >= 0 ? new Vector2(p.Z, p.X) : new Vector2(p.X, p.Z))
+ : (normal.Z >= 0 ? new Vector2(p.X, p.Y) : new Vector2(p.Y, p.X));
+ }
+
+ Span<int> remaining = stackalloc int[n];
+ for (var i = 0; i < n; i++)
+ remaining[i] = i;
+ var count = n;
+ var guard = n * n;
+ var start = part.Indices.Count;
+ while (count > 3 && guard-- > 0)
+ {
+ var clipped = false;
+ for (var i = 0; i < count; i++)
+ {
+ var prev = remaining[(i + count - 1) % count];
+ var cur = remaining[i];
+ var next = remaining[(i + 1) % count];
+ if (Cross(points[prev], points[cur], points[next]) <= 0)
+ continue; // reflex or degenerate corner
+ var inside = false;
+ for (var j = 0; j < count && !inside; j++)
+ {
+ var k = remaining[j];
+ if (k != prev && k != cur && k != next && InTriangle(points[k], points[prev], points[cur], points[next]))
+ inside = true;
+ }
+ if (inside)
+ continue;
+ part.AddTriangle(corners[prev], corners[cur], corners[next]);
+ remaining[(i + 1)..count].CopyTo(remaining[i..]);
+ count--;
+ clipped = true;
+ break;
+ }
+ if (!clipped)
+ {
+ part.Indices.RemoveRange(start, part.Indices.Count - start);
+ return false;
+ }
+ }
+ part.AddTriangle(corners[remaining[0]], corners[remaining[1]], corners[remaining[2]]);
+ return true;
+ }
+
+ private static float Cross(Vector2 a, Vector2 b, Vector2 c) => (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X);
+
+ private static bool InTriangle(Vector2 p, Vector2 a, Vector2 b, Vector2 c) =>
+ Cross(a, b, p) >= 0 && Cross(b, c, p) >= 0 && Cross(c, a, p) >= 0;
+}
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index cf18bdab..6080d851 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -60,7 +60,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
}
@@ -112,7 +112,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
var ids = store.Profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));
Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));
@@ -127,7 +127,7 @@ public class UserDataStoreTests
{
// As written by 1.0.x with schema 5: no catalog presets, donuts or extensions.
var presets = BuiltInData.CreatePresets().Where(p => BuiltInData.CatalogPresets().All(c => c.Id != p.Id)).ToList();
- var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).ToHashSet();
+ var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).Append("models").ToHashSet();
var profiles = BuiltInData.CreateProfiles().Where(p => !catalogIds.Contains(p.Id)).ToList();
profiles.Single(p => p.Id == "images").Extensions = ["png", "jpg"];
profiles.Single(p => p.Id == "pdf").PresetIds.Remove("to-docx");
@@ -139,7 +139,8 @@ public class UserDataStoreTests
var ids = profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("text") + 1, ids.IndexOf("ebooks"));
- Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("fonts"));
+ Assert.Equal(ids.IndexOf("fonts") + 1, ids.IndexOf("models"));
+ Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("models"));
Assert.Contains("cr2", profiles.Single(p => p.Id == "images").Extensions);
Assert.DoesNotContain("mp3", profiles.Single(p => p.Id == "audio").Extensions);
Assert.Contains("flac", profiles.Single(p => p.Id == "audio").Extensions);
@@ -210,13 +211,44 @@ public class UserDataStoreTests
Assert.False(SettingsMigrations.ApplyToLibrary(9, presets, profiles)); // once only
}
+ [Fact]
+ public void Version_10_libraries_get_3d_model_presets_and_their_donut_after_fonts()
+ {
+ // As written by 1.10.x: no 3D formats.
+ var modelIds = BuiltInData.ModelPresets().Select(p => p.Id).ToHashSet();
+ var presets = BuiltInData.CreatePresets().Where(p => !modelIds.Contains(p.Id)).ToList();
+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "models").ToList();
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(10, presets, profiles));
+
+ Assert.Equal(["to-glb", "to-stl", "to-obj", "to-3mf", "to-ply", "to-gltf"], presets.Where(p => modelIds.Contains(p.Id)).Select(p => p.Id));
+ var ids = profiles.Select(p => p.Id).ToList();
+ Assert.Equal(ids.IndexOf("fonts") + 1, ids.IndexOf("models"));
+ var models = profiles.Single(p => p.Id == "models");
+ Assert.Equal(["glb", "gltf", "stl", "obj", "3mf", "ply"], models.Extensions);
+ Assert.Equal(BuiltInData.ModelProfile().PresetIds, models.PresetIds);
+ Assert.False(SettingsMigrations.ApplyToLibrary(10, presets, profiles)); // once only
+ }
+
+ [Fact]
+ public void The_3d_donut_leaves_out_extensions_a_profile_of_the_user_takes()
+ {
+ var presets = BuiltInData.CreatePresets();
+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "models").ToList();
+ profiles.Insert(0, new ToolbarProfile { Id = "printing", Name = "Printing", Extensions = ["stl", "3mf"] });
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(10, presets, profiles));
+
+ Assert.Equal(["glb", "gltf", "obj", "ply"], profiles.Single(p => p.Id == "models").Extensions);
+ }
+
[Fact]
public void Catalog_migration_ignores_extensions_checked_on_mixed_profiles()
{
// Schema-5 data where the user already limited a mixed-files donut to MP3 and JPG: those checks must not
// count as "taken" when the catalog donuts and extensions are added.
var presets = BuiltInData.CreatePresets().Where(p => BuiltInData.CatalogPresets().All(c => c.Id != p.Id)).ToList();
- var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).ToHashSet();
+ var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).Append("models").ToHashSet();
var profiles = BuiltInData.CreateProfiles().Where(p => !catalogIds.Contains(p.Id)).ToList();
profiles.Single(p => p.Id == "images").Extensions = ["png"];
profiles.Add(new ToolbarProfile { Id = "music-mix", Name = "Music mix", IsFallback = true, Extensions = ["mp3", "jpg"] });
diff --git a/tests/Filee.Engines.Tests/ModelBuilders.cs b/tests/Filee.Engines.Tests/ModelBuilders.cs
new file mode 100644
index 00000000..7e22b6c7
--- /dev/null
+++ b/tests/Filee.Engines.Tests/ModelBuilders.cs
@@ -0,0 +1,167 @@
+// Generated 3D test meshes (no sample files): a textured cube with face normals and UVs, a sphere with smooth
+// normals and vertex colours, and a flat fan of coloured triangles. All in Filee's model convention: millimetres,
+// Y up, counter-clockwise front faces.
+
+using System.Numerics;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Models3D;
+using SkiaSharp;
+
+namespace Filee.Engines.Tests;
+
+internal static class ModelBuilders
+{
+ public static readonly Vector4 CubeColor = new(0.8f, 0.2f, 0.1f, 1);
+
+ /// <summary>A 20 mm cube from (0, 0, 0) to (20, 20, 20): 24 vertices with face normals and UVs, a textured material.</summary>
+ public static Model3D Cube()
+ {
+ var model = new Model3D();
+ model.Materials.Add(new Material3D { Name = "Brick red", BaseColor = CubeColor, BaseColorTexture = new Texture3D(Checker(), "png", "checker") });
+ var part = new MeshPart { Name = "Cube", Material = 0, Normals = [], TexCoords = [] };
+ var center = new Vector3(10);
+ foreach (var n in new[] { Vector3.UnitX, -Vector3.UnitX, Vector3.UnitY, -Vector3.UnitY, Vector3.UnitZ, -Vector3.UnitZ })
+ {
+ var u = MathF.Abs(n.Y) < 0.9f ? Vector3.Normalize(Vector3.Cross(Vector3.UnitY, n)) : Vector3.Normalize(Vector3.Cross(n, Vector3.UnitX));
+ var v = Vector3.Cross(n, u);
+ var face = center + n * 10;
+ var first = part.AddVertex(face + (-u - v) * 10, n, new Vector2(0, 0));
+ part.AddVertex(face + (u - v) * 10, n, new Vector2(1, 0));
+ part.AddVertex(face + (u + v) * 10, n, new Vector2(1, 1));
+ part.AddVertex(face + (-u + v) * 10, n, new Vector2(0, 1));
+ part.AddTriangle(first, first + 1, first + 2);
+ part.AddTriangle(first, first + 2, first + 3);
+ }
+ model.Parts.Add(part);
+ return model;
+ }
+
+ /// <summary>A sphere of radius 10 mm around the origin with smooth normals and colours from the normal direction.</summary>
+ public static Model3D Sphere(int stacks = 12, int slices = 16)
+ {
+ var part = new MeshPart { Name = "Sphere", Normals = [], Colors = [] };
+ int Add(Vector3 n) => part.AddVertex(n * 10, n, color: SphereColor(n));
+ var top = Add(Vector3.UnitY);
+ var rings = new int[stacks - 1, slices];
+ for (var i = 1; i < stacks; i++)
+ {
+ var phi = MathF.PI * i / stacks;
+ for (var j = 0; j < slices; j++)
+ {
+ var theta = 2 * MathF.PI * j / slices;
+ rings[i - 1, j] = Add(new Vector3(MathF.Sin(phi) * MathF.Cos(theta), MathF.Cos(phi), -MathF.Sin(phi) * MathF.Sin(theta)));
+ }
+ }
+ var bottom = Add(-Vector3.UnitY);
+ for (var j = 0; j < slices; j++)
+ {
+ var next = (j + 1) % slices;
+ part.AddTriangle(top, rings[0, j], rings[0, next]);
+ for (var i = 0; i < stacks - 2; i++)
+ {
+ part.AddTriangle(rings[i, j], rings[i + 1, j], rings[i + 1, next]);
+ part.AddTriangle(rings[i, j], rings[i + 1, next], rings[i, next]);
+ }
+ part.AddTriangle(bottom, rings[stacks - 2, next], rings[stacks - 2, j]);
+ }
+ var model = new Model3D();
+ model.Parts.Add(part);
+ return model;
+ }
+
+ /// <summary>The colour the sphere has where its normal is <paramref name="n"/> (sRGB).</summary>
+ public static Vector4 SphereColor(Vector3 n) => new((n.X + 1) / 2, (n.Y + 1) / 2, (n.Z + 1) / 2, 1);
+
+ /// <summary>Six triangles around a white centre, flat in the XZ plane facing up, with pure colours on the rim.</summary>
+ public static Model3D Fan()
+ {
+ var part = new MeshPart { Name = "Fan", Colors = [] };
+ var center = part.AddVertex(Vector3.Zero, color: Vector4.One);
+ Vector4[] colors = [new(1, 0, 0, 1), new(1, 1, 0, 1), new(0, 1, 0, 1), new(0, 1, 1, 1), new(0, 0, 1, 1), new(1, 0, 1, 1)];
+ for (var k = 0; k < 6; k++)
+ {
+ var angle = MathF.PI / 3 * k;
+ part.AddVertex(new Vector3(MathF.Cos(angle), 0, -MathF.Sin(angle)) * 10, color: colors[k]);
+ }
+ for (var k = 0; k < 6; k++)
+ part.AddTriangle(center, 1 + k, 1 + (k + 1) % 6);
+ var model = new Model3D();
+ model.Parts.Add(part);
+ return model;
+ }
+
+ public static Model3D Make(string kind) => kind switch
+ {
+ "cube" => Cube(),
+ "sphere" => Sphere(),
+ "fan" => Fan(),
+ _ => throw new ArgumentOutOfRangeException(nameof(kind)),
+ };
+
+ /// <summary>A 4 × 4 PNG checkerboard.</summary>
+ public static byte[] Checker()
+ {
+ using var bitmap = new SKBitmap(4, 4);
+ for (var y = 0; y < 4; y++)
+ for (var x = 0; x < 4; x++)
+ bitmap.SetPixel(x, y, (x + y) % 2 == 0 ? new SKColor(250, 240, 230) : new SKColor(40, 60, 200));
+ using var data = bitmap.Encode(SKEncodedImageFormat.Png, 100);
+ return data.ToArray();
+ }
+
+ /// <summary>Writes <paramref name="model"/> as <paramref name="format"/> into <paramref name="folder"/>; returns the main file.</summary>
+ public static string Save(Model3D model, string folder, string name, string format)
+ {
+ var outputs = new List<string>();
+ ModelConverter.Write(model, format, new FolderAllocator(folder, name), new ImageOptions(), outputs, CancellationToken.None);
+ return outputs[0];
+ }
+
+ public static Model3D Load(string path, string format) => ModelConverter.Read(path, format, null, CancellationToken.None);
+
+ /// <summary>Signed volume (positive for a closed mesh with outward faces): changes sign when the winding flips.</summary>
+ public static double SignedVolume(Model3D model)
+ {
+ double volume = 0;
+ foreach (var part in model.Parts)
+ {
+ for (var t = 0; t < part.TriangleCount; t++)
+ {
+ var a = part.Position(part.Indices[t * 3]);
+ var b = part.Position(part.Indices[t * 3 + 1]);
+ var c = part.Position(part.Indices[t * 3 + 2]);
+ volume += Vector3.Dot(a, Vector3.Cross(b, c)) / 6.0;
+ }
+ }
+ return volume;
+ }
+
+ public static double Area(Model3D model)
+ {
+ double area = 0;
+ foreach (var part in model.Parts)
+ {
+ for (var t = 0; t < part.TriangleCount; t++)
+ {
+ var a = part.Position(part.Indices[t * 3]);
+ var b = part.Position(part.Indices[t * 3 + 1]);
+ var c = part.Position(part.Indices[t * 3 + 2]);
+ area += Vector3.Cross(b - a, c - a).Length() / 2;
+ }
+ }
+ return area;
+ }
+
+ /// <summary>Rounds a position to 1/100 mm so positions from different files compare equal.</summary>
+ public static (int, int, int) Key(Vector3 p) => ((int)MathF.Round(p.X * 100), (int)MathF.Round(p.Y * 100), (int)MathF.Round(p.Z * 100));
+
+ public static HashSet<(int, int, int)> Positions(Model3D model) =>
+ [.. model.Parts.SelectMany(p => Enumerable.Range(0, p.VertexCount).Select(v => Key(p.Position(v))))];
+
+ /// <summary>Hands out files named <c>name{suffix}.ext</c> in one folder.</summary>
+ public sealed class FolderAllocator(string folder, string name) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => Path.Combine(folder, $"{name}{suffix}.{extension}");
+ }
+}
diff --git a/tests/Filee.Engines.Tests/ModelTests.cs b/tests/Filee.Engines.Tests/ModelTests.cs
new file mode 100644
index 00000000..9dd89b9d
--- /dev/null
+++ b/tests/Filee.Engines.Tests/ModelTests.cs
@@ -0,0 +1,692 @@
+// 3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other and to pictures. Meshes are generated (ModelBuilders)
+// or written as text / bytes here; every format pair is converted through the job queue and read back.
+
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Numerics;
+using System.Text;
+using System.Text.Json.Nodes;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Models3D;
+using ImageMagick;
+using SharpGLTF.Schema2;
+
+namespace Filee.Engines.Tests;
+
+public class ModelTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly string[] Formats = ModelConverter.Formats;
+ private static readonly string[] WithNormals = ["obj", "ply", "glb", "gltf"];
+ private static readonly string[] WithUvs = ["obj", "ply", "glb", "gltf"];
+ private static readonly string[] WithVertexColors = ["obj", "ply", "3mf", "glb", "gltf"];
+ private static readonly string[] WithMaterials = ["obj", "3mf", "glb", "gltf"];
+ private static readonly string[] WithTextures = ["obj", "glb", "gltf"];
+
+ private async Task<ConversionJob> RunAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job;
+ }
+
+ private async Task<string> FailAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.Equal(JobState.Failed, job.State);
+ return job.Files.Single().ErrorDetail ?? "";
+ }
+
+ public static TheoryData<string, string, string> Pairs()
+ {
+ var data = new TheoryData<string, string, string>();
+ foreach (var kind in new[] { "cube", "sphere", "fan" })
+ foreach (var from in Formats)
+ foreach (var to in Formats.Where(t => t != from))
+ data.Add(kind, from, to);
+ return data;
+ }
+
+ // ───────────────────────── Routes ─────────────────────────
+
+ [Fact]
+ public void Every_pair_and_every_picture_is_one_step_of_the_3d_engine()
+ {
+ var planner = fx.Catalog.CreatePlanner();
+ foreach (var from in Formats)
+ {
+ foreach (var to in Formats.Where(t => t != from).Concat(["png", "jpg", "webp"]))
+ {
+ var route = planner.Plan(from, to);
+ Assert.NotNull(route);
+ Assert.Equal("model3d", Assert.Single(route.Steps).Converter.Id);
+ }
+ }
+ }
+
+ // ───────────────────────── Every format pair ─────────────────────────
+
+ [Theory]
+ [MemberData(nameof(Pairs))]
+ public async Task Converting_keeps_geometry_and_what_both_formats_store(string kind, string from, string to)
+ {
+ var folder = fx.NewFolder();
+ var source = ModelBuilders.Save(ModelBuilders.Make(kind), folder, kind, from);
+ var expected = ModelBuilders.Load(source, from);
+
+ var job = await RunAsync(source, to);
+ var output = job.Outputs.First(o => o.EndsWith("." + to, StringComparison.OrdinalIgnoreCase));
+ var actual = ModelBuilders.Load(output, to);
+
+ Assert.Equal(expected.TriangleCount, actual.TriangleCount);
+ var (expectedMin, expectedMax) = expected.Bounds();
+ var (actualMin, actualMax) = actual.Bounds();
+ AssertClose(expectedMin, actualMin, 1e-3f);
+ AssertClose(expectedMax, actualMax, 1e-3f);
+ Assert.Equal(ModelBuilders.SignedVolume(expected), ModelBuilders.SignedVolume(actual), 0.05);
+ Assert.Equal(ModelBuilders.Area(expected), ModelBuilders.Area(actual), 0.05);
+ Assert.Equal(ModelBuilders.Positions(expected), ModelBuilders.Positions(actual));
+
+ if (WithNormals.Contains(to) && expected.Parts.Any(p => p.Normals is not null))
+ AssertAttributesMatch(expected, actual, p => p.Normals is not null, (p, v) => new Vector4(p.Normal(v), 0), 1e-3f);
+ if (WithUvs.Contains(to) && expected.Parts.Any(p => p.TexCoords is not null))
+ AssertAttributesMatch(expected, actual, p => p.TexCoords is not null, (p, v) => new Vector4(p.TexCoord(v), 0, 0), 1e-4f);
+ if (WithVertexColors.Contains(to) && expected.Parts.Any(p => p.Colors is not null))
+ AssertAttributesMatch(expected, actual, p => p.Colors is not null, (p, v) => p.Color(v), 2.5f / 255);
+
+ if (WithMaterials.Contains(to) && expected.Materials.Count > 0)
+ {
+ var color = Assert.Single(actual.Materials).BaseColor;
+ AssertClose(expected.Materials[0].BaseColor, color, to == "3mf" ? 0.01f : 1e-4f);
+ if (WithTextures.Contains(to) && expected.Materials[0].BaseColorTexture is { } texture)
+ Assert.Equal(texture.Data, actual.Materials[0].BaseColorTexture?.Data);
+ }
+ }
+
+ /// <summary>Every vertex of <paramref name="actual"/> has a value that some vertex at the same place had before.</summary>
+ private static void AssertAttributesMatch(Model3D expected, Model3D actual, Func<MeshPart, bool> has, Func<MeshPart, int, Vector4> value, float tolerance)
+ {
+ var known = new Dictionary<(int, int, int), List<Vector4>>();
+ foreach (var part in expected.Parts.Where(has))
+ {
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var key = ModelBuilders.Key(part.Position(v));
+ if (!known.TryGetValue(key, out var list))
+ known[key] = list = [];
+ list.Add(value(part, v));
+ }
+ }
+ Assert.Contains(actual.Parts, p => has(p));
+ foreach (var part in actual.Parts.Where(has))
+ {
+ for (var v = 0; v < part.VertexCount; v++)
+ {
+ var found = value(part, v);
+ var candidates = known[ModelBuilders.Key(part.Position(v))];
+ Assert.True(candidates.Any(c => Vector4.Distance(c, found) <= tolerance * 2),
+ $"Vertex {v} at {part.Position(v)} has {found}; expected one of {string.Join(", ", candidates)}");
+ }
+ }
+ }
+
+ private static void AssertClose(Vector3 expected, Vector3 actual, float tolerance) =>
+ Assert.True(Vector3.Distance(expected, actual) <= tolerance, $"Expected {expected}, got {actual}");
+
+ private static void AssertClose(Vector4 expected, Vector4 actual, float tolerance) =>
+ Assert.True(Vector4.Distance(expected, actual) <= tolerance, $"Expected {expected}, got {actual}");
+
+ // ───────────────────────── Units and axes ─────────────────────────
+
+ [Fact]
+ public async Task Stl_millimetres_and_z_up_become_gltf_metres_and_y_up()
+ {
+ // A box 10 × 20 mm wide and 50 mm tall along Z, as a 3D printer sees it.
+ var folder = fx.NewFolder();
+ var stl = Path.Combine(folder, "tower.stl");
+ WriteBinaryStl(stl, Box(new Vector3(0, 0, 0), new Vector3(10, 20, 50)));
+
+ var glb = (await RunAsync(stl, "glb")).Outputs.Single();
+ var root = ModelRoot.Load(glb);
+ var position = root.LogicalMeshes.Single().Primitives.Single().GetVertexAccessor("POSITION");
+ var (min, max) = position.Bounds;
+ Assert.Equal(0.010, max[0] - min[0], 1e-6);
+ Assert.Equal(0.050, max[1] - min[1], 1e-6); // up
+ Assert.Equal(0.020, max[2] - min[2], 1e-6);
+
+ // And back: the same box, standing on Z again.
+ var raw = ReadBinaryStl((await RunAsync(glb, "stl")).Outputs.Single());
+ Assert.Equal(new Vector3(10, 20, 50), raw.Max - raw.Min);
+ Assert.Equal(12, raw.Facets.Count);
+ }
+
+ [Fact]
+ public async Task Gltf_from_3mf_in_inches_is_scaled_to_metres()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "inch.3mf");
+ Write3mf(path, """
+ <model unit="inch" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
+ <resources>
+ <object id="1" type="model"><mesh>
+ <vertices><vertex x="0" y="0" z="0"/><vertex x="1" y="0" z="0"/><vertex x="0" y="1" z="0"/><vertex x="0" y="0" z="1"/></vertices>
+ <triangles><triangle v1="0" v2="2" v3="1"/><triangle v1="0" v2="1" v3="3"/><triangle v1="0" v2="3" v3="2"/><triangle v1="1" v2="2" v3="3"/></triangles>
+ </mesh></object>
+ </resources>
+ <build><item objectid="1"/></build>
+ </model>
+ """);
+ var glb = (await RunAsync(path, "glb")).Outputs.Single();
+ var (min, max) = ModelRoot.Load(glb).LogicalMeshes.Single().Primitives.Single().GetVertexAccessor("POSITION").Bounds;
+ Assert.Equal(0.0254, max[0] - min[0], 1e-6);
+ Assert.Equal(0.0254, max[1] - min[1], 1e-6);
+ }
+
+ [Fact]
+ public async Task Stl_facet_normals_point_outward()
+ {
+ var folder = fx.NewFolder();
+ var source = ModelBuilders.Save(ModelBuilders.Cube(), folder, "cube", "glb");
+ var stl = ReadBinaryStl((await RunAsync(source, "stl")).Outputs.Single());
+ var center = (stl.Min + stl.Max) / 2;
+ Assert.Equal(12, stl.Facets.Count);
+ foreach (var (normal, a, b, c) in stl.Facets)
+ {
+ Assert.Equal(1, normal.Length(), 1e-4);
+ Assert.True(Vector3.Dot(normal, (a + b + c) / 3 - center) > 0);
+ }
+ }
+
+ // ───────────────────────── Outputs with several files ─────────────────────────
+
+ [Fact]
+ public async Task Obj_output_writes_the_material_library_and_texture_next_to_it()
+ {
+ var folder = fx.NewFolder();
+ var glb = ModelBuilders.Save(ModelBuilders.Cube(), folder, "kubus", "glb");
+ var job = await RunAsync(glb, "obj");
+
+ var obj = job.Outputs.Single(o => o.EndsWith(".obj", StringComparison.Ordinal));
+ var mtl = job.Outputs.Single(o => o.EndsWith(".mtl", StringComparison.Ordinal));
+ var png = job.Outputs.Single(o => o.EndsWith(".png", StringComparison.Ordinal));
+ Assert.All(job.Outputs, o => Assert.Equal(Path.GetDirectoryName(obj), Path.GetDirectoryName(o)));
+ Assert.Contains($"mtllib {Path.GetFileName(mtl)}", File.ReadAllText(obj));
+ Assert.Contains($"map_Kd {Path.GetFileName(png)}", File.ReadAllText(mtl));
+ Assert.Equal(ModelBuilders.Checker(), File.ReadAllBytes(png));
+ }
+
+ [Fact]
+ public async Task Gltf_output_is_one_file_with_the_buffer_inside()
+ {
+ var folder = fx.NewFolder();
+ var source = ModelBuilders.Save(ModelBuilders.Cube(), folder, "cube", "obj");
+ var gltf = (await RunAsync(source, "gltf")).Outputs.Single();
+ var json = JsonNode.Parse(File.ReadAllText(gltf))!;
+ Assert.StartsWith("data:application/octet-stream;base64,", (string)json["buffers"]![0]!["uri"]!);
+ Assert.Empty(Directory.GetFiles(folder, "*.bin"));
+ var root = ModelRoot.Load(gltf);
+ Assert.Equal(12, root.LogicalMeshes.Single().Primitives.Single().GetTriangleIndices().Count());
+ Assert.NotNull(root.LogicalMaterials.Single().FindChannel("BaseColor")!.Value.Texture);
+ }
+
+ [Fact]
+ public async Task Gltf_with_a_separate_buffer_and_texture_is_read()
+ {
+ var folder = fx.NewFolder();
+ var root = ModelRoot.CreateModel();
+ var material = root.CreateMaterial("Painted");
+ material.InitializePBRMetallicRoughness();
+ material.FindChannel("BaseColor")!.Value.SetTexture(0, root.UseImage(new SharpGLTF.Memory.MemoryImage(ModelBuilders.Checker())), null,
+ TextureWrapMode.REPEAT, TextureWrapMode.REPEAT, TextureMipMapFilter.DEFAULT, TextureInterpolationFilter.DEFAULT);
+ var mesh = root.CreateMesh("Quad");
+ var primitive = mesh.CreatePrimitive();
+ primitive.SetVertexAccessor("POSITION", Accessor(root, [new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0)]));
+ primitive.SetVertexAccessor("TEXCOORD_0", Accessor(root, [new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 0)]));
+ var indices = root.CreateAccessor();
+ indices.SetIndexData(root.UseBufferView(new byte[] { 0, 0, 1, 0, 2, 0, 0, 0, 2, 0, 3, 0 }, 0, null, 0, BufferMode.ELEMENT_ARRAY_BUFFER), 0, 6, IndexEncodingType.UNSIGNED_SHORT);
+ primitive.SetIndexAccessor(indices);
+ primitive.Material = material;
+ // The node scales by 2 and moves up by 1 m: both end up in the vertices.
+ var node = root.UseScene("Scene").CreateNode("Quad");
+ node.Mesh = mesh;
+ node.LocalMatrix = Matrix4x4.CreateScale(2) * Matrix4x4.CreateTranslation(0, 1, 0);
+ var gltf = Path.Combine(folder, "quad.gltf");
+ root.SaveGLTF(gltf, new WriteSettings { ImageWriting = ResourceWriteMode.SatelliteFile });
+ Assert.NotEmpty(Directory.GetFiles(folder, "*.bin"));
+
+ var model = ModelBuilders.Load((await RunAsync(gltf, "ply")).Outputs.Single(), "ply");
+ var (min, max) = model.Bounds();
+ AssertClose(new Vector3(0, 1000, 0), min, 1e-2f);
+ AssertClose(new Vector3(2000, 3000, 0), max, 1e-2f);
+ Assert.Equal(2, model.TriangleCount);
+ // glTF's UV origin is the top left, PLY's the bottom left.
+ Assert.Equal(new Vector2(0, 0), model.Parts[0].TexCoord(Enumerable.Range(0, 4).Single(v => model.Parts[0].Position(v) is { X: < 1, Y: < 1001 })));
+
+ var objJob = await RunAsync(gltf, "obj");
+ Assert.Equal(3, objJob.Outputs.Count()); // .obj, .mtl and the texture
+ }
+
+ private static Accessor Accessor<T>(ModelRoot root, T[] values) where T : unmanaged
+ {
+ var view = root.UseBufferView(System.Runtime.InteropServices.MemoryMarshal.AsBytes(values.AsSpan()).ToArray(), 0, null, 0, BufferMode.ARRAY_BUFFER);
+ var accessor = root.CreateAccessor();
+ accessor.SetVertexData(view, 0, values.Length, new SharpGLTF.Memory.AttributeFormat(typeof(T) == typeof(Vector3) ? DimensionType.VEC3 : DimensionType.VEC2));
+ accessor.UpdateBounds();
+ return accessor;
+ }
+
+ // ───────────────────────── Real-world files ─────────────────────────
+
+ [Fact]
+ public async Task Ascii_stl_with_two_solids_becomes_two_meshes()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "two.stl");
+ File.WriteAllText(path, """
+ solid first
+ facet normal 0 0 1
+ outer loop
+ vertex 0 0 0
+ vertex 1 0 0
+ vertex 0 1 0
+ endloop
+ endfacet
+ endsolid first
+ solid second
+ facet normal 0 0 1
+ outer loop
+ vertex 5 0 0
+ vertex 6.5e0 0 0
+ vertex 5 1 0
+ endloop
+ endfacet
+ endsolid second
+ """);
+ var model = ModelBuilders.Load(path, "stl");
+ Assert.Equal(["first", "second"], model.Parts.Select(p => p.Name));
+ var glb = ModelRoot.Load((await RunAsync(path, "glb")).Outputs.Single());
+ Assert.Equal(2, glb.LogicalMeshes.Count);
+ }
+
+ [Fact]
+ public void Binary_stl_with_a_solid_header_and_extra_bytes_is_read_as_binary()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "solid.stl");
+ WriteBinaryStl(path, Box(Vector3.Zero, new Vector3(1, 2, 3)));
+ var data = File.ReadAllBytes(path);
+ "solid exported by a CAD program"u8.CopyTo(data);
+ File.WriteAllBytes(path, [.. data, .. "trailing"u8]);
+ var model = ModelBuilders.Load(path, "stl");
+ Assert.Equal(12, model.TriangleCount);
+ Assert.Equal(8, model.VertexCount);
+ }
+
+ [Fact]
+ public async Task Obj_with_polygons_negative_indices_colours_and_a_material_library()
+ {
+ var folder = fx.NewFolder();
+ File.WriteAllBytes(Path.Combine(folder, "wood grain.png"), ModelBuilders.Checker());
+ File.WriteAllText(Path.Combine(folder, "parts.mtl"), """
+ newmtl wood
+ Kd 0.5 0.25 0.125
+ map_Kd -s 1 1 1 -bm 0.5 wood grain.png
+ """);
+ // A U-shaped octagon (concave: a fan from its first corner would cover the notch) and a quad with
+ // negative indices and vertex colours.
+ File.WriteAllText(Path.Combine(folder, "parts.obj"), """
+ mtllib parts.mtl
+ o U
+ v 2 2 0 1 0 0
+ v 2 1 0 1 0 0
+ v 1 1 0 1 0 0
+ v 1 2 0 1 0 0
+ v 0 2 0 1 0 0
+ v 0 0 0 1 0 0
+ v 3 0 0 1 0 0
+ v 3 2 0 1 0 0
+ usemtl wood
+ f 1 2 3 4 5 6 7 8
+ o Quad
+ v 10 0 0 0 0 255
+ v 11 0 0 0 0 255
+ v 11 1 0 0 0 255
+ v 10 1 0 0 0 255
+ vt 0 0
+ vt 1 1
+ f -4/-2 -3/-2 -2/-1 -1/-1
+ """);
+ var model = ModelBuilders.Load(Path.Combine(folder, "parts.obj"), "obj");
+ var u = model.Parts.Single(p => p.Name == "U");
+ Assert.Equal(6, u.TriangleCount);
+ Assert.Equal(5, ModelBuilders.Area(new Model3D { Parts = { u } }), 1e-4);
+ Assert.Equal("wood", model.MaterialOf(u)!.Name);
+ Assert.Equal(new Vector4(0.5f, 0.25f, 0.125f, 1), model.MaterialOf(u)!.BaseColor);
+ Assert.Equal(ModelBuilders.Checker(), model.MaterialOf(u)!.BaseColorTexture!.Data);
+ var quad = model.Parts.Single(p => p.Name == "Quad");
+ Assert.Equal(2, quad.TriangleCount);
+ Assert.Equal(new Vector4(0, 0, 1, 1), quad.Color(0)); // 0–255 values are scaled
+
+ var glb = ModelRoot.Load((await RunAsync(Path.Combine(folder, "parts.obj"), "glb")).Outputs.Single());
+ Assert.Equal(8, glb.LogicalMeshes.Sum(m => m.Primitives.Sum(p => p.GetTriangleIndices().Count())));
+ Assert.NotNull(glb.LogicalMaterials.Single(m => m.Name == "wood").FindChannel("BaseColor")!.Value.Texture);
+ }
+
+ [Fact]
+ public void Ply_ascii_with_quads_and_colours_and_big_endian_binary_are_read()
+ {
+ var folder = fx.NewFolder();
+ var ascii = Path.Combine(folder, "ascii.ply");
+ File.WriteAllText(ascii, """
+ ply
+ format ascii 1.0
+ comment a quad and a triangle
+ element vertex 5
+ property float x
+ property float y
+ property float z
+ property uchar red
+ property uchar green
+ property uchar blue
+ element face 2
+ property list uchar int vertex_indices
+ end_header
+ 0 0 0 255 0 0
+ 1 0 0 0 255 0
+ 1 1 0 0 0 255
+ 0 1 0 255 255 255
+ 2 0 0 0 0 0
+ 4 0 1 2 3
+ 3 1 4 2
+
+ """);
+ var model = ModelBuilders.Load(ascii, "ply");
+ Assert.Equal(3, model.TriangleCount);
+ Assert.Equal(new Vector4(0, 1, 0, 1), model.Parts[0].Color(1));
+ // Z up → Y up: the quad lies in the XZ plane.
+ Assert.Equal(new Vector3(1, 0, -1), model.Parts[0].Position(2));
+
+ var binary = Path.Combine(folder, "big.ply");
+ using (var stream = File.Create(binary))
+ {
+ stream.Write(Encoding.ASCII.GetBytes("ply\nformat binary_big_endian 1.0\nelement vertex 3\nproperty double x\nproperty double y\nproperty double z\nproperty ushort red\nproperty ushort green\nproperty ushort blue\nelement edge 1\nproperty int vertex1\nproperty int vertex2\nelement face 1\nproperty list uchar uint vertex_indices\nend_header\n"));
+ Span<byte> buffer = stackalloc byte[8];
+ foreach (var (x, y, z) in new[] { (0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 3.0, 0.0) })
+ {
+ foreach (var value in new[] { x, y, z })
+ {
+ BinaryPrimitives.WriteDoubleBigEndian(buffer, value);
+ stream.Write(buffer);
+ }
+ foreach (var channel in new ushort[] { 65535, 0, 32768 })
+ {
+ BinaryPrimitives.WriteUInt16BigEndian(buffer, channel);
+ stream.Write(buffer[..2]);
+ }
+ }
+ BinaryPrimitives.WriteInt32BigEndian(buffer, 0);
+ stream.Write(buffer[..4]);
+ BinaryPrimitives.WriteInt32BigEndian(buffer, 1);
+ stream.Write(buffer[..4]);
+ stream.WriteByte(3);
+ foreach (var index in new uint[] { 0, 1, 2 })
+ {
+ BinaryPrimitives.WriteUInt32BigEndian(buffer, index);
+ stream.Write(buffer[..4]);
+ }
+ }
+ var big = ModelBuilders.Load(binary, "ply");
+ Assert.Equal(1, big.TriangleCount);
+ Assert.Equal(6, ModelBuilders.Area(big), 1e-5);
+ Assert.Equal(1, big.Parts[0].Color(0).X, 1e-4);
+ Assert.Equal(0.5, big.Parts[0].Color(0).Z, 1e-3);
+ }
+
+ [Fact]
+ public void Three_mf_components_transforms_materials_and_colour_groups_are_read()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "assembly.3mf");
+ Write3mf(path, """
+ <model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02">
+ <resources>
+ <basematerials id="1"><base name="Orange" displaycolor="#FF8000"/><base name="Blue" displaycolor="#0000FFFF"/></basematerials>
+ <m:colorgroup id="2"><m:color color="#FF0000"/><m:color color="#00FF00"/></m:colorgroup>
+ <object id="3" type="model" pid="1" pindex="0"><mesh>
+ <vertices><vertex x="0" y="0" z="0"/><vertex x="10" y="0" z="0"/><vertex x="0" y="10" z="0"/><vertex x="10" y="10" z="0"/></vertices>
+ <triangles><triangle v1="0" v2="1" v3="2"/><triangle v1="1" v2="3" v3="2" pid="1" p1="1"/></triangles>
+ </mesh></object>
+ <object id="4" type="model"><mesh>
+ <vertices><vertex x="0" y="0" z="0"/><vertex x="1" y="0" z="0"/><vertex x="0" y="1" z="0"/></vertices>
+ <triangles><triangle v1="0" v2="1" v3="2" pid="2" p1="0" p2="1"/></triangles>
+ </mesh></object>
+ <object id="5" type="support"><mesh>
+ <vertices><vertex x="0" y="0" z="0"/><vertex x="1" y="0" z="0"/><vertex x="0" y="1" z="0"/></vertices>
+ <triangles><triangle v1="0" v2="1" v3="2"/></triangles>
+ </mesh></object>
+ <object id="6" type="model"><components>
+ <component objectid="3"/>
+ <component objectid="4" transform="1 0 0 0 1 0 0 0 1 100 0 0"/>
+ <component objectid="5"/>
+ </components></object>
+ </resources>
+ <build><item objectid="6" transform="1 0 0 0 1 0 0 0 1 0 0 5"/></build>
+ </model>
+ """);
+ var model = ModelBuilders.Load(path, "3mf");
+ Assert.Equal(3, model.TriangleCount); // the support is left out
+ Assert.Equal(["Orange", "Blue"], model.Materials.Select(m => m.Name));
+ AssertClose(new Vector4(1, MeshMath.SrgbToLinear(128 / 255f), 0, 1), model.Materials[0].BaseColor, 1e-4f);
+ var colored = model.Parts.Single(p => p.Colors is not null);
+ var corner = Enumerable.Range(0, colored.VertexCount).Single(v => colored.Position(v).X > 100.5f);
+ Assert.Equal(new Vector4(0, 1, 0, 1), colored.Color(corner)); // p2 → second colour
+ // Z up → Y up, and the item's 5 mm lift becomes Y.
+ Assert.All(model.Parts, p => Assert.Equal(5, p.Position(0).Y, 1e-4));
+ }
+
+ [Fact]
+ public async Task Ply_output_turns_material_colours_into_vertex_colours()
+ {
+ var folder = fx.NewFolder();
+ var source = ModelBuilders.Save(ModelBuilders.Cube(), folder, "cube", "3mf");
+ var model = ModelBuilders.Load((await RunAsync(source, "ply")).Outputs.Single(), "ply");
+ var expected = MeshMath.LinearToSrgb(ModelBuilders.CubeColor);
+ Assert.All(Enumerable.Range(0, model.VertexCount), v => AssertClose(expected, model.Parts[0].Color(v), 1.5f / 255));
+ }
+
+ [Fact]
+ public async Task Missing_normals_are_computed_where_the_output_has_them()
+ {
+ // A sphere with normals and a fan without, in one OBJ (the fan's faces have no "vn"): every vertex of the
+ // PLY gets a unit normal, the fan's pointing up.
+ var model = ModelBuilders.Sphere();
+ var fan = ModelBuilders.Fan().Parts[0];
+ fan.Colors = null;
+ model.Parts.Add(fan);
+ var folder = fx.NewFolder();
+ var obj = ModelBuilders.Save(model, folder, "mixed", "obj");
+ var ply = ModelBuilders.Load((await RunAsync(obj, "ply")).Outputs.Single(), "ply");
+ var part = ply.Parts.Single();
+ Assert.NotNull(part.Normals);
+ for (var v = 0; v < part.VertexCount; v++)
+ Assert.Equal(1, part.Normal(v).Length(), 1e-3);
+ var fanVertices = Enumerable.Range(0, part.VertexCount).Where(v => part.Position(v).Y == 0 && part.Position(v).Length() > 9.9f && part.Normal(v).Y > 0.99f);
+ Assert.Equal(6, fanVertices.Count());
+
+ // A face without normals among faces with them: the part's normals are computed from the faces.
+ var path = Path.Combine(folder, "partial.obj");
+ File.WriteAllText(path, "v 0 0 0\nv 1 0 0\nv 0 0 -1\nv 1 0 -1\nvn 0 1 0\nf 1//1 2//1 3//1\nf 2 4 3\n");
+ var partial = ModelBuilders.Load(path, "obj").Parts.Single();
+ Assert.All(Enumerable.Range(0, partial.VertexCount), v => Assert.Equal(1, partial.Normal(v).Y, 1e-4));
+ }
+
+ // ───────────────────────── Pictures ─────────────────────────
+
+ [Fact]
+ public async Task A_model_renders_to_a_shaded_picture_with_a_transparent_background()
+ {
+ var folder = fx.NewFolder();
+ var source = ModelBuilders.Save(ModelBuilders.Sphere(), folder, "ball", "ply");
+ var png = (await RunAsync(source, "png")).Outputs.Single();
+ using var image = new MagickImage(png);
+ Assert.Equal(1024u, image.Width);
+ Assert.Equal(1024u, image.Height);
+ using var pixels = image.GetPixels();
+ Assert.Equal(0, pixels.GetPixel(2, 2)!.GetChannel(3));
+ var center = pixels.GetPixel(512, 512)!;
+ Assert.Equal(255, center.GetChannel(3));
+ // The sphere's colours come through (not a grey default).
+ var colors = Enumerable.Range(0, 16).Select(i => pixels.GetPixel(300 + i * 25, 512)!).Where(p => p.GetChannel(3) == 255)
+ .Select(p => (p.GetChannel(0), p.GetChannel(1), p.GetChannel(2))).Distinct().Count();
+ Assert.True(colors > 4);
+
+ var jpg = (await RunAsync(source, "jpg")).Outputs.Single();
+ Assert.Equal(MagickFormat.Jpeg, new MagickImageInfo(jpg).Format);
+ }
+
+ // ───────────────────────── Large files ─────────────────────────
+
+ [Fact]
+ public async Task A_million_triangle_stl_converts_in_seconds()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "terrain.stl");
+ const int grid = 708; // 708 × 708 × 2 = 1,002,528 triangles
+ using (var stream = new BufferedStream(File.Create(path), 1 << 20))
+ {
+ var header = new byte[84];
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(80), grid * grid * 2);
+ stream.Write(header);
+ var record = new byte[50];
+ Vector3 P(int x, int y) => new(x, y, MathF.Sin(x * 0.05f) * MathF.Cos(y * 0.05f) * 5);
+ for (var y = 0; y < grid; y++)
+ {
+ for (var x = 0; x < grid; x++)
+ {
+ WriteFacet(stream, record, P(x, y), P(x + 1, y), P(x + 1, y + 1));
+ WriteFacet(stream, record, P(x, y), P(x + 1, y + 1), P(x, y + 1));
+ }
+ }
+ }
+
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ var glb = (await RunAsync(path, "glb")).Outputs.Single();
+ watch.Stop();
+ Assert.True(watch.Elapsed < TimeSpan.FromSeconds(30), $"took {watch.Elapsed}");
+ var primitive = ModelRoot.Load(glb).LogicalMeshes.Single().Primitives.Single();
+ Assert.Equal(grid * grid * 2, primitive.GetIndexAccessor().Count / 3);
+ Assert.Equal((grid + 1) * (grid + 1), primitive.GetVertexAccessor("POSITION").Count); // merged by position
+ }
+
+ private static void WriteFacet(Stream stream, byte[] record, Vector3 a, Vector3 b, Vector3 c)
+ {
+ var i = 12;
+ foreach (var v in new[] { a, b, c })
+ {
+ BinaryPrimitives.WriteSingleLittleEndian(record.AsSpan(i), v.X);
+ BinaryPrimitives.WriteSingleLittleEndian(record.AsSpan(i + 4), v.Y);
+ BinaryPrimitives.WriteSingleLittleEndian(record.AsSpan(i + 8), v.Z);
+ i += 12;
+ }
+ stream.Write(record);
+ }
+
+ // ───────────────────────── Bad input ─────────────────────────
+
+ [Fact]
+ public async Task Broken_files_fail_with_a_clear_message()
+ {
+ var folder = fx.NewFolder();
+
+ var truncated = Path.Combine(folder, "cut.stl");
+ var header = new byte[84 + 50];
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(80), 10);
+ File.WriteAllBytes(truncated, header);
+ Assert.Contains("cut short", await FailAsync(truncated, "glb"));
+
+ var badIndex = Path.Combine(folder, "bad.obj");
+ File.WriteAllText(badIndex, "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 7\n");
+ Assert.Contains("vertex 7, which does not exist", await FailAsync(badIndex, "stl"));
+
+ var noFaces = Path.Combine(folder, "points.obj");
+ File.WriteAllText(noFaces, "v 0 0 0\nv 1 0 0\n");
+ Assert.Contains("contains no triangles", await FailAsync(noFaces, "stl"));
+
+ var notPly = Path.Combine(folder, "text.ply");
+ File.WriteAllText(notPly, "hello");
+ Assert.Contains("not a PLY file", await FailAsync(notPly, "stl"));
+
+ var not3mf = Path.Combine(folder, "text.3mf");
+ File.WriteAllText(not3mf, "hello");
+ Assert.Contains("not a 3MF package", await FailAsync(not3mf, "stl"));
+
+ var notGltf = Path.Combine(folder, "text.gltf");
+ File.WriteAllText(notGltf, "{ \"asset\": ");
+ Assert.Contains("glTF", await FailAsync(notGltf, "stl"));
+
+ var draco = Path.Combine(folder, "draco.gltf");
+ File.WriteAllText(draco, """
+ {"asset":{"version":"2.0"},"extensionsUsed":["KHR_draco_mesh_compression"],"extensionsRequired":["KHR_draco_mesh_compression"],
+ "meshes":[{"primitives":[{"attributes":{"POSITION":0},"extensions":{"KHR_draco_mesh_compression":{"bufferView":0,"attributes":{"POSITION":0}}}}]}],
+ "accessors":[{"componentType":5126,"count":3,"type":"VEC3","min":[0,0,0],"max":[1,1,0]}],
+ "bufferViews":[{"buffer":0,"byteLength":4}],"buffers":[{"byteLength":4,"uri":"data:application/octet-stream;base64,AAAAAA=="}],
+ "nodes":[{"mesh":0}],"scenes":[{"nodes":[0]}],"scene":0}
+ """);
+ Assert.Contains("Draco-compressed", await FailAsync(draco, "stl"));
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ private static void Write3mf(string path, string model)
+ {
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ using (var writer = new StreamWriter(zip.CreateEntry("_rels/.rels").Open()))
+ writer.Write("""<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/></Relationships>""");
+ using (var writer = new StreamWriter(zip.CreateEntry("3D/3dmodel.model").Open()))
+ writer.Write(model);
+ }
+
+ /// <summary>The 12 triangles of an axis-aligned box, outward facing.</summary>
+ private static List<(Vector3, Vector3, Vector3)> Box(Vector3 min, Vector3 max)
+ {
+ Vector3 C(int i) => new((i & 1) == 0 ? min.X : max.X, (i & 2) == 0 ? min.Y : max.Y, (i & 4) == 0 ? min.Z : max.Z);
+ int[][] quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
+ return [.. quads.SelectMany(q => new[] { (C(q[0]), C(q[1]), C(q[2])), (C(q[0]), C(q[2]), C(q[3])) })];
+ }
+
+ private static void WriteBinaryStl(string path, List<(Vector3, Vector3, Vector3)> triangles)
+ {
+ using var stream = File.Create(path);
+ var header = new byte[84];
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(80), (uint)triangles.Count);
+ stream.Write(header);
+ var record = new byte[50];
+ foreach (var (a, b, c) in triangles)
+ WriteFacet(stream, record, a, b, c);
+ }
+
+ private static (List<(Vector3 Normal, Vector3 A, Vector3 B, Vector3 C)> Facets, Vector3 Min, Vector3 Max) ReadBinaryStl(string path)
+ {
+ var data = File.ReadAllBytes(path);
+ var count = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(80));
+ var facets = new List<(Vector3, Vector3, Vector3, Vector3)>();
+ var min = new Vector3(float.MaxValue);
+ var max = new Vector3(float.MinValue);
+ for (var i = 0; i < count; i++)
+ {
+ var v = new Vector3[4];
+ for (var k = 0; k < 4; k++)
+ {
+ var o = 84 + i * 50 + k * 12;
+ v[k] = new Vector3(BitConverter.ToSingle(data, o), BitConverter.ToSingle(data, o + 4), BitConverter.ToSingle(data, o + 8));
+ if (k > 0)
+ {
+ min = Vector3.Min(min, v[k]);
+ max = Vector3.Max(max, v[k]);
+ }
+ }
+ facets.Add((v[0], v[1], v[2], v[3]));
+ }
+ return (facets, min, max);
+ }
+}