SPB Git

Repository Public License

InspectionTests.swift 24.2 KB 349 lines swift

1// ORIX Convert — Packages/EngineModel3D/Tests/EngineModel3DTests/InspectionTests.swift2// Description: Inspection facts, preflight warnings read from the actual file, the preview API, limits, the helper3//              process and cancellation.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import Testing7import SceneKit8import simd9import ConvertCore10@testable import EngineModel3D1112/// A glTF with an animation, a skin, a camera, a light, a morph target, two UV sets and a clearcoat material,13/// assembled from the writer's output of a quad by editing the JSON and appending to the buffer.14func featureRichGLTF(in directory: URL) throws -> URL {15    var scene = Fixtures.texturedQuadScene()16    scene.meshes[0].uvSets.append(scene.meshes[0].uvSets[0].map { $0 * 0.5 })17    scene.textures = []; scene.materials[0].baseColorTexture = nil18    let out = try GLTFWriter.write(scene, directory: directory, baseName: "features", container: .gltfEmbedded)19    var json = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: out.files[0])) as? [String: Any])20    var buffers = try #require(json["buffers"] as? [[String: Any]])21    let uri = try #require(buffers[0]["uri"] as? String)22    var bin = try #require(Data(base64Encoded: String(uri[uri.index(after: uri.firstIndex(of: ",")!)...])))23    var views = try #require(json["bufferViews"] as? [[String: Any]]), accessors = try #require(json["accessors"] as? [[String: Any]])24    func append(_ floats: [Float], type: String, count: Int, minMax: Bool = false) -> Int {25        while bin.count % 4 != 0 { bin.append(0) }26        views.append(["buffer": 0, "byteOffset": bin.count, "byteLength": floats.count * 4])27        floats.withUnsafeBytes { bin.append(contentsOf: $0) }28        var accessor: [String: Any] = ["bufferView": views.count - 1, "componentType": 5126, "count": count, "type": type]29        if minMax { accessor["min"] = [Double(floats.min()!)]; accessor["max"] = [Double(floats.max()!)] }30        accessors.append(accessor)31        return accessors.count - 132    }33    func appendBytes(_ bytes: [UInt8], type: String, count: Int) -> Int {34        while bin.count % 4 != 0 { bin.append(0) }35        views.append(["buffer": 0, "byteOffset": bin.count, "byteLength": bytes.count])36        bin.append(contentsOf: bytes)37        accessors.append(["bufferView": views.count - 1, "componentType": 5121, "count": count, "type": type])38        return accessors.count - 139    }40    let times = append([0, 1], type: "SCALAR", count: 2, minMax: true)41    let translations = append([0, 0, 0, 1, 0, 0], type: "VEC3", count: 2)42    let morph = append([0, 0, 0.5, 0, 0, 0.5, 0, 0, 0.5, 0, 0, 0.5], type: "VEC3", count: 4)43    accessors[morph]["min"] = [0.0, 0.0, 0.5]; accessors[morph]["max"] = [0.0, 0.0, 0.5]44    let joints = appendBytes([UInt8](repeating: 0, count: 16), type: "VEC4", count: 4)45    let weights = append([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], type: "VEC4", count: 4)46    let inverseBind = append([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], type: "MAT4", count: 1)47    var meshes = try #require(json["meshes"] as? [[String: Any]])48    var primitives = try #require(meshes[0]["primitives"] as? [[String: Any]])49    var attributes = try #require(primitives[0]["attributes"] as? [String: Any])50    attributes["JOINTS_0"] = joints; attributes["WEIGHTS_0"] = weights51    primitives[0]["attributes"] = attributes52    primitives[0]["targets"] = [["POSITION": morph]]53    meshes[0]["primitives"] = primitives54    meshes[0]["weights"] = [0.0]55    json["meshes"] = meshes56    var nodes = try #require(json["nodes"] as? [[String: Any]])57    nodes[0]["skin"] = 058    nodes.append(["name": "joint"])59    nodes.append(["name": "eye", "camera": 0, "translation": [0, 0, 5]])60    nodes.append(["name": "lamp", "extensions": ["KHR_lights_punctual": ["light": 0]]])61    json["nodes"] = nodes62    json["scenes"] = [["nodes": [0, 1, 2, 3]]]63    json["skins"] = [["joints": [1], "inverseBindMatrices": inverseBind]]64    json["cameras"] = [["type": "perspective", "perspective": ["yfov": 0.8, "znear": 0.1, "zfar": 100.0, "aspectRatio": 1.5]]]65    json["animations"] = [["name": "slide", "channels": [["sampler": 0, "target": ["node": 1, "path": "translation"]]], "samplers": [["input": times, "output": translations, "interpolation": "LINEAR"]]]]66    json["extensions"] = ["KHR_lights_punctual": ["lights": [["type": "point", "color": [1, 1, 1], "intensity": 10.0]]]]67    json["extensionsUsed"] = ["KHR_lights_punctual", "KHR_materials_clearcoat"]68    var materials = try #require(json["materials"] as? [[String: Any]])69    materials[0]["extensions"] = ["KHR_materials_clearcoat": ["clearcoatFactor": 1.0, "clearcoatRoughnessFactor": 0.1]]70    json["materials"] = materials71    json["bufferViews"] = views; json["accessors"] = accessors72    buffers[0] = ["byteLength": bin.count, "uri": "data:application/octet-stream;base64,\(bin.base64EncodedString())"]73    json["buffers"] = buffers74    try JSONSerialization.data(withJSONObject: json, options: [.sortedKeys]).write(to: out.files[0])75    return out.files[0]76}7778@Suite("Inspection and preflight")79struct InspectionTests {80    let engine = Model3DEngine()8182    @Test func summaryOfEveryFixture() async throws {83        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }84        for format in Model3DCatalog.sources {85            let sub = dir.appendingPathComponent(format.rawValue); try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)86            let source = try Fixtures.source(format, in: sub)87            let summary = try await engine.summary(of: source.url, format: format)88            #expect(summary.triangleCount == source.triangles, "\(format)")89            #expect(summary.boundingBox != nil && summary.vertexCount > 0 && summary.meshCount > 0 && summary.nodeCount > 0, "\(format)")90            #expect(summary.topology != nil, "\(format)")91            let inspection = summary.fileInspection()92            #expect(inspection.format == format && inspection.faceCount == source.triangles && inspection.vertexCount == summary.vertexCount)93            #expect(inspection.fields.contains { $0.group == "Geometry" && $0.key == "Dimensions" })94            // Third-party and system parsers ran in the helper process; own readers in-process.95            #expect(summary.isolated == (Importers.backend(for: format) != .native), "\(format)")96        }97    }9899    @Test func formatSpecificFacts() async throws {100        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }101        func summary(_ format: FormatID) async throws -> Model3DSummary {102            let sub = dir.appendingPathComponent(format.rawValue); try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)103            return try await engine.summary(of: try Fixtures.source(format, in: sub).url, format: format)104        }105        let obj = try await summary(.obj)106        #expect(obj.unit == nil && obj.upAxis == nil)107        #expect(obj.sourceFaceCount == 6 && obj.sourcePolygonCount == 6)108        #expect(obj.hasNormals && obj.hasUVs && obj.uvSetCount == 1 && !obj.hasVertexColors)109        #expect(obj.materialCount >= 1 && obj.texturesExternal == 1 && obj.texturesMissing == 0 && obj.texturesEmbedded == 0)110        #expect(obj.topology?.isWatertight == true)111        #expect(obj.boundingBox?.size == SIMD3<Double>(1, 1, 1))112        let stl = try await summary(.stl)113        #expect(stl.encoding == "ASCII" && stl.unit == nil && stl.topology?.isWatertight == true && !stl.hasNormals)114        #expect(stl.fileInspection().fields.contains { $0.key == "Unit" && $0.value == "Not stated by the file" })115        let ply = try await summary(.ply)116        #expect(ply.hasVertexColors && ply.encoding == "ascii" && ply.sourceFaceCount == 5 && ply.sourcePolygonCount == 1 && ply.generator == "hand-written pyramid")117        let gltf = try await summary(.gltf)118        #expect(gltf.formatVersion == "glTF 2.0" && gltf.generator == "hand-written" && gltf.unit == .meter && gltf.upAxis == .y)119        #expect(gltf.topology?.boundaryEdges == 3)120        let glb = try await summary(.glb)121        #expect(glb.texturesEmbedded == 1 && glb.nodeCount >= 3 && glb.hierarchyDepth >= 2 && glb.generator == "ORIX Convert")122        let dae = try await summary(.dae)123        #expect(dae.unit == .centimeter && dae.upAxis == .z && dae.formatVersion == "COLLADA 1.4.1" && dae.generator == "hand-written")124        #expect(dae.boundingBox?.min == SIMD3<Double>(5, 0, 0) && dae.boundingBox?.max == SIMD3<Double>(7, 1, 0))125        let usda = try await summary(.usda)126        #expect(usda.unit == .centimeter && usda.upAxis == .z && usda.formatVersion == "USD text 1.0" && usda.materialCount == 1)127        #expect(usda.sourcePolygonCount == nil)     // Model I/O triangulated the quad: the source face count is unknown128        #expect(usda.boundingBox?.min == SIMD3<Double>(10, 0, 0) && usda.boundingBox?.max == SIMD3<Double>(11, 2, 0))129        let usdc = try await summary(.usdc)130        #expect(usdc.formatVersion?.hasPrefix("USD crate") == true && usdc.upAxis == .z)131        #expect(usdc.unit == nil)   // Model I/O wrote the fixture: metersPerUnit is not authored.132        #expect(usdc.notes.contains { $0.code == "usd-unit-not-authored" })133        let usdz = try await summary(.usdz)134        #expect(usdz.unit == .meter && usdz.upAxis == .y && usdz.texturesEmbedded == 1 && usdz.generator == "ORIX Convert")135        let threeMF = try await summary(.threeMF)136        #expect(threeMF.unit == .millimeter && threeMF.upAxis == .z && threeMF.materialCount == 1 && threeMF.topology?.isWatertight == true)137        #expect(threeMF.boundingBox?.min == SIMD3<Double>(20, 0, 0))138        let fbx = try await summary(.fbx)139        #expect(fbx.formatVersion?.hasPrefix("FBX ") == true)140        #expect(fbx.unit != nil && fbx.upAxis != nil)141        #expect(fbx.importer.hasPrefix("Assimp"))142    }143144    @Test func crateMetadataReader() throws {145        // Written by Apple's usdcat from a text layer with metersPerUnit = 0.01 (stored out of line) and upAxis = "Z".146        let fixture = try #require(Bundle.module.url(forResource: "usdcat-cm-zup", withExtension: "usdc", subdirectory: "Fixtures"))147        let info = USDLayerInfo.read(fixture, limits: ModelLimits())148        #expect(info.metersPerUnit == 0.01 && info.upAxis == .z && info.metadataReadable && info.crateVersion == "0.8.0")149        // Written by SceneKit: metersPerUnit = 1 (stored inline).150        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }151        let url = dir.appendingPathComponent("scenekit.usdc")152        let scene = Model3DPreviewLoader.makeSCNScene(from: Scene3D(mesh: Fixtures.cube()))153        #expect(scene.write(to: url, options: nil, delegate: nil, progressHandler: nil))154        let written = USDLayerInfo.read(url, limits: ModelLimits())155        #expect(written.metersPerUnit == 1 && written.metadataReadable)156        #expect(USDLayerInfo.parse(Data("PXR-USDC".utf8) + Data(count: 80)).metersPerUnit == nil)157    }158159    @Test func unconvertedContentIsCountedAndWarnedAbout() async throws {160        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }161        let url = try featureRichGLTF(in: dir)162        #expect(try GLTFDocument.load(url, limits: ModelLimits()).check().problems.isEmpty)163        let summary = try await engine.summary(of: url, format: .gltf)164        #expect(summary.unconverted.animations == 1 && summary.unconverted.skins == 1 && summary.unconverted.cameras == 1 && summary.unconverted.lights == 1)165        #expect(summary.unconverted.morphTargets >= 1)166        #expect(summary.uvSetCount == 2)167        #expect(summary.extensions.contains("KHR_materials_clearcoat") && summary.extensions.contains("KHR_lights_punctual"))168        #expect(summary.materialFeaturesNotCarried.contains("clearcoat"))169        #expect(summary.triangleCount == 2)170        let inspection = summary.fileInspection()171        #expect(inspection.isAnimated == true)172173        func codes(_ destination: FormatID) -> Set<String> {174            Set(engine.preflight(ConversionRequest(source: url, sourceFormat: .gltf, destinationFormat: destination), inspection: inspection).map(\.code))175        }176        let always: Set<String> = ["animation-dropped", "skin-dropped", "morph-targets-dropped", "cameras-dropped", "lights-dropped", "material-features-dropped"]177        #expect(codes(.stl).isSuperset(of: always.union(["materials-dropped", "uv-dropped", "hierarchy-flattened", "not-watertight"])))178        #expect(codes(.obj).isSuperset(of: always.union(["materials-approximated", "uv-sets-reduced"])))179        #expect(codes(.glb).isSuperset(of: always) && !codes(.glb).contains("uv-sets-reduced") && !codes(.glb).contains("materials-dropped"))180        #expect(codes(.threeMF).isSuperset(of: ["materials-reduced", "uv-dropped", "not-watertight"]))181        // The same losses are reported by the conversion itself, and the geometry still validates.182        let work = dir.appendingPathComponent("w")183        let (output, recorder, request) = try await engine.run(url, from: .gltf, to: .usdz, work: work)184        #expect(recorder.codes().isSuperset(of: always))185        #expect(recorder.warnings.filter { always.contains($0.code) }.allSatisfy { $0.severity == .dataLoss })186        for check in try await engine.validate(output, request: request, source: nil) { #expect(check.passed, "\(check.name): \(check.detail)") }187    }188189    @Test func preflightForUnitsAxesAndFormats() async throws {190        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }191        let stl = try Fixtures.source(.stl, in: dir)192        let inspection = try await engine.inspect(stl.url, format: .stl)193        func codes(_ destination: FormatID, _ options: [String: OptionValue] = [:]) -> Set<String> {194            Set(engine.preflight(ConversionRequest(source: stl.url, sourceFormat: .stl, destinationFormat: destination, options: ConversionOptions(options)), inspection: inspection).map(\.code))195        }196        #expect(codes(.glb).isSuperset(of: ["unit-unknown", "axis-unknown"]))197        #expect(!codes(.glb, ["unit.source": .string("mm"), "axis.source": .string("z")]).contains("unit-unknown"))198        #expect(!codes(.glb, ["unit.source": .string("mm"), "axis.source": .string("z")]).contains("axis-unknown"))199        #expect(codes(.usdc).contains("usdc-unit"))200        #expect(codes(.ply).isEmpty)201        #expect(!codes(.threeMF).contains("not-watertight"))     // the tetrahedron is closed202        let fbxCodes = Set(engine.preflight(ConversionRequest(source: stl.url, sourceFormat: .fbx, destinationFormat: .glb), inspection: nil).map(\.code))203        #expect(fbxCodes.contains("fbx-experimental"))204    }205206    @Test func optionsDescribeEveryPath() {207        for path in engine.paths {208            let options = engine.options(for: path)209            let ids = Set(options.map(\.id))210            #expect(ids.count == options.count)211            #expect(ids.isSuperset(of: ["unit.source", "unit.target", "axis.source", "axis.target", "weld.mode", "normals.mode", "simplify.enabled", "simplify.ratio"]))212            #expect(ids.contains("encoding") == [.stl, .ply].contains(path.destination))213            #expect(ids.contains("gltf.embed") == (path.destination == .gltf))214            #expect(ids.contains("materials.write") == ![.stl, .ply].contains(path.destination))215            #expect(ids.contains("hierarchy.flatten") == [.gltf, .glb, .usd, .usda, .usdc, .usdz, .dae].contains(path.destination))216        }217    }218219    @Test func invalidOptionsAreRejected() async throws {220        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }221        let stl = try Fixtures.source(.stl, in: dir)222        let work = dir.appendingPathComponent("w")223        for options: [String: OptionValue] in [["unit.source": .string("parsec")], ["weld.mode": .string("melt")], ["normals.mode": .string("spiky")],224                                               ["simplify.enabled": .bool(true), "simplify.ratio": .double(0)], ["normals.mode": .string("smooth"), "normals.crease-angle": .double(400)]] {225            await #expect(throws: ConversionError.self) { _ = try await engine.run(stl.url, from: .stl, to: .ply, options: options, work: work) }226        }227        await #expect(throws: ConversionError.self) { _ = try await engine.run(stl.url, from: .stl, to: .fbx, work: work) }228    }229}230231@Suite("Preview API, limits, helper process, cancellation")232struct RuntimeTests {233    @Test func previewLoadsAnyFormatIntoSceneKit() async throws {234        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }235        #expect(Set(Model3DPreviewLoader.supportedFormats) == Set(Model3DCatalog.sources))236        for format in [FormatID.glb, .threeMF, .usda, .obj, .stl] {237            let sub = dir.appendingPathComponent(format.rawValue); try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)238            let source = try Fixtures.source(format, in: sub)239            let preview = try await Model3DPreviewLoader.load(source.url, format: format)240            #expect(preview.summary.triangleCount == source.triangles)241            let scene = Model3DPreviewLoader.makeSCNScene(from: preview.scene)242            var triangles = 0, geometries = 0243            var pivot = false244            scene.rootNode.enumerateHierarchy { node, _ in245                if node.name == "ORIX_up_axis" { pivot = true }246                if let g = node.geometry { geometries += 1; triangles += g.elements.reduce(0) { $0 + $1.primitiveCount } }247            }248            #expect(triangles == source.triangles, "\(format)")249            #expect(geometries == preview.scene.instances().count)250            #expect(pivot == (preview.scene.metadata.upAxis == .z), "\(format)")251            if format == .glb {252                var textured = false253                scene.rootNode.enumerateHierarchy { node, _ in if let m = node.geometry?.firstMaterial, m.name == "painted" { textured = m.diffuse.contents != nil && m.lightingModel == .physicallyBased } }254                #expect(textured)255            }256        }257        // Bounded: a model above the preview limits is refused, not loaded.258        var tiny = ModelLimits.preview259        tiny.maxTriangles = 3260        let stl = try Fixtures.source(.stl, in: dir)261        await #expect(throws: ConversionError.self) { _ = try await Model3DPreviewLoader.load(stl.url, format: .stl, limits: tiny) }262    }263264    @Test func limitsAreEnforcedByEveryBackend() async throws {265        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }266        var limits = ModelLimits()267        limits.maxTriangles = 1; limits.maxVertices = 2268        let engine = Model3DEngine(limits: limits)269        for format in [FormatID.stl, .ply, .threeMF, .obj, .glb, .dae, .usda, .usdz, .fbx] {270            let sub = dir.appendingPathComponent(format.rawValue); try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)271            let source = try Fixtures.source(format, in: sub)272            do {273                _ = try await engine.run(source.url, from: format, to: format == .stl ? .ply : .stl, work: sub.appendingPathComponent("w"))274                Issue.record("\(format) was converted although it exceeds the limits")275            } catch let error as ConversionError {276                guard case .limitExceeded = error else { Issue.record("\(format): \(error)"); continue }277            }278        }279        var small = ModelLimits()280        small.maxFileSize = 16281        let source = try Fixtures.source(.obj, in: dir)282        for format in [FormatID.obj] {283            do { _ = try await Model3DEngine(limits: small).run(source.url, from: format, to: .stl, work: dir.appendingPathComponent("w")); Issue.record("size limit ignored") }284            catch let error as ConversionError { guard case .limitExceeded = error else { Issue.record("\(error)"); continue } }285        }286    }287288    @Test func helperProcessIsolatesThirdPartyParsers() async throws {289        #expect(Model3DEngine.isHelperAvailable)290        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }291        for format in [FormatID.obj, .glb, .dae, .fbx, .usda, .usdz] {292            let sub = dir.appendingPathComponent(format.rawValue); try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)293            let source = try Fixtures.source(format, in: sub)294            let isolated = try await Importers.load(source.url, format: format, limits: ModelLimits(), isolation: .required)295            let local = try await Importers.load(source.url, format: format, limits: ModelLimits(), isolation: .inProcess)296            #expect(isolated.isolated && !local.isolated)297            #expect(isolated.scene.triangleCount == local.scene.triangleCount && isolated.scene.vertexCount == local.scene.vertexCount, "\(format)")298            #expect(isolated.scene.nodes.count == local.scene.nodes.count && isolated.scene.materials.count == local.scene.materials.count)299            #expect(isolated.scene.textures.map(\.data) == local.scene.textures.map(\.data))300            #expect(Geometry.worldPositions(of: isolated.scene) == Geometry.worldPositions(of: local.scene))301            #expect(isolated.scene.metadata.unit == local.scene.metadata.unit && isolated.scene.metadata.upAxis == local.scene.metadata.upAxis)302        }303        // The helper reports failures on its error stream with a status, never by crashing the caller.304        #expect(runModel3DHelper(arguments: ["helper", "bogus"]) == 3)305        let missing = dir.appendingPathComponent("missing.obj")306        await #expect(throws: ConversionError.self) { _ = try await Importers.load(missing, format: .obj, limits: ModelLimits(), isolation: .required) }307    }308309    @Test func sceneBlobRoundTrip() throws {310        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }311        var scene = Fixtures.richScene()312        scene.meshes[1].tangents = [SIMD4<Float>](repeating: SIMD4(1, 0, 0, -1), count: 4)313        scene.meshes[0].colors = scene.meshes[0].positions.map { SIMD4($0.x, $0.y, $0.z, 1) }314        scene.notes = [SceneNote(.caution, "x", "y")]315        scene.unconverted.cameras = 2316        let url = dir.appendingPathComponent("scene.blob")317        try SceneBlob.write(scene, to: url)318        let back = try SceneBlob.read(url, limits: ModelLimits())319        #expect(back.meshes.count == 2 && back.meshes[0].positions == scene.meshes[0].positions && back.meshes[0].indices == scene.meshes[0].indices)320        #expect(back.meshes[1].tangents == scene.meshes[1].tangents && back.meshes[1].uvSets == scene.meshes[1].uvSets && back.meshes[0].colors == scene.meshes[0].colors)321        #expect(back.nodes.map(\.transform) == scene.nodes.map(\.transform) && back.roots == scene.roots)322        #expect(back.textures[0].data == scene.textures[0].data && back.materials[0].name == "painted" && back.notes == scene.notes && back.unconverted.cameras == 2)323        // A truncated or foreign blob is an error, not a crash.324        let bytes = try Data(contentsOf: url)325        for cut in [0, 7, 12, 40, bytes.count / 2, bytes.count - 1] {326            try bytes.prefix(cut).write(to: url)327            #expect(throws: ConversionError.self) { _ = try SceneBlob.read(url, limits: ModelLimits()) }328        }329    }330331    @Test func cancellationStopsAConversion() async throws {332        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }333        let input = dir.appendingPathComponent("big.ply")334        try PLYCodec.write(Scene3D(mesh: Fixtures.grid(400)), to: input, binary: true)      // 320 000 triangles335        let engine = Model3DEngine()336        let work = dir.appendingPathComponent("w")337        let task = Task { try await engine.run(input, from: .ply, to: .stl, options: ["simplify.enabled": .bool(true), "simplify.ratio": .double(0.01)], work: work) }338        try await Task.sleep(for: .milliseconds(120))339        task.cancel()340        do { _ = try await task.value; Issue.record("the conversion was not cancelled") }341        catch is CancellationError {}342        catch { Issue.record("unexpected error \(error)") }343        // A task cancelled before it starts never reads the file.344        let early = Task { try await engine.run(input, from: .ply, to: .stl, work: work) }345        early.cancel()346        do { _ = try await early.value; Issue.record("the conversion was not cancelled") } catch is CancellationError {} catch { Issue.record("unexpected error \(error)") }347    }348}349
Files main
Menu

Theme