Repository Public License
1// ORIX Convert — Packages/EngineVector/Tests/EngineVectorTests/TracerTests.swift2// Description: Tests of the tracer itself (Vectorizer and its stages) on fixtures drawn in code.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import CoreGraphics5import Foundation6import Testing7@testable import EngineVector89/// Traces, checks that the SVG text is a valid traced drawing, and returns the result with the drawing parsed10/// back from the SVG text (so every geometric assertion below is made on the file content, not on memory).11func traced(_ image: CGImage, _ settings: VectorSettings, sourceLocation: SourceLocation = #_sourceLocation) throws -> (result: VectorResult, parsed: VectorDocument) {12 let result = try Vectorizer().trace(image, settings: settings)13 let parsed = try TracedSVGReader.read(result.svg)14 #expect(result.svg.contains("<path"), sourceLocation: sourceLocation)15 #expect(!result.svg.contains("<image"), sourceLocation: sourceLocation)16 #expect(!result.svg.contains("base64"), sourceLocation: sourceLocation)17 #expect(!result.svg.contains("data:"), sourceLocation: sourceLocation)18 #expect(parsed.report.isValid, "\(parsed.report)", sourceLocation: sourceLocation)19 #expect(parsed.report.pathCount == result.statistics.pathCount, sourceLocation: sourceLocation)20 #expect(result.statistics.svgByteCount == result.svg.utf8.count, sourceLocation: sourceLocation)21 return (result, parsed.document)22}2324@Suite("Tracer: fidelity") struct TracerFidelityTests {25 @Test("Re-rasterised SVG matches the source within a per-fixture pixel-error bound", arguments: [26 "disc", "ring", "polygons", "text", "thin-lines", "illustration", "icon", "hard-polygons",27 ])28 func rerasterised(_ name: String) throws {29 let image: CGImage, settings: VectorSettings, bound: Double30 switch name {31 case "disc": (image, settings, bound) = (Fixture.disc(), VectorSettings(mode: .logo), 0.25)32 case "ring": (image, settings, bound) = (Fixture.ring(), VectorSettings(mode: .logo), 0.4)33 case "polygons": (image, settings, bound) = (Fixture.polygons(), VectorSettings(mode: .logo), 0.1)34 case "text": (image, settings, bound) = (Fixture.text(), VectorSettings(mode: .logo), 0.6)35 case "thin-lines": (image, settings, bound) = (Fixture.thinLines(), VectorSettings(mode: .lineArt), 1.5)36 case "illustration": (image, settings, bound) = (Fixture.illustration(), VectorSettings(mode: .illustration), 0.6)37 case "icon": (image, settings, bound) = (Fixture.transparentIcon(), VectorSettings(mode: .icon), 0.4)38 default:39 image = Fixture.hardEdged(200, 200) { x, y in (x > 30 && x < 120 && y > 40 && y < 90) || ((x - 130) * (x - 130) + (y - 140) * (y - 140) < 1600) }40 (settings, bound) = (VectorSettings(mode: .technical), 1.2)41 }42 let (result, parsed) = try traced(image, settings)43 let rendering = try #require(parsed.makeImage(pixelWidth: image.width, pixelHeight: image.height))44 let error = Fixture.meanAbsoluteError(image, rendering)45 #expect(error < bound, "\(name): mean absolute error \(error)")46 // The similarity reported to the user is measured, and agrees with this independent measurement.47 let similarity = try #require(result.similarity)48 #expect(similarity.meanAbsoluteError < bound + 0.5)49 #expect(similarity.edgeRecall > 0.95)50 #expect(similarity.matchingPixelFraction > 0.9)51 }5253 @Test func ringKeepsItsHole() throws {54 let (result, parsed) = try traced(Fixture.ring(), VectorSettings(mode: .monochrome))55 #expect(parsed.layers.count == 1)56 let ring = try #require(parsed.layers.first)57 #expect(ring.subpaths.count == 2)58 let areas = ring.subpaths.map(Probe.signedArea)59 #expect(areas[0] * areas[1] < 0, "outer boundary and hole must have opposite orientations")60 let expectedOuter = Double.pi * 96 * 96, expectedInner = Double.pi * 56 * 5661 #expect(abs(areas.map(abs).max()! - expectedOuter) / expectedOuter < 0.01)62 #expect(abs(areas.map(abs).min()! - expectedInner) / expectedInner < 0.01)63 let image = try #require(parsed.makeImage(pixelWidth: 256, pixelHeight: 256))64 #expect(Probe.pixel(image, 128, 128)[3] == 0, "the centre of the ring is empty")65 #expect(Probe.pixel(image, 128 + 76, 128)[3] == 255, "the ring itself is filled")66 #expect(Probe.pixel(image, 4, 4)[3] == 0)67 #expect(result.statistics.backgroundRemoved)68 // Same answer with both fill rules.69 let ctx = CGContext(data: nil, width: 256, height: 256, bitsPerComponent: 8, bytesPerRow: 0, space: Fixture.sRGB, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!70 ctx.translateBy(x: 0, y: 256); ctx.scaleBy(x: 1, y: -1)71 ctx.addPath(ring.cgPath); ctx.fillPath(using: .evenOdd)72 let evenOdd = ctx.makeImage()!73 #expect(Probe.pixel(evenOdd, 128, 128)[3] == 0)74 #expect(Probe.pixel(evenOdd, 128 + 76, 128)[3] == 255)75 }7677 @Test func circleNeedsFewCurvesAndKeepsItsRadius() throws {78 for (radius, cx, cy) in [(80.3, 128.3, 127.6), (20.0, 100.5, 90.25), (110.0, 128.0, 128.0)] {79 let image = Fixture.disc(256, radius: radius, center: (cx, cy))80 let (_, parsed) = try traced(image, VectorSettings(mode: .monochrome))81 let layer = try #require(parsed.layers.first)82 #expect(layer.subpaths.count == 1)83 let segments = layer.subpaths[0].segments84 #expect(segments.count <= 8, "radius \(radius): \(segments.count) segments")85 #expect(segments.allSatisfy { if case .cubic = $0 { true } else { false } })86 let errors = Probe.samples(layer).map { abs((($0.x - cx) * ($0.x - cx) + ($0.y - cy) * ($0.y - cy)).squareRoot() - radius) }87 #expect(errors.max()! < 0.3, "radius \(radius): max radial error \(errors.max()!)")88 #expect(errors.reduce(0, +) / Double(errors.count) < 0.1)89 }90 // Without anti-aliasing the pixel grid is all there is: half a pixel is the honest bound.91 let hard = Fixture.hardEdged(256, 256) { x, y in (x - 128.3) * (x - 128.3) + (y - 127.6) * (y - 127.6) <= 80.3 * 80.3 }92 let (_, parsed) = try traced(hard, VectorSettings(mode: .monochrome))93 let errors = Probe.samples(parsed.layers[0]).map { abs((($0.x - 128.3) * ($0.x - 128.3) + ($0.y - 127.6) * ($0.y - 127.6)).squareRoot() - 80.3) }94 #expect(errors.max()! < 0.75)95 #expect(parsed.layers[0].subpaths[0].segments.count <= 16)96 }9798 @Test func straightEdgesStayLinesWithSubPixelCorners() throws {99 // Anti-aliased rectangle (fractional edges) and triangle.100 var settings = VectorSettings(mode: .logo)101 settings.precision = 3102 let (result, parsed) = try traced(Fixture.polygons(), settings)103 let ink = try #require(Probe.layer(parsed, near: .black))104 #expect(ink.subpaths.count == 2)105 #expect(ink.subpaths.allSatisfy { sub in sub.segments.allSatisfy { if case .line = $0 { true } else { false } } }, "only straight segments")106 #expect(result.statistics.curveSegmentCount == 0)107 let vertices = ink.subpaths.flatMap { [$0.start] + $0.segments.map(\.end) }108 for (x, y) in [(40.25, 30.5), (140.75, 30.5), (140.75, 90.75), (40.25, 90.75), (60.0, 230.0), (200.0, 215.0), (120.0, 120.0)] {109 #expect(Probe.nearest(vertices, to: x, y) < 0.15, "corner (\(x), \(y)) off by \(Probe.nearest(vertices, to: x, y))")110 }111 #expect(ink.nodeCount <= 9)112113 // Hard-edged technical drawing: lines only, corners within the pixel grid's own uncertainty.114 let hard = Fixture.hardEdged(240, 200) { x, y in115 let rect = x > 20 && x < 100 && y > 30 && y < 150116 // Triangle (130,170) (220,160) (160,40)117 func side(_ ax: Double, _ ay: Double, _ bx: Double, _ by: Double) -> Double { (bx - ax) * (y - ay) - (by - ay) * (x - ax) }118 let a = side(130, 170, 220, 160), b = side(220, 160, 160, 40), c = side(160, 40, 130, 170)119 return rect || (a < 0 && b < 0 && c < 0) || (a > 0 && b > 0 && c > 0)120 }121 let (_, technical) = try traced(hard, VectorSettings(mode: .technical))122 let drawing = try #require(technical.layers.first)123 #expect(drawing.subpaths.count == 2)124 #expect(drawing.subpaths.allSatisfy { sub in sub.segments.allSatisfy { if case .line = $0 { true } else { false } } })125 #expect(drawing.nodeCount <= 8)126 let corners = drawing.subpaths.flatMap { [$0.start] + $0.segments.map(\.end) }127 for (x, y) in [(20.0, 30.0), (100.0, 30.0), (100.0, 150.0), (20.0, 150.0), (130.0, 170.0), (220.0, 160.0), (160.0, 40.0)] {128 #expect(Probe.nearest(corners, to: x, y) < 1.0, "corner (\(x), \(y)) off by \(Probe.nearest(corners, to: x, y))")129 }130 }131132 @Test func neighbouringRegionsLeaveNoGap() throws {133 let image = Fixture.illustration()134 let (_, parsed) = try traced(image, VectorSettings(mode: .illustration))135 let rendering = try #require(parsed.makeImage(pixelWidth: image.width * 2, pixelHeight: image.height * 2))136 let data = Fixture.pixels(rendering)137 var notOpaque = 0138 for i in stride(from: 3, to: data.count, by: 4) where data[i] != 255 { notOpaque += 1 }139 #expect(notOpaque == 0, "\(notOpaque) pixels show the canvas through the drawing")140141 // The cut-out layout is exact tiling too (each shape only its own area), valid, with fewer hidden parts.142 var cutout = VectorSettings(mode: .illustration)143 cutout.composition = .cutout144 let (_, tiles) = try traced(image, cutout)145 #expect(tiles.layers.count == parsed.layers.count)146 let tiled = try #require(tiles.makeImage(pixelWidth: image.width, pixelHeight: image.height))147 #expect(Fixture.meanAbsoluteError(image, tiled) < 1.0)148 }149150 @Test func denseJunctionsStillTileThePlane() throws {151 // Voronoi cells in 9 colours (many three-way junctions) and a checkerboard (four-way junctions everywhere).152 var random = Fixture.Random(state: 2026)153 let size = 160154 let palette: [(UInt8, UInt8, UInt8)] = [(230, 60, 50), (40, 120, 210), (250, 205, 40), (60, 170, 90), (150, 80, 190), (245, 245, 240), (30, 30, 40), (240, 140, 40), (90, 200, 220)]155 let seeds = (0..<60).map { _ in (random.unit() * Double(size), random.unit() * Double(size), Int(random.next() % 9)) }156 var voronoi = [UInt8](repeating: 255, count: size * size * 4)157 for y in 0..<size { for x in 0..<size {158 var best = 0, bestD = Double.infinity159 for (i, s) in seeds.enumerated() { let d = (s.0 - Double(x)) * (s.0 - Double(x)) + (s.1 - Double(y)) * (s.1 - Double(y)); if d < bestD { bestD = d; best = i } }160 let c = palette[seeds[best].2], i = (y * size + x) * 4161 voronoi[i] = c.0; voronoi[i + 1] = c.1; voronoi[i + 2] = c.2162 } }163 var checker = [UInt8](repeating: 255, count: 64 * 64 * 4)164 for y in 0..<64 { for x in 0..<64 where (x / 4 + y / 4) % 2 == 0 { let i = (y * 64 + x) * 4; checker[i] = 0; checker[i + 1] = 0; checker[i + 2] = 0 } }165 for (image, mode) in [(Fixture.image(fromRGBA: voronoi, width: size, height: size), VectorMode.illustration), (Fixture.image(fromRGBA: checker, width: 64, height: 64), .logo)] {166 for composition in [LayerComposition.stacked, .cutout] {167 var settings = VectorSettings(mode: mode)168 settings.composition = composition169 settings.minimumRegionArea = 0170 let (result, parsed) = try traced(image, settings)171 let rendering = try #require(parsed.makeImage(pixelWidth: image.width, pixelHeight: image.height))172 #expect(Fixture.meanAbsoluteError(image, rendering) < 6, "\(mode) \(composition): \(Fixture.meanAbsoluteError(image, rendering))")173 if composition == .stacked {174 let data = Fixture.pixels(try #require(parsed.makeImage(pixelWidth: image.width * 3, pixelHeight: image.height * 3)))175 #expect(stride(from: 3, to: data.count, by: 4).allSatisfy { data[$0] == 255 }, "\(mode): the stacked drawing has a hole")176 }177 #expect(result.statistics.regionCount >= (mode == .logo ? 2 : 20))178 }179 }180 }181182 @Test func antiAliasedEdgesDoNotBecomeSliverRegions() throws {183 // Red disc on blue: the blended edge pixels are purple, which must not become a third colour.184 let image = Fixture.render(200, 200, background: Fixture.color(20, 40, 220)) { ctx in185 ctx.setFillColor(Fixture.color(230, 30, 30))186 ctx.fillEllipse(in: CGRect(x: 40.3, y: 50.7, width: 120, height: 100))187 }188 var settings = VectorSettings(mode: .illustration)189 settings.colorCount = 12190 let (result, parsed) = try traced(image, settings)191 #expect(parsed.layers.count == 2)192 #expect(result.statistics.regionCount == 2)193 #expect(Probe.layer(parsed, near: VectorColor(red: 230, green: 30, blue: 30), tolerance: 6) != nil)194 #expect(Probe.layer(parsed, near: VectorColor(red: 20, green: 40, blue: 220), tolerance: 6) != nil)195 }196197 @Test func transparentBackgroundIsPreserved() throws {198 let image = Fixture.transparentIcon()199 let (result, parsed) = try traced(image, VectorSettings(mode: .icon))200 #expect(result.transparency.background == .transparent)201 #expect(result.transparency.hasTransparency)202 #expect(parsed.background == nil)203 let rendering = try #require(parsed.makeImage(pixelWidth: 128, pixelHeight: 128))204 #expect(Probe.pixel(rendering, 2, 2)[3] == 0)205 #expect(Probe.pixel(rendering, 125, 125)[3] == 0)206 #expect(Probe.pixel(rendering, 20, 64) == [10, 132, 255, 255])207 #expect(Probe.pixel(rendering, 64, 70) == [255, 255, 255, 255])208 #expect(result.similarity!.meanAlphaError < 0.5)209210 // Flattening is a choice, and it is reported.211 var flat = VectorSettings(mode: .icon)212 flat.transparency = .flattenWhite213 let flattened = try Vectorizer().trace(image, settings: flat)214 #expect(flattened.warnings.contains { $0.code == "transparency-flattened" && $0.isDataLoss })215 let opaque = try #require(flattened.document.makeImage(pixelWidth: 128, pixelHeight: 128))216 #expect(Probe.pixel(opaque, 2, 2) == [255, 255, 255, 255])217 }218219 @Test func whiteGlyphOnTransparentBackgroundIsInk() throws {220 let image = Fixture.text("Ok", width: 260, height: 160, fontSize: 110, foreground: Fixture.color(255, 255, 255), background: nil)221 let (result, parsed) = try traced(image, VectorSettings(mode: .monochrome))222 #expect(parsed.layers.count == 1)223 #expect(parsed.layers[0].color == .white)224 #expect(result.statistics.subpathCount >= 3) // O outer, O hole, k225 }226227 @Test func backgroundRemovalVariants() throws {228 let image = Fixture.ring()229 var settings = VectorSettings(mode: .logo)230 settings.backgroundRemoval = .removeConnected231 let connected = try traced(image, settings).parsed.makeImage(pixelWidth: 256, pixelHeight: 256)!232 #expect(Probe.pixel(connected, 4, 4)[3] == 0, "outside removed")233 #expect(Probe.pixel(connected, 128, 128) == [255, 255, 255, 255], "the enclosed white disc is kept")234 settings.backgroundRemoval = .removeAll235 let everywhere = try traced(image, settings).parsed.makeImage(pixelWidth: 256, pixelHeight: 256)!236 #expect(Probe.pixel(everywhere, 4, 4)[3] == 0)237 #expect(Probe.pixel(everywhere, 128, 128)[3] == 0)238 settings.backgroundRemoval = .keep239 settings.backgroundFill = VectorColor(red: 0, green: 255, blue: 0)240 let kept = try traced(image, settings)241 #expect(kept.result.svg.contains("<rect width=\"256\" height=\"256\" fill=\"#0f0\"/>"))242 #expect(kept.parsed.background == VectorColor(red: 0, green: 255, blue: 0))243 }244}245246@Suite("Tracer: controls") struct TracerControlTests {247 @Test func minimumRegionSizeRemovesSpeckles() throws {248 let (image, specks) = Fixture.speckled()249 var settings = VectorSettings(mode: .monochrome)250 settings.minimumRegionArea = 0251 let all = try traced(image, settings).result252 #expect(all.statistics.subpathCount == specks + 1)253 settings.minimumRegionArea = 12254 let clean = try traced(image, settings).result255 #expect(clean.statistics.subpathCount == 1)256 #expect(clean.statistics.regionCount == 1)257258 // A speck inside a shape is merged into the shape (not punched out as a hole).259 let holed = Fixture.render(120, 120, antialias: false) { ctx in260 ctx.setFillColor(Fixture.color(200, 30, 30)); ctx.fill(CGRect(x: 20, y: 20, width: 80, height: 80))261 ctx.setFillColor(Fixture.color(30, 30, 200)); ctx.fill(CGRect(x: 50, y: 50, width: 2, height: 2))262 }263 var colour = VectorSettings(mode: .illustration)264 colour.minimumRegionArea = 16265 let merged = try traced(holed, colour)266 let red = try #require(Probe.layer(merged.parsed, near: VectorColor(red: 200, green: 30, blue: 30)))267 #expect(red.subpaths.count == 1)268 #expect(merged.parsed.layers.count == 2)269 let rendering = merged.parsed.makeImage(pixelWidth: 120, pixelHeight: 120)!270 #expect(Probe.pixel(rendering, 51, 51) == [200, 30, 30, 255])271 }272273 @Test func colourCountIsHonoured() throws {274 let image = Fixture.illustration()275 for (requested, expected) in [(5, 5), (16, 5), (3, 3), (2, 2)] {276 var settings = VectorSettings(mode: .illustration)277 settings.colorCount = requested278 let (result, parsed) = try traced(image, settings)279 #expect(parsed.layers.count == expected, "requested \(requested): \(parsed.layers.count) colours")280 #expect(result.statistics.colorCount <= requested)281 #expect(Set(parsed.layers.map(\.color)).count == parsed.layers.count)282 }283 var settings = VectorSettings(mode: .illustration)284 settings.colorCount = 5285 let parsed = try traced(image, settings).parsed286 for (r, g, b) in [(245, 240, 225), (40, 120, 200), (230, 70, 50), (250, 200, 40), (30, 30, 40)] {287 #expect(Probe.layer(parsed, near: VectorColor(red: UInt8(r), green: UInt8(g), blue: UInt8(b)), tolerance: 4) != nil, "colour \(r),\(g),\(b) missing")288 }289 }290291 /// FNV-1a, to compare outputs across processes (Swift's own hashing is seeded per process).292 static func fingerprint(_ text: String) -> String {293 var h: UInt64 = 0xcbf29ce484222325294 for b in text.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 }295 return String(h, radix: 16)296 }297298 @Test func tracingIsDeterministicAcrossProcesses() throws {299 // Reference fingerprints recorded on this Mac; a second process (another hash seed, another thread300 // schedule) must reproduce them exactly. Set ORIX_VECTOR_PRINT_FINGERPRINTS=1 to print new ones.301 let cases: [(String, CGImage, VectorSettings)] = [302 ("text", Fixture.text(), VectorSettings(mode: .logo)),303 ("illustration", Fixture.illustration(), VectorSettings(mode: .illustration)),304 ("photo", Fixture.photoLike(128), VectorSettings(mode: .illustration)),305 ]306 let prints = try cases.map { ($0.0, Self.fingerprint(try Vectorizer().trace($0.1, settings: $0.2, measureSimilarity: false).svg)) }307 if ProcessInfo.processInfo.environment["ORIX_VECTOR_PRINT_FINGERPRINTS"] == "1" { print("FINGERPRINTS", prints) }308 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-vector-fingerprints-\(getuid()).txt")309 let line = prints.map { "\($0.0)=\($0.1)" }.joined(separator: ",")310 if let previous = try? String(contentsOf: url, encoding: .utf8), previous.hasPrefix("v1:\(Self.sourceStamp):") {311 #expect(previous == "v1:\(Self.sourceStamp):" + line, "a previous test process produced different SVG text")312 }313 try ("v1:\(Self.sourceStamp):" + line).write(to: url, atomically: true, encoding: .utf8)314 }315316 /// Changes whenever the tracer's sources change, so a stale fingerprint file is ignored.317 static let sourceStamp: String = {318 let dir = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Sources/EngineVector")319 let files = ((try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []).sorted { $0.path < $1.path }320 let stamp = files.map { "\($0.lastPathComponent):\(((try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate)?.timeIntervalSince1970 ?? 0))" }.joined()321 return fingerprint(stamp)322 }()323324 @Test func tracingIsDeterministic() throws {325 for (image, settings) in [(Fixture.text(), VectorSettings(mode: .logo)), (Fixture.illustration(), VectorSettings(mode: .illustration)),326 (Fixture.photoLike(128), VectorSettings(mode: .illustration)), (Fixture.noisyScan(160), VectorSettings(mode: .lineArt))] {327 let a = try Vectorizer().trace(image, settings: settings)328 let b = try Vectorizer().trace(image, settings: settings)329 #expect(a.svg == b.svg)330 #expect(a.document == b.document)331 #expect(a.similarity == b.similarity)332 }333 }334335 @Test func thresholdControl() throws {336 // A grey ramp of five bars: the manual threshold decides how many are ink.337 let image = Fixture.render(250, 60, antialias: false) { ctx in338 for (i, level) in [20, 70, 120, 170, 220].enumerated() {339 ctx.setFillColor(Fixture.color(level, level, level)); ctx.fill(CGRect(x: 10 + i * 48, y: 10, width: 30, height: 40))340 }341 }342 var settings = VectorSettings(mode: .monochrome)343 settings.automaticThreshold = false344 settings.minimumRegionArea = 0345 var counts: [Int] = []346 for threshold in [0.2, 0.4, 0.6, 0.8] {347 settings.threshold = threshold348 let result = try Vectorizer().trace(image, settings: settings)349 counts.append(result.statistics.subpathCount)350 #expect(abs((result.statistics.thresholdUsed ?? 0) - threshold) < 0.01)351 }352 #expect(counts == [1, 2, 3, 4], "\(counts)")353 settings.automaticThreshold = true354 let auto = try Vectorizer().trace(Fixture.disc(), settings: settings)355 let used = try #require(auto.statistics.thresholdUsed)356 #expect(used > 0.2 && used < 0.8)357 #expect(Quantizer.otsu((0..<256).map { $0 < 40 ? 100 : ($0 > 200 ? 300 : 0) }) > 40)358 #expect(Quantizer.otsu((0..<256).map { $0 < 40 ? 100 : ($0 > 200 ? 300 : 0) }) <= 201)359 }360361 @Test func detailSmoothnessAndSimplificationChangeTheOutput() throws {362 let image = Fixture.text("Sg&", width: 420, height: 200, fontSize: 130)363 var low = VectorSettings(mode: .logo); low.detail = 0.1; low.simplification = 0.8364 var high = VectorSettings(mode: .logo); high.detail = 1.0; high.simplification = 0365 let coarse = try traced(image, low).result, fine = try traced(image, high).result366 #expect(coarse.statistics.nodeCount < fine.statistics.nodeCount)367 #expect(coarse.statistics.svgByteCount < fine.statistics.svgByteCount)368 #expect(fine.similarity!.meanAbsoluteError <= coarse.similarity!.meanAbsoluteError)369370 // Smoothness: a square keeps four corners at low values and loses them at the maximum.371 let square = Fixture.render(120, 120) { ctx in ctx.setFillColor(Fixture.color(0, 0, 0)); ctx.fill(CGRect(x: 30.5, y: 30.5, width: 60, height: 60)) }372 var sharp = VectorSettings(mode: .monochrome); sharp.curveSmoothness = 0.2373 var round = VectorSettings(mode: .monochrome); round.curveSmoothness = 1.0374 #expect(try traced(square, sharp).result.statistics.curveSegmentCount == 0)375 #expect(try traced(square, round).result.statistics.curveSegmentCount > 0)376377 // Precision: no decimal point at 0, at most three decimals at 3.378 var integers = VectorSettings(mode: .logo); integers.precision = 0379 let svg = try traced(Fixture.disc(), integers).result.svg380 let data = svg.components(separatedBy: " d=\"").dropFirst().map { $0.prefix(while: { $0 != "\"" }) }.joined()381 #expect(!data.contains("."))382 }383384 @Test func denoisingCleansANoisyScan() throws {385 let image = Fixture.noisyScan()386 var raw = VectorSettings(mode: .monochrome)387 raw.minimumRegionArea = 0388 let noisy = try traced(image, raw).result389 var clean = VectorSettings(mode: .monochrome)390 clean.denoise = .median391 let (result, parsed) = try traced(image, clean)392 #expect(noisy.statistics.subpathCount > 20, "the specks are really in the fixture")393 #expect(result.statistics.subpathCount == 2, "disc and bar only")394 let rendering = parsed.makeImage(pixelWidth: 256, pixelHeight: 256)!395 #expect(Probe.pixel(rendering, 110, 100)[3] == 255)396 #expect(Probe.pixel(rendering, 130, 205)[3] == 255)397 #expect(Probe.pixel(rendering, 20, 20)[3] == 0)398 var bilateral = VectorSettings(mode: .monochrome)399 bilateral.denoise = .bilateral400 #expect(try traced(image, bilateral).result.statistics.subpathCount < noisy.statistics.subpathCount)401 }402403 @Test func enlargementIsOptionalAndKeepsSourceCoordinates() throws {404 let image = Fixture.transparentIcon(32)405 let (plain, parsedPlain) = try traced(image, VectorSettings(mode: .icon))406 #expect(plain.statistics.tracedWidth == 32)407 var enlarged = VectorSettings(mode: .icon); enlarged.upscale = .x4408 let (result, parsed) = try traced(image, enlarged)409 #expect(result.statistics.tracedWidth == 128)410 #expect(parsed.width == 32 && parsed.height == 32)411 for document in [parsedPlain, parsed] {412 let rendering = document.makeImage(pixelWidth: 32, pixelHeight: 32)!413 #expect(Fixture.meanAbsoluteError(image, rendering) < 1.0)414 }415 // Bilinear enlargement does not ring: a hard edge stays between its two levels.416 let hard = try Raster(image: Fixture.hardEdged(16, 16) { x, _ in x < 8 }, width: 16, height: 16).enlarged(by: 4)417 #expect(hard.width == 64)418 #expect(Set(hard.data).isSubset(of: Set((0...255).map(UInt8.init))))419 #expect(hard.data[(8 * 64 + 2) * 4] == 0 && hard.data[(8 * 64 + 60) * 4] == 255)420 }421422 @Test func previewPassIsFasterAndUsesFullSizeCoordinates() throws {423 let image = Fixture.text("ORIX", width: 1536, height: 600, fontSize: 390)424 let full = try Vectorizer().trace(image, settings: VectorSettings(mode: .logo), measureSimilarity: false)425 let preview = try Vectorizer().trace(image, settings: VectorSettings(mode: .logo), quality: .preview(maxDimension: 256), measureSimilarity: false)426 #expect(preview.statistics.tracedWidth == 256)427 #expect(preview.document.width == 1536 && preview.document.height == 600)428 #expect(preview.statistics.totalSeconds < full.statistics.totalSeconds)429 #expect(!preview.warnings.contains { $0.code == "traced-reduced" })430 // Same drawing, coarser: the preview is close to the full trace when both are rasterised.431 let a = full.document.makeImage(pixelWidth: 384, pixelHeight: 150)!, b = preview.document.makeImage(pixelWidth: 384, pixelHeight: 150)!432 #expect(Fixture.meanAbsoluteError(a, b) < 3.0)433 // CGPath representation for on-screen drawing.434 let layers = preview.document.cgLayers435 #expect(layers.count == preview.document.layers.count)436 #expect(layers.allSatisfy { !$0.path.isEmpty && $0.path.boundingBoxOfPath.maxX <= 1536.5 })437 }438}439440@Suite("Tracer: honesty and limits") struct TracerLimitTests {441 @Test func photographicContentIsDetectedAndReported() throws {442 let photo = try Vectorizer().trace(Fixture.photoLike(), settings: VectorSettings(mode: .illustration))443 #expect(photo.content.kind == .photographic)444 #expect(photo.warnings.contains { $0.code == "photographic-content" })445 #expect(photo.content.colorEntropyBits > 7)446 // The measured similarity says what the user will see: far from the source.447 #expect(photo.similarity!.meanDeltaE > 2)448 #expect(photo.statistics.nodeCount > 500)449450 // A smooth gradient is not a photograph, but it is not flat artwork either.451 var data = [UInt8](repeating: 255, count: 200 * 200 * 4)452 for y in 0..<200 { for x in 0..<200 { let i = (y * 200 + x) * 4; data[i] = UInt8(x * 255 / 199); data[i + 1] = UInt8(y * 255 / 199); data[i + 2] = 128 } }453 let gradient = try Vectorizer().trace(Fixture.image(fromRGBA: data, width: 200, height: 200), settings: VectorSettings(mode: .illustration))454 #expect(gradient.content.kind != .flat)455 #expect(gradient.warnings.contains { $0.code == "shaded-content" || $0.code == "photographic-content" })456457 for flat in [Fixture.text(), Fixture.illustration(), Fixture.transparentIcon(), Fixture.polygons()] {458 let result = try Vectorizer().trace(flat, settings: VectorSettings(mode: .logo), measureSimilarity: false)459 #expect(result.content.kind == .flat)460 #expect(!result.warnings.contains { $0.code.hasSuffix("-content") })461 }462 }463464 @Test func complexityIsCapped() throws {465 let image = Fixture.photoLike(200)466 var settings = VectorSettings(mode: .highDetail)467 settings.minimumRegionArea = 0468 settings.maximumRegions = 64469 do {470 let result = try Vectorizer().trace(image, settings: settings, measureSimilarity: false)471 #expect(result.statistics.regionCount <= 64 * 2)472 #expect(result.warnings.contains { $0.code == "regions-coarsened" && $0.isDataLoss })473 #expect(result.statistics.minimumRegionAreaUsed > 0)474 } catch let error as VectorError {475 guard case .tooComplex = error else { Issue.record("unexpected error \(error)"); return }476 }477 var nodes = VectorSettings(mode: .illustration)478 nodes.maximumNodes = 256479 do {480 let result = try Vectorizer().trace(image, settings: nodes, measureSimilarity: false)481 #expect(result.warnings.contains { $0.code == "nodes-coarsened" })482 } catch let error as VectorError {483 guard case .tooComplex(let message) = error else { Issue.record("unexpected error \(error)"); return }484 #expect(message.contains("256"))485 }486 }487488 @Test func cancellationStopsTheTrace() async throws {489 let image = Fixture.photoLike(256)490 #expect(throws: CancellationError.self) {491 _ = try Vectorizer().trace(image, settings: VectorSettings(mode: .illustration), isCancelled: { true })492 }493 // Cancel after the trace has started.494 let counter = Counter()495 #expect(throws: CancellationError.self) {496 _ = try Vectorizer().trace(image, settings: VectorSettings(mode: .illustration), isCancelled: { counter.increment() > 6 })497 }498 // Task cancellation reaches the asynchronous entry point.499 let big = Fixture.photoLike(512)500 let boxed = Unchecked(big)501 let task = Task { try await Vectorizer().trace(boxed.value, settings: VectorSettings(mode: .highDetail)) }502 try await Task.sleep(nanoseconds: 30_000_000)503 task.cancel()504 await #expect(throws: CancellationError.self) { _ = try await task.value }505 }506507 @Test func oversizedImagesAreTracedReducedAndSaySo() throws {508 let image = Fixture.disc(512, radius: 180)509 var settings = VectorSettings(mode: .monochrome)510 settings.maximumTracePixels = 128 * 128511 let result = try Vectorizer().trace(image, settings: settings)512 #expect(result.statistics.tracedWidth == 128 && result.statistics.sourceWidth == 512)513 #expect(result.document.width == 512 && result.svg.contains("viewBox=\"0 0 512 512\""))514 #expect(result.warnings.contains { $0.code == "traced-reduced" })515 let errors = Probe.samples(result.document.layers[0]).map { abs((($0.x - 256) * ($0.x - 256) + ($0.y - 256) * ($0.y - 256)).squareRoot() - 180) }516 #expect(errors.max()! < 2.0, "coordinates are in source pixels (one traced pixel = 4 source pixels): \(errors.max()!)")517 // A reduced copy with the original size given explicitly (what the engine does after a bounded decode).518 let small = Fixture.disc(128, radius: 45)519 let scaled = try Vectorizer().trace(small, settings: VectorSettings(mode: .monochrome), documentSize: (512, 512))520 #expect(scaled.document.width == 512)521 #expect(Probe.samples(scaled.document.layers[0]).map(\.x).max()! > 400)522 }523524 // Regression (2026-11-21): about 1 in 100 generated 12 MP images failed the engine's own check "A contour525 // leaves the viewBox". 324 generated images of nine sizes, three presets, traced at their own size and as526 // reduced copies of a 4× larger original (what the engine does above the tracing limit, where one traced pixel527 // is four document pixels): not a single curve may leave the canvas, measured on the curves' true extent.528 @Test func noContourEverLeavesTheCanvas() throws {529 struct Case: Sendable { let width: Int; let height: Int; let scale: Int; let seed: Int; let mode: VectorMode }530 let sizes: [(Int, Int, Int)] = [(64, 64, 1), (150, 100, 1), (301, 517, 1), (400, 300, 1), (640, 480, 1), (800, 600, 1),531 (320, 240, 4), (500, 375, 4), (640, 427, 4)]532 let modes: [VectorMode] = [.logo, .illustration, .highDetail]533 var cases: [Case] = []534 for (n, size) in sizes.enumerated() {535 for seed in 1...36 { cases.append(Case(width: size.0, height: size.1, scale: size.2, seed: seed + 100 * n, mode: modes[seed % 3])) }536 }537 #expect(cases.count == 324)538 let failures = Counter(), traced = Counter()539 let log = Messages()540 DispatchQueue.concurrentPerform(iterations: cases.count) { index in541 let c = cases[index]542 let image = Fixture.seeded(width: c.width, height: c.height, seed: c.seed)543 do {544 let result = try Vectorizer().trace(image, settings: .preset(c.mode), documentSize: (c.width * c.scale, c.height * c.scale), measureSimilarity: false)545 _ = traced.increment()546 let out = Fixture.excursion(result.document)547 let report = try TracedSVGReader.read(result.svg).report548 if out > 1e-9 || !report.withinViewBox || !report.allSubpathsClosed || !report.allNumbersFinite || result.document.layers.isEmpty {549 _ = failures.increment()550 log.add("\(c.width)×\(c.height) ×\(c.scale) seed \(c.seed) \(c.mode.rawValue): leaves the canvas by \(out) px")551 }552 } catch {553 _ = failures.increment()554 log.add("\(c.width)×\(c.height) ×\(c.scale) seed \(c.seed) \(c.mode.rawValue): \(error)")555 }556 }557 #expect(traced.current == cases.count)558 #expect(failures.current == 0, "\(failures.current) of \(cases.count) traces failed: \(log.all.prefix(5))")559 }560561 @Test func emptyAndBlankImages() throws {562 let blank = Fixture.render(64, 64) { _ in }563 let result = try Vectorizer().trace(blank, settings: VectorSettings(mode: .monochrome))564 #expect(result.document.layers.isEmpty)565 #expect(result.warnings.contains { $0.code == "nothing-traced" })566 let clear = Fixture.render(64, 64, background: nil) { _ in }567 #expect(try Vectorizer().trace(clear, settings: VectorSettings(mode: .logo)).document.layers.isEmpty)568 let onePixel = Fixture.render(1, 1) { _ in }569 let tiny = try Vectorizer().trace(onePixel, settings: VectorSettings(mode: .logo))570 #expect(tiny.document.width == 1)571 }572}573574final class Messages: @unchecked Sendable {575 private let lock = NSLock()576 private var items: [String] = []577 func add(_ s: String) { lock.lock(); items.append(s); lock.unlock() }578 var all: [String] { lock.lock(); defer { lock.unlock() }; return items.sorted() }579}580581final class Counter: @unchecked Sendable {582 private let lock = NSLock()583 private var value = 0584 func increment() -> Int { lock.lock(); defer { lock.unlock() }; value += 1; return value }585 var current: Int { lock.lock(); defer { lock.unlock() }; return value }586}587