Repository Public License
1// ORIX Convert — Packages/EngineModel3D/Tests/EngineModel3DTests/MalformedTests.swift2// Description: Malformed, truncated and corrupted inputs of every format: the engine must answer with an error (or a3// valid conversion), never crash the process. Third-party parsers are exercised through the helper4// process; the engine's own readers are fuzzed in-process, where a crash would stop the test run.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation7import Testing8import simd9import ConvertCore10@testable import EngineModel3D1112/// Deterministic generator for the mutations.13struct Mutator {14 var state: UInt6415 init(seed: UInt64) { state = seed &* 0x9E3779B97F4A7C15 | 1 }16 mutating func next() -> UInt64 { state ^= state << 13; state ^= state >> 7; state ^= state << 17; return state }17 mutating func below(_ n: Int) -> Int { n <= 0 ? 0 : Int(next() % UInt64(n)) }1819 /// Truncations and byte-level corruptions of `data`.20 mutating func variants(of data: Data, corruptions: Int) -> [(String, Data)] {21 var out: [(String, Data)] = []22 for fraction in [0.0, 0.03, 0.2, 0.5, 0.8, 0.97] { out.append(("cut-\(fraction)", data.prefix(Int(Double(data.count) * fraction)))) }23 if data.count > 1 { out.append(("cut-last", data.dropLast(1))) }24 for i in 0..<corruptions {25 var copy = data26 let edits = 1 + below(8)27 for _ in 0..<edits where !copy.isEmpty {28 let at = below(copy.count)29 switch below(4) {30 case 0: copy[copy.startIndex + at] = UInt8(truncatingIfNeeded: next())31 case 1: copy[copy.startIndex + at] = 0xFF32 case 2: copy[copy.startIndex + at] = 033 default:34 // Overwrite a run with a large little-endian number (hits counts, offsets and lengths).35 for k in 0..<4 where at + k < copy.count { copy[copy.startIndex + at + k] = k == 3 ? 0x7F : 0xFF }36 }37 }38 out.append(("flip-\(i)", copy))39 }40 return out41 }42}4344@Suite("Malformed inputs never crash")45struct MalformedTests {46 /// Converts and inspects a damaged file; any outcome but a crash or a non-engine error is accepted.47 static func exercise(_ engine: Model3DEngine, url: URL, format: FormatID, work: URL) async -> String {48 var outcome = ""49 do { _ = try await engine.inspect(url, format: format); outcome += "inspected " }50 catch is ConversionError { outcome += "inspect-error " }51 catch { Issue.record("\(url.lastPathComponent): unexpected error type from inspect: \(error)") }52 do {53 let (output, _, request) = try await engine.run(url, from: format, to: format == .stl ? .ply : .stl, work: work)54 _ = try? await engine.validate(output, request: request, source: nil)55 outcome += "converted"56 } catch let error as ConversionError {57 outcome += "convert-error"58 // With ORIX_M3D_FUZZ_LOG set, parser crashes that the helper process contained are listed.59 if ProcessInfo.processInfo.environment["ORIX_M3D_FUZZ_LOG"] != nil, error.errorDescription?.contains("stopped unexpectedly") == true {60 print("FUZZ-CRASH-IN-HELPER \(format.rawValue) \(url.deletingLastPathComponent().lastPathComponent)")61 }62 }63 catch { Issue.record("\(url.lastPathComponent): unexpected error type from convert: \(error)") }64 return outcome65 }6667 @Test("truncated and corrupted fixtures", arguments: Model3DCatalog.sources.map(\.rawValue))68 func damagedFixtures(format raw: String) async throws {69 let format = FormatID(raw)70 // The helper must be there: this is what keeps a parser crash away from the test process.71 try #require(Model3DEngine.isHelperAvailable)72 let engine = Model3DEngine(isolation: .required)73 let dir = Fixtures.directory("damaged"); defer { try? FileManager.default.removeItem(at: dir) }74 let pristine = dir.appendingPathComponent("pristine", isDirectory: true)75 try FileManager.default.createDirectory(at: pristine, withIntermediateDirectories: true)76 let source = try Fixtures.source(format, in: pristine)77 let original = try Data(contentsOf: source.url)78 var mutator = Mutator(seed: UInt64(raw.utf8.reduce(7) { $0 &* 31 &+ Int($1) }))79 var errors = 0, conversions = 080 for (label, bytes) in mutator.variants(of: original, corruptions: 10) {81 let sub = dir.appendingPathComponent(label, isDirectory: true)82 // Side files (MTL, texture) stay intact next to the damaged model.83 try FileManager.default.copyItem(at: pristine, to: sub)84 let url = sub.appendingPathComponent(source.url.lastPathComponent)85 try bytes.write(to: url)86 let outcome = await Self.exercise(engine, url: url, format: format, work: sub.appendingPathComponent("w"))87 if outcome.hasSuffix("convert-error") { errors += 1 } else if outcome.hasSuffix("converted") { conversions += 1 }88 }89 // An empty file and a file cut in its first bytes are always errors.90 #expect(errors >= 2, "\(format): \(errors) errors, \(conversions) conversions")91 #expect(errors + conversions == 17)92 }9394 @Test func emptyGarbageAndMislabelledFiles() async throws {95 let engine = Model3DEngine(isolation: .required)96 let dir = Fixtures.directory("garbage"); defer { try? FileManager.default.removeItem(at: dir) }97 var mutator = Mutator(seed: 99)98 let noise = Data((0..<4096).map { _ in UInt8(truncatingIfNeeded: mutator.next()) })99 let png = Fixtures.png()100 for format in Model3DCatalog.sources {101 let ext = FormatCatalog.format(format)?.preferredExtension ?? format.rawValue102 for (label, bytes) in [("empty", Data()), ("noise", noise), ("png", png), ("text", Data("hello, this is not a model\n".utf8)), ("zeros", Data(count: 1000))] {103 let url = dir.appendingPathComponent("\(label)-\(format.rawValue).\(ext)")104 try bytes.write(to: url)105 do { _ = try await engine.run(url, from: format, to: format == .stl ? .ply : .stl, work: dir.appendingPathComponent("w")); Issue.record("\(label).\(ext) was converted") }106 catch is ConversionError {} catch { Issue.record("\(label).\(ext): \(error)") }107 do { _ = try await engine.inspect(url, format: format); Issue.record("\(label).\(ext) was inspected") }108 catch is ConversionError {} catch { Issue.record("\(label).\(ext): \(error)") }109 }110 }111 await #expect(throws: ConversionError.self) { _ = try await engine.inspect(dir.appendingPathComponent("absent.glb"), format: .glb) }112 }113114 @Test func declaredSizesAreNeverTrusted() throws {115 let dir = Fixtures.directory("lies"); defer { try? FileManager.default.removeItem(at: dir) }116 let limits = ModelLimits()117 // Binary STL announcing four billion triangles in a 134-byte file.118 var stl = Data(count: 80); stl.append(contentsOf: [0xFF, 0xFF, 0xFF, 0xFF]); stl.append(Data(count: 50))119 let stlURL = dir.appendingPathComponent("lie.stl"); try stl.write(to: stlURL)120 #expect(throws: ConversionError.self) { _ = try STLCodec.read(stlURL, limits: limits) }121 // PLY announcing more vertices than the file can hold, an absurd list length, and a negative index.122 for body in ["element vertex 4000000000\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n",123 "element vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uint int vertex_indices\nend_header\n0 0 0\n1 0 0\n0 1 0\n4000000000 0 1 2\n",124 "element vertex 1\nproperty list uchar float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n",125 "element vertex 3\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n1 0 nan\nabc 1 0\n"] {126 let url = dir.appendingPathComponent("lie-\(UUID().uuidString).ply")127 try Data(("ply\nformat ascii 1.0\n" + body).utf8).write(to: url)128 #expect(throws: ConversionError.self) { _ = try PLYCodec.read(url, limits: limits) }129 }130 var binary = Data("ply\nformat binary_little_endian 1.0\nelement vertex 1000000\nproperty float x\nproperty float y\nproperty float z\nend_header\n".utf8)131 binary.append(Data(count: 24))132 let binaryURL = dir.appendingPathComponent("short.ply"); try binary.write(to: binaryURL)133 #expect(throws: ConversionError.self) { _ = try PLYCodec.read(binaryURL, limits: limits) }134 // Out-of-range face indices are dropped and reported, not followed.135 let outOfRange = dir.appendingPathComponent("range.ply")136 try Data("ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 2\nproperty list uchar int vertex_indices\nend_header\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n3 0 1 7\n".utf8).write(to: outOfRange)137 let scene = try PLYCodec.read(outOfRange, limits: limits)138 #expect(scene.triangleCount == 1 && scene.notes.contains { $0.code == "invalid-triangles" })139 // ZIP entry announcing a huge inflated size.140 var zip = ZipWriter()141 try zip.add(name: "3D/3dmodel.model", contents: Data(Fixtures.threeMFModel.utf8), deflate: true)142 var package = zip.finish()143 let central = try #require(package.range(of: Data([0x50, 0x4B, 0x01, 0x02])))144 package.replaceSubrange((central.lowerBound + 24)..<(central.lowerBound + 28), with: [0xFF, 0xFF, 0xFF, 0x7F])145 let packageURL = dir.appendingPathComponent("bomb.3mf"); try package.write(to: packageURL)146 #expect(throws: ConversionError.self) { _ = try ThreeMF.read(packageURL, limits: limits) }147 // 3MF triangle indices out of range are dropped.148 let bad = Fixtures.threeMFModel.replacingOccurrences(of: "<triangle v1=\"1\" v2=\"2\" v3=\"3\"/>", with: "<triangle v1=\"1\" v2=\"2\" v3=\"99\"/>")149 let badURL = dir.appendingPathComponent("range.3mf")150 try Fixtures.storedZip([("3D/3dmodel.model", Data(bad.utf8))]).write(to: badURL)151 let badScene = try ThreeMF.read(badURL, limits: limits)152 #expect(badScene.triangleCount == 3 && badScene.notes.contains { $0.code == "invalid-triangles" })153 // A 3MF whose components refer to each other in a cycle terminates.154 let cyclic = "<model unit=\"millimeter\" xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\"><resources>"155 + "<object id=\"1\"><mesh><vertices><vertex x=\"0\" y=\"0\" z=\"0\"/><vertex x=\"1\" y=\"0\" z=\"0\"/><vertex x=\"0\" y=\"1\" z=\"0\"/></vertices><triangles><triangle v1=\"0\" v2=\"1\" v3=\"2\"/></triangles></mesh></object>"156 + "<object id=\"2\"><components><component objectid=\"3\"/><component objectid=\"1\"/></components></object>"157 + "<object id=\"3\"><components><component objectid=\"2\"/></components></object></resources><build><item objectid=\"2\"/></build></model>"158 let cyclicURL = dir.appendingPathComponent("cycle.3mf")159 try Fixtures.storedZip([("3D/3dmodel.model", Data(cyclic.utf8))]).write(to: cyclicURL)160 var bounded = ModelLimits(); bounded.maxNodes = 5000161 let cyclicScene = try ThreeMF.read(cyclicURL, limits: bounded)162 #expect(cyclicScene.nodes.count <= 5000 && cyclicScene.triangleCount == 1)163 }164165 @Test func ownReadersSurviveHeavyFuzzing() throws {166 let dir = Fixtures.directory("fuzz"); defer { try? FileManager.default.removeItem(at: dir) }167 let limits = ModelLimits()168 let cube = Scene3D(mesh: Fixtures.sphere(segments: 8, rings: 4))169 var seeds: [(String, Data, (URL) throws -> Void)] = []170 let stl = dir.appendingPathComponent("seed.stl"); try STLCodec.write(cube, to: stl, binary: true)171 seeds.append(("stl", try Data(contentsOf: stl), { _ = try STLCodec.read($0, limits: limits) }))172 seeds.append(("stl", Data(Fixtures.stlText.utf8), { _ = try STLCodec.read($0, limits: limits) }))173 let ply = dir.appendingPathComponent("seed.ply"); try PLYCodec.write(Fixtures.vertexColorScene(), to: ply, binary: true)174 seeds.append(("ply", try Data(contentsOf: ply), { _ = try PLYCodec.read($0, limits: limits) }))175 seeds.append(("ply", Data(Fixtures.plyText.utf8), { _ = try PLYCodec.read($0, limits: limits) }))176 seeds.append(("3mf", Fixtures.threeMFPackage(), { _ = try ThreeMF.read($0, limits: limits) }))177 let written3MF = dir.appendingPathComponent("seed.3mf"); try ThreeMF.write(Fixtures.multiMaterialScene(), to: written3MF, unit: .millimeter)178 seeds.append(("3mf", try Data(contentsOf: written3MF), { _ = try ThreeMF.read($0, limits: limits) }))179 let glb = try GLTFWriter.write(Fixtures.richScene(), directory: dir, baseName: "seed", container: .glb).files[0]180 seeds.append(("glb", try Data(contentsOf: glb), { _ = try GLTFDocument.load($0, limits: limits).check() }))181 seeds.append(("gltf", Data(Fixtures.gltfText.utf8), { _ = try GLTFDocument.load($0, limits: limits).check(); _ = try GLTFDocument.load($0, limits: limits).facts() }))182 let crate = try #require(Bundle.module.url(forResource: "usdcat-cm-zup", withExtension: "usdc", subdirectory: "Fixtures"))183 seeds.append(("usdc", try Data(contentsOf: crate), { _ = USDLayerInfo.read($0, limits: limits).escapingAssetPaths() }))184 seeds.append(("usda", Data(Fixtures.usdaText.utf8), { _ = USDLayerInfo.read($0, limits: limits).escapingAssetPaths() }))185 let usdz = dir.appendingPathComponent("seed.usdz"); _ = try USDWriter.writeUSDZ(Fixtures.richScene(), to: usdz, baseName: "seed", unit: .meter, upAxis: .y)186 seeds.append(("usdz", try Data(contentsOf: usdz), { _ = USDLayerInfo.read($0, limits: limits); _ = try ZipReader(try Data(contentsOf: $0)) }))187 seeds.append(("dae", Data(Fixtures.daeText.utf8), { _ = try ColladaCheck.read($0, limits: limits); _ = FormatFacts.collada($0) }))188 let blob = dir.appendingPathComponent("seed.blob"); try SceneBlob.write(Fixtures.richScene(), to: blob)189 seeds.append(("blob", try Data(contentsOf: blob), { var s = try SceneBlob.read($0, limits: limits); s.sanitize(); _ = Model3DSummary(scene: s, format: .glb, isolated: false) }))190191 var mutator = Mutator(seed: 2026)192 var rejected = 0, accepted = 0193 for (index, seed) in seeds.enumerated() {194 let url = dir.appendingPathComponent("mutant-\(index).\(seed.0)")195 for (_, bytes) in mutator.variants(of: seed.1, corruptions: 220) {196 try bytes.write(to: url)197 do { try seed.2(url); accepted += 1 } catch is ConversionError { rejected += 1 } catch { Issue.record("\(seed.0): unexpected error \(error)") }198 }199 }200 #expect(rejected > 200 && accepted > 200, "\(rejected) rejected, \(accepted) accepted")201 }202203 @Test func dracoAndMeshoptAreRefusedClearly() async throws {204 let dir = Fixtures.directory("draco"); defer { try? FileManager.default.removeItem(at: dir) }205 let engine = Model3DEngine()206 var json = try #require(try JSONSerialization.jsonObject(with: Data(Fixtures.gltfText.utf8)) as? [String: Any])207 json["extensionsUsed"] = ["KHR_draco_mesh_compression"]; json["extensionsRequired"] = ["KHR_draco_mesh_compression"]208 let draco = dir.appendingPathComponent("draco.gltf")209 try JSONSerialization.data(withJSONObject: json).write(to: draco)210 do { _ = try await engine.run(draco, from: .gltf, to: .stl, work: dir.appendingPathComponent("w")); Issue.record("a Draco file was accepted") }211 catch let error as ConversionError { #expect(error.errorDescription?.contains("Draco") == true) }212 json["extensionsUsed"] = ["EXT_meshopt_compression"]; json["extensionsRequired"] = ["EXT_meshopt_compression"]213 let meshopt = dir.appendingPathComponent("meshopt.gltf")214 try JSONSerialization.data(withJSONObject: json).write(to: meshopt)215 do { _ = try await engine.run(meshopt, from: .gltf, to: .stl, work: dir.appendingPathComponent("w")); Issue.record("a meshopt file was accepted") }216 catch let error as ConversionError { #expect(error.errorDescription?.contains("meshopt") == true) }217 }218219 @Test func modelsWithoutTrianglesAreRefused() async throws {220 let dir = Fixtures.directory("points"); defer { try? FileManager.default.removeItem(at: dir) }221 let cloud = dir.appendingPathComponent("cloud.ply")222 try Data("ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n1 0 0\n0 1 0\n".utf8).write(to: cloud)223 let engine = Model3DEngine()224 let summary = try await engine.summary(of: cloud, format: .ply)225 #expect(summary.triangleCount == 0 && summary.unconverted.pointsAndLines == 3 && summary.notes.contains { $0.code == "point-cloud" })226 do { _ = try await engine.run(cloud, from: .ply, to: .stl, work: dir.appendingPathComponent("w")); Issue.record("a point cloud was converted") }227 catch let error as ConversionError { #expect(error.errorDescription?.contains("points") == true) }228 let lines = dir.appendingPathComponent("lines.obj")229 try Data("v 0 0 0\nv 1 0 0\nv 1 1 0\nl 1 2 3\n".utf8).write(to: lines)230 await #expect(throws: ConversionError.self) { _ = try await engine.run(lines, from: .obj, to: .stl, work: dir.appendingPathComponent("w")) }231 }232}233234@Suite("Own codecs")235struct CodecTests {236 @Test func gltfCheckerFindsStructuralErrors() throws {237 let dir = Fixtures.directory("checker"); defer { try? FileManager.default.removeItem(at: dir) }238 func problems(_ edit: (inout [String: Any]) -> Void) throws -> [String] {239 var json = try #require(try JSONSerialization.jsonObject(with: Data(Fixtures.gltfText.utf8)) as? [String: Any])240 edit(&json)241 let url = dir.appendingPathComponent("\(UUID().uuidString).gltf")242 try JSONSerialization.data(withJSONObject: json).write(to: url)243 return try GLTFDocument.load(url, limits: ModelLimits()).check().problems244 }245 #expect(try problems { _ in }.isEmpty)246 #expect(try problems { $0["asset"] = nil }.contains { $0.contains("asset.version") })247 #expect(try problems { $0["asset"] = ["version": "1.0"] }.contains { $0.contains("not 2.x") })248 #expect(try problems { var a = $0["accessors"] as! [[String: Any]]; a[1]["count"] = 4; $0["accessors"] = a }.contains { $0.contains("reads past its bufferView") })249 #expect(try problems { var a = $0["accessors"] as! [[String: Any]]; a[1]["min"] = nil; $0["accessors"] = a }.contains { $0.contains("min/max") })250 #expect(try problems { var a = $0["accessors"] as! [[String: Any]]; a[0]["componentType"] = 5122; $0["accessors"] = a }.contains { $0.contains("unsigned SCALAR") })251 #expect(try problems { var v = $0["bufferViews"] as! [[String: Any]]; v[1]["byteLength"] = 400; $0["bufferViews"] = v }.contains { $0.contains("exceeds its buffer") })252 #expect(try problems { var b = $0["buffers"] as! [[String: Any]]; b[0]["byteLength"] = 4000; $0["buffers"] = b }.contains { $0.contains("only 44 are available") })253 #expect(try problems { $0["nodes"] = [["mesh": 3]] }.contains { $0.contains("nodes[0].mesh") })254 #expect(try problems { $0["scenes"] = [["nodes": [9]]] }.contains { $0.contains("does not exist") })255 #expect(try problems { $0["meshes"] = [["primitives": [["attributes": ["POSITION": 1], "indices": 1]]]] }.contains { $0.contains("unsigned SCALAR") })256 // Index values beyond the vertex count: two positions only.257 #expect(try problems { var a = $0["accessors"] as! [[String: Any]]; a[1]["count"] = 2; $0["accessors"] = a }.contains { $0.contains("exceed the vertex count") })258 // GLB container: wrong length in the header.259 var glb = try Data(contentsOf: try GLTFWriter.write(Scene3D(mesh: Fixtures.cube()), directory: dir, baseName: "c", container: .glb).files[0])260 glb.replaceSubrange(8..<12, with: [1, 0, 0, 0])261 let bad = dir.appendingPathComponent("bad.glb"); try glb.write(to: bad)262 #expect(try GLTFDocument.load(bad, limits: ModelLimits()).check().problems.contains { $0.contains("GLB header length") })263 }264265 @Test func plyVariants() throws {266 let dir = Fixtures.directory("ply"); defer { try? FileManager.default.removeItem(at: dir) }267 // Big-endian binary with a double-precision vertex, an extra property, a quad and CRLF header lines.268 var data = Data("ply\r\nformat binary_big_endian 1.0\r\nelement vertex 4\r\nproperty double x\r\nproperty double y\r\nproperty double z\r\nproperty uchar quality\r\nelement face 1\r\nproperty list uchar ushort vertex_index\r\nend_header\r\n".utf8)269 for p in [SIMD3<Double>(0, 0, 0), SIMD3(1, 0, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0.5)] {270 for v in [p.x, p.y, p.z] { withUnsafeBytes(of: v.bitPattern.bigEndian) { data.append(contentsOf: $0) } }271 data.append(7)272 }273 data.append(4)274 for i: UInt16 in [0, 1, 2, 3] { withUnsafeBytes(of: i.bigEndian) { data.append(contentsOf: $0) } }275 let url = dir.appendingPathComponent("be.ply"); try data.write(to: url)276 let scene = try PLYCodec.read(url, limits: ModelLimits())277 #expect(scene.meshes[0].positions == [SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0.5)])278 #expect(scene.meshes[0].indices == [0, 1, 2, 0, 2, 3] && scene.metadata.sourcePolygonCount == 1 && scene.metadata.encoding == "binary big endian")279 // Normals, UVs and colours survive a binary and an ASCII round trip.280 var mesh = Fixtures.sphere(segments: 8, rings: 4)281 mesh.colors = mesh.positions.map { SIMD4(abs($0.x), abs($0.y), abs($0.z), 1) }282 for binary in [true, false] {283 let out = dir.appendingPathComponent("rt-\(binary).ply")284 try PLYCodec.write(Scene3D(mesh: mesh), to: out, binary: binary)285 let back = try PLYCodec.read(out, limits: ModelLimits()).meshes[0]286 #expect(back.positions == mesh.positions && back.indices == mesh.indices && back.normals == mesh.normals && back.uvSets == mesh.uvSets)287 for (a, b) in zip(back.colors!, mesh.colors!) { #expect(simd_reduce_max(simd_abs(a - b)) <= 0.5 / 255 + 1e-6) }288 }289 }290291 @Test func stlVariants() throws {292 let dir = Fixtures.directory("stl"); defer { try? FileManager.default.removeItem(at: dir) }293 let ascii = dir.appendingPathComponent("a.stl")294 try Data(Fixtures.stlText.replacingOccurrences(of: "\n", with: "\r\n").replacingOccurrences(of: "vertex 1 0 0", with: "vertex 1.0E+00 0.0e0 -0").utf8).write(to: ascii)295 let scene = try STLCodec.read(ascii, limits: ModelLimits())296 #expect(scene.triangleCount == 4 && scene.meshes[0].name == "tetra" && scene.metadata.encoding == "ASCII")297 #expect(Set(scene.meshes[0].positions.map { [$0.x, $0.y, $0.z] }) == [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]])298 // Binary whose header starts with "solid" (common), with attribute bytes and trailing data.299 let binary = dir.appendingPathComponent("b.stl")300 try STLCodec.write(Scene3D(mesh: Fixtures.cube()), to: binary, binary: true)301 var bytes = try Data(contentsOf: binary)302 bytes.replaceSubrange(0..<5, with: Data("solid".utf8))303 bytes[84 + 48] = 0x1F304 try bytes.write(to: binary)305 let b = try STLCodec.read(binary, limits: ModelLimits())306 #expect(b.triangleCount == 12 && b.metadata.encoding == "binary" && b.notes.contains { $0.code == "stl-attributes" })307 // Exact round trip of awkward floats through the ASCII writer.308 let odd = Mesh3D(name: "odd", positions: [SIMD3(0.1, 1e-20, -3.4028235e38), SIMD3(Float.leastNormalMagnitude, 16777216, 0.30000001), SIMD3(1, 2, 3)], indices: [0, 1, 2])309 for isBinary in [true, false] {310 let out = dir.appendingPathComponent("odd-\(isBinary).stl")311 try STLCodec.write(Scene3D(mesh: odd), to: out, binary: isBinary)312 #expect(try STLCodec.read(out, limits: ModelLimits()).meshes[0].positions == odd.positions)313 }314 #expect(throws: ConversionError.self) { try STLCodec.write(Scene3D(mesh: Mesh3D(name: "e", positions: [], indices: [])), to: dir.appendingPathComponent("e.stl"), binary: true) }315 }316317 @Test func zipWriterAndReader() throws {318 var mutator = Mutator(seed: 5)319 let big = Data((0..<20_000).map { UInt8($0 % 7) }), random = Data((0..<3000).map { _ in UInt8(truncatingIfNeeded: mutator.next()) })320 for alignment in [0, 64] {321 var writer = ZipWriter(alignment: alignment)322 try writer.add(name: "a.txt", contents: Data("hello".utf8), deflate: true)323 try writer.add(name: "dir/big.bin", contents: big, deflate: true)324 try writer.add(name: "dir/random.bin", contents: random, deflate: true)325 let archive = writer.finish()326 let reader = try ZipReader(archive)327 #expect(reader.entries.map(\.name) == ["a.txt", "dir/big.bin", "dir/random.bin"])328 #expect(try reader.contents(of: reader.entries[1], maxSize: 1 << 20) == big)329 #expect(try reader.contents(of: try #require(reader.entry(named: "/dir/random.bin")), maxSize: 1 << 20) == random)330 #expect(reader.entries[1].method == (alignment == 0 ? 8 : 0))331 #expect(throws: ConversionError.self) { _ = try reader.contents(of: reader.entries[1], maxSize: 100) }332 // The system's unzip agrees with the archive (independent reader).333 let dir = Fixtures.directory("zip"); defer { try? FileManager.default.removeItem(at: dir) }334 let url = dir.appendingPathComponent("t.zip"); try archive.write(to: url)335 let process = Process()336 process.executableURL = URL(fileURLWithPath: "/usr/bin/unzip")337 process.arguments = ["-tq", url.path]338 process.standardOutput = FileHandle.nullDevice; process.standardError = FileHandle.nullDevice339 try process.run(); process.waitUntilExit()340 #expect(process.terminationStatus == 0)341 // A flipped byte in the stored data fails the checksum.342 var damaged = archive343 let at = try #require(damaged.range(of: Data("hello".utf8)))344 if alignment == 64 { damaged[at.lowerBound] ^= 0xFF; #expect(throws: ConversionError.self) { _ = try ZipReader(damaged).contents(of: ZipReader(damaged).entries[0], maxSize: 100) } }345 }346 #expect(Checksum.crc32(Data("123456789".utf8)) == 0xCBF43926)347 #expect(Fixtures.crc32(Data("123456789".utf8)) == 0xCBF43926)348 #expect(throws: ConversionError.self) { _ = try ZipReader(Data("not a zip at all, definitely".utf8)) }349 }350351 @Test func threeMFComponentsUnitsAndColours() throws {352 let dir = Fixtures.directory("3mf"); defer { try? FileManager.default.removeItem(at: dir) }353 let model = "<model unit=\"inch\" xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\"><resources>"354 + "<basematerials id=\"5\"><base name=\"a\" displaycolor=\"#FF0000\"/><base name=\"b\" displaycolor=\"#0000FF80\"/></basematerials>"355 + "<object id=\"1\" pid=\"5\" pindex=\"0\"><mesh><vertices><vertex x=\"0\" y=\"0\" z=\"0\"/><vertex x=\"1\" y=\"0\" z=\"0\"/><vertex x=\"0\" y=\"1\" z=\"0\"/><vertex x=\"0\" y=\"0\" z=\"1\"/></vertices>"356 + "<triangles><triangle v1=\"0\" v2=\"2\" v3=\"1\"/><triangle v1=\"0\" v2=\"1\" v3=\"3\" pid=\"5\" p1=\"1\"/></triangles></mesh></object>"357 + "<object id=\"2\"><components><component objectid=\"1\" transform=\"1 0 0 0 1 0 0 0 1 0 0 5\"/><component objectid=\"1\"/></components></object>"358 + "</resources><build><item objectid=\"2\" transform=\"2 0 0 0 2 0 0 0 2 10 0 0\"/></build></model>"359 let url = dir.appendingPathComponent("c.3mf")360 try Fixtures.storedZip([("3D/3dmodel.model", Data(model.utf8))]).write(to: url)361 let scene = try ThreeMF.read(url, limits: ModelLimits())362 #expect(scene.metadata.unit == .inch && scene.materials.count == 2 && scene.meshes.count == 2)363 #expect(scene.materials[1].baseColor.w < 0.51 && scene.materials[1].alphaMode == "BLEND")364 #expect(scene.instances().count == 4)365 let box = try #require(Geometry.boundingBox(of: scene))366 #expect(box.min == SIMD3<Double>(10, 0, 0) && box.max == SIMD3<Double>(12, 2, 12))367 #expect(ThreeMF.declaredUnit(url, limits: ModelLimits()) == "inch")368 // Writer → reader keeps instances, transforms and unit.369 let out = dir.appendingPathComponent("w.3mf")370 try ThreeMF.write(scene, to: out, unit: .inch)371 let back = try ThreeMF.read(out, limits: ModelLimits())372 #expect(back.metadata.unit == .inch && back.triangleCount == 2 && back.instances().count == 4)373 #expect(Geometry.boundingBox(of: back) == box)374 #expect(abs(ThreeMF.linearToSRGB(ThreeMF.srgbToLinear(0.5)) - 0.5) < 1e-6)375 }376377 @Test func assimpBuildHasExactlyTheNeededFormats() {378 #expect(AssimpBridge.version == "6.0.2")379 for ext in ["obj", "stl", "ply", "gltf", "glb", "fbx", "dae", "3mf"] { #expect(AssimpBridge.canImport(extension: ext), "\(ext)") }380 for ext in ["blend", "3ds", "x", "ifc", "usd", "usdz", "lwo", "md5mesh", "pbrt"] { #expect(!AssimpBridge.canImport(extension: ext), "\(ext)") }381 for id in ["collada", "fbx", "obj", "stl", "ply", "glb2", "gltf2", "3mf"] { #expect(AssimpBridge.canExport(formatID: id), "\(id)") }382 #expect(!AssimpBridge.canExport(formatID: "x3d") && !AssimpBridge.canExport(formatID: "3ds"))383 }384385 @Test func fbxRoundTripThroughAssimpOnly() throws {386 // FBX support rests on this single observation: a file written by Assimp's FBX exporter is read back by387 // Assimp's FBX importer with the same geometry. No independent FBX reader or third-party file was available.388 let dir = Fixtures.directory("fbx"); defer { try? FileManager.default.removeItem(at: dir) }389 let source = try Fixtures.source(.fbx, in: dir)390 #expect(String(decoding: try Data(contentsOf: source.url).prefix(18), as: UTF8.self) == "Kaydara FBX Binary")391 let scene = try Importers.loadInProcess(source.url, format: .fbx, backend: .assimp, limits: ModelLimits())392 let expected = Fixtures.richScene()393 #expect(scene.instances().reduce(0) { $0 + scene.meshes[$1.mesh].triangleCount } == 26)394 #expect(scene.metadata.unit != nil)395 // Assimp's exporter labels the file as centimetres (UnitScaleFactor 1) and writes the numbers unchanged:396 // positions are compared in file units, and the declared unit is reported as read.397 #expect(scene.metadata.unit == .centimeter)398 var got = Mesh3D(name: "", positions: Geometry.worldPositions(of: scene), indices: [])399 var want = Mesh3D(name: "", positions: Geometry.worldPositions(of: expected), indices: [])400 Welding.weld(&got, tolerance: 1e-4); Welding.weld(&want, tolerance: 1e-4)401 #expect(containsAll(got.positions, want.positions, tolerance: 1e-3), "unit \(String(describing: scene.metadata.unit)) got \(got.positions.prefix(6)) want \(want.positions.prefix(6))")402 }403}404