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.

Pictures can be traced into SVG, and SVG drawings saved as DXF and DWG

KnifeLemon6672e556e969
diff --git a/README.ko.md b/README.ko.md
index f6e5d109..8dac8572 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -81,8 +81,8 @@
| 원본 | 변환 대상 |
|---|---|
-| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등)는 읽기 | 위 형식끼리(HEIC⁵), PDF, 크기 조정, 흑백 |
-| **벡터**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF(벡터), PNG 등 이미지, SVG ↔ SVGZ, PDF → EPS/PS¹ |
+| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등)는 읽기 | 위 형식끼리(HEIC⁵), PDF, SVG(벡터화), 크기 조정, 흑백 |
+| **벡터**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF(벡터), PNG 등 이미지, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹ |
| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ; 합치기, 나누기, 페이지 범위 |
| **문서**: DOCX, DOCM, DOTX, EML · DOC, ODT, RTF, WPS, WPD, Pages 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML |
| **스프레드시트**: XLSX, XLSM, XLS, ODS, CSV, TSV · Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, HWPX, HTML |
diff --git a/README.md b/README.md
index c2f73df1..f9a375b9 100644
--- a/README.md
+++ b/README.md
@@ -81,8 +81,8 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
| From | To |
|---|---|
-| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …) read | any of these (HEIC⁵), PDF, resized, grayscale |
-| **Vector**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF (vector), PNG and other images, SVG ↔ SVGZ, PDF → EPS/PS¹ |
+| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …) read | any of these (HEIC⁵), PDF, SVG (traced), resized, grayscale |
+| **Vector**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF (vector), PNG and other images, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹ |
| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ; merge, split, page ranges |
| **Documents**: DOCX, DOCM, DOTX, EML · DOC, ODT, RTF, WPS, WPD, Pages, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML |
| **Spreadsheets**: XLSX, XLSM, XLS, ODS, CSV, TSV · Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, HWPX, HTML |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9ca8989c..f52f832f 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -80,8 +80,8 @@
| 源格式 | 目标格式 |
|---|---|
-| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)仅读取 | 上述格式互转(HEIC⁵)、PDF、缩放、灰度 |
-| **矢量图**:SVG、SVGZ、EMF、WMF、AI · EPS、PS¹ · CDR、VSD、CGM、ODG² | PDF(矢量)、PNG 等图片、SVG ↔ SVGZ、PDF → EPS/PS¹ |
+| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)仅读取 | 上述格式互转(HEIC⁵)、PDF、SVG(描摹)、缩放、灰度 |
+| **矢量图**:SVG、SVGZ、EMF、WMF、AI · EPS、PS¹ · CDR、VSD、CGM、ODG² | PDF(矢量)、PNG 等图片、SVG ↔ SVGZ、SVG → DXF/DWG、PDF → EPS/PS¹ |
| **PDF** | DOCX、HWPX、TXT、PNG、JPG、TIFF、CBZ;合并、拆分、页码范围 |
| **文档**:DOCX、DOCM、DOTX、EML · DOC、ODT、RTF、WPS、WPD、Pages 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML |
| **表格**:XLSX、XLSM、XLS、ODS、CSV、TSV · Numbers、ET² | PDF、XLSX、ODS、CSV、TSV、HWPX、HTML |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index da0fca5f..f51a38b0 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -6,7 +6,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| Engine | How it gets there | Handles |
|---|---|---|
| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM ↔ each other; HEIC (written with FFmpeg), XCF, camera RAW (LibRaw) and EMF/WMF (Windows) read |
-| Vector graphics | built in (Svg.Skia, SkiaSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, PDF-compatible AI → PDF |
+| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI → PDF |
| ICNS | built in | images → ICNS (16–1024 px), ICNS → images |
| PDFsharp | built in (library) | images → PDF, merge, split, page ranges |
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
@@ -101,6 +101,63 @@ current.
- EPS and PS → PNG go straight through Ghostscript's `pngalpha` device, so the background stays transparent;
JPG, WebP, … and AI reach images through PDF (Ghostscript → PDFium), and SVG reaches EPS through PDF.
+## Tracing (raster images → SVG)
+
+Built in (`Vector/Tracing`), no Potrace or other program: Filee's own code, written from published descriptions of the
+steps (no code of Potrace, AutoTrace or VTracer is used). Every raster format ImageMagick reads (PNG, JPG, BMP, GIF,
+WEBP, TIFF, HEIC, PSD, RAW, …) is traced; anything else that becomes a PNG first (ICNS, PDF pages, …) is traced from
+that PNG. The first frame or page is used, turned upright, in sRGB. The SVG has the picture's pixel size
+(`width`/`height`/`viewBox` in pixels), so it lines up with the original.
+
+- **Black and white** (*Line art to SVG*: logos, signatures, scans): pixels darker than Otsu's threshold are ink
+ (transparent pixels count as white paper). On a transparent background the opaque pixels are the ink, or only their
+ darker part when the opaque area itself is light and dark. One black `<path>` on a transparent background.
+- **Colour** (*Trace to SVG*: illustrations, icons): k-means reduces the picture to the preset's number of colours
+ (2–64; run on the mean colours of 32 768 colour boxes weighted by their pixel counts, so it sees every pixel). One-pixel
+ bands of in-between colours along edges (anti-aliasing) join the colour on either side; regions smaller than a few
+ pixels (more on large pictures) join the neighbour they share most border with. Colours are stacked largest first,
+ and each colour's shape is the union of itself and every colour above it: lower shapes run under upper ones, so no
+ background shows through between neighbouring shapes. Transparent areas stay transparent. One `<path>` per colour.
+- **Outlines**: each shape's boundary is followed along the pixel edges (inside always on the right, so holes come out
+ reversed and fill correctly with the non-zero rule; pixels touching only at a corner stay one shape). Outlines
+ smaller than the speck size are dropped (and small holes filled).
+- **Curves**: the staircase is replaced by points on the edge it approximates (midpoints of the steps); corners are
+ kept where two long pixel runs meet, at the ends of thin lines, where the direction turns sharply within two
+ pixels, or where a gentler turn happens all at once (unlike a small circle). Points between corners are smoothed;
+ stretches that stay within half a pixel of a line without bending become lines; the rest becomes cubic Béziers
+ fitted by least squares (Philip J. Schneider, "An Algorithm for Automatically Fitting Digitized Curves", Graphics
+ Gems, 1990), meeting lines and each other with matching tangents.
+- **Options** (Settings → Presets): mode, colours (colour mode) and *Detail* 0–100. Low detail drops larger specks,
+ smooths more and allows the curves 1.15 px of deviation; high detail keeps every pixel's shape (0.25 px). The
+ default 50 drops specks under 6 px (black and white) or merges regions under 17 px (colour), at 0.7 px; speck and
+ region sizes grow with pictures larger than 1000 px (up to four times).
+- **Size and speed**: pictures over 6 megapixels or 4096 px on a side are reduced before tracing; the SVG keeps the
+ original size and says so in a comment. A 2000 × 2000 illustration traces in 1–3 s at 16 colours and well under a
+ second in black and white; a noisy 2000 × 2000 photo at 16 colours takes about 4 s (64 colours about 5 s, and a
+ 20 MB SVG). Photos are not what tracing is for: they come out as posterized patches.
+- **Routes**: tracing is the only raster → SVG route and costs 40 (`VectorConverter.TraceCost`), more than any route
+ from an image to a format SVG leads to, so it is never a step on the way to PDF, PNG, EPS, …; a test checks every
+ pair of formats. Through SVG, pictures reach DXF and DWG. Formats without a vector route to SVG (PDF, EPS, AI;
+ EMF/WMF without LibreOffice) are traced from their rendering.
+
+## SVG → DXF / DWG
+
+`Vector/SvgDxfWriter.cs` writes the drawing's outlines with ACadSharp (DXF, AutoCAD 2018 like the CAD engine; DWG is
+DXF → DWG by the CAD engine). The SVG is loaded with Svg.Skia as for PDF output, so groups, transforms, `<use>`,
+nested `<svg>`, CSS and text are resolved the same way.
+
+- Circles and ellipses become CIRCLE and ELLIPSE (also rotated, scaled or skewed: the transformed axes come from the
+ singular values of the transform). Paths, lines, polylines, polygons and rectangles (rounded too) become
+ LWPOLYLINEs, closed where the shape is closed, or a LINE for one straight segment. Bézier curves and arcs are divided
+ into straight pieces within 0.01 mm of the curve: every CAD and CAM program reads polylines, while SPLINE support
+ varies. Text becomes its glyph outlines.
+- Units: SVG user units are CSS pixels, 96 per inch, so 1 px = 25.4 / 96 mm and the DXF is in millimetres
+ (`$INSUNITS` 4, metric): a drawing 100 mm wide in the SVG is 100 mm wide in CAD. The y axis is flipped (SVG points
+ down, DXF up) with the viewport's bottom-left corner at (0, 0).
+- Colours are kept as true colours (the stroke's, else the fill's; black for gradients). Fills, stroke widths,
+ clipping, masks, images and filters are not represented; a shape both filled and stroked is written once. An SVG
+ with nothing to outline fails with a message.
+
## HWPX writer
Filee writes OWPML (HWPX) itself, so saving as HWPX needs no Hancom Office and shows no approval dialog.
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 2828fbba..ae1dda91 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -72,7 +72,7 @@
"engine.docx-writer.description": "Writes Word documents (DOCX) from PDF, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.",
"engine.pdf-text.description": "Extracts the text of PDFs in reading order, also from two-column pages (no OCR for scans).",
"engine.email.description": "E-mails (EML) to HTML and text with sender, recipients and date, pictures included; attachments into a ZIP.",
- "engine.vector.description": "SVG and SVGZ to vector PDF and to images; Illustrator files saved with PDF content.",
+ "engine.vector.description": "SVG and SVGZ to vector PDF, images and DXF; pictures traced into SVG; Illustrator files saved with PDF content.",
"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.",
@@ -108,6 +108,8 @@
"preset.long_image": "Long image",
"preset.extract": "Extract",
"preset.zip_all": "One ZIP",
+ "preset.trace_svg": "Trace to SVG",
+ "preset.trace_line_art": "Line art to SVG",
"format.folder": "Folder",
"format.category.Image": "Image",
@@ -362,6 +364,14 @@
"presets.archive_level.Maximum": "Maximum (slower)",
"presets.combine": "Put all files into one archive",
"presets.extract_note": "Each archive is extracted into a folder of its own. Where it goes is set under Output.",
+ "presets.group.trace": "Tracing",
+ "presets.trace_note": "Used when a picture (PNG, JPG, …) is traced into vector shapes.",
+ "presets.trace_mode": "Mode",
+ "presets.trace_mode.Color": "Colour",
+ "presets.trace_mode.BlackAndWhite": "Black and white (line art)",
+ "presets.trace_colors": "Colours",
+ "presets.trace_detail": "Detail",
+ "presets.trace_detail_hint": "Low smooths the outlines and drops specks.\nHigh follows the pixels closely and keeps small details.",
"presets.group.output": "Output",
"presets.location": "Save to",
"presets.location.Default": "Default save location (Settings > General)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index c0074be4..762b4dcb 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -72,7 +72,7 @@
"engine.docx-writer.description": "PDF, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 워드 문서(DOCX)를 만들어요.",
"engine.pdf-text.description": "PDF의 글자를 읽는 순서대로 뽑아내요.\n2단 편집도 순서대로 읽어요(스캔 이미지 글자 인식은 안 해요).",
"engine.email.description": "이메일(EML)을 보낸 사람·받는 사람·날짜와 본문 그림까지 담아 HTML·텍스트로 바꾸고, 첨부 파일은 ZIP으로 모아요.",
- "engine.vector.description": "SVG·SVGZ를 벡터 PDF와 이미지로, PDF 내용이 들어 있는 일러스트레이터 파일도 변환해요.",
+ "engine.vector.description": "SVG·SVGZ를 벡터 PDF, 이미지, DXF로 바꾸고 그림을 SVG로 벡터화해요. PDF 내용이 들어 있는 일러스트레이터 파일도 변환해요.",
"engine.icns.description": "macOS 앱 아이콘(ICNS)을 이미지로, 이미지를 ICNS로.",
"engine.font.description": "글꼴: TTF, OTF, WOFF, WOFF2, EOT를 서로 변환해요.",
"engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.",
@@ -108,6 +108,8 @@
"preset.long_image": "긴 이미지",
"preset.extract": "압축 풀기",
"preset.zip_all": "ZIP 하나로",
+ "preset.trace_svg": "벡터화",
+ "preset.trace_line_art": "흑백 선화",
"format.folder": "폴더",
"format.category.Image": "이미지",
@@ -362,6 +364,14 @@
"presets.archive_level.Maximum": "최대 (느림)",
"presets.combine": "모든 파일을 압축 파일 하나로 묶기",
"presets.extract_note": "압축 파일마다 따로 폴더를 만들어 풀어요. 저장 위치는 아래 출력에서 정해요.",
+ "presets.group.trace": "벡터화",
+ "presets.trace_note": "그림(PNG, JPG 등)을 벡터 도형으로 바꿀 때 쓰여요.",
+ "presets.trace_mode": "방식",
+ "presets.trace_mode.Color": "컬러",
+ "presets.trace_mode.BlackAndWhite": "흑백 (선화)",
+ "presets.trace_colors": "색 수",
+ "presets.trace_detail": "세밀도",
+ "presets.trace_detail_hint": "낮을수록 윤곽이 매끄럽고 작은 점은 지워요.\n높을수록 픽셀을 따라가며 작은 부분까지 살려요.",
"presets.group.output": "출력",
"presets.location": "저장 위치",
"presets.location.Default": "기본 저장 위치 (설정 > 일반)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 8ec41bb7..d7ed4de7 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -72,7 +72,7 @@
"engine.docx-writer.description": "用 PDF、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 Word 文档(DOCX)。",
"engine.pdf-text.description": "按阅读顺序提取 PDF 中的文字,双栏页面也能正确排序(不对扫描件做文字识别)。",
"engine.email.description": "将电子邮件(EML)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。",
- "engine.vector.description": "将 SVG、SVGZ 转为矢量 PDF 和图片;也支持包含 PDF 内容的 Illustrator 文件。",
+ "engine.vector.description": "将 SVG、SVGZ 转为矢量 PDF、图片和 DXF,并可将图片描摹为 SVG。也支持包含 PDF 内容的 Illustrator 文件。",
"engine.icns.description": "macOS 应用图标(ICNS)与图片互转。",
"engine.font.description": "字体:TTF、OTF、WOFF、WOFF2 和 EOT 互相转换。",
"engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。",
@@ -108,6 +108,8 @@
"preset.long_image": "长图",
"preset.extract": "解压",
"preset.zip_all": "打包成一个 ZIP",
+ "preset.trace_svg": "描摹",
+ "preset.trace_line_art": "黑白描摹",
"format.folder": "文件夹",
"format.category.Image": "图片",
@@ -362,6 +364,14 @@
"presets.archive_level.Maximum": "最大(较慢)",
"presets.combine": "将所有文件放入一个压缩文件",
"presets.extract_note": "每个压缩文件解压到各自的文件夹。保存位置在下方“输出”中设置。",
+ "presets.group.trace": "描摹",
+ "presets.trace_note": "将图片(PNG、JPG 等)描摹为矢量图形时使用。",
+ "presets.trace_mode": "模式",
+ "presets.trace_mode.Color": "彩色",
+ "presets.trace_mode.BlackAndWhite": "黑白(线稿)",
+ "presets.trace_colors": "颜色数",
+ "presets.trace_detail": "细节",
+ "presets.trace_detail_hint": "越低轮廓越平滑,并去除小斑点。\n越高越贴合像素,保留细小部分。",
"presets.group.output": "输出",
"presets.location": "保存到",
"presets.location.Default": "默认保存位置(设置 > 常规)",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index b608376d..d8c6503d 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -72,6 +72,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
r => r == 0 ? loc["presets.sample_rate.source"] : $"{r / 1000.0:0.##} kHz");
WavFormats = Enum.GetValues<WavSampleFormat>().Select(v => new Choice<WavSampleFormat>(v, loc[$"presets.wav_format.{v}"])).ToList();
ArchiveLevels = Enum.GetValues<ArchiveLevel>().Select(v => new Choice<ArchiveLevel>(v, loc[$"presets.archive_level.{v}"])).ToList();
+ TraceModes = Enum.GetValues<TracingMode>().Select(v => new Choice<TracingMode>(v, loc[$"presets.trace_mode.{v}"])).ToList();
_name = string.IsNullOrWhiteSpace(_edit.Name) ? loc.DisplayName(_edit) : _edit.Name;
_target = Targets.FirstOrDefault(t => t.Value == _edit.TargetFormat) ?? Targets[1];
@@ -89,6 +90,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_wavFormat = WavFormats.First(f => f.Value == _edit.Media.WavFormat);
_archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level);
_combineIntoOne = _edit.Archive.CombineIntoOne;
+ _traceMode = TraceModes.First(m => m.Value == _edit.Trace.Mode);
+ _traceColors = Math.Clamp(_edit.Trace.Colors, TracingOptions.MinColors, TracingOptions.MaxColors);
+ _traceDetail = Math.Clamp(_edit.Trace.Detail, 0, 100);
_quality = _edit.Image.Quality;
_resizePercent = _edit.Image.ResizePercent;
_longEdge = _edit.Image.LongEdge;
@@ -135,6 +139,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public IReadOnlyList<Choice<int>> SampleRates { get; }
public IReadOnlyList<Choice<WavSampleFormat>> WavFormats { get; }
public IReadOnlyList<Choice<ArchiveLevel>> ArchiveLevels { get; }
+ public IReadOnlyList<Choice<TracingMode>> TraceModes { get; }
[ObservableProperty, NotifyPropertyChangedFor(nameof(NameError), nameof(IsValid))]
private string _name;
@@ -144,7 +149,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
nameof(ShowAudioChannels), nameof(ShowWav),
- nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote))]
+ nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote), nameof(ShowTrace))]
private Choice<string> _target;
[ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge), nameof(ShowWidth))]
@@ -219,6 +224,12 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private Choice<ArchiveLevel> _archiveLevel;
[ObservableProperty] private bool _combineIntoOne;
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowTraceColors))]
+ private Choice<TracingMode> _traceMode;
+
+ [ObservableProperty] private int _traceColors;
+ [ObservableProperty] private int _traceDetail;
+
private string TargetId => Target.Value;
private FormatCategory? TargetCategory => FormatRegistry.FindById(TargetId)?.Category;
private bool TargetIsImage => TargetId == BuiltInData.SameAsSource || TargetCategory == FormatCategory.Image;
@@ -253,6 +264,12 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowArchiveOptions => ShowArchive && TargetId != FormatRegistry.Folder;
/// <summary>"Extract" has nothing to set; a line says what it does instead.</summary>
public bool ShowExtractNote => TargetId == FormatRegistry.Folder;
+ /// <summary>
+ /// Tracing options: raster images reach SVG (and DXF / DWG through it) only by tracing. For other sources (a
+ /// drawing, a CAD file) the options are ignored.
+ /// </summary>
+ public bool ShowTrace => TargetId is "svg" or "svgz" or "dxf" or "dwg";
+ public bool ShowTraceColors => TraceMode.Value == TracingMode.Color;
public bool ShowPercent => Resize.Value == ResizeMode.Percent;
public bool ShowLongEdge => Resize.Value == ResizeMode.LongEdge;
public bool ShowWidth => Resize.Value == ResizeMode.Width;
@@ -321,6 +338,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
media.WavFormat = WavFormat.Value;
_original.Archive.Level = ArchiveLevel.Value;
_original.Archive.CombineIntoOne = CombineIntoOne;
+ _original.Trace.Mode = TraceMode.Value;
+ _original.Trace.Colors = Math.Clamp(TraceColors, TracingOptions.MinColors, TracingOptions.MaxColors);
+ _original.Trace.Detail = Math.Clamp(TraceDetail, 0, 100);
var output = _original.Output;
output.Location = Location.Value;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 4f6ae7b9..f246241c 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -162,6 +162,35 @@
</StackPanel>
</Border>
+ <!-- Tracing options (raster image → SVG, and DXF / DWG through SVG) -->
+ <Border x:Name="TraceCard" Classes="card" IsVisible="{Binding ShowTrace}" Padding="14">
+ <StackPanel Spacing="10">
+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.trace}" />
+ <TextBlock Classes="caption" Text="{DynamicResource presets.trace_note}" TextWrapping="Wrap" />
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.trace_mode}" />
+ <ComboBox ItemsSource="{Binding TraceModes}" SelectedItem="{Binding TraceMode}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowTraceColors}">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding TraceColors}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource presets.trace_colors}" />
+ </DockPanel>
+ <Slider Minimum="2" Maximum="64" Value="{Binding TraceColors}" TickFrequency="1" IsSnapToTickEnabled="True" />
+ </StackPanel>
+ </Grid>
+ <StackPanel>
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding TraceDetail}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource presets.trace_detail}" />
+ </DockPanel>
+ <Slider Minimum="0" Maximum="100" Value="{Binding TraceDetail}" TickFrequency="1" IsSnapToTickEnabled="True"
+ ToolTip.Tip="{DynamicResource presets.trace_detail_hint}" />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+
<!-- PDF options (render settings also apply when a PDF is converted to images) -->
<Border Classes="card" Padding="14" IsVisible="{Binding ShowPdf}">
<StackPanel Spacing="10">
diff --git a/src/Filee.Core/Conversion/RoutePlanner.cs b/src/Filee.Core/Conversion/RoutePlanner.cs
index 0b923e31..29b1e732 100644
--- a/src/Filee.Core/Conversion/RoutePlanner.cs
+++ b/src/Filee.Core/Conversion/RoutePlanner.cs
@@ -18,8 +18,8 @@ public sealed class RoutePlanner
/// <summary>Maximum number of hops. Longer chains are almost always lossy and slow.</summary>
public const int MaxSteps = 3;
- private readonly IReadOnlyList<IConverter> _converters;
- private readonly Func<IConverter, int> _priorityPenalty;
+ /// <summary>Every edge with its cost (priority penalty included), by source format.</summary>
+ private readonly Dictionary<string, List<(IConverter Converter, ConversionEdge Edge, int Cost)>> _edgesFrom;
/// <param name="converters">Converters that are currently available.</param>
/// <param name="priorityPenalty">
@@ -28,8 +28,12 @@ public sealed class RoutePlanner
/// </param>
public RoutePlanner(IEnumerable<IConverter> converters, Func<IConverter, int>? priorityPenalty = null)
{
- _converters = converters.ToList();
- _priorityPenalty = priorityPenalty ?? (_ => 0);
+ var penalty = priorityPenalty ?? (_ => 0);
+ _edgesFrom = converters
+ .SelectMany(c => c.Edges.Select(e =>
+ (c, e with { From = e.From.ToLowerInvariant(), To = e.To.ToLowerInvariant() }, e.Cost + penalty(c))))
+ .GroupBy(e => e.Item2.From)
+ .ToDictionary(g => g.Key, g => g.ToList());
}
/// <summary>Returns the cheapest route, or <c>null</c> if the conversion is impossible.</summary>
@@ -41,8 +45,8 @@ public sealed class RoutePlanner
// Same-format "conversions" (re-encode, split, compress) must use an explicit self edge.
if (from == to)
{
- var best = AllEdges()
- .Where(e => e.Edge.From == from && e.Edge.To == to)
+ var best = EdgesFrom(from)
+ .Where(e => e.Edge.To == to)
.OrderBy(e => e.Cost)
.FirstOrDefault();
return best.Converter is null
@@ -50,9 +54,7 @@ public sealed class RoutePlanner
: new Route([new RouteStep(best.Converter, from, to)], best.Cost);
}
- // Dijkstra over formats. The graph is tiny (dozens of nodes), so a simple list-based
- // priority queue is fine and easy to read.
- var edges = AllEdges().Where(e => e.Edge.From != e.Edge.To).ToList();
+ // Dijkstra over formats. The graph is small (a few hundred nodes).
var dist = new Dictionary<string, int> { [from] = 0 };
var prev = new Dictionary<string, (string Node, RouteStep Step)>();
var hops = new Dictionary<string, int> { [from] = 0 };
@@ -68,8 +70,10 @@ public sealed class RoutePlanner
if (hops[node] >= MaxSteps)
continue;
- foreach (var (converter, edge, edgeCost) in edges.Where(e => e.Edge.From == node))
+ foreach (var (converter, edge, edgeCost) in EdgesFrom(node))
{
+ if (edge.To == edge.From)
+ continue;
var next = cost + edgeCost;
if (dist.TryGetValue(edge.To, out var known) && known <= next)
continue;
@@ -94,7 +98,6 @@ public sealed class RoutePlanner
/// <summary>True if <paramref name="from"/> can be converted to <paramref name="to"/>.</summary>
public bool CanConvert(string from, string to) => Plan(from, to) is not null;
- private IEnumerable<(IConverter Converter, ConversionEdge Edge, int Cost)> AllEdges() =>
- _converters.SelectMany(c => c.Edges.Select(e =>
- (c, e with { From = e.From.ToLowerInvariant(), To = e.To.ToLowerInvariant() }, e.Cost + _priorityPenalty(c))));
+ private IReadOnlyList<(IConverter Converter, ConversionEdge Edge, int Cost)> EdgesFrom(string format) =>
+ _edgesFrom.TryGetValue(format, out var edges) ? edges : [];
}
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index 65fab5c3..6d0f7d2e 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -74,6 +74,18 @@ public static class BuiltInData
new() { Id = "to-html", Name = "HTML", TargetFormat = "html" },
.. SpreadsheetPresets(),
.. CatalogPresets(),
+ .. TracePresets(),
+ ];
+
+ /// <summary>Raster → SVG tracing, in colour and as black line art (added in settings schema 11).</summary>
+ public static List<Preset> TracePresets() =>
+ [
+ new() { Id = "trace-svg", NameKey = "preset.trace_svg", TargetFormat = "svg" },
+ new()
+ {
+ Id = "trace-line-art", NameKey = "preset.trace_line_art", TargetFormat = "svg",
+ Trace = { Mode = TracingMode.BlackAndWhite },
+ },
];
/// <summary>HWP as a target, through HWPX (added in settings schema 7, see SettingsMigrations).</summary>
@@ -172,7 +184,7 @@ public static class BuiltInData
{
Id = "images", NameKey = "profile.images",
Extensions = ExtensionsOf(FormatCategory.Image),
- PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "to-tiff", "to-bmp", "to-ico", "half-size"],
+ PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "trace-svg", "trace-line-art", "to-tiff", "to-bmp", "to-ico", "half-size"],
},
new()
{
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 8ef81e8a..3b949af6 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -38,6 +38,9 @@ public sealed class Preset
/// <summary>Options used for archives (ZIP, 7Z, TAR ...).</summary>
public ArchiveOptions Archive { get; set; } = new();
+ /// <summary>Options used when a raster image is traced into vector shapes (PNG → SVG, DXF ...).</summary>
+ public TracingOptions Trace { get; set; } = new();
+
/// <summary>Where and how output files are written.</summary>
public OutputRule Output { get; set; } = new();
@@ -56,6 +59,7 @@ public sealed class Preset
Document = Document.Clone(),
Media = Media.Clone(),
Archive = Archive.Clone(),
+ Trace = Trace.Clone(),
Output = Output.Clone(),
};
}
@@ -276,3 +280,32 @@ public sealed class ArchiveOptions
public ArchiveOptions Clone() => (ArchiveOptions)MemberwiseClone();
}
+
+/// <summary>How a raster image is traced.</summary>
+public enum TracingMode
+{
+ /// <summary>The image is reduced to <see cref="TracingOptions.Colors"/> colours, each traced as stacked shapes.</summary>
+ Color,
+ /// <summary>Dark pixels become black shapes on a transparent background (logos, signatures, scans).</summary>
+ BlackAndWhite,
+}
+
+/// <summary>Raster → vector tracing options.</summary>
+public sealed class TracingOptions
+{
+ /// <summary>Smallest and largest <see cref="Colors"/>.</summary>
+ public const int MinColors = 2, MaxColors = 64;
+
+ public TracingMode Mode { get; set; } = TracingMode.Color;
+
+ /// <summary>Number of colours in <see cref="TracingMode.Color"/> mode (2–64).</summary>
+ public int Colors { get; set; } = 16;
+
+ /// <summary>
+ /// 0–100: low values smooth the outlines and drop specks, high values follow the pixels more closely and keep
+ /// small details.
+ /// </summary>
+ public int Detail { get; set; } = 50;
+
+ public TracingOptions Clone() => (TracingOptions)MemberwiseClone();
+}
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 7e4f98ea..4df29b84 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;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index ae92ef14..4b3a18ee 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -360,6 +360,19 @@ internal static class SettingsMigrations
presets.Add(BuiltInData.CreatePresets().Single(p => p.Id == "remove-background"));
changed = true;
}
+
+ // v11: raster → SVG tracing ("Trace to SVG" in colour, "Line art to SVG" in black), on the images donut after
+ // PDF.
+ if (from < 11)
+ {
+ foreach (var preset in BuiltInData.TracePresets().Where(p => presets.All(existing => existing.Id != p.Id)))
+ {
+ presets.Add(preset);
+ changed = true;
+ }
+ changed |= Offer(presets, profiles, "images", "trace-svg", "to-pdf");
+ changed |= Offer(presets, profiles, "images", "trace-line-art", "trace-svg");
+ }
return changed;
}
diff --git a/src/Filee.Engines/Vector/OutlinedTextPlayback.cs b/src/Filee.Engines/Vector/OutlinedTextPlayback.cs
index 79494975..ff380c8f 100644
--- a/src/Filee.Engines/Vector/OutlinedTextPlayback.cs
+++ b/src/Filee.Engines/Vector/OutlinedTextPlayback.cs
@@ -36,43 +36,68 @@ internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
private void Draw(CanvasCommand command, SKCanvas canvas)
{
- var handled = command switch
+ if (command is DrawPictureCanvasCommand { Picture: { } nested })
{
- DrawPictureCanvasCommand { Picture: { } nested } => DrawNested(nested, canvas),
- DrawTextCanvasCommand text => DrawText(text, canvas),
- DrawTextBlobCanvasCommand blob => DrawTextBlob(blob, canvas),
- DrawPositionedTextRunCanvasCommand run => DrawPositionedRun(run, canvas),
- _ => false,
- };
+ Draw(nested, canvas);
+ return;
+ }
// Everything else, and text that can't be shaped (text on a path, fonts without outlines), is drawn by
// Svg.Skia itself.
- if (!handled)
+ using var outline = TextOutline(command, out var shimPaint);
+ if (outline is null)
+ {
model.Draw(command, canvas);
+ return;
+ }
+ // The outlines with the text's paint (fill or stroke, colour, gradient, opacity).
+ using var paint = shimPaint is null ? null : model.ToSKPaint(shimPaint);
+ if (paint is not null && !outline.IsEmpty)
+ canvas.DrawPath(outline, paint);
}
- private bool DrawNested(ShimSkiaSharp.SKPicture picture, SKCanvas canvas)
+ /// <summary>
+ /// The glyph outlines of a text command, in the command's coordinates, with the text's paint; <c>null</c> when the
+ /// command is no text or its text can't be shaped. Empty text gives an empty path.
+ /// </summary>
+ public SKPath? TextOutline(CanvasCommand command, out SKPaint? paint)
{
- Draw(picture, canvas);
- return true;
+ paint = command switch
+ {
+ DrawTextCanvasCommand text => text.Paint,
+ DrawTextBlobCanvasCommand blob => blob.Paint,
+ DrawPositionedTextRunCanvasCommand run => run.Paint,
+ _ => null,
+ };
+ if (paint is null)
+ return null;
+ var path = new SKPath();
+ var shaped = command switch
+ {
+ DrawTextCanvasCommand text => OutlineText(text, path),
+ DrawTextBlobCanvasCommand blob => OutlineTextBlob(blob, path),
+ DrawPositionedTextRunCanvasCommand run => OutlinePositionedRun(run, path),
+ _ => false,
+ };
+ if (shaped)
+ return path;
+ path.Dispose();
+ return null;
}
- private bool DrawText(DrawTextCanvasCommand command, SKCanvas canvas)
+ private bool OutlineText(DrawTextCanvasCommand command, SKPath path)
{
- if (command.Paint is null || string.IsNullOrEmpty(command.Text))
- return command.Paint is not null;
- using var font = command.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint);
- var align = model.ToSKTextAlign(command.TextAlign ?? command.Paint.TextAlign);
- using var path = new SKPath();
- if (font?.Typeface is null || !AppendShaped(path, command.Text, font, command.X, command.Y, align))
- return false;
- return Fill(canvas, path, command.Paint);
+ if (string.IsNullOrEmpty(command.Text))
+ return true;
+ using var font = command.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint!);
+ var align = model.ToSKTextAlign(command.TextAlign ?? command.Paint!.TextAlign);
+ return font?.Typeface is not null && AppendShaped(path, command.Text, font, command.X, command.Y, align);
}
- private bool DrawTextBlob(DrawTextBlobCanvasCommand command, SKCanvas canvas)
+ private bool OutlineTextBlob(DrawTextBlobCanvasCommand command, SKPath path)
{
- if (command.Paint is null || command.TextBlob?.Points is not { } points)
- return command.Paint is not null;
- using var font = command.TextBlob.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint);
+ if (command.TextBlob?.Points is not { } points)
+ return true;
+ using var font = command.TextBlob.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint!);
if (font is null)
return false;
var glyphs = command.TextBlob.Glyphs is { Length: > 0 } ids ? ids
@@ -80,21 +105,19 @@ internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
: [];
if (glyphs.Length != points.Length)
return false;
- using var path = new SKPath();
for (var i = 0; i < glyphs.Length; i++)
AppendGlyph(path, font, glyphs[i], command.X + points[i].X, command.Y + points[i].Y);
- return Fill(canvas, path, command.Paint);
+ return true;
}
- private bool DrawPositionedRun(DrawPositionedTextRunCanvasCommand command, SKCanvas canvas)
+ private bool OutlinePositionedRun(DrawPositionedTextRunCanvasCommand command, SKPath path)
{
- if (command.Paint is null || command.Fragments is not { Count: > 0 })
- return command.Paint is not null;
- using var font = command.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint);
+ if (command.Fragments is not { Count: > 0 })
+ return true;
+ using var font = command.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint!);
if (font?.Typeface is null)
return false;
- var align = model.ToSKTextAlign(command.TextAlign ?? command.Paint.TextAlign);
- using var path = new SKPath();
+ var align = model.ToSKTextAlign(command.TextAlign ?? command.Paint!.TextAlign);
foreach (var fragment in command.Fragments)
{
using var part = new SKPath();
@@ -109,15 +132,6 @@ internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
part.Transform(transform);
path.AddPath(part);
}
- return Fill(canvas, path, command.Paint);
- }
-
- /// <summary>Draws the outlines with the text's paint (fill or stroke, colour, gradient, opacity).</summary>
- private bool Fill(SKCanvas canvas, SKPath path, SKPaint shimPaint)
- {
- using var paint = model.ToSKPaint(shimPaint);
- if (paint is not null && !path.IsEmpty)
- canvas.DrawPath(path, paint);
return true;
}
diff --git a/src/Filee.Engines/Vector/SvgDxfWriter.cs b/src/Filee.Engines/Vector/SvgDxfWriter.cs
new file mode 100644
index 00000000..f09844b0
--- /dev/null
+++ b/src/Filee.Engines/Vector/SvgDxfWriter.cs
@@ -0,0 +1,316 @@
+// SVG → DXF: the drawing's outlines as CAD geometry, written with ACadSharp (MIT).
+//
+// The SVG is loaded with Svg.Skia like for PDF output, so groups, transforms, <use>, nested <svg> and CSS are resolved
+// the same way. Its drawing commands are replayed on a canvas that draws nothing (Svg.Skia keeps track of the
+// transforms) and every shape becomes outlines:
+// - circles and ellipses become CIRCLE and ELLIPSE entities (an ellipse also when a transform skews a circle);
+// - everything else (paths, lines, polylines, polygons, rectangles, rounded corners, arcs) becomes LWPOLYLINEs,
+// closed where the shape is closed, or a LINE for a single straight segment; Bézier curves and arcs are divided
+// into straight pieces that stay within 0.01 mm of the curve, which every CAD and CAM program reads;
+// - text becomes its glyph outlines.
+// Colours are kept as true colours (the stroke's, else the fill's); fills, stroke widths, gradients, clipping, masks,
+// images and filters are not represented.
+//
+// Units: SVG user units are CSS pixels, 96 per inch, so 1 px = 25.4 / 96 mm and the DXF is in millimetres ($INSUNITS
+// 4): a drawing made 100 mm wide in an SVG editor is 100 mm wide in CAD. SVG's y axis points down and DXF's up, so
+// y is flipped, with the bottom-left corner of the SVG's viewport at (0, 0).
+
+using ACadSharp;
+using ACadSharp.Entities;
+using ACadSharp.Header;
+using ACadSharp.Types.Units;
+using CSMath;
+using Filee.Engines.Cad;
+using ShimSkiaSharp;
+using SkiaSharp;
+using SKCanvas = SkiaSharp.SKCanvas;
+using SKMatrix = SkiaSharp.SKMatrix;
+using SKPath = SkiaSharp.SKPath;
+using SKPoint = SkiaSharp.SKPoint;
+using SKRect = SkiaSharp.SKRect;
+
+namespace Filee.Engines.Vector;
+
+/// <summary>Writes the outlines of an SVG drawing as a DXF.</summary>
+internal sealed class SvgDxfWriter
+{
+ /// <summary>Millimetres per CSS pixel (96 per inch).</summary>
+ public const double MillimetresPerPixel = 25.4 / 96;
+
+ /// <summary>Largest distance, in millimetres, between a curve and the straight pieces that replace it.</summary>
+ public const double FlatnessMillimetres = 0.01;
+
+ private const int MaxPiecesPerCurve = 512;
+
+ private readonly CadDocument _document = new();
+ private readonly SvgRenderer.Drawing _drawing;
+ private readonly SKRect _bounds;
+ private readonly double _flatness = FlatnessMillimetres / MillimetresPerPixel;
+ private readonly CancellationToken _ct;
+
+ private SvgDxfWriter(SvgRenderer.Drawing drawing, CancellationToken ct)
+ {
+ _drawing = drawing;
+ _bounds = drawing.Bounds;
+ _ct = ct;
+ _document.Header.InsUnits = UnitsType.Millimeters;
+ _document.Header.MeasurementUnits = MeasurementUnits.Metric;
+ }
+
+ /// <summary>Number of entities written (for tests and the log).</summary>
+ public int EntityCount { get; private set; }
+
+ /// <summary>Writes <paramref name="drawing"/> to <paramref name="output"/> as DXF (AutoCAD 2018).</summary>
+ /// <exception cref="InvalidDataException">The drawing has no outlines to write.</exception>
+ public static void Write(SvgRenderer.Drawing drawing, string output, CancellationToken ct)
+ {
+ var writer = new SvgDxfWriter(drawing, ct);
+ writer.Collect();
+ if (writer.EntityCount == 0)
+ throw new InvalidDataException("The SVG has no shapes that can be written as CAD geometry (only images or empty groups).");
+ CadFile.Write(writer._document, output, "dxf");
+ }
+
+ private void Collect()
+ {
+ if (_drawing.Svg.Model is not { } picture || _drawing.Svg.SkiaModel is not { } model)
+ return;
+ using var canvas = new SKNoDrawCanvas((int)Math.Ceiling(_bounds.Right) + 1, (int)Math.Ceiling(_bounds.Bottom) + 1);
+ using var text = new OutlinedTextPlayback(model);
+ Replay(picture, canvas, model, text);
+ }
+
+ private void Replay(ShimSkiaSharp.SKPicture picture, SKCanvas canvas, Svg.Skia.SkiaModel model, OutlinedTextPlayback text)
+ {
+ if (picture.Commands is null)
+ return;
+ ShimSkiaSharp.SKPath? previous = null;
+ var previousMatrix = SKMatrix.Identity;
+ foreach (var command in picture.Commands)
+ {
+ _ct.ThrowIfCancellationRequested();
+ switch (command)
+ {
+ case DrawPathCanvasCommand { Path: { } path } draw:
+ // A shape with fill and stroke is drawn twice: write its outline once.
+ var matrix = canvas.TotalMatrix;
+ if (!ReferenceEquals(path, previous) || !matrix.Equals(previousMatrix))
+ AddPath(path, matrix, model, ColorOf(draw.Paint));
+ previous = path;
+ previousMatrix = matrix;
+ break;
+ case DrawPictureCanvasCommand { Picture: { } nested }:
+ canvas.Save();
+ Replay(nested, canvas, model, text);
+ canvas.Restore();
+ break;
+ case DrawTextCanvasCommand or DrawTextBlobCanvasCommand or DrawPositionedTextRunCanvasCommand:
+ using (var outline = text.TextOutline(command, out var paint))
+ {
+ if (outline is { IsEmpty: false })
+ {
+ outline.Transform(canvas.TotalMatrix);
+ AddOutlines(outline, ColorOf(paint));
+ }
+ }
+ break;
+ case SaveCanvasCommand or SaveLayerCanvasCommand or RestoreCanvasCommand or SetMatrixCanvasCommand:
+ model.Draw(command, canvas);
+ break;
+ // Clips, images and text on a path have no outline to write.
+ }
+ }
+ }
+
+ /// <summary>The colour of a paint as a DXF true colour; black for gradients and patterns.</summary>
+ private static Color ColorOf(ShimSkiaSharp.SKPaint? paint) =>
+ paint?.Shader is null && paint?.Color is { } color
+ ? new Color(color.Red, color.Green, color.Blue)
+ : new Color(0, 0, 0);
+
+ private void AddPath(ShimSkiaSharp.SKPath path, SKMatrix matrix, Svg.Skia.SkiaModel model, Color color)
+ {
+ using var rest = new SKPath();
+ foreach (var command in path.Commands ?? [])
+ {
+ switch (command)
+ {
+ case AddCirclePathCommand circle:
+ AddEllipse(circle.X, circle.Y, circle.Radius, circle.Radius, matrix, color);
+ break;
+ case AddOvalPathCommand oval:
+ AddEllipse((oval.Rect.Left + oval.Rect.Right) / 2, (oval.Rect.Top + oval.Rect.Bottom) / 2, oval.Rect.Width / 2, oval.Rect.Height / 2, matrix, color);
+ break;
+ default:
+ model.ToSKPath(command, rest);
+ break;
+ }
+ }
+ if (rest.IsEmpty)
+ return;
+ rest.Transform(matrix);
+ AddOutlines(rest, color);
+ }
+
+ // ───────────────────────── Circles and ellipses ─────────────────────────
+
+ /// <summary>
+ /// An axis-aligned ellipse (centre, radii) of the drawing, transformed by <paramref name="matrix"/>: its image is
+ /// an ellipse whose axes come from the singular values of the transformed radius vectors.
+ /// </summary>
+ private void AddEllipse(float cx, float cy, float rx, float ry, SKMatrix matrix, Color color)
+ {
+ if (rx <= 0 || ry <= 0)
+ return;
+ var center = matrix.MapPoint(cx, cy);
+ // Conjugate semi-diameters after the transform (the linear part only).
+ double ux = matrix.ScaleX * rx, uy = matrix.SkewY * rx;
+ double vx = matrix.SkewX * ry, vy = matrix.ScaleY * ry;
+ double a = ux * ux + vx * vx, b = ux * uy + vx * vy, c = uy * uy + vy * vy;
+ var root = Math.Sqrt((a - c) * (a - c) / 4 + b * b);
+ var major = Math.Sqrt(Math.Max(0, (a + c) / 2 + root));
+ var minor = Math.Sqrt(Math.Max(0, (a + c) / 2 - root));
+ if (major <= 1e-9)
+ return;
+ var centre = ToDxf(center.X, center.Y);
+ if (minor / major > 1 - 1e-6)
+ {
+ Add(new Circle { Center = centre, Radius = major * MillimetresPerPixel, Color = color });
+ return;
+ }
+ var angle = 0.5 * Math.Atan2(2 * b, a - c);
+ // The y flip mirrors the axis direction.
+ var axis = new XYZ(Math.Cos(angle) * major * MillimetresPerPixel, -Math.Sin(angle) * major * MillimetresPerPixel, 0);
+ Add(new Ellipse
+ {
+ Center = centre,
+ MajorAxisEndPoint = axis,
+ RadiusRatio = minor / major,
+ StartParameter = 0,
+ EndParameter = 2 * Math.PI,
+ Color = color,
+ });
+ }
+
+ // ───────────────────────── Outlines ─────────────────────────
+
+ /// <summary>Adds every subpath of <paramref name="path"/> (already in drawing coordinates) as a polyline.</summary>
+ private void AddOutlines(SKPath path, Color color)
+ {
+ using var iterator = path.CreateRawIterator();
+ var points = new SKPoint[4];
+ var current = new List<SKPoint>();
+ SKPathVerb verb;
+ while ((verb = iterator.Next(points)) != SKPathVerb.Done)
+ {
+ switch (verb)
+ {
+ case SKPathVerb.Move:
+ Flush(current, closed: false, color);
+ current.Add(points[0]);
+ break;
+ case SKPathVerb.Line:
+ current.Add(points[1]);
+ break;
+ case SKPathVerb.Quad:
+ AddQuad(current, points[0], points[1], points[2]);
+ break;
+ case SKPathVerb.Conic:
+ foreach (var quad in ConicToQuads(points[0], points[1], points[2], iterator.ConicWeight()))
+ AddQuad(current, quad.A, quad.B, quad.C);
+ break;
+ case SKPathVerb.Cubic:
+ AddCubic(current, points[0], points[1], points[2], points[3]);
+ break;
+ case SKPathVerb.Close:
+ var start = current.Count > 0 ? current[0] : default;
+ Flush(current, closed: true, color);
+ current.Add(start);
+ break;
+ }
+ }
+ Flush(current, closed: false, color);
+ }
+
+ private void AddQuad(List<SKPoint> points, SKPoint p0, SKPoint p1, SKPoint p2)
+ {
+ var bend = Distance(p0.X - 2 * p1.X + p2.X, p0.Y - 2 * p1.Y + p2.Y);
+ var pieces = Pieces(bend / 4);
+ for (var i = 1; i <= pieces; i++)
+ {
+ var t = i / (double)pieces;
+ var mt = 1 - t;
+ points.Add(new SKPoint((float)(mt * mt * p0.X + 2 * mt * t * p1.X + t * t * p2.X),
+ (float)(mt * mt * p0.Y + 2 * mt * t * p1.Y + t * t * p2.Y)));
+ }
+ }
+
+ private void AddCubic(List<SKPoint> points, SKPoint p0, SKPoint p1, SKPoint p2, SKPoint p3)
+ {
+ // A chord of a curve divided into n equal parameter steps is off by at most 1/8 · max|B''| / n², and
+ // max|B''| ≤ 6 · the largest second difference of the control points.
+ var bend = Math.Max(Distance(p0.X - 2 * p1.X + p2.X, p0.Y - 2 * p1.Y + p2.Y),
+ Distance(p1.X - 2 * p2.X + p3.X, p1.Y - 2 * p2.Y + p3.Y));
+ var pieces = Pieces(bend * 0.75);
+ for (var i = 1; i <= pieces; i++)
+ {
+ var t = i / (double)pieces;
+ var mt = 1 - t;
+ double b0 = mt * mt * mt, b1 = 3 * mt * mt * t, b2 = 3 * mt * t * t, b3 = t * t * t;
+ points.Add(new SKPoint((float)(b0 * p0.X + b1 * p1.X + b2 * p2.X + b3 * p3.X),
+ (float)(b0 * p0.Y + b1 * p1.Y + b2 * p2.Y + b3 * p3.Y)));
+ }
+ }
+
+ /// <summary>Pieces needed when a single chord would be off by <paramref name="deviation"/> pixels.</summary>
+ private int Pieces(double deviation) =>
+ Math.Clamp((int)Math.Ceiling(Math.Sqrt(deviation / _flatness)), 1, MaxPiecesPerCurve);
+
+ private static List<(SKPoint A, SKPoint B, SKPoint C)> ConicToQuads(SKPoint p0, SKPoint p1, SKPoint p2, float weight)
+ {
+ var quads = SKPath.ConvertConicToQuads(p0, p1, p2, weight, 4);
+ var result = new List<(SKPoint, SKPoint, SKPoint)>();
+ for (var i = 0; i + 2 < quads.Length; i += 2)
+ result.Add((quads[i], quads[i + 1], quads[i + 2]));
+ return result;
+ }
+
+ private static double Distance(double x, double y) => Math.Sqrt(x * x + y * y);
+
+ /// <summary>Writes the collected points as one entity and clears them.</summary>
+ private void Flush(List<SKPoint> points, bool closed, Color color)
+ {
+ // Repeated points (zero-length pieces) mean nothing in CAD.
+ var clean = new List<XYZ>(points.Count);
+ foreach (var point in points)
+ {
+ var p = ToDxf(point.X, point.Y);
+ if (clean.Count == 0 || !Near(clean[^1], p))
+ clean.Add(p);
+ }
+ points.Clear();
+ if (closed && clean.Count > 2 && Near(clean[0], clean[^1]))
+ clean.RemoveAt(clean.Count - 1);
+ if (clean.Count < 2)
+ return;
+ if (clean.Count == 2 && !closed)
+ {
+ Add(new Line(clean[0], clean[1]) { Color = color });
+ return;
+ }
+ var polyline = new LwPolyline(clean.Select(p => new LwPolyline.Vertex(p.X, p.Y))) { IsClosed = closed, Color = color };
+ Add(polyline);
+ }
+
+ private static bool Near(XYZ a, XYZ b) => Math.Abs(a.X - b.X) < 1e-6 && Math.Abs(a.Y - b.Y) < 1e-6;
+
+ /// <summary>Drawing coordinates (CSS pixels, y down) → DXF (millimetres, y up, viewport's bottom-left at 0, 0).</summary>
+ private XYZ ToDxf(double x, double y) =>
+ new((x - _bounds.Left) * MillimetresPerPixel, (_bounds.Bottom - y) * MillimetresPerPixel, 0);
+
+ private void Add(Entity entity)
+ {
+ _document.Entities.Add(entity);
+ EntityCount++;
+ }
+}
diff --git a/src/Filee.Engines/Vector/Tracing/ColorRegions.cs b/src/Filee.Engines/Vector/Tracing/ColorRegions.cs
new file mode 100644
index 00000000..e60a3670
--- /dev/null
+++ b/src/Filee.Engines/Vector/Tracing/ColorRegions.cs
@@ -0,0 +1,370 @@
+// Colour mode, before outlines are traced: the picture is reduced to a few colours (k-means) and cleaned up, so each
+// colour forms regions worth an outline.
+//
+// 1. Quantization: every opaque pixel goes into one of 32 768 boxes (5 bits per channel). k-means runs on the boxes'
+// mean colours weighted by their pixel counts, so it sees every pixel at a fraction of the cost; the start
+// colours are picked greedily by weight × squared distance to the colours already picked (deterministic).
+// 2. Edge bands: anti-aliasing leaves one-pixel bands of in-between colours along every edge. A pixel of a band
+// whose colour lies between the colours on either side joins the closer of the two; thin lines of a colour of
+// their own are kept.
+// 3. Small regions: connected regions (4-connected) smaller than the minimum join the neighbouring region they
+// share the longest border with, smallest first.
+
+namespace Filee.Engines.Vector.Tracing;
+
+/// <summary>Colour quantization and region cleanup for colour tracing.</summary>
+internal static class ColorRegions
+{
+ /// <summary>Label of transparent pixels.</summary>
+ public const byte Transparent = 255;
+
+ /// <summary>Pixels less opaque than this are transparent.</summary>
+ public const byte OpaqueAlpha = 128;
+
+ private const int MaxIterations = 24;
+
+ /// <summary>
+ /// Reduces the RGBA pixels to at most <paramref name="colors"/> colours. Returns the palette (0xRRGGBB) and one
+ /// label per pixel: an index into the palette, or <see cref="Transparent"/>.
+ /// </summary>
+ public static (int[] Palette, byte[] Labels) Quantize(byte[] rgba, int width, int height, int colors, CancellationToken ct)
+ {
+ var pixelCount = width * height;
+ var counts = new long[32768];
+ var sums = new long[32768 * 3];
+ for (var p = 0; p < pixelCount; p++)
+ {
+ var o = p * 4;
+ if (rgba[o + 3] < OpaqueAlpha)
+ continue;
+ var box = Box(rgba[o], rgba[o + 1], rgba[o + 2]);
+ counts[box]++;
+ sums[box * 3] += rgba[o];
+ sums[box * 3 + 1] += rgba[o + 1];
+ sums[box * 3 + 2] += rgba[o + 2];
+ }
+ ct.ThrowIfCancellationRequested();
+
+ // The occupied boxes, as weighted points.
+ var boxes = new List<int>();
+ for (var b = 0; b < counts.Length; b++)
+ if (counts[b] > 0)
+ boxes.Add(b);
+ var labels = new byte[pixelCount];
+ if (boxes.Count == 0)
+ {
+ Array.Fill(labels, Transparent);
+ return ([], labels);
+ }
+ var points = new double[boxes.Count * 3];
+ var weights = new double[boxes.Count];
+ for (var i = 0; i < boxes.Count; i++)
+ {
+ var b = boxes[i];
+ weights[i] = counts[b];
+ for (var c = 0; c < 3; c++)
+ points[i * 3 + c] = sums[b * 3 + c] / (double)counts[b];
+ }
+
+ var k = Math.Min(colors, boxes.Count);
+ var centers = InitialCenters(points, weights, k);
+ var assignment = new int[boxes.Count];
+ Array.Fill(assignment, -1);
+ for (var iteration = 0; iteration < MaxIterations; iteration++)
+ {
+ ct.ThrowIfCancellationRequested();
+ var changed = false;
+ for (var i = 0; i < boxes.Count; i++)
+ {
+ var nearest = Nearest(centers, k, points[i * 3], points[i * 3 + 1], points[i * 3 + 2]);
+ if (nearest != assignment[i])
+ {
+ assignment[i] = nearest;
+ changed = true;
+ }
+ }
+ if (!changed)
+ break;
+ Recenter(points, weights, assignment, centers, k);
+ }
+ Recenter(points, weights, assignment, centers, k);
+
+ // Drop colours nothing was assigned to and build the palette.
+ var used = new bool[k];
+ foreach (var a in assignment)
+ used[a] = true;
+ var remap = new int[k];
+ var palette = new List<int>();
+ for (var c = 0; c < k; c++)
+ {
+ if (!used[c])
+ continue;
+ remap[c] = palette.Count;
+ palette.Add((ToByte(centers[c * 3]) << 16) | (ToByte(centers[c * 3 + 1]) << 8) | ToByte(centers[c * 3 + 2]));
+ }
+
+ // Every pixel takes its box's colour.
+ var boxLabel = new byte[32768];
+ for (var i = 0; i < boxes.Count; i++)
+ boxLabel[boxes[i]] = (byte)remap[assignment[i]];
+ for (var p = 0; p < pixelCount; p++)
+ {
+ var o = p * 4;
+ labels[p] = rgba[o + 3] < OpaqueAlpha ? Transparent : boxLabel[Box(rgba[o], rgba[o + 1], rgba[o + 2])];
+ }
+ return ([.. palette], labels);
+ }
+
+ private static int Box(byte r, byte g, byte b) => ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
+
+ private static int ToByte(double value) => (int)Math.Clamp(Math.Round(value), 0, 255);
+
+ private static double[] InitialCenters(double[] points, double[] weights, int k)
+ {
+ var count = weights.Length;
+ var centers = new double[k * 3];
+ var distance = new double[count];
+ Array.Fill(distance, double.MaxValue);
+ // The most common colour first, then each time the colour with the largest weight × squared distance.
+ var pick = 0;
+ for (var i = 1; i < count; i++)
+ if (weights[i] > weights[pick])
+ pick = i;
+ for (var c = 0; c < k; c++)
+ {
+ for (var j = 0; j < 3; j++)
+ centers[c * 3 + j] = points[pick * 3 + j];
+ var best = -1.0;
+ var next = 0;
+ for (var i = 0; i < count; i++)
+ {
+ var d = Distance(points, i, centers, c);
+ if (d < distance[i])
+ distance[i] = d;
+ var score = distance[i] * weights[i];
+ if (score > best)
+ {
+ best = score;
+ next = i;
+ }
+ }
+ pick = next;
+ }
+ return centers;
+ }
+
+ private static void Recenter(double[] points, double[] weights, int[] assignment, double[] centers, int k)
+ {
+ var sums = new double[k * 3];
+ var totals = new double[k];
+ for (var i = 0; i < assignment.Length; i++)
+ {
+ var c = assignment[i];
+ totals[c] += weights[i];
+ for (var j = 0; j < 3; j++)
+ sums[c * 3 + j] += points[i * 3 + j] * weights[i];
+ }
+ for (var c = 0; c < k; c++)
+ {
+ if (totals[c] <= 0)
+ continue;
+ for (var j = 0; j < 3; j++)
+ centers[c * 3 + j] = sums[c * 3 + j] / totals[c];
+ }
+ }
+
+ private static int Nearest(double[] centers, int k, double r, double g, double b)
+ {
+ var best = 0;
+ var bestDistance = double.MaxValue;
+ for (var c = 0; c < k; c++)
+ {
+ double dr = centers[c * 3] - r, dg = centers[c * 3 + 1] - g, db = centers[c * 3 + 2] - b;
+ var d = dr * dr + dg * dg + db * db;
+ if (d < bestDistance)
+ {
+ bestDistance = d;
+ best = c;
+ }
+ }
+ return best;
+ }
+
+ private static double Distance(double[] points, int i, double[] centers, int c)
+ {
+ double dr = points[i * 3] - centers[c * 3], dg = points[i * 3 + 1] - centers[c * 3 + 1], db = points[i * 3 + 2] - centers[c * 3 + 2];
+ return dr * dr + dg * dg + db * db;
+ }
+
+ // ───────────────────────── Edge bands ─────────────────────────
+
+ /// <summary>
+ /// Pixels in one-pixel bands between two other colours join the closer side when their own colour lies between
+ /// the two (anti-aliasing), so edges between colours don't get a sliver shape of their own.
+ /// </summary>
+ public static void MergeEdgeBands(byte[] labels, byte[] rgba, int[] palette, int width, int height)
+ {
+ var source = (byte[])labels.Clone();
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ var p = y * width + x;
+ var own = source[p];
+ if (own == Transparent)
+ continue;
+ int a = -1, b = -1;
+ var up = y > 0 ? source[p - width] : Transparent;
+ var down = y < height - 1 ? source[p + width] : Transparent;
+ var left = x > 0 ? source[p - 1] : Transparent;
+ var right = x < width - 1 ? source[p + 1] : Transparent;
+ if (up != own && down != own && up != Transparent && down != Transparent && up != down)
+ (a, b) = (up, down);
+ else if (left != own && right != own && left != Transparent && right != Transparent && left != right)
+ (a, b) = (left, right);
+ if (a < 0 || !IsBetween(palette[own], palette[a], palette[b]))
+ continue;
+ var o = p * 4;
+ var pixel = (rgba[o] << 16) | (rgba[o + 1] << 8) | rgba[o + 2];
+ labels[p] = (byte)(ColorDistance(pixel, palette[a]) <= ColorDistance(pixel, palette[b]) ? a : b);
+ }
+ }
+ }
+
+ /// <summary>True when colour <paramref name="c"/> lies roughly on the way from <paramref name="a"/> to <paramref name="b"/>.</summary>
+ internal static bool IsBetween(int c, int a, int b)
+ {
+ double ar = a >> 16, ag = (a >> 8) & 255, ab = a & 255;
+ double dr = (b >> 16) - ar, dg = ((b >> 8) & 255) - ag, db = (b & 255) - ab;
+ double cr = (c >> 16) - ar, cg = ((c >> 8) & 255) - ag, cb = (c & 255) - ab;
+ var length2 = dr * dr + dg * dg + db * db;
+ if (length2 < 1)
+ return false;
+ var t = (cr * dr + cg * dg + cb * db) / length2;
+ if (t is < 0.08 or > 0.92)
+ return false;
+ double er = cr - t * dr, eg = cg - t * dg, eb = cb - t * db;
+ return er * er + eg * eg + eb * eb < 0.09 * length2;
+ }
+
+ private static int ColorDistance(int x, int y)
+ {
+ int dr = (x >> 16) - (y >> 16), dg = ((x >> 8) & 255) - ((y >> 8) & 255), db = (x & 255) - (y & 255);
+ return dr * dr + dg * dg + db * db;
+ }
+
+ // ───────────────────────── Small regions ─────────────────────────
+
+ /// <summary>
+ /// Regions (4-connected pixels of one label) smaller than <paramref name="minRegion"/> pixels join the neighbour
+ /// they share the longest border with (the closer colour on a tie), smallest regions first.
+ /// </summary>
+ public static void MergeSmallRegions(byte[] labels, int[] palette, int width, int height, int minRegion, CancellationToken ct)
+ {
+ if (minRegion <= 1)
+ return;
+ var pixelCount = width * height;
+ var region = new int[pixelCount];
+ Array.Fill(region, -1);
+ var regionLabel = new List<byte>();
+ var regionArea = new List<int>();
+ var regionSeed = new List<int>();
+ var stack = new Stack<int>();
+
+ for (var start = 0; start < pixelCount; start++)
+ {
+ if (region[start] >= 0)
+ continue;
+ if ((start & 0xFFFF) == 0)
+ ct.ThrowIfCancellationRequested();
+ var id = regionLabel.Count;
+ var label = labels[start];
+ regionLabel.Add(label);
+ regionSeed.Add(start);
+ var area = 0;
+ region[start] = id;
+ stack.Push(start);
+ while (stack.Count > 0)
+ {
+ var p = stack.Pop();
+ area++;
+ int x = p % width, y = p / width;
+ if (x > 0 && region[p - 1] < 0 && labels[p - 1] == label) { region[p - 1] = id; stack.Push(p - 1); }
+ if (x < width - 1 && region[p + 1] < 0 && labels[p + 1] == label) { region[p + 1] = id; stack.Push(p + 1); }
+ if (y > 0 && region[p - width] < 0 && labels[p - width] == label) { region[p - width] = id; stack.Push(p - width); }
+ if (y < height - 1 && region[p + width] < 0 && labels[p + width] == label) { region[p + width] = id; stack.Push(p + width); }
+ }
+ regionArea.Add(area);
+ }
+
+ var count = regionLabel.Count;
+ var parent = new int[count];
+ for (var i = 0; i < count; i++)
+ parent[i] = i;
+ int Find(int i)
+ {
+ while (parent[i] != i)
+ {
+ parent[i] = parent[parent[i]];
+ i = parent[i];
+ }
+ return i;
+ }
+
+ var small = Enumerable.Range(0, count).Where(i => regionArea[i] < minRegion).OrderBy(i => regionArea[i]).ToList();
+ var shared = new Dictionary<int, int>();
+ var seen = new HashSet<int>();
+ foreach (var id in small)
+ {
+ ct.ThrowIfCancellationRequested();
+ var root = Find(id);
+ if (regionArea[root] >= minRegion)
+ continue;
+
+ // The region's pixels (it may have taken in smaller ones) and how long a border it shares with each neighbour.
+ shared.Clear();
+ seen.Clear();
+ stack.Push(regionSeed[root]);
+ seen.Add(regionSeed[root]);
+ while (stack.Count > 0)
+ {
+ var p = stack.Pop();
+ int x = p % width, y = p / width;
+ Span<int> neighbours = [x > 0 ? p - 1 : -1, x < width - 1 ? p + 1 : -1, y > 0 ? p - width : -1, y < height - 1 ? p + width : -1];
+ foreach (var q in neighbours)
+ {
+ if (q < 0)
+ continue;
+ var other = Find(region[q]);
+ if (other == root)
+ {
+ if (seen.Add(q))
+ stack.Push(q);
+ }
+ else
+ {
+ shared[other] = shared.GetValueOrDefault(other) + 1;
+ }
+ }
+ }
+
+ var target = -1;
+ foreach (var (other, length) in shared)
+ {
+ if (target < 0 || length > shared[target]
+ || (length == shared[target] && LabelDistance(regionLabel[root], regionLabel[other], palette) < LabelDistance(regionLabel[root], regionLabel[target], palette)))
+ target = other;
+ }
+ if (target < 0)
+ continue; // the whole picture is one region
+ parent[root] = target;
+ regionArea[target] += regionArea[root];
+ }
+
+ for (var p = 0; p < pixelCount; p++)
+ labels[p] = regionLabel[Find(region[p])];
+ }
+
+ private static int LabelDistance(byte a, byte b, int[] palette) =>
+ a == Transparent || b == Transparent ? int.MaxValue : ColorDistance(palette[a], palette[b]);
+}
diff --git a/src/Filee.Engines/Vector/Tracing/CurveFitter.cs b/src/Filee.Engines/Vector/Tracing/CurveFitter.cs
new file mode 100644
index 00000000..66bc5058
--- /dev/null
+++ b/src/Filee.Engines/Vector/Tracing/CurveFitter.cs
@@ -0,0 +1,601 @@
+// Step 2 of tracing: a pixel outline becomes a smooth closed path of straight lines and cubic Béziers.
+//
+// 1. Sampling: the staircase of pixel edges is replaced by points on it. Short runs (the steps of a slanted or
+// curved edge) contribute their midpoint, which lies on the edge the pixels approximate; long runs contribute
+// points along themselves. A pixel corner between two long runs (a rectangle), and the two corners of a short
+// run between long ones that both turn the same way (the end of a thin line), stay corners.
+// 2. Corners: a point where the direction turns sharply within about two pixels, or turns less but all at once
+// (most of the turn seen four pixels either side already happens within two), which a small circle doesn't.
+// 3. Smoothing: points between corners are averaged with their neighbours (1-2-1) to calm the remaining jaggies.
+// 4. Straight stretches: runs of points that stay within half a pixel of a line and don't bend become lines.
+// 5. Fitting: the rest between corners and straight stretches becomes cubic Béziers fitted by least squares with
+// Newton–Raphson reparameterization, split where the error is largest (Philip J. Schneider, "An Algorithm for
+// Automatically Fitting Digitized Curves", Graphics Gems, 1990). Curves leave and join straight stretches in
+// their direction, and meet each other with matching tangents, except at corners.
+
+namespace Filee.Engines.Vector.Tracing;
+
+/// <summary>A 2D point or vector in pixels.</summary>
+internal readonly record struct Vec(double X, double Y)
+{
+ public static Vec operator +(Vec a, Vec b) => new(a.X + b.X, a.Y + b.Y);
+ public static Vec operator -(Vec a, Vec b) => new(a.X - b.X, a.Y - b.Y);
+ public static Vec operator -(Vec a) => new(-a.X, -a.Y);
+ public static Vec operator *(Vec a, double s) => new(a.X * s, a.Y * s);
+ public static Vec operator *(double s, Vec a) => new(a.X * s, a.Y * s);
+
+ public double Dot(Vec other) => X * other.X + Y * other.Y;
+ public double Length => Math.Sqrt(X * X + Y * Y);
+ public double LengthSquared => X * X + Y * Y;
+
+ public Vec Normalized()
+ {
+ var length = Length;
+ return length < 1e-12 ? new Vec(0, 0) : new Vec(X / length, Y / length);
+ }
+}
+
+/// <summary>One piece of a traced path: a line to <see cref="End"/>, or a cubic Bézier with two control points.</summary>
+internal readonly record struct PathSegment(bool IsLine, Vec Control1, Vec Control2, Vec End)
+{
+ public static PathSegment Line(Vec end) => new(true, end, end, end);
+ public static PathSegment Cubic(Vec c1, Vec c2, Vec end) => new(false, c1, c2, end);
+}
+
+/// <summary>A closed path starting at <see cref="Start"/>.</summary>
+internal sealed record TracedPath(Vec Start, List<PathSegment> Segments);
+
+/// <summary>Fits smooth paths to pixel outlines.</summary>
+internal static class CurveFitter
+{
+ /// <summary>Distance in pixels over which a turn counts as one corner.</summary>
+ private const double CornerReach = 2.0;
+
+ /// <summary>Points sampled along a long run are at most this far apart (close enough to be smoothed).</summary>
+ private const double SampleSpacing = 2.0;
+
+ private const int MaxReparameterizations = 4;
+
+ public static TracedPath Fit(PixelOutline outline, TraceSettings settings)
+ {
+ var (points, hard) = Sample(outline, settings.CornerRun);
+ var corners = FindCorners(points, hard, settings.CornerAngle);
+ Smooth(points, corners, settings.SmoothingPasses);
+
+ var tolerance = settings.CurveTolerance;
+ var segments = new List<PathSegment>();
+ var count = points.Count;
+ var first = Array.IndexOf(corners, true);
+
+ if (first < 0)
+ {
+ // A smooth closed curve. With a straight stretch, start at it and go round back into it.
+ var loop = Rotated(points, 0);
+ var stretches = FindStretches(loop, 0, count);
+ if (stretches.Count > 0)
+ {
+ loop = Rotated(points, stretches[0].Start);
+ var direction = (loop[stretches[0].End - stretches[0].Start] - loop[0]).Normalized();
+ FitBetween(loop, 0, count, direction, -direction, FindStretches(loop, 0, count), tolerance, segments);
+ return new TracedPath(loop[0], segments);
+ }
+
+ // Otherwise two halves that meet with matching tangents at both ends.
+ var half = count / 2;
+ var atStart = CenterTangent(loop, 0, 0, count - 1, closed: true);
+ var atHalf = CenterTangent(loop, half, 0, count);
+ FitCubic(loop, 0, half, -atStart, atHalf, tolerance, segments);
+ FitCubic(loop, half, count, -atHalf, atStart, tolerance, segments);
+ return new TracedPath(loop[0], segments);
+ }
+
+ // Start at the first corner and go round once, back to it.
+ var path = Rotated(points, first);
+ var from = 0;
+ for (var i = 1; i <= count; i++)
+ {
+ if (i < count && !corners[(first + i) % count])
+ continue;
+ FitPiece(path, from, i, tolerance, segments);
+ from = i;
+ }
+ return new TracedPath(path[0], segments);
+ }
+
+ /// <summary>The closed list of points starting at <paramref name="start"/>, with the first point repeated at the end.</summary>
+ private static Vec[] Rotated(List<Vec> points, int start)
+ {
+ var count = points.Count;
+ var result = new Vec[count + 1];
+ for (var i = 0; i <= count; i++)
+ result[i] = points[(start + i) % count];
+ return result;
+ }
+
+ // ───────────────────────── 1. Sampling ─────────────────────────
+
+ /// <summary>Points along the outline and whether each is a corner that must stay sharp.</summary>
+ internal static (List<Vec> Points, List<bool> Hard) Sample(PixelOutline outline, int cornerRun)
+ {
+ var n = outline.Count;
+ var lengths = new int[n];
+ var turns = new int[n]; // at corner i: +1 turns clockwise on screen, -1 counter-clockwise
+ for (var i = 0; i < n; i++)
+ {
+ var next = (i + 1) % n;
+ lengths[i] = Math.Abs(outline.Xs[next] - outline.Xs[i]) + Math.Abs(outline.Ys[next] - outline.Ys[i]);
+ }
+ for (var i = 0; i < n; i++)
+ {
+ var previous = (i + n - 1) % n;
+ var next = (i + 1) % n;
+ long inX = outline.Xs[i] - outline.Xs[previous], inY = outline.Ys[i] - outline.Ys[previous];
+ long outX = outline.Xs[next] - outline.Xs[i], outY = outline.Ys[next] - outline.Ys[i];
+ turns[i] = Math.Sign(inX * outY - inY * outX);
+ }
+
+ // Corner i lies between run i-1 (arriving) and run i (leaving).
+ var hardCorner = new bool[n];
+ for (var i = 0; i < n; i++)
+ {
+ var before = lengths[(i + n - 1) % n];
+ var after = lengths[i];
+ if (before >= cornerRun && after >= cornerRun)
+ hardCorner[i] = true;
+
+ // The end of a thin line: a short run whose two corners turn the same way, between two long runs.
+ var next = (i + 1) % n;
+ if (after <= 2 && turns[i] == turns[next] && before >= cornerRun && lengths[next] >= cornerRun)
+ {
+ hardCorner[i] = true;
+ hardCorner[next] = true;
+ }
+ }
+
+ var points = new List<Vec>(n * 2);
+ var hard = new List<bool>(n * 2);
+ for (var i = 0; i < n; i++)
+ {
+ var start = new Vec(outline.Xs[i], outline.Ys[i]);
+ var next = (i + 1) % n;
+ var end = new Vec(outline.Xs[next], outline.Ys[next]);
+ if (hardCorner[i])
+ {
+ points.Add(start);
+ hard.Add(true);
+ }
+ var length = lengths[i];
+ var direction = (end - start) * (1.0 / length);
+ if (length <= 2)
+ {
+ points.Add(start + direction * (length / 2.0));
+ hard.Add(false);
+ continue;
+ }
+ // From one pixel after the start to one before the end: the run's ends may be steps of a slanted edge.
+ var samples = Math.Max(2, (int)Math.Ceiling((length - 2) / SampleSpacing) + 1);
+ for (var s = 0; s < samples; s++)
+ {
+ var offset = 1 + (length - 2) * s / (double)(samples - 1);
+ points.Add(start + direction * offset);
+ hard.Add(false);
+ }
+ }
+ return (points, hard);
+ }
+
+ // ───────────────────────── 2. Corners ─────────────────────────
+
+ internal static bool[] FindCorners(List<Vec> points, List<bool> hard, double cornerAngle)
+ {
+ var count = points.Count;
+ var corners = new bool[count];
+ for (var i = 0; i < count; i++)
+ corners[i] = hard[i];
+ if (count < 6)
+ return corners;
+
+ var limit = count / 3;
+ var angles = new double[count];
+ var reachBack = new int[count];
+ var reachForward = new int[count];
+ var candidate = new bool[count];
+ var gentleAngle = cornerAngle - 20;
+ for (var i = 0; i < count; i++)
+ {
+ reachBack[i] = Reach(points, i, -1, CornerReach, limit);
+ reachForward[i] = Reach(points, i, +1, CornerReach, limit);
+ angles[i] = Turn(points[reachBack[i]], points[i], points[reachForward[i]]);
+ if (hard[i] || angles[i] <= gentleAngle)
+ continue;
+ if (angles[i] > cornerAngle)
+ {
+ candidate[i] = true;
+ continue;
+ }
+ // A gentler turn is a corner when it happens at once: seen from twice as far it hardly grows (on a circle
+ // it would double).
+ var wide = Turn(points[Reach(points, i, -1, 2 * CornerReach, limit)], points[i],
+ points[Reach(points, i, +1, 2 * CornerReach, limit)]);
+ candidate[i] = angles[i] >= 0.65 * wide;
+ }
+
+ for (var i = 0; i < count; i++)
+ {
+ if (!candidate[i])
+ continue;
+ // Only the sharpest point of a turn, and none right next to a corner that is kept anyway.
+ var best = !hard[reachBack[i]] && !hard[reachForward[i]];
+ for (var j = reachBack[i]; j != reachForward[i] && best; j = (j + 1) % count)
+ {
+ if (j == i)
+ continue;
+ if (hard[j] || (candidate[j] && (angles[j] > angles[i] || (angles[j] == angles[i] && j < i))))
+ best = false;
+ }
+ if (best)
+ corners[i] = true;
+ }
+ return corners;
+ }
+
+ /// <summary>How many degrees the direction turns at <paramref name="here"/>.</summary>
+ private static double Turn(Vec before, Vec here, Vec after)
+ {
+ var incoming = here - before;
+ var outgoing = after - here;
+ var denominator = incoming.Length * outgoing.Length;
+ return denominator < 1e-12 ? 0 : Math.Acos(Math.Clamp(incoming.Dot(outgoing) / denominator, -1, 1)) * 180 / Math.PI;
+ }
+
+ /// <summary>The first point at least <paramref name="distance"/> away from point <paramref name="i"/>.</summary>
+ private static int Reach(List<Vec> points, int i, int step, double distance, int limit)
+ {
+ var count = points.Count;
+ var j = i;
+ for (var steps = 0; steps < limit; steps++)
+ {
+ j = (j + step + count) % count;
+ if ((points[j] - points[i]).LengthSquared >= distance * distance)
+ break;
+ }
+ return j;
+ }
+
+ // ───────────────────────── 3. Smoothing ─────────────────────────
+
+ private static void Smooth(List<Vec> points, bool[] corners, int passes)
+ {
+ var count = points.Count;
+ if (count < 5)
+ return;
+ var next = new Vec[count];
+ for (var pass = 0; pass < passes; pass++)
+ {
+ for (var i = 0; i < count; i++)
+ {
+ var before = points[(i + count - 1) % count];
+ var after = points[(i + 1) % count];
+ var here = points[i];
+ // Points sampled along long runs lie on the edge already.
+ next[i] = corners[i] || (here - before).LengthSquared > 6.25 || (after - here).LengthSquared > 6.25
+ ? here
+ : (before + here * 2 + after) * 0.25;
+ }
+ for (var i = 0; i < count; i++)
+ points[i] = next[i];
+ }
+ }
+
+ // ───────────────────────── 4. Fitting ─────────────────────────
+
+ /// <summary>Fits the points from <paramref name="first"/> to <paramref name="last"/>, two corners.</summary>
+ private static void FitPiece(Vec[] d, int first, int last, double tolerance, List<PathSegment> output)
+ {
+ // Straight within a pixel (the jaggies of a thresholded edge) or within the tolerance.
+ if (last - first <= 1 || IsStraight(d, first, last, Math.Max(1.0, tolerance)))
+ {
+ output.Add(PathSegment.Line(d[last]));
+ return;
+ }
+ FitBetween(d, first, last, EndTangent(d, first, last, +1), EndTangent(d, last, first, -1),
+ FindStretches(d, first, last), tolerance, output);
+ }
+
+ /// <summary>
+ /// Fits <paramref name="first"/>..<paramref name="last"/>: the straight stretches as lines, the parts between
+ /// them as curves that leave and join the lines in their direction.
+ /// </summary>
+ private static void FitBetween(Vec[] d, int first, int last, Vec startTangent, Vec endTangent,
+ List<(int Start, int End)> stretches, double tolerance, List<PathSegment> output)
+ {
+ var cursor = first;
+ var tangent = startTangent;
+ foreach (var (start, end) in stretches)
+ {
+ var direction = (d[end] - d[start]).Normalized();
+ if (start > cursor)
+ FitCubic(d, cursor, start, tangent, -direction, tolerance, output);
+ output.Add(PathSegment.Line(d[end]));
+ cursor = end;
+ tangent = direction;
+ }
+ if (cursor < last)
+ FitCubic(d, cursor, last, tangent, endTangent, tolerance, output);
+ }
+
+ /// <summary>Length, in pixels, a straight stretch must at least have.</summary>
+ private const double MinStretch = 10;
+
+ /// <summary>How far, in pixels, the points of a straight stretch may be from it.</summary>
+ private const double StretchTolerance = 0.5;
+
+ /// <summary>The most a straight stretch may bend, in radians (2°): a gentle arc stays a curve.</summary>
+ private const double StretchBend = 0.035;
+
+ /// <summary>The straight stretches among the points <paramref name="first"/>..<paramref name="last"/>, in order.</summary>
+ private static List<(int Start, int End)> FindStretches(Vec[] d, int first, int last)
+ {
+ var stretches = new List<(int, int)>();
+ var i = first;
+ while (i < last - 1)
+ {
+ var end = LongestStretch(d, i, last);
+ if ((d[end] - d[i]).Length >= MinStretch && !Bends(d, i, end))
+ {
+ stretches.Add((i, end));
+ i = end;
+ }
+ else
+ {
+ i++;
+ }
+ }
+ return stretches;
+ }
+
+ /// <summary>The farthest point such that the points from <paramref name="start"/> to it lie near their chord.</summary>
+ private static int LongestStretch(Vec[] d, int start, int last)
+ {
+ var end = start + 1;
+ for (var j = start + 2; j <= last; j++)
+ {
+ if (!IsStraight(d, start, j, StretchTolerance))
+ break;
+ end = j;
+ }
+ return end;
+ }
+
+ /// <summary>
+ /// True when the points bend like an arc rather than scatter around a line: the least-squares sagitta of a
+ /// parabola through the chord's ends, compared with the chord.
+ /// </summary>
+ private static bool Bends(Vec[] d, int start, int end)
+ {
+ var chord = d[end] - d[start];
+ var length = chord.Length;
+ var normal = new Vec(-chord.Y / length, chord.X / length);
+ double numerator = 0, denominator = 0;
+ for (var i = start + 1; i < end; i++)
+ {
+ var offset = d[i] - d[start];
+ var t = Math.Clamp(offset.Dot(chord) / (length * length), 0, 1);
+ var shape = 4 * t * (1 - t);
+ numerator += offset.Dot(normal) * shape;
+ denominator += shape * shape;
+ }
+ var sagitta = denominator > 0 ? numerator / denominator : 0;
+ // An arc of chord c and sagitta s turns by about 8 s / c.
+ return Math.Abs(8 * sagitta / length) > StretchBend;
+ }
+
+ private static bool IsStraight(Vec[] d, int first, int last, double tolerance)
+ {
+ var a = d[first];
+ var chord = d[last] - a;
+ var length = chord.Length;
+ if (length < 1e-9)
+ return false;
+ var normal = new Vec(-chord.Y / length, chord.X / length);
+ for (var i = first + 1; i < last; i++)
+ {
+ var offset = d[i] - a;
+ if (Math.Abs(offset.Dot(normal)) > tolerance)
+ return false;
+ var along = offset.Dot(chord) / (length * length);
+ if (along < -0.05 || along > 1.05)
+ return false;
+ }
+ return true;
+ }
+
+ /// <summary>
+ /// Unit tangent at end <paramref name="at"/> of the piece, pointing into it: towards the first point a few pixels
+ /// along (more stable than the next point alone).
+ /// </summary>
+ private static Vec EndTangent(Vec[] d, int at, int other, int step)
+ {
+ var i = at;
+ while (i != other)
+ {
+ i += step;
+ if ((d[i] - d[at]).LengthSquared >= 6.25)
+ break;
+ }
+ return (d[i] - d[at]).Normalized();
+ }
+
+ /// <summary>
+ /// Unit tangent through point <paramref name="center"/>, pointing back (towards earlier points), from the points
+ /// about 1.5 pixels before and after it. <paramref name="closed"/> wraps around a closed list of
+ /// <paramref name="last"/> + 1 points.
+ /// </summary>
+ private static Vec CenterTangent(Vec[] d, int center, int first, int last, bool closed = false)
+ {
+ int Clamp(int i) => closed ? ((i % (last + 1)) + last + 1) % (last + 1) : Math.Clamp(i, first, last);
+ var span = closed ? last + 1 : last - first + 1;
+ int back = center, forward = center;
+ for (var steps = 0; steps < span / 3 + 1; steps++)
+ {
+ var candidate = Clamp(back - 1);
+ if (candidate == back)
+ break;
+ back = candidate;
+ if ((d[back] - d[center]).LengthSquared >= 2.25)
+ break;
+ }
+ for (var steps = 0; steps < span / 3 + 1; steps++)
+ {
+ var candidate = Clamp(forward + 1);
+ if (candidate == forward)
+ break;
+ forward = candidate;
+ if ((d[forward] - d[center]).LengthSquared >= 2.25)
+ break;
+ }
+ var tangent = (d[back] - d[forward]).Normalized();
+ return tangent.LengthSquared > 0 ? tangent : (d[Clamp(center - 1)] - d[Clamp(center + 1)]).Normalized();
+ }
+
+ /// <summary>
+ /// Fits cubic Béziers to the points <paramref name="first"/>..<paramref name="last"/> within
+ /// <paramref name="tolerance"/> pixels. <paramref name="startTangent"/> points into the piece,
+ /// <paramref name="endTangent"/> points back from its end.
+ /// </summary>
+ private static void FitCubic(Vec[] d, int first, int last, Vec startTangent, Vec endTangent, double tolerance, List<PathSegment> output)
+ {
+ var error = tolerance * tolerance;
+ // Depth-first with an explicit stack (long outlines would otherwise recurse thousands of levels deep); the
+ // left half is handled first so segments come out in order.
+ var pending = new Stack<(int First, int Last, Vec T1, Vec T2)>();
+ pending.Push((first, last, startTangent, endTangent));
+ while (pending.Count > 0)
+ {
+ var (a, b, t1, t2) = pending.Pop();
+ if (b - a == 1)
+ {
+ var distance = (d[b] - d[a]).Length / 3;
+ output.Add(PathSegment.Cubic(d[a] + t1 * distance, d[b] + t2 * distance, d[b]));
+ continue;
+ }
+
+ var u = ChordLengths(d, a, b);
+ var bezier = GenerateBezier(d, a, b, u, t1, t2);
+ var (maxError, split) = MaxError(d, a, b, bezier, u);
+ if (maxError > error && maxError < error * 4)
+ {
+ for (var i = 0; i < MaxReparameterizations && maxError > error; i++)
+ {
+ u = Reparameterize(d, a, b, u, bezier);
+ bezier = GenerateBezier(d, a, b, u, t1, t2);
+ (maxError, split) = MaxError(d, a, b, bezier, u);
+ }
+ }
+ if (maxError <= error)
+ {
+ output.Add(PathSegment.Cubic(bezier[1], bezier[2], bezier[3]));
+ continue;
+ }
+
+ var center = CenterTangent(d, split, a, b);
+ pending.Push((split, b, -center, t2));
+ pending.Push((a, split, t1, center));
+ }
+ }
+
+ private static double[] ChordLengths(Vec[] d, int first, int last)
+ {
+ var u = new double[last - first + 1];
+ for (var i = first + 1; i <= last; i++)
+ u[i - first] = u[i - first - 1] + (d[i] - d[i - 1]).Length;
+ var total = u[^1];
+ for (var i = 1; i < u.Length; i++)
+ u[i] = total > 0 ? u[i] / total : i / (double)(u.Length - 1);
+ return u;
+ }
+
+ /// <summary>Least-squares control points for fixed end points and tangent directions.</summary>
+ private static Vec[] GenerateBezier(Vec[] d, int first, int last, double[] u, Vec t1, Vec t2)
+ {
+ double c00 = 0, c01 = 0, c11 = 0, x0 = 0, x1 = 0;
+ var p0 = d[first];
+ var p3 = d[last];
+ for (var i = 0; i < u.Length; i++)
+ {
+ var t = u[i];
+ var mt = 1 - t;
+ var b0 = mt * mt * mt;
+ var b1 = 3 * t * mt * mt;
+ var b2 = 3 * t * t * mt;
+ var b3 = t * t * t;
+ var a1 = t1 * b1;
+ var a2 = t2 * b2;
+ c00 += a1.Dot(a1);
+ c01 += a1.Dot(a2);
+ c11 += a2.Dot(a2);
+ var rest = d[first + i] - (p0 * (b0 + b1) + p3 * (b2 + b3));
+ x0 += a1.Dot(rest);
+ x1 += a2.Dot(rest);
+ }
+
+ var determinant = c00 * c11 - c01 * c01;
+ double alpha1 = 0, alpha2 = 0;
+ if (Math.Abs(determinant) > 1e-12)
+ {
+ alpha1 = (x0 * c11 - x1 * c01) / determinant;
+ alpha2 = (c00 * x1 - c01 * x0) / determinant;
+ }
+
+ // Fall back to a third of the chord when the solution is degenerate or would loop.
+ var chord = (p3 - p0).Length;
+ var epsilon = 1e-6 * chord;
+ if (alpha1 < epsilon || alpha2 < epsilon || alpha1 > chord * 2 || alpha2 > chord * 2)
+ alpha1 = alpha2 = chord / 3;
+ return [p0, p0 + t1 * alpha1, p3 + t2 * alpha2, p3];
+ }
+
+ private static (double Error, int Split) MaxError(Vec[] d, int first, int last, Vec[] bezier, double[] u)
+ {
+ var split = (first + last) / 2;
+ var max = 0.0;
+ for (var i = first + 1; i < last; i++)
+ {
+ var error = (Evaluate(bezier, u[i - first]) - d[i]).LengthSquared;
+ if (error >= max)
+ {
+ max = error;
+ split = i;
+ }
+ }
+ return (max, split);
+ }
+
+ private static double[] Reparameterize(Vec[] d, int first, int last, double[] u, Vec[] bezier)
+ {
+ var result = new double[u.Length];
+ for (var i = 0; i < u.Length; i++)
+ result[i] = NewtonRaphson(bezier, d[first + i], u[i]);
+ return result;
+ }
+
+ /// <summary>One Newton–Raphson step towards the parameter of the curve point nearest <paramref name="point"/>.</summary>
+ private static double NewtonRaphson(Vec[] q, Vec point, double u)
+ {
+ var difference = Evaluate(q, u) - point;
+ var mt = 1 - u;
+ var first = 3 * (mt * mt * (q[1] - q[0]) + 2 * mt * u * (q[2] - q[1]) + u * u * (q[3] - q[2]));
+ var second = 6 * (mt * (q[2] - q[1] * 2 + q[0]) + u * (q[3] - q[2] * 2 + q[1]));
+ var numerator = difference.Dot(first);
+ var denominator = first.Dot(first) + difference.Dot(second);
+ if (Math.Abs(denominator) < 1e-12)
+ return u;
+ return Math.Clamp(u - numerator / denominator, 0, 1);
+ }
+
+ internal static Vec Evaluate(Vec[] q, double t)
+ {
+ var mt = 1 - t;
+ return q[0] * (mt * mt * mt) + q[1] * (3 * t * mt * mt) + q[2] * (3 * t * t * mt) + q[3] * (t * t * t);
+ }
+}
diff --git a/src/Filee.Engines/Vector/Tracing/ImageTracer.cs b/src/Filee.Engines/Vector/Tracing/ImageTracer.cs
new file mode 100644
index 00000000..d54a17bb
--- /dev/null
+++ b/src/Filee.Engines/Vector/Tracing/ImageTracer.cs
@@ -0,0 +1,274 @@
+// Raster → vector tracing, written for Filee from the published descriptions of the steps (see PixelOutlines,
+// CurveFitter and ColorRegions); no code of Potrace, AutoTrace or VTracer is used.
+//
+// Black and white: pixels darker than Otsu's threshold (or, on a transparent background, the opaque pixels) are
+// traced as one black shape. Colour: the picture is reduced to N colours and each colour is traced as the union of
+// itself and every colour stacked above it, bottom (largest) colour first. A lower shape therefore runs underneath
+// the shapes above it instead of meeting them edge to edge, so no background shows through between them.
+
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.Text;
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Vector.Tracing;
+
+/// <summary>One colour of a traced picture.</summary>
+internal sealed record TracedLayer(int Color, List<TracedPath> Paths);
+
+/// <summary>A traced picture: its size in pixels and its shapes, bottom first.</summary>
+internal sealed record TraceResult(int Width, int Height, List<TracedLayer> Layers);
+
+internal static class ImageTracer
+{
+ /// <summary>
+ /// Traces RGBA pixels (straight alpha, 4 bytes per pixel, rows top to bottom).
+ /// </summary>
+ public static TraceResult Trace(byte[] rgba, int width, int height, TraceSettings settings,
+ IProgress<double>? progress = null, CancellationToken ct = default)
+ {
+ var layers = settings.Mode == TracingMode.BlackAndWhite
+ ? TraceBlackAndWhite(rgba, width, height, settings, progress, ct)
+ : TraceColors(rgba, width, height, settings, progress, ct);
+ return new TraceResult(width, height, layers);
+ }
+
+ // ───────────────────────── Black and white ─────────────────────────
+
+ private static List<TracedLayer> TraceBlackAndWhite(byte[] rgba, int width, int height, TraceSettings settings,
+ IProgress<double>? progress, CancellationToken ct)
+ {
+ var mask = InkMask(rgba, width, height);
+ ct.ThrowIfCancellationRequested();
+ progress?.Report(0.2);
+ var outlines = PixelOutlines.Trace(mask, width, height, settings.SpeckleArea, ct);
+ progress?.Report(0.5);
+ var paths = FitAll(outlines, settings, ct);
+ return paths.Count == 0 ? [] : [new TracedLayer(0x000000, paths)];
+ }
+
+ /// <summary>
+ /// 1 for ink. On an opaque picture: darker than Otsu's threshold (transparent pixels count as white paper). On a
+ /// picture with a transparent background: the opaque pixels, or only their darker ones when the opaque part itself
+ /// has light and dark areas (a black logo on a white plate).
+ /// </summary>
+ internal static byte[] InkMask(byte[] rgba, int width, int height)
+ {
+ var count = width * height;
+ var luminance = new byte[count];
+ var histogram = new long[256];
+ var opaqueHistogram = new long[256];
+ long transparent = 0;
+ for (var p = 0; p < count; p++)
+ {
+ var o = p * 4;
+ var alpha = rgba[o + 3];
+ var y = (rgba[o] * 299 + rgba[o + 1] * 587 + rgba[o + 2] * 114) / 1000;
+ // Over white paper.
+ var onWhite = (byte)(255 - (255 - y) * alpha / 255);
+ luminance[p] = onWhite;
+ histogram[onWhite]++;
+ if (alpha >= ColorRegions.OpaqueAlpha)
+ opaqueHistogram[y]++;
+ else
+ transparent++;
+ }
+
+ var mask = new byte[count];
+ if (transparent >= count / 100 + 1)
+ {
+ // Transparent background: decide by the opaque pixels alone.
+ var spread = Percentile(opaqueHistogram, 0.95) - Percentile(opaqueHistogram, 0.05);
+ var threshold = spread < 64 ? 256 : Otsu(opaqueHistogram);
+ for (var p = 0; p < count; p++)
+ {
+ var o = p * 4;
+ if (rgba[o + 3] < ColorRegions.OpaqueAlpha)
+ continue;
+ var y = (rgba[o] * 299 + rgba[o + 1] * 587 + rgba[o + 2] * 114) / 1000;
+ if (y < threshold)
+ mask[p] = 1;
+ }
+ return mask;
+ }
+
+ var cut = Percentile(histogram, 0.99) - Percentile(histogram, 0.01) < 32 ? 128 : Otsu(histogram);
+ for (var p = 0; p < count; p++)
+ if (luminance[p] < cut)
+ mask[p] = 1;
+ return mask;
+ }
+
+ /// <summary>Otsu's threshold: values below it are one class, the rest the other.</summary>
+ internal static int Otsu(long[] histogram)
+ {
+ long total = 0;
+ double sum = 0;
+ for (var i = 0; i < 256; i++)
+ {
+ total += histogram[i];
+ sum += i * (double)histogram[i];
+ }
+ if (total == 0)
+ return 128;
+ double backgroundSum = 0, best = -1;
+ long background = 0;
+ var threshold = 128;
+ for (var t = 0; t < 255; t++)
+ {
+ background += histogram[t];
+ if (background == 0)
+ continue;
+ var foreground = total - background;
+ if (foreground == 0)
+ break;
+ backgroundSum += t * (double)histogram[t];
+ var meanBackground = backgroundSum / background;
+ var meanForeground = (sum - backgroundSum) / foreground;
+ var between = background * (double)foreground * (meanBackground - meanForeground) * (meanBackground - meanForeground);
+ if (between > best)
+ {
+ best = between;
+ threshold = t + 1;
+ }
+ }
+ return threshold;
+ }
+
+ private static int Percentile(long[] histogram, double fraction)
+ {
+ long total = 0;
+ foreach (var h in histogram)
+ total += h;
+ if (total == 0)
+ return 0;
+ var target = (long)(total * fraction);
+ long running = 0;
+ for (var i = 0; i < 256; i++)
+ {
+ running += histogram[i];
+ if (running > target)
+ return i;
+ }
+ return 255;
+ }
+
+ // ───────────────────────── Colour ─────────────────────────
+
+ private static List<TracedLayer> TraceColors(byte[] rgba, int width, int height, TraceSettings settings,
+ IProgress<double>? progress, CancellationToken ct)
+ {
+ var (palette, labels) = ColorRegions.Quantize(rgba, width, height, settings.Colors, ct);
+ if (palette.Length == 0)
+ return [];
+ progress?.Report(0.15);
+ if (settings.MergeEdgeBands)
+ ColorRegions.MergeEdgeBands(labels, rgba, palette, width, height);
+ ColorRegions.MergeSmallRegions(labels, palette, width, height, settings.MinRegion, ct);
+ progress?.Report(0.3);
+
+ // Bottom to top by area: the background first, small details last.
+ var areas = new long[palette.Length];
+ foreach (var label in labels)
+ if (label != ColorRegions.Transparent)
+ areas[label]++;
+ var order = Enumerable.Range(0, palette.Length).Where(c => areas[c] > 0).OrderByDescending(c => areas[c]).ThenBy(c => c).ToArray();
+ var rank = new int[256];
+ Array.Fill(rank, -1);
+ for (var i = 0; i < order.Length; i++)
+ rank[order[i]] = i;
+
+ var results = new TracedLayer[order.Length];
+ var done = 0;
+ Parallel.For(0, order.Length, new ParallelOptions { CancellationToken = ct }, layer =>
+ {
+ // This colour and every colour above it.
+ var mask = new byte[labels.Length];
+ for (var p = 0; p < labels.Length; p++)
+ mask[p] = rank[labels[p]] >= layer ? (byte)1 : (byte)0;
+ var outlines = PixelOutlines.Trace(mask, width, height, settings.SpeckleArea, ct);
+ var paths = new List<TracedPath>(outlines.Count);
+ foreach (var outline in outlines)
+ paths.Add(CurveFitter.Fit(outline, settings));
+ results[layer] = new TracedLayer(palette[order[layer]], paths);
+ progress?.Report(0.3 + 0.65 * Interlocked.Increment(ref done) / order.Length);
+ });
+ return results.Where(l => l.Paths.Count > 0).ToList();
+ }
+
+ private static List<TracedPath> FitAll(List<PixelOutline> outlines, TraceSettings settings, CancellationToken ct)
+ {
+ var paths = new TracedPath[outlines.Count];
+ Parallel.ForEach(Partitioner.Create(0, outlines.Count), new ParallelOptions { CancellationToken = ct }, range =>
+ {
+ for (var i = range.Item1; i < range.Item2; i++)
+ paths[i] = CurveFitter.Fit(outlines[i], settings);
+ });
+ return [.. paths];
+ }
+
+ // ───────────────────────── SVG ─────────────────────────
+
+ /// <summary>
+ /// Writes the traced picture as SVG, <paramref name="outputWidth"/> × <paramref name="outputHeight"/> pixels
+ /// (the source image's size; the traced pixels are scaled up to it when the picture was reduced for tracing).
+ /// </summary>
+ public static void WriteSvg(TraceResult result, Stream stream, int outputWidth, int outputHeight, string? comment = null)
+ {
+ var scaleX = outputWidth / (double)result.Width;
+ var scaleY = outputHeight / (double)result.Height;
+ using var writer = new StreamWriter(stream, new UTF8Encoding(false), 1 << 16, leaveOpen: true);
+ writer.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ writer.Write(string.Create(CultureInfo.InvariantCulture,
+ $"<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"{outputWidth}\" height=\"{outputHeight}\" viewBox=\"0 0 {outputWidth} {outputHeight}\">\n"));
+ if (!string.IsNullOrEmpty(comment))
+ writer.Write($"<!-- {comment.Replace("--", "- -", StringComparison.Ordinal)} -->\n");
+ var data = new StringBuilder();
+ foreach (var layer in result.Layers)
+ {
+ data.Clear();
+ foreach (var path in layer.Paths)
+ AppendPath(data, path, scaleX, scaleY);
+ writer.Write($"<path fill=\"#{layer.Color:x6}\" d=\"");
+ writer.Write(data);
+ writer.Write("\"/>\n");
+ }
+ writer.Write("</svg>\n");
+ }
+
+ internal static void AppendPath(StringBuilder data, TracedPath path, double scaleX, double scaleY)
+ {
+ data.Append('M');
+ Point(data, path.Start, scaleX, scaleY);
+ foreach (var segment in path.Segments)
+ {
+ if (segment.IsLine)
+ {
+ data.Append('L');
+ }
+ else
+ {
+ data.Append('C');
+ Point(data, segment.Control1, scaleX, scaleY);
+ data.Append(' ');
+ Point(data, segment.Control2, scaleX, scaleY);
+ data.Append(' ');
+ }
+ Point(data, segment.End, scaleX, scaleY);
+ }
+ data.Append('Z');
+ }
+
+ private static void Point(StringBuilder data, Vec point, double scaleX, double scaleY)
+ {
+ Number(data, point.X * scaleX);
+ data.Append(' ');
+ Number(data, point.Y * scaleY);
+ }
+
+ private static void Number(StringBuilder data, double value)
+ {
+ var rounded = Math.Round(value, 2);
+ data.Append((rounded == 0 ? 0 : rounded).ToString("0.##", CultureInfo.InvariantCulture));
+ }
+}
diff --git a/src/Filee.Engines/Vector/Tracing/PixelOutlines.cs b/src/Filee.Engines/Vector/Tracing/PixelOutlines.cs
new file mode 100644
index 00000000..696f7207
--- /dev/null
+++ b/src/Filee.Engines/Vector/Tracing/PixelOutlines.cs
@@ -0,0 +1,131 @@
+// Step 1 of tracing: the outlines of a pixel mask, as closed polygons along the pixel edges.
+//
+// Every edge between an inside and an outside pixel is a directed edge of the pixel grid, oriented so the inside is
+// on its right (on screen, with y pointing down): around a filled area the outline runs clockwise, around a hole
+// counter-clockwise, so the outlines fill correctly with the non-zero rule. Each grid point has as many edges
+// leaving as arriving; where two inside pixels touch only at a corner (a "saddle") two edges leave, and the walk turns
+// left, which keeps diagonally touching pixels in one shape (8-connected shapes, 4-connected holes).
+
+using System.Numerics;
+
+namespace Filee.Engines.Vector.Tracing;
+
+/// <summary>A closed outline along pixel edges: its corner points (where the direction changes) in order.</summary>
+/// <param name="Xs">X of each corner.</param>
+/// <param name="Ys">Y of each corner.</param>
+/// <param name="Area">Signed area in square pixels: positive around filled areas, negative around holes.</param>
+internal sealed record PixelOutline(int[] Xs, int[] Ys, double Area)
+{
+ public int Count => Xs.Length;
+}
+
+/// <summary>Finds the outlines of the inside pixels of a mask.</summary>
+internal static class PixelOutlines
+{
+ private static readonly int[] StepX = [1, 0, -1, 0];
+ private static readonly int[] StepY = [0, 1, 0, -1];
+
+ /// <summary>Directions as used below: 0 right, 1 down, 2 left, 3 up (clockwise on screen).</summary>
+ private const int Right = 0;
+
+ /// <summary>
+ /// Every outline of the pixels where <paramref name="mask"/> is not 0. Outlines enclosing less than
+ /// <paramref name="minArea"/> square pixels are left out: specks disappear and small holes are filled.
+ /// </summary>
+ public static List<PixelOutline> Trace(byte[] mask, int width, int height, double minArea, CancellationToken ct)
+ {
+ var outlines = new List<PixelOutline>();
+ var stride = width + 1;
+ // One bit per direction and grid point: edges already walked.
+ var visited = new byte[stride * (height + 1)];
+ var xs = new List<int>();
+ var ys = new List<int>();
+
+ for (var y = 0; y < height; y++)
+ {
+ ct.ThrowIfCancellationRequested();
+ var row = y * width;
+ for (var x = 0; x < width; x++)
+ {
+ // Every outline has an edge going right: the top edge of an inside pixel below an outside one.
+ if (mask[row + x] == 0 || (y > 0 && mask[row - width + x] != 0) || (visited[y * stride + x] & 1) != 0)
+ continue;
+ var area2 = Walk(mask, width, height, visited, x, y, xs, ys);
+ if (Math.Abs(area2) / 2.0 >= Math.Max(minArea, 1e-9) && xs.Count >= 4)
+ outlines.Add(new PixelOutline([.. xs], [.. ys], area2 / 2.0));
+ }
+ }
+ return outlines;
+ }
+
+ /// <summary>Walks one outline from the right-going edge at (x, y); returns twice its signed area.</summary>
+ private static long Walk(byte[] mask, int width, int height, byte[] visited, int startX, int startY, List<int> xs, List<int> ys)
+ {
+ xs.Clear();
+ ys.Clear();
+ var stride = width + 1;
+ int x = startX, y = startY, direction = Right;
+ long area2 = 0;
+ while (true)
+ {
+ visited[y * stride + x] |= (byte)(1 << direction);
+ int nx = x + StepX[direction], ny = y + StepY[direction];
+ area2 += (long)x * ny - (long)nx * y;
+ x = nx;
+ y = ny;
+
+ var leaving = Leaving(mask, width, height, x, y);
+ int next;
+ if ((leaving & (leaving - 1)) == 0)
+ {
+ next = BitOperations.TrailingZeroCount(leaving);
+ }
+ else
+ {
+ // Saddle: turn left, so pixels touching at the corner stay together.
+ next = (direction + 3) & 3;
+ if ((leaving & (1 << next)) == 0)
+ next = (direction + 1) & 3;
+ }
+
+ if (x == startX && y == startY && next == Right)
+ {
+ if (direction != Right)
+ {
+ xs.Add(x);
+ ys.Add(y);
+ }
+ return area2;
+ }
+ if (next != direction)
+ {
+ xs.Add(x);
+ ys.Add(y);
+ }
+ direction = next;
+ }
+ }
+
+ /// <summary>Bits of the edges leaving grid point (x, y), from the four pixels around it.</summary>
+ private static int Leaving(byte[] mask, int width, int height, int x, int y)
+ {
+ var topLeft = Inside(mask, width, height, x - 1, y - 1);
+ var topRight = Inside(mask, width, height, x, y - 1);
+ var bottomLeft = Inside(mask, width, height, x - 1, y);
+ var bottomRight = Inside(mask, width, height, x, y);
+ // Each edge has the inside pixel on its right-hand side.
+ var bits = 0;
+ if (bottomRight && !topRight)
+ bits |= 1; // right
+ if (bottomLeft && !bottomRight)
+ bits |= 2; // down
+ if (topLeft && !bottomLeft)
+ bits |= 4; // left
+ if (topRight && !topLeft)
+ bits |= 8; // up
+ return bits;
+ }
+
+ private static bool Inside(byte[] mask, int width, int height, int x, int y) =>
+ (uint)x < (uint)width && (uint)y < (uint)height && mask[y * width + x] != 0;
+}
diff --git a/src/Filee.Engines/Vector/Tracing/RasterTracing.cs b/src/Filee.Engines/Vector/Tracing/RasterTracing.cs
new file mode 100644
index 00000000..e17abcf7
--- /dev/null
+++ b/src/Filee.Engines/Vector/Tracing/RasterTracing.cs
@@ -0,0 +1,73 @@
+// Raster image → SVG step of the vector engine: reads the picture with ImageMagick (first frame or page, turned
+// upright, in sRGB), reduces very large pictures, traces them and writes the SVG at the picture's own pixel size.
+
+using System.Globalization;
+using Filee.Core.Conversion;
+using Filee.Engines.Magick;
+using ImageMagick;
+
+namespace Filee.Engines.Vector.Tracing;
+
+internal static class RasterTracing
+{
+ /// <summary>
+ /// Pictures larger than this are reduced before tracing (time and memory grow with the pixel count, and outlines
+ /// of a 24-megapixel photo would not get better). The SVG keeps the original size.
+ /// </summary>
+ public const int MaxPixels = 6_000_000;
+
+ /// <summary>Longest side traced; longer pictures are reduced like <see cref="MaxPixels"/>.</summary>
+ public const int MaxSide = 4096;
+
+ public static IReadOnlyList<string> Run(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
+ {
+ int width, height, tracedWidth, tracedHeight;
+ byte[] pixels;
+ using (var images = ImageReader.Read(step.InputPath, step.From, step.Preset))
+ {
+ if (images.Count == 0)
+ throw new InvalidDataException("The image has no pictures to trace.");
+ var frame = ImageEncoder.SelectFrames(images, step.From, "png")[0];
+ frame.AutoOrient();
+ width = (int)frame.Width;
+ height = (int)frame.Height;
+ (tracedWidth, tracedHeight) = TracedSize(width, height);
+ if (tracedWidth != width || tracedHeight != height)
+ {
+ frame.Resize(new MagickGeometry((uint)tracedWidth, (uint)tracedHeight) { IgnoreAspectRatio = true });
+ (tracedWidth, tracedHeight) = ((int)frame.Width, (int)frame.Height);
+ }
+ if (frame.ColorSpace is not (ColorSpace.sRGB or ColorSpace.RGB or ColorSpace.Gray or ColorSpace.LinearGray))
+ frame.ColorSpace = ColorSpace.sRGB;
+ using var collection = frame.GetPixels();
+ pixels = collection.ToByteArray(PixelMapping.RGBA)
+ ?? throw new InvalidDataException("The image's pixels could not be read.");
+ }
+ ct.ThrowIfCancellationRequested();
+ progress?.Report(0.1);
+
+ var settings = TraceSettings.From(step.Preset.Trace, Math.Max(tracedWidth, tracedHeight));
+ var result = ImageTracer.Trace(pixels, tracedWidth, tracedHeight, settings,
+ progress is null ? null : new Progress<double>(p => progress.Report(0.1 + 0.85 * p)), ct);
+
+ var output = step.Output.Allocate("svg");
+ if (output is null)
+ return [];
+ var comment = tracedWidth == width && tracedHeight == height
+ ? null
+ : string.Create(CultureInfo.InvariantCulture,
+ $"Traced by Filee from a {width} x {height} px image reduced to {tracedWidth} x {tracedHeight} px.");
+ using (var stream = File.Create(output))
+ ImageTracer.WriteSvg(result, stream, width, height, comment);
+ return [output];
+ }
+
+ /// <summary>The size a <paramref name="width"/> × <paramref name="height"/> picture is traced at.</summary>
+ internal static (int Width, int Height) TracedSize(int width, int height)
+ {
+ var scale = Math.Min(1, Math.Min(MaxSide / (double)Math.Max(width, height), Math.Sqrt(MaxPixels / ((double)width * height))));
+ if (scale >= 1)
+ return (width, height);
+ return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
+ }
+}
diff --git a/src/Filee.Engines/Vector/Tracing/TraceSettings.cs b/src/Filee.Engines/Vector/Tracing/TraceSettings.cs
new file mode 100644
index 00000000..ac4d7a22
--- /dev/null
+++ b/src/Filee.Engines/Vector/Tracing/TraceSettings.cs
@@ -0,0 +1,58 @@
+// Turns the preset's three tracing options (mode, colours, detail) into the numbers the tracing steps use.
+
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Vector.Tracing;
+
+/// <summary>Parameters of one tracing run, derived from <see cref="TracingOptions"/>.</summary>
+internal sealed record TraceSettings
+{
+ public TracingMode Mode { get; init; } = TracingMode.Color;
+
+ /// <summary>Colours of the palette (colour mode).</summary>
+ public int Colors { get; init; } = 16;
+
+ /// <summary>Outlines enclosing fewer square pixels than this are dropped (specks, and holes that get filled).</summary>
+ public double SpeckleArea { get; init; } = 6;
+
+ /// <summary>Colour mode: connected regions smaller than this many pixels join the neighbouring region.</summary>
+ public int MinRegion { get; init; } = 16;
+
+ /// <summary>
+ /// Colour mode: thin bands of in-between colours along edges (anti-aliasing) join the colours on either side.
+ /// </summary>
+ public bool MergeEdgeBands { get; init; } = true;
+
+ /// <summary>Largest distance, in pixels, between the fitted curves and the smoothed outline.</summary>
+ public double CurveTolerance { get; init; } = 0.7;
+
+ /// <summary>A turn sharper than this many degrees within a couple of pixels is kept as a corner.</summary>
+ public double CornerAngle { get; init; } = 55;
+
+ /// <summary>A pixel corner between two straight runs at least this long is kept as a corner (rectangles).</summary>
+ public int CornerRun { get; init; } = 3;
+
+ /// <summary>Passes of neighbour averaging over the outline before fitting.</summary>
+ public int SmoothingPasses { get; init; } = 2;
+
+ /// <summary>The settings for a preset; <paramref name="longEdge"/> is the traced image's longer side in pixels.</summary>
+ public static TraceSettings From(TracingOptions options, int longEdge)
+ {
+ var f = Math.Clamp(options.Detail, 0, 100) / 100.0;
+ var coarse = (1 - f) * (1 - f);
+ // Specks are counted in pixels, so a larger picture of the same artwork has larger specks.
+ var sizeFactor = Math.Clamp(longEdge / 1000.0, 1, 4);
+ return new TraceSettings
+ {
+ Mode = options.Mode,
+ Colors = Math.Clamp(options.Colors, TracingOptions.MinColors, TracingOptions.MaxColors),
+ SpeckleArea = Math.Round(24 * coarse * sizeFactor),
+ MinRegion = (int)Math.Round(1 + 64 * coarse * sizeFactor),
+ MergeEdgeBands = f < 0.9,
+ CurveTolerance = 0.25 + 0.9 * (1 - f),
+ CornerAngle = 70 - 30 * f,
+ CornerRun = f > 0.8 ? 2 : 3,
+ SmoothingPasses = f < 0.34 ? 3 : f < 0.67 ? 2 : f < 0.9 ? 1 : 0,
+ };
+ }
+}
diff --git a/src/Filee.Engines/Vector/VectorConverter.cs b/src/Filee.Engines/Vector/VectorConverter.cs
index 5d30bd86..4814c00c 100644
--- a/src/Filee.Engines/Vector/VectorConverter.cs
+++ b/src/Filee.Engines/Vector/VectorConverter.cs
@@ -1,5 +1,6 @@
// Built-in vector graphics: SVG/SVGZ → PDF (vector) and → raster images with Svg.Skia and SkiaSharp, SVG ↔ SVGZ,
-// and Illustrator files → PDF. Other vector formats reach PNG, JPG, … through PDF and PDFium.
+// SVG → DXF (ACadSharp), raster images → SVG (tracing) and Illustrator files → PDF. Other vector formats reach PNG,
+// JPG, … through PDF and PDFium.
using System.IO.Compression;
using System.Text;
@@ -7,12 +8,20 @@ using Filee.Core.Conversion;
using Filee.Core.Formats;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
+using Filee.Engines.Vector.Tracing;
namespace Filee.Engines.Vector;
-/// <summary>SVG, SVGZ and AI conversions that need no external program.</summary>
+/// <summary>SVG, SVGZ and AI conversions and raster image tracing that need no external program.</summary>
public sealed class VectorConverter : IConverter
{
+ /// <summary>
+ /// Cost of tracing a raster image into SVG. Tracing redraws the picture, so it must never be a step on the way to
+ /// another format (PNG → SVG → PDF instead of PNG → PDF): its cost is higher than any route from an image to a
+ /// format SVG leads to, and the planner only takes it when SVG (or DXF, DWG through SVG) is the target.
+ /// </summary>
+ public const int TraceCost = 40;
+
public string Id => "vector";
public string DisplayName => "Vector graphics (built-in)";
public int MaxParallelism => 0;
@@ -24,8 +33,12 @@ public sealed class VectorConverter : IConverter
new("svg", "svgz"),
new("svgz", "svg"),
.. ImageEncoder.Writable.SelectMany(target => new[] { ImageEncoder.Edge("svg", target), ImageEncoder.Edge("svgz", target) }),
+ new("svg", "dxf"),
+ new("svgz", "dxf"),
// Illustrator files are PDF inside (or PostScript, see ConvertIllustratorAsync).
new("ai", "pdf"),
+ // Raster images (and, through PNG, anything that becomes one) are traced.
+ .. ImageEncoder.Readable.Select(source => new ConversionEdge(source, "svg", TraceCost)),
];
public EngineStatus GetStatus() => EngineStatus.Available(version: $"{EngineVersions.BuiltIn} · {EngineVersions.Library("Svg.Skia", typeof(Svg.Skia.SKSvg))}");
@@ -37,6 +50,8 @@ public sealed class VectorConverter : IConverter
("ai", "pdf") => await ConvertIllustratorAsync(step, progress, cancellationToken),
("svg", "svgz") => await Task.Run(() => Compress(step), cancellationToken),
("svgz", "svg") => await Task.Run(() => Decompress(step), cancellationToken),
+ (_, "svg") => await Task.Run(() => RasterTracing.Run(step, progress, cancellationToken), cancellationToken),
+ (_, "dxf") => await Task.Run(() => ToDxf(step, cancellationToken), cancellationToken),
(_, "pdf") => await Task.Run(() => ToPdf(step, cancellationToken), cancellationToken),
_ => await Task.Run(() => ToRaster(step, progress, cancellationToken), cancellationToken),
};
@@ -55,6 +70,17 @@ public sealed class VectorConverter : IConverter
return [output];
}
+ private static IReadOnlyList<string> ToDxf(ConversionStep step, CancellationToken ct)
+ {
+ using var drawing = SvgRenderer.Load(step.InputPath);
+ ct.ThrowIfCancellationRequested();
+ var output = step.Output.Allocate("dxf");
+ if (output is null)
+ return [];
+ SvgDxfWriter.Write(drawing, output, ct);
+ return [output];
+ }
+
private static IReadOnlyList<string> ToRaster(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
{
using var drawing = SvgRenderer.Load(step.InputPath);
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 4a1abc28..1d908236 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -355,7 +355,7 @@ public class RenderTests
window.DonutControl.SetExternalHighlight(1);
Pump();
- Assert.Equal(8, vm.Items.Count);
+ Assert.Equal(10, vm.Items.Count); // with "Trace to SVG" and "Line art to SVG"
Assert.Equal("JPG 3개", vm.CenterTitle);
Save(window, "donut-images-ko.png");
window.Close();
@@ -757,6 +757,50 @@ public class RenderTests
}
}
+ /// <summary>The preset popup of "Trace to SVG": mode, colours and detail; colours only in colour mode.</summary>
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ [InlineData("zh-CN")]
+ public void Preset_editor_shows_tracing_options(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var store = AppHost.Get<UserDataStore>();
+ var vm = new PresetEditorViewModel(store.FindPreset("trace-svg")!.Clone(), AppHost.Get<ILocalizer>());
+ Assert.True(vm.ShowTrace && vm.ShowTraceColors);
+ Assert.False(vm.ShowImage || vm.ShowMedia || vm.ShowArchive);
+
+ var window = new PresetEditorWindow { DataContext = vm, Height = 760 };
+ window.Show();
+ Pump();
+ Assert.True(window.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "TraceCard").IsVisible);
+ Save(window, $"preset-trace-{language}.png");
+ window.Close();
+
+ vm.TraceMode = vm.TraceModes.Single(m => m.Value == Filee.Core.Presets.TracingMode.BlackAndWhite);
+ Assert.False(vm.ShowTraceColors);
+ vm.Target = vm.Targets.Single(t => t.Value == "dxf");
+ Assert.True(vm.ShowTrace);
+ vm.Target = vm.Targets.Single(t => t.Value == "png");
+ Assert.False(vm.ShowTrace);
+ }
+
+ [AvaloniaFact]
+ public void Preset_editor_saves_tracing_options()
+ {
+ TestServices.EnsureInitialized("en");
+ var preset = new Filee.Core.Presets.Preset { TargetFormat = "svg", Name = "Logo" };
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ Assert.Equal(["Colour", "Black and white (line art)"], vm.TraceModes.Select(m => m.Label));
+
+ vm.TraceMode = vm.TraceModes.Single(m => m.Value == Filee.Core.Presets.TracingMode.BlackAndWhite);
+ vm.TraceColors = 200;
+ vm.TraceDetail = 80;
+ Assert.True(vm.Apply());
+
+ Assert.Equal((Filee.Core.Presets.TracingMode.BlackAndWhite, 64, 80), (preset.Trace.Mode, preset.Trace.Colors, preset.Trace.Detail));
+ }
+
[AvaloniaFact]
public void Preset_editor_saves_media_and_archive_options()
{
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index cf18bdab..78ecd888 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -210,6 +210,43 @@ public class UserDataStoreTests
Assert.False(SettingsMigrations.ApplyToLibrary(9, presets, profiles)); // once only
}
+ [Fact]
+ public void Version_10_libraries_get_the_tracing_presets_on_the_images_donut_after_pdf()
+ {
+ // As written before tracing: no trace presets, and the images donut without them.
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id is "trace-svg" or "trace-line-art");
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.PresetIds.RemoveAll(id => id is "trace-svg" or "trace-line-art");
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(10, presets, profiles));
+
+ Assert.Equal(TracingMode.Color, presets.Single(p => p.Id == "trace-svg").Trace.Mode);
+ Assert.Equal(TracingMode.BlackAndWhite, presets.Single(p => p.Id == "trace-line-art").Trace.Mode);
+ Assert.All(presets.Where(p => p.Id.StartsWith("trace-", StringComparison.Ordinal)), p => Assert.Equal("svg", p.TargetFormat));
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "images").PresetIds, images.PresetIds);
+ Assert.False(SettingsMigrations.ApplyToLibrary(10, presets, profiles)); // once only
+ }
+
+ [Fact]
+ public void Trace_options_survive_a_save_and_load()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ var preset = store.Presets.Single(p => p.Id == "trace-svg");
+ preset.Trace.Colors = 6;
+ preset.Trace.Detail = 80;
+ store.SaveLibrary();
+
+ var reloaded = new UserDataStore(dir.Path);
+ reloaded.Load();
+ var trace = reloaded.Presets.Single(p => p.Id == "trace-svg").Trace;
+ Assert.Equal((TracingMode.Color, 6, 80), (trace.Mode, trace.Colors, trace.Detail));
+ Assert.Equal(TracingMode.BlackAndWhite, reloaded.Presets.Single(p => p.Id == "trace-line-art").Trace.Mode);
+ }
+
[Fact]
public void Catalog_migration_ignores_extensions_checked_on_mixed_profiles()
{
diff --git a/tests/Filee.Engines.Tests/TracingTests.cs b/tests/Filee.Engines.Tests/TracingTests.cs
new file mode 100644
index 00000000..c5a4e940
--- /dev/null
+++ b/tests/Filee.Engines.Tests/TracingTests.cs
@@ -0,0 +1,581 @@
+// Raster → SVG tracing and SVG → DXF / DWG. Pictures are drawn with SkiaSharp in the tests; the traced SVG is rendered
+// back with Svg.Skia and compared with the input pixel by pixel, and DXF output is read back with ACadSharp.
+
+using System.Diagnostics;
+using System.Globalization;
+using System.Xml.Linq;
+using ACadSharp;
+using ACadSharp.Entities;
+using ACadSharp.IO;
+using ACadSharp.Types.Units;
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Engines.Vector;
+using Filee.Engines.Vector.Tracing;
+using ImageMagick;
+using SkiaSharp;
+
+namespace Filee.Engines.Tests;
+
+public class TracingTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly XNamespace Svg = "http://www.w3.org/2000/svg";
+
+ private async Task<string> ConvertAsync(string input, Preset preset)
+ {
+ var job = await fx.ConvertAsync([input], preset);
+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));
+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");
+ return job.Outputs.Single();
+ }
+
+ private static Preset LineArt(int detail = 50) =>
+ new() { Name = "Line art", TargetFormat = "svg", Trace = { Mode = TracingMode.BlackAndWhite, Detail = detail } };
+
+ private static Preset Colors(int colors, int detail = 50) =>
+ new() { Name = "Trace", TargetFormat = "svg", Trace = { Mode = TracingMode.Color, Colors = colors, Detail = detail } };
+
+ /// <summary>Draws a picture with SkiaSharp and saves it as PNG (or, through ImageMagick, another format).</summary>
+ private static string Draw(string folder, string name, int width, int height, SKColor background, Action<SKCanvas> draw)
+ {
+ using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
+ using (var canvas = new SKCanvas(bitmap))
+ {
+ canvas.Clear(background);
+ draw(canvas);
+ }
+ using var data = bitmap.Encode(SKEncodedImageFormat.Png, 100);
+ var png = Path.Combine(folder, Path.ChangeExtension(name, ".png"));
+ File.WriteAllBytes(png, data.ToArray());
+ if (Path.GetExtension(name) is ".png")
+ return png;
+ var path = Path.Combine(folder, name);
+ using (var image = new MagickImage(png))
+ image.Write(path);
+ File.Delete(png);
+ return path;
+ }
+
+ private static SKPaint Fill(SKColor color, bool antialias = true) => new() { Color = color, IsAntialias = antialias, Style = SKPaintStyle.Fill };
+
+ /// <summary>Line art: a disc, a rectangle, a ring (with a hole), a thin bar and a slanted bar.</summary>
+ private static void DrawLineArt(SKCanvas canvas)
+ {
+ using var black = Fill(SKColors.Black);
+ canvas.DrawCircle(80, 80, 55, black);
+ canvas.DrawRect(170, 30, 120, 90, black);
+ canvas.DrawCircle(90, 220, 60, black);
+ using (var white = Fill(SKColors.White))
+ canvas.DrawCircle(90, 220, 30, white);
+ canvas.DrawRect(180, 170, 180, 3, black);
+ canvas.Save();
+ canvas.RotateDegrees(-25, 270, 240);
+ canvas.DrawRect(200, 230, 140, 14, black);
+ canvas.Restore();
+ }
+
+ /// <summary>RGBA pixels of a picture file drawn over <paramref name="background"/>.</summary>
+ private static byte[] Pixels(string path, int width, int height, SKColor background)
+ {
+ using var source = SKBitmap.Decode(path) ?? SKBitmap.Decode(new MagickImage(path).ToByteArray(MagickFormat.Png));
+ Assert.NotNull(source);
+ return Render(width, height, background, canvas => canvas.DrawBitmap(source, new SKRect(0, 0, width, height)));
+ }
+
+ /// <summary>RGBA pixels of an SVG rendered at <paramref name="width"/> × <paramref name="height"/>.</summary>
+ private static byte[] RenderSvg(string path, int width, int height, SKColor background)
+ {
+ using var drawing = SvgRenderer.Load(path);
+ return Render(width, height, background, canvas =>
+ {
+ canvas.Scale(width / drawing.Bounds.Width, height / drawing.Bounds.Height);
+ canvas.Translate(-drawing.Bounds.Left, -drawing.Bounds.Top);
+ canvas.DrawPicture(drawing.Picture);
+ });
+ }
+
+ private static byte[] Render(int width, int height, SKColor background, Action<SKCanvas> draw)
+ {
+ using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
+ using (var canvas = new SKCanvas(bitmap))
+ {
+ canvas.Clear(background);
+ draw(canvas);
+ }
+ return bitmap.GetPixelSpan().ToArray();
+ }
+
+ /// <summary>Share of pixels whose colour differs by more than <paramref name="tolerance"/> in some channel.</summary>
+ private static double Difference(byte[] a, byte[] b, int tolerance = 64)
+ {
+ Assert.Equal(a.Length, b.Length);
+ var different = 0;
+ for (var i = 0; i < a.Length; i += 4)
+ {
+ if (Math.Abs(a[i] - b[i]) > tolerance || Math.Abs(a[i + 1] - b[i + 1]) > tolerance
+ || Math.Abs(a[i + 2] - b[i + 2]) > tolerance || Math.Abs(a[i + 3] - b[i + 3]) > tolerance)
+ different++;
+ }
+ return different / (a.Length / 4.0);
+ }
+
+ private static XElement[] PathsOf(string svg) => XDocument.Load(svg).Descendants(Svg + "path").ToArray();
+
+ private static int SubpathsOf(XElement path) => path.Attribute("d")!.Value.Count(c => c == 'M');
+
+ // ───────────────────────── Black and white ─────────────────────────
+
+ [Fact]
+ public async Task Line_art_becomes_one_black_path_that_looks_like_the_picture()
+ {
+ var dir = fx.NewFolder();
+ var png = Draw(dir, "logo.png", 400, 300, SKColors.White, DrawLineArt);
+
+ var svg = await ConvertAsync(png, LineArt());
+
+ var root = XDocument.Load(svg).Root!;
+ Assert.Equal(("400", "300", "0 0 400 300"), (root.Attribute("width")?.Value, root.Attribute("height")?.Value, root.Attribute("viewBox")?.Value));
+ var path = Assert.Single(PathsOf(svg));
+ Assert.Equal("#000000", path.Attribute("fill")?.Value);
+ // Disc, rectangle, ring outside + inside, thin bar, slanted bar.
+ Assert.Equal(6, SubpathsOf(path));
+ var data = path.Attribute("d")!.Value;
+ Assert.Contains('C', data); // curves for the round shapes
+ Assert.Contains('L', data); // straight lines for the rectangle
+
+ var difference = Difference(Pixels(png, 400, 300, SKColors.White), RenderSvg(svg, 400, 300, SKColors.White));
+ Assert.True(difference < 0.01, $"{difference:P2} of the pixels differ");
+ }
+
+ [Fact]
+ public async Task Line_art_drops_specks_unless_the_detail_is_highest()
+ {
+ var dir = fx.NewFolder();
+ var specks = 0;
+ var png = Draw(dir, "scan.png", 300, 200, SKColors.White, canvas =>
+ {
+ using var black = Fill(SKColors.Black, antialias: false);
+ canvas.DrawRect(50, 50, 200, 100, black);
+ var random = new Random(7);
+ for (var i = 0; i < 40; i++)
+ {
+ var x = random.Next(0, 300);
+ var y = random.Next(0, 200);
+ if (x is >= 45 and <= 255 && y is >= 45 and <= 155)
+ continue;
+ canvas.DrawRect(x, y, 2, 1, black); // dust: 2 pixels each
+ specks++;
+ }
+ });
+
+ var cleaned = PathsOf(await ConvertAsync(png, LineArt()));
+ var everything = PathsOf(await ConvertAsync(png, LineArt(detail: 100).Also(p => p.Output.FileNamePattern = "{name}_all")));
+
+ Assert.Equal(1, SubpathsOf(Assert.Single(cleaned)));
+ Assert.InRange(SubpathsOf(Assert.Single(everything)), 1 + specks * 0.8, 1 + specks);
+ }
+
+ [Fact]
+ public async Task Line_art_on_a_transparent_background_traces_the_opaque_shapes()
+ {
+ var dir = fx.NewFolder();
+ // A white logo on nothing: over white paper it would vanish, so the opaque pixels are the ink.
+ var png = Draw(dir, "white-logo.png", 200, 200, SKColors.Transparent, canvas =>
+ {
+ using var white = Fill(SKColors.White);
+ canvas.DrawCircle(100, 100, 70, white);
+ });
+
+ var path = Assert.Single(PathsOf(await ConvertAsync(png, LineArt())));
+ Assert.Equal(1, SubpathsOf(path));
+ }
+
+ // ───────────────────────── Colour ─────────────────────────
+
+ private static void DrawIllustration(SKCanvas canvas)
+ {
+ using var red = Fill(new SKColor(0xE5, 0x39, 0x35));
+ using var blue = Fill(new SKColor(0x1E, 0x63, 0xC8));
+ using var green = Fill(new SKColor(0x2E, 0x9D, 0x4F));
+ using var yellow = Fill(new SKColor(0xF9, 0xC8, 0x2B));
+ canvas.DrawCircle(110, 110, 80, red);
+ canvas.DrawRect(150, 120, 120, 110, blue);
+ using (var triangle = new SKPath())
+ {
+ triangle.MoveTo(40, 280);
+ triangle.LineTo(120, 170);
+ triangle.LineTo(200, 280);
+ triangle.Close();
+ canvas.DrawPath(triangle, green);
+ }
+ canvas.DrawCircle(210, 175, 25, yellow);
+ }
+
+ [Fact]
+ public async Task Colour_tracing_stacks_one_path_per_colour_without_gaps()
+ {
+ var dir = fx.NewFolder();
+ var png = Draw(dir, "illustration.png", 300, 300, SKColors.White, DrawIllustration);
+
+ var svg = await ConvertAsync(png, Colors(8));
+
+ var paths = PathsOf(svg);
+ // White, red, blue, green, yellow: the anti-aliased edges don't get colours of their own.
+ Assert.Equal(5, paths.Length);
+ Assert.Equal("#ffffff", paths[0].Attribute("fill")?.Value); // the background at the bottom
+ Assert.Equal(1, SubpathsOf(paths[0]));
+
+ var expected = Pixels(png, 300, 300, SKColors.White);
+ Assert.True(Difference(expected, RenderSvg(svg, 300, 300, SKColors.White)) < 0.02);
+ // Drawn over magenta, no magenta shows: lower shapes run under the upper ones.
+ var overMagenta = RenderSvg(svg, 300, 300, SKColors.Magenta);
+ Assert.True(Difference(expected, overMagenta) < 0.02);
+ var magenta = 0;
+ for (var i = 0; i < overMagenta.Length; i += 4)
+ if (overMagenta[i] > 200 && overMagenta[i + 1] < 60 && overMagenta[i + 2] > 200)
+ magenta++;
+ Assert.True(magenta < 30, $"{magenta} magenta pixels");
+ }
+
+ [Fact]
+ public async Task Colour_tracing_reduces_to_the_colour_count()
+ {
+ var dir = fx.NewFolder();
+ var png = Draw(dir, "gradient.png", 256, 64, SKColors.White, canvas =>
+ {
+ using var shader = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(256, 0), [SKColors.Black, SKColors.White], SKShaderTileMode.Clamp);
+ using var paint = new SKPaint { Shader = shader };
+ canvas.DrawRect(0, 0, 256, 64, paint);
+ });
+
+ var paths = PathsOf(await ConvertAsync(png, Colors(4)));
+
+ Assert.Equal(4, paths.Length);
+ Assert.Equal(4, paths.Select(p => p.Attribute("fill")!.Value).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task Transparent_areas_stay_transparent_in_colour_tracing()
+ {
+ var dir = fx.NewFolder();
+ var png = Draw(dir, "sticker.png", 200, 200, SKColors.Transparent, canvas =>
+ {
+ using var red = Fill(SKColors.Red);
+ canvas.DrawCircle(100, 100, 60, red);
+ });
+
+ var svg = await ConvertAsync(png, Colors(8));
+
+ var path = Assert.Single(PathsOf(svg));
+ Assert.Equal("#ff0000", path.Attribute("fill")?.Value);
+ var rendered = RenderSvg(svg, 200, 200, SKColors.Transparent);
+ Assert.Equal(0, rendered[(10 * 200 + 10) * 4 + 3]); // corner
+ Assert.Equal(255, rendered[(100 * 200 + 100) * 4 + 3]); // centre
+ }
+
+ // ───────────────────────── Inputs and size ─────────────────────────
+
+ [Theory]
+ [InlineData("jpg")]
+ [InlineData("bmp")]
+ [InlineData("gif")]
+ [InlineData("webp")]
+ [InlineData("tiff")]
+ public async Task Common_image_formats_are_traced(string format)
+ {
+ var dir = fx.NewFolder();
+ var input = Draw(dir, "art." + format, 300, 300, SKColors.White, DrawIllustration);
+
+ var svg = await ConvertAsync(input, Colors(8));
+
+ Assert.Equal(".svg", Path.GetExtension(svg));
+ Assert.InRange(PathsOf(svg).Length, 4, 8);
+ var difference = Difference(Pixels(input, 300, 300, SKColors.White), RenderSvg(svg, 300, 300, SKColors.White));
+ Assert.True(difference < 0.03, $"{difference:P2} of the pixels differ");
+ }
+
+ [Fact]
+ public async Task Only_the_first_page_of_a_tiff_is_traced()
+ {
+ var dir = fx.NewFolder();
+ var tiff = EngineFixture.MakeMultiPageTiff(dir, 3);
+
+ var job = await fx.ConvertAsync([tiff], Colors(4));
+
+ Assert.Equal(JobState.Completed, job.State);
+ var path = Assert.Single(PathsOf(Assert.Single(job.Outputs)));
+ Assert.Equal("#ff7f50", path.Attribute("fill")?.Value); // coral, the first page
+ }
+
+ [Fact]
+ public async Task Huge_pictures_are_reduced_for_tracing_and_keep_their_size()
+ {
+ var dir = fx.NewFolder();
+ var png = Draw(dir, "banner.png", 5000, 400, SKColors.White, canvas =>
+ {
+ using var black = Fill(SKColors.Black);
+ for (var x = 100; x < 4900; x += 600)
+ canvas.DrawCircle(x, 200, 150, black);
+ });
+
+ var svg = await ConvertAsync(png, LineArt());
+
+ var root = XDocument.Load(svg).Root!;
+ Assert.Equal(("5000", "400"), (root.Attribute("width")?.Value, root.Attribute("height")?.Value));
+ Assert.Contains(XDocument.Load(svg).DescendantNodes().OfType<XComment>(), c => c.Value.Contains("reduced to 4096 x 328", StringComparison.Ordinal));
+ Assert.Equal(8, SubpathsOf(Assert.Single(PathsOf(svg))));
+ var difference = Difference(Pixels(png, 1250, 100, SKColors.White), RenderSvg(svg, 1250, 100, SKColors.White));
+ Assert.True(difference < 0.02, $"{difference:P2} of the pixels differ");
+ }
+
+ [Theory]
+ [InlineData(5000, 400, 4096, 328)]
+ [InlineData(4000, 4000, 2449, 2449)]
+ [InlineData(2000, 2000, 2000, 2000)]
+ public void Traced_size_is_capped(int width, int height, int tracedWidth, int tracedHeight) =>
+ Assert.Equal((tracedWidth, tracedHeight), RasterTracing.TracedSize(width, height));
+
+ [Fact]
+ public async Task A_2000_pixel_illustration_traces_in_a_few_seconds()
+ {
+ var dir = fx.NewFolder();
+ var random = new Random(3);
+ SKColor[] palette = [new(0xE5, 0x39, 0x35), new(0x1E, 0x63, 0xC8), new(0x2E, 0x9D, 0x4F), new(0xF9, 0xC8, 0x2B),
+ new(0x6A, 0x1B, 0x9A), new(0x00, 0x83, 0x8F), new(0x37, 0x47, 0x4F), new(0xFF, 0x8F, 0x00)];
+ var png = Draw(dir, "poster.png", 2000, 2000, new SKColor(0xFA, 0xF7, 0xF0), canvas =>
+ {
+ for (var i = 0; i < 150; i++)
+ {
+ using var paint = Fill(palette[random.Next(palette.Length)]);
+ var x = random.Next(0, 2000);
+ var y = random.Next(0, 2000);
+ if (i % 3 == 0)
+ canvas.DrawRect(x, y, random.Next(40, 300), random.Next(40, 300), paint);
+ else
+ canvas.DrawCircle(x, y, random.Next(10, 160), paint);
+ }
+ using var text = Fill(SKColors.Black);
+ using var font = new SKFont(SKTypeface.Default, 120);
+ canvas.DrawText("Filee 2000", 200, 1000, font, text);
+ });
+
+ foreach (var preset in new[] { Colors(16), LineArt() })
+ {
+ preset.Output.FileNamePattern = "{name}_" + preset.Trace.Mode;
+ var watch = Stopwatch.StartNew();
+ var svg = await ConvertAsync(png, preset);
+ watch.Stop();
+ TestContext.Current.TestOutputHelper?.WriteLine(string.Create(CultureInfo.InvariantCulture,
+ $"{preset.Trace.Mode}: {watch.Elapsed.TotalSeconds:0.00} s, {new FileInfo(svg).Length / 1024} KB, {PathsOf(svg).Sum(SubpathsOf)} outlines"));
+ Assert.True(watch.Elapsed < TimeSpan.FromSeconds(30), $"{preset.Trace.Mode} took {watch.Elapsed}");
+ if (preset.Trace.Mode == TracingMode.Color)
+ {
+ var difference = Difference(Pixels(png, 500, 500, SKColors.White), RenderSvg(svg, 500, 500, SKColors.White));
+ Assert.True(difference < 0.03, $"{difference:P2} of the pixels differ");
+ }
+ }
+ }
+
+ // ───────────────────────── Routes ─────────────────────────
+
+ [Theory]
+ [InlineData("png")]
+ [InlineData("jpg")]
+ [InlineData("bmp")]
+ [InlineData("gif")]
+ [InlineData("webp")]
+ [InlineData("tiff")]
+ [InlineData("heic")]
+ public void Raster_images_reach_svg_by_tracing_and_cad_through_svg(string from)
+ {
+ var planner = fx.Catalog.CreatePlanner();
+
+ Assert.Equal("vector", Assert.Single(planner.Plan(from, "svg")!.Steps).Converter.Id);
+ Assert.Equal(["svg", "dxf"], planner.Plan(from, "dxf")!.Steps.Select(s => s.To));
+ Assert.Equal(["svg", "dxf", "dwg"], planner.Plan(from, "dwg")!.Steps.Select(s => s.To));
+ // Everything else keeps the image engines' routes.
+ Assert.Equal("pdfsharp", Assert.Single(planner.Plan(from, "pdf")!.Steps).Converter.Id);
+ Assert.DoesNotContain(planner.Plan(from, "eps")?.Steps ?? [], s => s.To == "svg");
+ }
+
+ [Fact]
+ public void Tracing_is_never_a_step_towards_a_format_that_has_another_route()
+ {
+ // Every engine as if installed, so optional engines' edges are part of the check.
+ var everyEngine = fx.Converters.Select(c => c.Id).ToArray();
+ var withTracing = fx.Catalog.CreatePlanner(everyEngine);
+ var without = new ConverterCatalog(fx.Converters.Select(c => c is VectorConverter ? new WithoutTracing(c) : c))
+ {
+ Priority = fx.Catalog.Priority,
+ }.CreatePlanner(everyEngine);
+
+ var formats = FormatRegistry.Known.Select(f => f.Id).ToList();
+ var checkedRoutes = 0;
+ foreach (var from in formats)
+ {
+ foreach (var to in formats.Where(t => t != from))
+ {
+ var other = without.Plan(from, to);
+ if (other is null)
+ continue;
+ var route = withTracing.Plan(from, to);
+ Assert.NotNull(route);
+ Assert.False(route.Steps.Any(IsTracing), $"{from} → {to} traces: {string.Join(" → ", route.Steps.Select(s => s.To))}");
+ Assert.Equal(other.Cost, route.Cost);
+ checkedRoutes++;
+ }
+ }
+ Assert.True(checkedRoutes > 1000);
+ }
+
+ private static bool IsTracing(RouteStep step) => step.Converter is VectorConverter && step.To == "svg" && step.From is not "svgz";
+
+ /// <summary>The vector engine without its tracing edges.</summary>
+ private sealed class WithoutTracing(IConverter inner) : IConverter
+ {
+ public string Id => inner.Id;
+ public string DisplayName => inner.DisplayName;
+ public int MaxParallelism => inner.MaxParallelism;
+ public IReadOnlyList<ConversionEdge> Edges { get; } = inner.Edges.Where(e => e.Cost != VectorConverter.TraceCost).ToList();
+ public EngineStatus GetStatus() => inner.GetStatus();
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ inner.ConvertAsync(step, progress, cancellationToken);
+ }
+
+ // ───────────────────────── SVG → DXF / DWG ─────────────────────────
+
+ private const string Drawing = """
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="96" viewBox="0 0 96 96">
+ <defs><rect id="tile" width="10" height="10"/></defs>
+ <rect x="10" y="10" width="30" height="20" fill="#ff0000"/>
+ <circle cx="60" cy="20" r="9.6" fill="none" stroke="#0000ff"/>
+ <ellipse cx="20" cy="60" rx="12" ry="6" transform="rotate(30 20 60)" fill="#00ff00"/>
+ <line x1="50" y1="50" x2="90" y2="50" stroke="black"/>
+ <polyline points="50,60 60,70 70,60 80,70" fill="none" stroke="black"/>
+ <polygon points="50,80 60,90 40,90"/>
+ <path d="M 10 80 C 10 70, 30 70, 30 80 A 5 5 0 0 1 20 85 Z" fill="none" stroke="black"/>
+ <g transform="translate(70 75) scale(2)"><use xlink:href="#tile"/></g>
+ </svg>
+ """;
+
+ [Fact]
+ public async Task Svg_becomes_dxf_in_millimetres_with_y_up()
+ {
+ var dir = fx.NewFolder();
+ var svg = Path.Combine(dir, "parts.svg");
+ await File.WriteAllTextAsync(svg, Drawing, TestContext.Current.CancellationToken);
+
+ var dxf = await ConvertAsync(svg, new Preset { TargetFormat = "dxf" });
+
+ var document = DxfReader.Read(dxf);
+ Assert.Equal(UnitsType.Millimeters, document.Header.InsUnits);
+ const double mm = 25.4 / 96; // 96 px = 1 inch, so the drawing is 25.4 mm square
+ var entities = document.Entities.ToList();
+
+ // The rectangle: closed, its top-left corner (10, 10) at y = 96 - 10 from the bottom.
+ var rectangle = entities.OfType<LwPolyline>().Single(p => p.Color.R == 255 && p.Color.G == 0);
+ Assert.True(rectangle.IsClosed);
+ Assert.Equal(4, rectangle.Vertices.Count);
+ Assert.Contains(rectangle.Vertices, v => Near(v.Location.X, 10 * mm) && Near(v.Location.Y, 86 * mm));
+ Assert.Contains(rectangle.Vertices, v => Near(v.Location.X, 40 * mm) && Near(v.Location.Y, 66 * mm));
+
+ var circle = Assert.Single(entities.OfType<Circle>());
+ Assert.True(Near(circle.Center.X, 60 * mm) && Near(circle.Center.Y, 76 * mm) && Near(circle.Radius, 9.6 * mm), $"{circle.Center} r {circle.Radius}");
+ Assert.Equal((0, 0, 255), (circle.Color.R, circle.Color.G, circle.Color.B));
+
+ var ellipse = Assert.Single(entities.OfType<Ellipse>());
+ Assert.True(Near(ellipse.Center.X, 20 * mm) && Near(ellipse.Center.Y, 36 * mm));
+ Assert.True(Near(ellipse.RadiusRatio, 0.5));
+ Assert.True(Near(ellipse.MajorAxisEndPoint.X, 12 * mm * Math.Cos(Math.PI / 6)) && Near(ellipse.MajorAxisEndPoint.Y, -12 * mm * Math.Sin(Math.PI / 6)),
+ ellipse.MajorAxisEndPoint.ToString());
+
+ var line = Assert.Single(entities.OfType<Line>());
+ Assert.True(Near(line.StartPoint.X, 50 * mm) && Near(line.StartPoint.Y, 46 * mm) && Near(line.EndPoint.X, 90 * mm));
+
+ Assert.Contains(entities.OfType<LwPolyline>(), p => !p.IsClosed && p.Vertices.Count == 4); // the polyline
+ Assert.Contains(entities.OfType<LwPolyline>(), p => p.IsClosed && p.Vertices.Count == 3); // the polygon
+ // The path's curve and arc are divided into short straight pieces.
+ var curved = entities.OfType<LwPolyline>().Single(p => p.IsClosed && p.Vertices.Count > 20);
+ // The arc is too short for its radius, so SVG enlarges it (to 5.59) and it bulges a little past x = 30.
+ Assert.All(curved.Vertices, v => Assert.InRange(v.Location.X, 9.99 * mm, 30.7 * mm));
+ Assert.Contains(curved.Vertices, v => v.Location.X > 30.5 * mm);
+ Assert.Contains(curved.Vertices, v => Near(v.Location.Y, (96 - 85) * mm, 0.05));
+
+ // <use> inside a translated and scaled group: (70, 75) to (90, 95).
+ var tile = entities.OfType<LwPolyline>().Single(p => p.IsClosed && p.Vertices.Count == 4 && p.Color.R == 0);
+ Assert.Contains(tile.Vertices, v => Near(v.Location.X, 70 * mm) && Near(v.Location.Y, 21 * mm));
+ Assert.Contains(tile.Vertices, v => Near(v.Location.X, 90 * mm) && Near(v.Location.Y, 1 * mm));
+ }
+
+ private static bool Near(double a, double b, double tolerance = 1e-3) => Math.Abs(a - b) < tolerance;
+
+ [Fact]
+ public async Task Svg_text_becomes_outlines_in_dxf()
+ {
+ var dir = fx.NewFolder();
+ var svg = Path.Combine(dir, "label.svg");
+ await File.WriteAllTextAsync(svg, """
+ <svg xmlns="http://www.w3.org/2000/svg" width="200" height="60"><text x="10" y="45" font-size="40" font-family="sans-serif">Hi</text></svg>
+ """, TestContext.Current.CancellationToken);
+
+ var document = DxfReader.Read(await ConvertAsync(svg, new Preset { TargetFormat = "dxf" }));
+
+ var outlines = document.Entities.OfType<LwPolyline>().ToList();
+ Assert.True(outlines.Count >= 3, $"{outlines.Count} outlines"); // H, the stem and dot of i
+ Assert.All(outlines, o => Assert.True(o.IsClosed));
+ }
+
+ [Fact]
+ public async Task Svg_reaches_dwg_through_dxf()
+ {
+ var dir = fx.NewFolder();
+ var svg = Path.Combine(dir, "parts.svg");
+ await File.WriteAllTextAsync(svg, Drawing, TestContext.Current.CancellationToken);
+
+ Assert.Equal("vector,cad", string.Join(',', fx.Catalog.CreatePlanner().Plan("svg", "dwg")!.Steps.Select(s => s.Converter.Id)));
+ var dwg = await ConvertAsync(svg, new Preset { TargetFormat = "dwg" });
+
+ var document = DwgReader.Read(dwg);
+ Assert.Single(document.Entities.OfType<Circle>());
+ Assert.Single(document.Entities.OfType<Ellipse>());
+ Assert.Equal(8, document.Entities.Count()); // every shape of the drawing
+ }
+
+ [Fact]
+ public async Task Traced_line_art_becomes_closed_dxf_outlines()
+ {
+ var dir = fx.NewFolder();
+ var png = Draw(dir, "logo.png", 400, 300, SKColors.White, DrawLineArt);
+
+ var dxf = await ConvertAsync(png, LineArt().Also(p => p.TargetFormat = "dxf"));
+
+ var outlines = DxfReader.Read(dxf).Entities.OfType<LwPolyline>().ToList();
+ Assert.Equal(6, outlines.Count);
+ Assert.All(outlines, o => Assert.True(o.IsClosed));
+ // 400 px wide at 96 px per inch.
+ Assert.True(outlines.Max(o => o.Vertices.Max(v => v.Location.X)) < 400 * 25.4 / 96);
+ }
+
+ [Fact]
+ public async Task Svg_with_nothing_to_outline_fails_with_a_message()
+ {
+ var dir = fx.NewFolder();
+ var svg = Path.Combine(dir, "empty.svg");
+ await File.WriteAllTextAsync(svg, """<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><g/></svg>""", TestContext.Current.CancellationToken);
+
+ var job = await fx.ConvertAsync([svg], new Preset { TargetFormat = "dxf" });
+
+ Assert.Equal(JobState.Failed, job.State);
+ }
+}
+
+internal static class PresetTestExtensions
+{
+ /// <summary>Changes a preset in an expression.</summary>
+ public static Preset Also(this Preset preset, Action<Preset> change)
+ {
+ change(preset);
+ return preset;
+ }
+}