Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift

594 lines · 27415 bytes

36 symbols in this file
  1import simd
  2
  3public enum FoldDefect: Equatable, Sendable {
  4    case vertexIndexOutOfRange(edge: Int)
  5    case faceVertexOutOfRange(face: Int)
  6    case vertexCountChanged(frame: Int)
  7    case foldAngleOutOfRange(frame: Int, edge: Int, degrees: Double)
  8    case foldAngleSignDisagreesWithAssignment(frame: Int, edge: Int)
  9    case boundaryEdgeFolded(frame: Int, edge: Int)
 10    case faceOrderNotAntisymmetric(frame: Int, f: Int, g: Int)
 11    case cyclicFaceOrder(frame: Int, cycle: [Int])
 12    case nonIsometricTransition(step: Int, edge: Int, from: Double, to: Double)
 13    case overlappingMovingSetsWithoutMidFoldOrder(step: Int)
 14    case startAndEndOrderDisagreeOnStillFaces(step: Int, f: Int, g: Int)
 15    case foldAndUnfoldWithoutPeakOrder(step: Int)
 16    case orderDisagreesWithCrease(frame: Int, edge: Int)
 17    case interleavedFolds(frame: Int, edges: [Int])
 18    case faceInsideFold(frame: Int, face: Int, edge: Int)
 19    case nonConvexFace(face: Int)
 20    case missingInstruction(step: Int)
 21    case authorNotTraditional(String?)
 22    case missingFirstCreasedAtStep(edge: Int)
 23    case faceDistorted(frame: Int, face: Int)
 24    /// A non-rigid step without a pop, or a pop whose `popped` lacks a position per vertex or
 25    /// whose phases are not 0 < p0 < p1 < 1.
 26    case popMalformed(step: Int)
 27    /// In step `step`, the face `moving` departs toward the still face `still` it overlaps in
 28    /// frame n − 1, or arrives from the side of it opposite the one frame n's order gives.
 29    case movesThroughStillFace(step: Int, moving: Int, still: Int)
 30    /// Step `step`'s viewpoint has an `eye` or `up` of zero length, or an `up` along its `eye`, so
 31    /// it names no screen-up.
 32    case viewpointDegenerate(step: Int)
 33}
 34
 35/// Lengths are compared to within this fraction of the sheet's longer side.
 36private let relativeTolerance = 1e-6
 37/// A crease within this many degrees of ±180 is folded flat.
 38private let flatAngleTolerance = 1e-6
 39/// Two unit normals whose dot product's magnitude reaches this lie on one line.
 40private let parallelCosine = 1 - 1e-9
 41/// A normal component smaller than this is treated as zero when choosing the canonical normal.
 42private let canonicalComponentThreshold = 1e-6
 43
 44public func validate(_ file: FoldFile) -> [FoldDefect] {
 45    var defects: [FoldDefect] = []
 46    let vertexCount = file.frames[0].verticesCoords.count
 47    let inRange = { (v: Int) in v >= 0 && v < vertexCount }
 48    for (e, ends) in file.edgesVertices.enumerated() where ends.count != 2 || !ends.allSatisfy(inRange) {
 49        defects.append(.vertexIndexOutOfRange(edge: e))
 50    }
 51    for (f, corners) in file.facesVertices.enumerated() where !corners.allSatisfy(inRange) {
 52        defects.append(.faceVertexOutOfRange(face: f))
 53    }
 54    let topologyIsSound = defects.isEmpty
 55
 56    if file.fileAuthor != "Traditional" {
 57        defects.append(.authorNotTraditional(file.fileAuthor))
 58    }
 59    for n in file.frames.indices.dropFirst() {
 60        let instruction = file.frames[n].step?.instruction ?? ""
 61        if instruction.allSatisfy(\.isWhitespace) {
 62            defects.append(.missingInstruction(step: n))
 63        }
 64    }
 65    guard topologyIsSound else { return defects }
 66
 67    let tolerance = sheetSize(file) * relativeTolerance
 68    let edgeFaces = edgesFaces(file)
 69    defects += nonConvexFaces(file)
 70    defects += missingFirstCreasedAtStep(file, edgeFaces: edgeFaces)
 71
 72    var geometryIsSound: [Bool] = []
 73    for (n, frame) in file.frames.enumerated() {
 74        let sound = frame.verticesCoords.count == vertexCount
 75        geometryIsSound.append(sound)
 76        if !sound { defects.append(.vertexCountChanged(frame: n)) }
 77        defects += angleDefects(frame, n, edgeCount: file.edgesVertices.count)
 78        if sound {
 79            defects += layerOrderDefects(frame, n, file, edgeFaces: edgeFaces, tolerance: tolerance)
 80            defects += faceShapeDefects(frame, n, file, tolerance: tolerance)
 81        }
 82    }
 83
 84    for n in file.frames.indices.dropFirst() {
 85        guard let step = file.frames[n].step else { continue }
 86        let frame = file.frames[n]
 87        if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil {
 88            defects.append(.foldAndUnfoldWithoutPeakOrder(step: n))
 89        }
 90        let eye = step.viewpoint.eye, up = step.viewpoint.up
 91        let viewpointIsSound = length(eye) > 0 && length(up) > 0
 92            && abs(dot(normalize(eye), normalize(up))) < parallelCosine
 93        if !viewpointIsSound { defects.append(.viewpointDegenerate(step: n)) }
 94        if step.nonRigid || step.pop != nil {
 95            let wellFormed = step.pop.map { pop in
 96                pop.popped.count == vertexCount && pop.phases.count == 2
 97                    && 0 < pop.phases[0] && pop.phases[0] < pop.phases[1] && pop.phases[1] < 1
 98            } ?? false
 99            if !wellFormed { defects.append(.popMalformed(step: n)) }
100        }
101        guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue }
102        if viewpointIsSound && frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) {
103            defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n))
104        }
105        defects += isometryDefects(file, step: n, tolerance: tolerance)
106        defects += stillFaceDefects(file, step: n, moving: Set(step.axes.flatMap(\.movingFaces)))
107    }
108    return defects
109}
110
111/// Whether two of step `n`'s moving sets overlap in projection along the step's viewpoint, with
112/// both sets where they arrive, in frame `n`.
113public func movingSetsOverlapInProjection(step n: Int, _ file: FoldFile) -> Bool {
114    guard n >= 1, n < file.frames.count, let step = file.frames[n].step, step.axes.count > 1 else {
115        return false
116    }
117    let points = file.frames[n].verticesCoords
118    let eye = normalize(step.viewpoint.eye)
119    let right = normalize(cross(step.viewpoint.up, eye))
120    let up = cross(eye, right)
121    let tolerance = sheetSize(file) * relativeTolerance
122
123    func outline(_ face: Int) -> [SIMD2<Double>]? {
124        guard face >= 0, face < file.facesVertices.count else { return nil }
125        let corners = file.facesVertices[face]
126        guard corners.allSatisfy({ $0 >= 0 && $0 < points.count }) else { return nil }
127        return corners.map { SIMD2(dot(points[$0], right), dot(points[$0], up)) }
128    }
129
130    let sets = step.axes.map { axis in axis.movingFaces.compactMap { face in outline(face).map { (face, $0) } } }
131    for i in sets.indices {
132        for j in sets.indices where j > i {
133            for (a, p) in sets[i] {
134                for (b, q) in sets[j] where a != b && convexPolygonsOverlap(p, q, tolerance: tolerance) {
135                    return true
136                }
137            }
138        }
139    }
140    return false
141}
142
143/// Each face's unit normal in `frame`, from the counterclockwise order of `faces_vertices`.
144/// A degenerate face, or one naming a vertex the frame lacks, has a zero normal.
145public func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>] {
146    faceNormals(positions: frame.verticesCoords, faces: file.facesVertices)
147}
148
149/// Each face's unit normal with its vertices at `positions`, from the counterclockwise order of
150/// `faces`. A degenerate face, or one naming a vertex `positions` lacks, has a zero normal.
151public func faceNormals(positions: [SIMD3<Double>], faces: [[Int]]) -> [SIMD3<Double>] {
152    faces.map { corners in
153        guard corners.allSatisfy({ $0 >= 0 && $0 < positions.count }) else { return .zero }
154        let n = newellNormal(corners.map { positions[$0] })
155        let size = length(n)
156        return size > 0 ? n / size : .zero
157    }
158}
159
160/// The faces on each side of each edge, from consecutive corners of `faces_vertices`. An edge
161/// without two ends has none.
162public func edgesFaces(_ file: FoldFile) -> [[Int]] {
163    var byEnds: [SIMD2<Int>: [Int]] = [:]
164    for (f, corners) in file.facesVertices.enumerated() {
165        for i in corners.indices {
166            let u = corners[i], v = corners[(i + 1) % corners.count]
167            byEnds[SIMD2(min(u, v), max(u, v)), default: []].append(f)
168        }
169    }
170    return file.edgesVertices.map { ends in
171        guard ends.count == 2 else { return [] }
172        return byEnds[SIMD2(min(ends[0], ends[1]), max(ends[0], ends[1]))] ?? []
173    }
174}
175
176/// Each triple `[f, g, s]` with `s ≠ 0` as a pair ordered along the canonical normal of the two
177/// faces' common plane, the one of `g`'s normal and its negation whose first nonzero component is
178/// positive. Triples with `s = 0`, a repeated face or a face outside `normals` are skipped.
179public func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(below: Int, above: Int)] {
180    validTriples(orders, faceCount: normals.count).map { f, g, s in
181        let ng = normals[g]
182        let fAbove = dot(ng, canonical(ng)) > 0 ? s > 0 : s < 0
183        return fAbove ? (below: g, above: f) : (below: f, above: g)
184    }
185}
186
187/// Each triple `[f, g, s]` with `s ≠ 0` in a form that a rigid motion of both faces together leaves
188/// unchanged: rewritten with the lower face first, `s` negated when swapping two faces whose
189/// normals agree (the spec's rule for a reverse triple). Triples with `s = 0`, a repeated face or
190/// a face outside `normals` are skipped.
191public func rigidInvariantFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(pair: SIMD2<Int>, s: Int)] {
192    validTriples(orders, faceCount: normals.count).map { f, g, s in
193        if f < g { return (SIMD2(f, g), s) }
194        return (SIMD2(g, f), dot(normals[f], normals[g]) > 0 ? -s : s)
195    }
196}
197
198/// A cycle in the stacking relation `pairs` over faces `0..<faceCount`, as the faces along it,
199/// each above the next, starting at the cycle's smallest face index; nil when there is none.
200/// Pairs naming a face outside `0..<faceCount` are skipped.
201public func faceOrderCycle(_ pairs: [(below: Int, above: Int)], faceCount: Int) -> [Int]? {
202    guard let cycle = firstCycle(stackingGraph(pairs, faceCount: faceCount)),
203          let start = cycle.indices.min(by: { cycle[$0] < cycle[$1] }) else { return nil }
204    return Array(cycle[start...] + cycle[..<start])
205}
206
207/// Whether two convex polygons share interior area wider than `tolerance`, by separating axes.
208/// Polygons that only touch do not.
209public func convexPolygonsOverlap(_ p: [SIMD2<Double>], _ q: [SIMD2<Double>], tolerance: Double) -> Bool {
210    var tested = false
211    for polygon in [p, q] {
212        for i in polygon.indices {
213            let edge = polygon[(i + 1) % polygon.count] - polygon[i]
214            guard length(edge) > tolerance else { continue }
215            let axis = normalize(SIMD2(-edge.y, edge.x))
216            let a = p.map { dot($0, axis) }, b = q.map { dot($0, axis) }
217            guard let aMin = a.min(), let aMax = a.max(), let bMin = b.min(), let bMax = b.max() else { return false }
218            if min(aMax, bMax) - max(aMin, bMin) <= tolerance { return false }
219            tested = true
220        }
221    }
222    return tested
223}
224
225// MARK: - File-level rules
226
227private func sheetSize(_ file: FoldFile) -> Double {
228    let points = file.frames[0].verticesCoords
229    guard let first = points.first else { return 0 }
230    let low = points.reduce(first) { simd_min($0, $1) }
231    let high = points.reduce(first) { simd_max($0, $1) }
232    return (high - low).max()
233}
234
235private func nonConvexFaces(_ file: FoldFile) -> [FoldDefect] {
236    let points = file.frames[0].verticesCoords
237    var defects: [FoldDefect] = []
238    for (f, corners) in file.facesVertices.enumerated() {
239        let polygon = corners.map { points[$0] }
240        let n = newellNormal(polygon)
241        guard length(n) > 0 else { continue }
242        let count = polygon.count
243        let reflex = polygon.indices.contains { i in
244            let into = polygon[i] - polygon[(i + count - 1) % count]
245            let out = polygon[(i + 1) % count] - polygon[i]
246            guard length(into) > 0, length(out) > 0 else { return false }
247            return dot(cross(normalize(into), normalize(out)), normalize(n)) < -1e-9
248        }
249        if reflex { defects.append(.nonConvexFace(face: f)) }
250    }
251    return defects
252}
253
254/// A non-boundary edge without `edges_krz:firstCreasedAtStep` is a defect unless it is a
255/// subdivision edge: `F` and flat in every frame, and creased by no step.
256private func missingFirstCreasedAtStep(_ file: FoldFile, edgeFaces: [[Int]]) -> [FoldDefect] {
257    let creased = creasedEdges(file, edgeFaces: edgeFaces)
258    return file.edgesVertices.indices.compactMap { e in
259        let assignment = file.frames[0].edgesAssignment
260        guard e < assignment.count, assignment[e] != .boundary else { return nil }
261        if e < file.edgesFirstCreasedAtStep.count, file.edgesFirstCreasedAtStep[e] != nil { return nil }
262        let subdivision = !creased.contains(e) && file.frames.allSatisfy { frame in
263            e < frame.edgesAssignment.count && e < frame.edgesFoldAngle.count
264                && frame.edgesAssignment[e] == .flat && frame.edgesFoldAngle[e] == 0
265        }
266        return subdivision ? nil : .missingFirstCreasedAtStep(edge: e)
267    }
268}
269
270/// The edges some step creases: those whose two faces the step moves differently. In each of a
271/// step's axis lists (`axes`, and a pop's `openAxes` and `closeAxes`), a face moves with the
272/// deepest axis whose `movingFaces` contains it, or stays fixed when none does. A pop does not
273/// crease its spine's edges: each was folded flat before the step or is a bend line, which bends
274/// while the flap is open and flattens again (decision 0003).
275private func creasedEdges(_ file: FoldFile, edgeFaces: [[Int]]) -> Set<Int> {
276    let lists: [(axes: [AxisRecord], spine: Set<Int>)] = file.frames.compactMap(\.step).flatMap { step in
277        [(step.axes, [])] + (step.pop.map { [($0.openAxes, Set($0.spine)), ($0.closeAxes, Set($0.spine))] } ?? [])
278    }
279    let groupings = lists.map { (groups: movementGroups($0.axes), spine: $0.spine) }
280    return Set(edgeFaces.indices.filter { e in
281        let faces = edgeFaces[e]
282        return faces.count == 2 && groupings.contains { !$0.spine.contains(e) && $0.groups[faces[0]] != $0.groups[faces[1]] }
283    })
284}
285
286/// Each moved face's axis: the deepest in the parent tree whose `movingFaces` contains it, the
287/// first listed among equals. A face absent from the result is fixed.
288private func movementGroups(_ axes: [AxisRecord]) -> [Int: Int] {
289    func depth(_ i: Int) -> Int {
290        var d = 0, j = i
291        while d < axes.count, let p = axes[j].parent, axes.indices.contains(p) {
292            d += 1
293            j = p
294        }
295        return d
296    }
297    var group: [Int: (axis: Int, depth: Int)] = [:]
298    for (i, axis) in axes.enumerated() {
299        let d = depth(i)
300        for f in axis.movingFaces where group[f].map({ d > $0.depth }) ?? true {
301            group[f] = (i, d)
302        }
303    }
304    return group.mapValues(\.axis)
305}
306
307// MARK: - Frame rules
308
309/// Every pair of a face's vertices must be as far apart as in frame 0.
310private func faceShapeDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, tolerance: Double) -> [FoldDefect] {
311    let flat = file.frames[0].verticesCoords, points = frame.verticesCoords
312    return file.facesVertices.indices.compactMap { f in
313        let corners = file.facesVertices[f]
314        let distorted = corners.indices.contains { i in
315            corners[(i + 1)...].contains { v in
316                let u = corners[i]
317                return abs(distance(points[u], points[v]) - distance(flat[u], flat[v])) > tolerance
318            }
319        }
320        return distorted ? .faceDistorted(frame: n, face: f) : nil
321    }
322}
323
324private func angleDefects(_ frame: FoldFrame, _ n: Int, edgeCount: Int) -> [FoldDefect] {
325    var defects: [FoldDefect] = []
326    for e in 0..<min(edgeCount, frame.edgesAssignment.count, frame.edgesFoldAngle.count) {
327        let angle = frame.edgesFoldAngle[e]
328        if abs(angle) > 180 {
329            defects.append(.foldAngleOutOfRange(frame: n, edge: e, degrees: angle))
330        }
331        switch frame.edgesAssignment[e] {
332        case .boundary:
333            if angle != 0 { defects.append(.boundaryEdgeFolded(frame: n, edge: e)) }
334        case .valley:
335            if !(angle > 0) { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) }
336        case .mountain:
337            if !(angle < 0) { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) }
338        case .flat, .unassigned:
339            if angle != 0 { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) }
340        }
341    }
342    return defects
343}
344
345/// Antisymmetry, cycles, and the crease, nesting and inside rules over the frame's `faceOrders`.
346private func layerOrderDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, edgeFaces: [[Int]],
347                               tolerance: Double) -> [FoldDefect] {
348    var defects: [FoldDefect] = []
349    let normals = faceNormals(frame, file)
350    let faceCount = file.facesVertices.count
351
352    var signs: [SIMD2<Int>: Int] = [:]
353    var reported: Set<SIMD2<Int>> = []
354    for (f, g, s) in validTriples(frame.faceOrders, faceCount: faceCount) {
355        if let t = signs[SIMD2(g, f)] {
356            let expected = dot(normals[f], normals[g]) > 0 ? -t : t
357            if s != expected && reported.insert(SIMD2(min(f, g), max(f, g))).inserted {
358                defects.append(.faceOrderNotAntisymmetric(frame: n, f: f, g: g))
359            }
360        }
361        signs[SIMD2(f, g)] = s
362    }
363
364    let pairs = normalisedFaceOrders(frame.faceOrders, normals: normals)
365    if let cycle = faceOrderCycle(pairs, faceCount: faceCount) {
366        defects.append(.cyclicFaceOrder(frame: n, cycle: cycle))
367    }
368    let graph = stackingGraph(pairs, faceCount: faceCount)
369
370    // isAbove[x][y]: y lies above x in the stack, directly or through other faces
371    let isAbove = reachability(graph)
372    let geometry = FrameGeometry(points: frame.verticesCoords, faces: file.facesVertices,
373                                 normals: normals, tolerance: tolerance)
374    let edgeCount = min(file.edgesVertices.count, frame.edgesAssignment.count, frame.edgesFoldAngle.count)
375    let flatCreases = (0..<edgeCount).filter { e in
376        abs(abs(frame.edgesFoldAngle[e]) - 180) <= flatAngleTolerance
377            && edgeFaces[e].count == 2 && edgeFaces[e][0] != edgeFaces[e][1]
378    }
379
380    // crease: a valley points each face's normal toward the other, a mountain away
381    for e in flatCreases {
382        let assignment = frame.edgesAssignment[e]
383        guard assignment == .valley || assignment == .mountain else { continue }
384        let f = edgeFaces[e][0], g = edgeFaces[e][1]
385        let gOnNormalSideOfF = assignment == .valley
386        let gAbove = gOnNormalSideOfF == (dot(normals[f], canonical(normals[f])) > 0)
387        let (below, above) = gAbove ? (f, g) : (g, f)
388        if isAbove[above][below] {
389            defects.append(.orderDisagreesWithCrease(frame: n, edge: e))
390        }
391    }
392
393    // nesting: the face pairs of two coincident creases nest or are disjoint in the stack
394    for (i, e1) in flatCreases.enumerated() {
395        for e2 in flatCreases[(i + 1)...] {
396            let pair1 = edgeFaces[e1], pair2 = edgeFaces[e2]
397            let four = pair1 + pair2
398            guard Set(four).count == 4,
399                  four.allSatisfy({ geometry.coplanar($0, pair1[0]) }),
400                  geometry.segmentsCoincide(file.edgesVertices[e1], file.edgesVertices[e2]),
401                  geometry.onSameSide(of: file.edgesVertices[e1], pair1[0], pair2[0]) else { continue }
402            let determined = four.allSatisfy { x in four.allSatisfy { y in x == y || isAbove[x][y] || isAbove[y][x] } }
403            guard determined else { continue }
404            let rank = { (x: Int) in four.filter { isAbove[$0][x] }.count }
405            let (p, q) = (min(rank(pair1[0]), rank(pair1[1])), max(rank(pair1[0]), rank(pair1[1])))
406            let (r, s) = (min(rank(pair2[0]), rank(pair2[1])), max(rank(pair2[0]), rank(pair2[1])))
407            if (p < r && r < q && q < s) || (r < p && p < s && s < q) {
408                defects.append(.interleavedFolds(frame: n, edges: [e1, e2]))
409            }
410        }
411    }
412
413    // inside: a face whose interior the crease runs through cannot lie between the crease's faces
414    for e in flatCreases {
415        let a = edgeFaces[e][0], b = edgeFaces[e][1]
416        for h in 0..<faceCount where h != a && h != b && geometry.coplanar(h, a) {
417            let between = (isAbove[a][h] && isAbove[h][b]) || (isAbove[b][h] && isAbove[h][a])
418            if between && geometry.segmentCrossesInterior(file.edgesVertices[e], face: h) {
419                defects.append(.faceInsideFold(frame: n, face: h, edge: e))
420            }
421        }
422    }
423    return defects
424}
425
426// MARK: - Step rules
427
428private func isometryDefects(_ file: FoldFile, step n: Int, tolerance: Double) -> [FoldDefect] {
429    let before = file.frames[n - 1].verticesCoords, after = file.frames[n].verticesCoords
430    return file.edgesVertices.enumerated().compactMap { e, ends in
431        let from = distance(before[ends[0]], before[ends[1]])
432        let to = distance(after[ends[0]], after[ends[1]])
433        return abs(to - from) > tolerance ? .nonIsometricTransition(step: n, edge: e, from: from, to: to) : nil
434    }
435}
436
437/// Frame n − 1 and frame n must order every pair of faces that step n leaves still the same way,
438/// compared with `rigidInvariantFaceOrders`.
439private func stillFaceDefects(_ file: FoldFile, step n: Int, moving: Set<Int>) -> [FoldDefect] {
440    func relations(_ frame: FoldFrame) -> [(pair: SIMD2<Int>, s: Int)] {
441        rigidInvariantFaceOrders(frame.faceOrders, normals: faceNormals(frame, file))
442            .filter { !moving.contains($0.pair[0]) && !moving.contains($0.pair[1]) }
443    }
444    var after: [SIMD2<Int>: Int] = [:]
445    for (pair, s) in relations(file.frames[n]) where after[pair] == nil {
446        after[pair] = s
447    }
448    var reported: Set<SIMD2<Int>> = []
449    var defects: [FoldDefect] = []
450    for (pair, s) in relations(file.frames[n - 1]) {
451        if let t = after[pair], t != s, reported.insert(pair).inserted {
452            defects.append(.startAndEndOrderDisagreeOnStillFaces(step: n, f: pair[0], g: pair[1]))
453        }
454    }
455    return defects
456}
457
458// MARK: - Helpers
459
460private func validTriples(_ orders: [[Int]], faceCount: Int) -> [(Int, Int, Int)] {
461    orders.compactMap { t in
462        guard t.count == 3 else { return nil }
463        let (f, g, s) = (t[0], t[1], t[2])
464        guard f >= 0, f < faceCount, g >= 0, g < faceCount, f != g, s == 1 || s == -1 else { return nil }
465        return (f, g, s)
466    }
467}
468
469/// `n` or `-n`, whichever has its first nonzero component positive.
470private func canonical(_ n: SIMD3<Double>) -> SIMD3<Double> {
471    for i in 0..<3 where abs(n[i]) > canonicalComponentThreshold {
472        return n[i] > 0 ? n : -n
473    }
474    return n
475}
476
477private func newellNormal(_ polygon: [SIMD3<Double>]) -> SIMD3<Double> {
478    var n = SIMD3<Double>.zero
479    for i in polygon.indices {
480        let p = polygon[i], q = polygon[(i + 1) % polygon.count]
481        n.x += (p.y - q.y) * (p.z + q.z)
482        n.y += (p.z - q.z) * (p.x + q.x)
483        n.z += (p.x - q.x) * (p.y + q.y)
484    }
485    return n
486}
487
488/// The first cycle a depth-first search of the below → above graph meets, as the faces along it,
489/// each above the next.
490private func firstCycle(_ graph: [[Int]]) -> [Int]? {
491    var state = Array(repeating: 0, count: graph.count) // 0 unvisited, 1 on the path, 2 finished
492    var path: [Int] = []
493    func visit(_ u: Int) -> [Int]? {
494        state[u] = 1
495        path.append(u)
496        for v in graph[u] {
497            if state[v] == 1, let start = path.lastIndex(of: v) { return Array(path[start...].reversed()) }
498            if state[v] == 0, let cycle = visit(v) { return cycle }
499        }
500        path.removeLast()
501        state[u] = 2
502        return nil
503    }
504    for u in graph.indices where state[u] == 0 {
505        if let cycle = visit(u) { return cycle }
506    }
507    return nil
508}
509
510/// For each face, the faces directly above it, in index order.
511private func stackingGraph(_ pairs: [(below: Int, above: Int)], faceCount: Int) -> [[Int]] {
512    var aboveOf = Array(repeating: Set<Int>(), count: faceCount)
513    for pair in pairs where (0..<faceCount).contains(pair.below) && (0..<faceCount).contains(pair.above) {
514        aboveOf[pair.below].insert(pair.above)
515    }
516    return aboveOf.map { $0.sorted() }
517}
518
519private func reachability(_ graph: [[Int]]) -> [[Bool]] {
520    graph.indices.map { start in
521        var seen = Array(repeating: false, count: graph.count)
522        var stack = graph[start]
523        while let u = stack.popLast() {
524            if seen[u] { continue }
525            seen[u] = true
526            stack += graph[u]
527        }
528        return seen
529    }
530}
531
532private struct FrameGeometry {
533    let points: [SIMD3<Double>]
534    let faces: [[Int]]
535    let normals: [SIMD3<Double>]
536    let tolerance: Double
537
538    func centroid(_ f: Int) -> SIMD3<Double> {
539        faces[f].reduce(.zero) { $0 + points[$1] } / Double(max(faces[f].count, 1))
540    }
541
542    func coplanar(_ f: Int, _ g: Int) -> Bool {
543        abs(dot(normals[f], normals[g])) >= parallelCosine
544            && abs(dot(centroid(g) - centroid(f), normals[f])) <= tolerance
545    }
546
547    /// Whether two edges lie on one line and share a stretch longer than `tolerance`.
548    func segmentsCoincide(_ e1: [Int], _ e2: [Int]) -> Bool {
549        let a = points[e1[0]], b = points[e1[1]]
550        let span = length(b - a)
551        guard span > tolerance else { return false }
552        let direction = (b - a) / span
553        let along = e2.map { dot(points[$0] - a, direction) }
554        let offLine = e2.contains { v in
555            let d = points[v] - a
556            return length(d - dot(d, direction) * direction) > tolerance
557        }
558        guard !offLine else { return false }
559        return min(along.max()!, span) - max(along.min()!, 0) > tolerance
560    }
561
562    /// Whether faces `f` and `g` lie on the same side of the line through `edge`, within their plane.
563    func onSameSide(of edge: [Int], _ f: Int, _ g: Int) -> Bool {
564        let a = points[edge[0]]
565        let across = cross(normals[f], points[edge[1]] - a)
566        return dot(centroid(f) - a, across) * dot(centroid(g) - a, across) > 0
567    }
568
569    /// Whether the segment `edge` runs through the interior of face `h` for longer than `tolerance`.
570    func segmentCrossesInterior(_ edge: [Int], face h: Int) -> Bool {
571        let a = points[edge[0]], b = points[edge[1]]
572        let polygon = faces[h].map { points[$0] }
573        let n = normals[h]
574        guard let corner = polygon.first,
575              abs(dot(a - corner, n)) <= tolerance, abs(dot(b - corner, n)) <= tolerance else { return false }
576        let d = b - a
577        var (t0, t1) = (0.0, 1.0)
578        for i in polygon.indices {
579            let p = polygon[i], side = polygon[(i + 1) % polygon.count] - p
580            guard length(side) > tolerance else { continue }
581            // counterclockwise about n, so cross(n, side) points inward; keep points deeper than tolerance
582            let inward = normalize(cross(n, side))
583            let start = dot(a - p, inward) - tolerance, rate = dot(d, inward)
584            if rate == 0 {
585                if start < 0 { return false }
586                continue
587            }
588            let t = -start / rate
589            if rate > 0 { t0 = max(t0, t) } else { t1 = min(t1, t) }
590            if t0 >= t1 { return false }
591        }
592        return (t1 - t0) * length(d) > tolerance
593    }
594}