Commit 9bbedb1fd5
Verified · cmc
Layout: unified · split
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift added +487
| @@ -0,0 +1,487 @@ | ||
| 1 | import simd | |
| 2 | ||
| 3 | public 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 | } | |
| 24 | ||
| 25 | /// Lengths are compared to within this fraction of the sheet's longer side. | |
| 26 | private let relativeTolerance = 1e-6 | |
| 27 | /// A crease within this many degrees of ±180 is folded flat. | |
| 28 | private let flatAngleTolerance = 1e-6 | |
| 29 | /// Two unit normals whose dot product's magnitude reaches this lie on one line. | |
| 30 | private let parallelCosine = 1 - 1e-9 | |
| 31 | /// A normal component smaller than this is treated as zero when choosing the canonical normal. | |
| 32 | private let canonicalComponentThreshold = 1e-6 | |
| 33 | ||
| 34 | public func validate(_ file: FoldFile) -> [FoldDefect] { | |
| 35 | var defects: [FoldDefect] = [] | |
| 36 | let vertexCount = file.frames[0].verticesCoords.count | |
| 37 | let inRange = { (v: Int) in v >= 0 && v < vertexCount } | |
| 38 | for (e, ends) in file.edgesVertices.enumerated() where ends.count != 2 || !ends.allSatisfy(inRange) { | |
| 39 | defects.append(.vertexIndexOutOfRange(edge: e)) | |
| 40 | } | |
| 41 | for (f, corners) in file.facesVertices.enumerated() where !corners.allSatisfy(inRange) { | |
| 42 | defects.append(.faceVertexOutOfRange(face: f)) | |
| 43 | } | |
| 44 | let topologyIsSound = defects.isEmpty | |
| 45 | ||
| 46 | if file.fileAuthor != "Traditional" { | |
| 47 | defects.append(.authorNotTraditional(file.fileAuthor)) | |
| 48 | } | |
| 49 | for n in file.frames.indices.dropFirst() { | |
| 50 | let instruction = file.frames[n].step?.instruction ?? "" | |
| 51 | if instruction.allSatisfy(\.isWhitespace) { | |
| 52 | defects.append(.missingInstruction(step: n)) | |
| 53 | } | |
| 54 | } | |
| 55 | guard topologyIsSound else { return defects } | |
| 56 | ||
| 57 | let tolerance = sheetSize(file) * relativeTolerance | |
| 58 | let edgeFaces = edgesFaces(file) | |
| 59 | defects += nonConvexFaces(file) | |
| 60 | defects += missingFirstCreasedAtStep(file) | |
| 61 | ||
| 62 | var geometryIsSound: [Bool] = [] | |
| 63 | for (n, frame) in file.frames.enumerated() { | |
| 64 | let sound = frame.verticesCoords.count == vertexCount | |
| 65 | geometryIsSound.append(sound) | |
| 66 | if !sound { defects.append(.vertexCountChanged(frame: n)) } | |
| 67 | defects += angleDefects(frame, n, edgeCount: file.edgesVertices.count) | |
| 68 | if sound { | |
| 69 | defects += layerOrderDefects(frame, n, file, edgeFaces: edgeFaces, tolerance: tolerance) | |
| 70 | } | |
| 71 | } | |
| 72 | ||
| 73 | for n in file.frames.indices.dropFirst() { | |
| 74 | guard let step = file.frames[n].step else { continue } | |
| 75 | let frame = file.frames[n] | |
| 76 | if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil { | |
| 77 | defects.append(.foldAndUnfoldWithoutPeakOrder(step: n)) | |
| 78 | } | |
| 79 | guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue } | |
| 80 | if frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) { | |
| 81 | defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n)) | |
| 82 | } | |
| 83 | defects += isometryDefects(file, step: n, tolerance: tolerance) | |
| 84 | defects += stillFaceDefects(file, step: n, moving: Set(step.axes.flatMap(\.movingFaces))) | |
| 85 | } | |
| 86 | return defects | |
| 87 | } | |
| 88 | ||
| 89 | /// Whether two of step `n`'s moving sets overlap in projection along the step's viewpoint, with | |
| 90 | /// both sets where they arrive, in frame `n`. | |
| 91 | public func movingSetsOverlapInProjection(step n: Int, _ file: FoldFile) -> Bool { | |
| 92 | guard n >= 1, n < file.frames.count, let step = file.frames[n].step, step.axes.count > 1 else { | |
| 93 | return false | |
| 94 | } | |
| 95 | let points = file.frames[n].verticesCoords | |
| 96 | let eye = normalize(step.viewpoint.eye) | |
| 97 | let right = normalize(cross(step.viewpoint.up, eye)) | |
| 98 | let up = cross(eye, right) | |
| 99 | let tolerance = sheetSize(file) * relativeTolerance | |
| 100 | ||
| 101 | func outline(_ face: Int) -> [SIMD2<Double>]? { | |
| 102 | guard face >= 0, face < file.facesVertices.count else { return nil } | |
| 103 | let corners = file.facesVertices[face] | |
| 104 | guard corners.allSatisfy({ $0 >= 0 && $0 < points.count }) else { return nil } | |
| 105 | return corners.map { SIMD2(dot(points[$0], right), dot(points[$0], up)) } | |
| 106 | } | |
| 107 | ||
| 108 | let sets = step.axes.map { axis in axis.movingFaces.compactMap { face in outline(face).map { (face, $0) } } } | |
| 109 | for i in sets.indices { | |
| 110 | for j in sets.indices where j > i { | |
| 111 | for (a, p) in sets[i] { | |
| 112 | for (b, q) in sets[j] where a != b && convexPolygonsOverlap(p, q, tolerance: tolerance) { | |
| 113 | return true | |
| 114 | } | |
| 115 | } | |
| 116 | } | |
| 117 | } | |
| 118 | return false | |
| 119 | } | |
| 120 | ||
| 121 | /// Each face's unit normal in `frame`, from the counterclockwise order of `faces_vertices`. | |
| 122 | /// A degenerate face, or one naming a vertex the frame lacks, has a zero normal. | |
| 123 | public func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>] { | |
| 124 | file.facesVertices.map { corners in | |
| 125 | guard corners.allSatisfy({ $0 >= 0 && $0 < frame.verticesCoords.count }) else { return .zero } | |
| 126 | let n = newellNormal(corners.map { frame.verticesCoords[$0] }) | |
| 127 | let size = length(n) | |
| 128 | return size > 0 ? n / size : .zero | |
| 129 | } | |
| 130 | } | |
| 131 | ||
| 132 | /// Each triple `[f, g, s]` with `s ≠ 0` as a pair ordered along the canonical normal of the two | |
| 133 | /// faces' common plane, the one of `g`'s normal and its negation whose first nonzero component is | |
| 134 | /// positive. Triples with `s = 0`, a repeated face or a face outside `normals` are skipped. | |
| 135 | public func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(below: Int, above: Int)] { | |
| 136 | validTriples(orders, faceCount: normals.count).map { f, g, s in | |
| 137 | let ng = normals[g] | |
| 138 | let fAbove = dot(ng, canonical(ng)) > 0 ? s > 0 : s < 0 | |
| 139 | return fAbove ? (below: g, above: f) : (below: f, above: g) | |
| 140 | } | |
| 141 | } | |
| 142 | ||
| 143 | // MARK: - File-level rules | |
| 144 | ||
| 145 | private func sheetSize(_ file: FoldFile) -> Double { | |
| 146 | let points = file.frames[0].verticesCoords | |
| 147 | guard let first = points.first else { return 0 } | |
| 148 | let low = points.reduce(first) { simd_min($0, $1) } | |
| 149 | let high = points.reduce(first) { simd_max($0, $1) } | |
| 150 | return (high - low).max() | |
| 151 | } | |
| 152 | ||
| 153 | /// The faces on each side of each edge, from consecutive corners of `faces_vertices`. | |
| 154 | private func edgesFaces(_ file: FoldFile) -> [[Int]] { | |
| 155 | var byEnds: [SIMD2<Int>: [Int]] = [:] | |
| 156 | for (f, corners) in file.facesVertices.enumerated() { | |
| 157 | for i in corners.indices { | |
| 158 | let u = corners[i], v = corners[(i + 1) % corners.count] | |
| 159 | byEnds[SIMD2(min(u, v), max(u, v)), default: []].append(f) | |
| 160 | } | |
| 161 | } | |
| 162 | return file.edgesVertices.map { byEnds[SIMD2(min($0[0], $0[1]), max($0[0], $0[1]))] ?? [] } | |
| 163 | } | |
| 164 | ||
| 165 | private func nonConvexFaces(_ file: FoldFile) -> [FoldDefect] { | |
| 166 | let points = file.frames[0].verticesCoords | |
| 167 | var defects: [FoldDefect] = [] | |
| 168 | for (f, corners) in file.facesVertices.enumerated() { | |
| 169 | let polygon = corners.map { points[$0] } | |
| 170 | let n = newellNormal(polygon) | |
| 171 | guard length(n) > 0 else { continue } | |
| 172 | let count = polygon.count | |
| 173 | let reflex = polygon.indices.contains { i in | |
| 174 | let into = polygon[i] - polygon[(i + count - 1) % count] | |
| 175 | let out = polygon[(i + 1) % count] - polygon[i] | |
| 176 | guard length(into) > 0, length(out) > 0 else { return false } | |
| 177 | return dot(cross(normalize(into), normalize(out)), normalize(n)) < -1e-9 | |
| 178 | } | |
| 179 | if reflex { defects.append(.nonConvexFace(face: f)) } | |
| 180 | } | |
| 181 | return defects | |
| 182 | } | |
| 183 | ||
| 184 | /// A non-boundary edge without `edges_krz:firstCreasedAtStep` is a defect unless it is a | |
| 185 | /// subdivision edge: `F` and flat in every frame. | |
| 186 | private func missingFirstCreasedAtStep(_ file: FoldFile) -> [FoldDefect] { | |
| 187 | file.edgesVertices.indices.compactMap { e in | |
| 188 | let assignment = file.frames[0].edgesAssignment | |
| 189 | guard e < assignment.count, assignment[e] != .boundary else { return nil } | |
| 190 | if e < file.edgesFirstCreasedAtStep.count, file.edgesFirstCreasedAtStep[e] != nil { return nil } | |
| 191 | let subdivision = file.frames.allSatisfy { frame in | |
| 192 | e < frame.edgesAssignment.count && e < frame.edgesFoldAngle.count | |
| 193 | && frame.edgesAssignment[e] == .flat && frame.edgesFoldAngle[e] == 0 | |
| 194 | } | |
| 195 | return subdivision ? nil : .missingFirstCreasedAtStep(edge: e) | |
| 196 | } | |
| 197 | } | |
| 198 | ||
| 199 | // MARK: - Frame rules | |
| 200 | ||
| 201 | private func angleDefects(_ frame: FoldFrame, _ n: Int, edgeCount: Int) -> [FoldDefect] { | |
| 202 | var defects: [FoldDefect] = [] | |
| 203 | for e in 0..<min(edgeCount, frame.edgesAssignment.count, frame.edgesFoldAngle.count) { | |
| 204 | let angle = frame.edgesFoldAngle[e] | |
| 205 | if abs(angle) > 180 { | |
| 206 | defects.append(.foldAngleOutOfRange(frame: n, edge: e, degrees: angle)) | |
| 207 | } | |
| 208 | switch frame.edgesAssignment[e] { | |
| 209 | case .boundary: | |
| 210 | if angle != 0 { defects.append(.boundaryEdgeFolded(frame: n, edge: e)) } | |
| 211 | case .valley: | |
| 212 | if !(angle > 0) { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) } | |
| 213 | case .mountain: | |
| 214 | if !(angle < 0) { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) } | |
| 215 | case .flat, .unassigned: | |
| 216 | if angle != 0 { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) } | |
| 217 | } | |
| 218 | } | |
| 219 | return defects | |
| 220 | } | |
| 221 | ||
| 222 | /// Antisymmetry, cycles, and the crease, nesting and inside rules over the frame's `faceOrders`. | |
| 223 | private func layerOrderDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, edgeFaces: [[Int]], | |
| 224 | tolerance: Double) -> [FoldDefect] { | |
| 225 | var defects: [FoldDefect] = [] | |
| 226 | let normals = faceNormals(frame, file) | |
| 227 | let faceCount = file.facesVertices.count | |
| 228 | ||
| 229 | var signs: [SIMD2<Int>: Int] = [:] | |
| 230 | var reported: Set<SIMD2<Int>> = [] | |
| 231 | for (f, g, s) in validTriples(frame.faceOrders, faceCount: faceCount) { | |
| 232 | if let t = signs[SIMD2(g, f)] { | |
| 233 | let expected = dot(normals[f], normals[g]) > 0 ? -t : t | |
| 234 | if s != expected && reported.insert(SIMD2(min(f, g), max(f, g))).inserted { | |
| 235 | defects.append(.faceOrderNotAntisymmetric(frame: n, f: f, g: g)) | |
| 236 | } | |
| 237 | } | |
| 238 | signs[SIMD2(f, g)] = s | |
| 239 | } | |
| 240 | ||
| 241 | var aboveOf = Array(repeating: Set<Int>(), count: faceCount) | |
| 242 | for pair in normalisedFaceOrders(frame.faceOrders, normals: normals) { | |
| 243 | aboveOf[pair.below].insert(pair.above) | |
| 244 | } | |
| 245 | let graph = aboveOf.map { $0.sorted() } | |
| 246 | if let cycle = firstCycle(graph) { | |
| 247 | defects.append(.cyclicFaceOrder(frame: n, cycle: cycle)) | |
| 248 | } | |
| 249 | ||
| 250 | // isAbove[x][y]: y lies above x in the stack, directly or through other faces | |
| 251 | let isAbove = reachability(graph) | |
| 252 | let geometry = FrameGeometry(points: frame.verticesCoords, faces: file.facesVertices, | |
| 253 | normals: normals, tolerance: tolerance) | |
| 254 | let edgeCount = min(file.edgesVertices.count, frame.edgesAssignment.count, frame.edgesFoldAngle.count) | |
| 255 | let flatCreases = (0..<edgeCount).filter { e in | |
| 256 | abs(abs(frame.edgesFoldAngle[e]) - 180) <= flatAngleTolerance | |
| 257 | && edgeFaces[e].count == 2 && edgeFaces[e][0] != edgeFaces[e][1] | |
| 258 | } | |
| 259 | ||
| 260 | // crease: a valley points each face's normal toward the other, a mountain away | |
| 261 | for e in flatCreases { | |
| 262 | let assignment = frame.edgesAssignment[e] | |
| 263 | guard assignment == .valley || assignment == .mountain else { continue } | |
| 264 | let f = edgeFaces[e][0], g = edgeFaces[e][1] | |
| 265 | let gOnNormalSideOfF = assignment == .valley | |
| 266 | let gAbove = gOnNormalSideOfF == (dot(normals[f], canonical(normals[f])) > 0) | |
| 267 | let (below, above) = gAbove ? (f, g) : (g, f) | |
| 268 | if isAbove[above][below] { | |
| 269 | defects.append(.orderDisagreesWithCrease(frame: n, edge: e)) | |
| 270 | } | |
| 271 | } | |
| 272 | ||
| 273 | // nesting: the face pairs of two coincident creases nest or are disjoint in the stack | |
| 274 | for (i, e1) in flatCreases.enumerated() { | |
| 275 | for e2 in flatCreases[(i + 1)...] { | |
| 276 | let pair1 = edgeFaces[e1], pair2 = edgeFaces[e2] | |
| 277 | let four = pair1 + pair2 | |
| 278 | guard Set(four).count == 4, | |
| 279 | four.allSatisfy({ geometry.coplanar($0, pair1[0]) }), | |
| 280 | geometry.segmentsCoincide(file.edgesVertices[e1], file.edgesVertices[e2]), | |
| 281 | geometry.onSameSide(of: file.edgesVertices[e1], pair1[0], pair2[0]) else { continue } | |
| 282 | let determined = four.allSatisfy { x in four.allSatisfy { y in x == y || isAbove[x][y] || isAbove[y][x] } } | |
| 283 | guard determined else { continue } | |
| 284 | let rank = { (x: Int) in four.filter { isAbove[$0][x] }.count } | |
| 285 | let (p, q) = (min(rank(pair1[0]), rank(pair1[1])), max(rank(pair1[0]), rank(pair1[1]))) | |
| 286 | let (r, s) = (min(rank(pair2[0]), rank(pair2[1])), max(rank(pair2[0]), rank(pair2[1]))) | |
| 287 | if (p < r && r < q && q < s) || (r < p && p < s && s < q) { | |
| 288 | defects.append(.interleavedFolds(frame: n, edges: [e1, e2])) | |
| 289 | } | |
| 290 | } | |
| 291 | } | |
| 292 | ||
| 293 | // inside: a face whose interior the crease runs through cannot lie between the crease's faces | |
| 294 | for e in flatCreases { | |
| 295 | let a = edgeFaces[e][0], b = edgeFaces[e][1] | |
| 296 | for h in 0..<faceCount where h != a && h != b && geometry.coplanar(h, a) { | |
| 297 | let between = (isAbove[a][h] && isAbove[h][b]) || (isAbove[b][h] && isAbove[h][a]) | |
| 298 | if between && geometry.segmentCrossesInterior(file.edgesVertices[e], face: h) { | |
| 299 | defects.append(.faceInsideFold(frame: n, face: h, edge: e)) | |
| 300 | } | |
| 301 | } | |
| 302 | } | |
| 303 | return defects | |
| 304 | } | |
| 305 | ||
| 306 | // MARK: - Step rules | |
| 307 | ||
| 308 | private func isometryDefects(_ file: FoldFile, step n: Int, tolerance: Double) -> [FoldDefect] { | |
| 309 | let before = file.frames[n - 1].verticesCoords, after = file.frames[n].verticesCoords | |
| 310 | return file.edgesVertices.enumerated().compactMap { e, ends in | |
| 311 | let from = distance(before[ends[0]], before[ends[1]]) | |
| 312 | let to = distance(after[ends[0]], after[ends[1]]) | |
| 313 | return abs(to - from) > tolerance ? .nonIsometricTransition(step: n, edge: e, from: from, to: to) : nil | |
| 314 | } | |
| 315 | } | |
| 316 | ||
| 317 | /// Frame n − 1 and frame n must order every pair of faces that step n leaves still the same way. | |
| 318 | /// Each triple is compared in a form a rigid motion leaves unchanged: rewritten with the lower | |
| 319 | /// face first, `s` negated when swapping two faces whose normals agree. | |
| 320 | private func stillFaceDefects(_ file: FoldFile, step n: Int, moving: Set<Int>) -> [FoldDefect] { | |
| 321 | func relations(_ frame: FoldFrame) -> [(pair: SIMD2<Int>, s: Int)] { | |
| 322 | let normals = faceNormals(frame, file) | |
| 323 | return validTriples(frame.faceOrders, faceCount: file.facesVertices.count) | |
| 324 | .filter { f, g, _ in !moving.contains(f) && !moving.contains(g) } | |
| 325 | .map { f, g, s in | |
| 326 | if f < g { return (SIMD2(f, g), s) } | |
| 327 | return (SIMD2(g, f), dot(normals[f], normals[g]) > 0 ? -s : s) | |
| 328 | } | |
| 329 | } | |
| 330 | var after: [SIMD2<Int>: Int] = [:] | |
| 331 | for (pair, s) in relations(file.frames[n]) where after[pair] == nil { | |
| 332 | after[pair] = s | |
| 333 | } | |
| 334 | var reported: Set<SIMD2<Int>> = [] | |
| 335 | var defects: [FoldDefect] = [] | |
| 336 | for (pair, s) in relations(file.frames[n - 1]) { | |
| 337 | if let t = after[pair], t != s, reported.insert(pair).inserted { | |
| 338 | defects.append(.startAndEndOrderDisagreeOnStillFaces(step: n, f: pair[0], g: pair[1])) | |
| 339 | } | |
| 340 | } | |
| 341 | return defects | |
| 342 | } | |
| 343 | ||
| 344 | // MARK: - Helpers | |
| 345 | ||
| 346 | private func validTriples(_ orders: [[Int]], faceCount: Int) -> [(Int, Int, Int)] { | |
| 347 | orders.compactMap { t in | |
| 348 | guard t.count == 3 else { return nil } | |
| 349 | let (f, g, s) = (t[0], t[1], t[2]) | |
| 350 | guard f >= 0, f < faceCount, g >= 0, g < faceCount, f != g, s == 1 || s == -1 else { return nil } | |
| 351 | return (f, g, s) | |
| 352 | } | |
| 353 | } | |
| 354 | ||
| 355 | /// `n` or `-n`, whichever has its first nonzero component positive. | |
| 356 | private func canonical(_ n: SIMD3<Double>) -> SIMD3<Double> { | |
| 357 | for i in 0..<3 where abs(n[i]) > canonicalComponentThreshold { | |
| 358 | return n[i] > 0 ? n : -n | |
| 359 | } | |
| 360 | return n | |
| 361 | } | |
| 362 | ||
| 363 | private func newellNormal(_ polygon: [SIMD3<Double>]) -> SIMD3<Double> { | |
| 364 | var n = SIMD3<Double>.zero | |
| 365 | for i in polygon.indices { | |
| 366 | let p = polygon[i], q = polygon[(i + 1) % polygon.count] | |
| 367 | n.x += (p.y - q.y) * (p.z + q.z) | |
| 368 | n.y += (p.z - q.z) * (p.x + q.x) | |
| 369 | n.z += (p.x - q.x) * (p.y + q.y) | |
| 370 | } | |
| 371 | return n | |
| 372 | } | |
| 373 | ||
| 374 | /// The first cycle a depth-first search of the below → above graph meets, as the faces along it. | |
| 375 | private func firstCycle(_ graph: [[Int]]) -> [Int]? { | |
| 376 | var state = Array(repeating: 0, count: graph.count) // 0 unvisited, 1 on the path, 2 finished | |
| 377 | var path: [Int] = [] | |
| 378 | func visit(_ u: Int) -> [Int]? { | |
| 379 | state[u] = 1 | |
| 380 | path.append(u) | |
| 381 | for v in graph[u] { | |
| 382 | if state[v] == 1, let start = path.lastIndex(of: v) { return Array(path[start...]) } | |
| 383 | if state[v] == 0, let cycle = visit(v) { return cycle } | |
| 384 | } | |
| 385 | path.removeLast() | |
| 386 | state[u] = 2 | |
| 387 | return nil | |
| 388 | } | |
| 389 | for u in graph.indices where state[u] == 0 { | |
| 390 | if let cycle = visit(u) { return cycle } | |
| 391 | } | |
| 392 | return nil | |
| 393 | } | |
| 394 | ||
| 395 | private func reachability(_ graph: [[Int]]) -> [[Bool]] { | |
| 396 | graph.indices.map { start in | |
| 397 | var seen = Array(repeating: false, count: graph.count) | |
| 398 | var stack = graph[start] | |
| 399 | while let u = stack.popLast() { | |
| 400 | if seen[u] { continue } | |
| 401 | seen[u] = true | |
| 402 | stack += graph[u] | |
| 403 | } | |
| 404 | return seen | |
| 405 | } | |
| 406 | } | |
| 407 | ||
| 408 | /// Whether two convex polygons share interior area wider than `tolerance`, by separating axes. | |
| 409 | private func convexPolygonsOverlap(_ p: [SIMD2<Double>], _ q: [SIMD2<Double>], tolerance: Double) -> Bool { | |
| 410 | var tested = false | |
| 411 | for polygon in [p, q] { | |
| 412 | for i in polygon.indices { | |
| 413 | let edge = polygon[(i + 1) % polygon.count] - polygon[i] | |
| 414 | guard length(edge) > tolerance else { continue } | |
| 415 | let axis = normalize(SIMD2(-edge.y, edge.x)) | |
| 416 | let a = p.map { dot($0, axis) }, b = q.map { dot($0, axis) } | |
| 417 | guard let aMin = a.min(), let aMax = a.max(), let bMin = b.min(), let bMax = b.max() else { return false } | |
| 418 | if min(aMax, bMax) - max(aMin, bMin) <= tolerance { return false } | |
| 419 | tested = true | |
| 420 | } | |
| 421 | } | |
| 422 | return tested | |
| 423 | } | |
| 424 | ||
| 425 | private struct FrameGeometry { | |
| 426 | let points: [SIMD3<Double>] | |
| 427 | let faces: [[Int]] | |
| 428 | let normals: [SIMD3<Double>] | |
| 429 | let tolerance: Double | |
| 430 | ||
| 431 | func centroid(_ f: Int) -> SIMD3<Double> { | |
| 432 | faces[f].reduce(.zero) { $0 + points[$1] } / Double(max(faces[f].count, 1)) | |
| 433 | } | |
| 434 | ||
| 435 | func coplanar(_ f: Int, _ g: Int) -> Bool { | |
| 436 | abs(dot(normals[f], normals[g])) >= parallelCosine | |
| 437 | && abs(dot(centroid(g) - centroid(f), normals[f])) <= tolerance | |
| 438 | } | |
| 439 | ||
| 440 | /// Whether two edges lie on one line and share a stretch longer than `tolerance`. | |
| 441 | func segmentsCoincide(_ e1: [Int], _ e2: [Int]) -> Bool { | |
| 442 | let a = points[e1[0]], b = points[e1[1]] | |
| 443 | let span = length(b - a) | |
| 444 | guard span > tolerance else { return false } | |
| 445 | let direction = (b - a) / span | |
| 446 | let along = e2.map { dot(points[$0] - a, direction) } | |
| 447 | let offLine = e2.contains { v in | |
| 448 | let d = points[v] - a | |
| 449 | return length(d - dot(d, direction) * direction) > tolerance | |
| 450 | } | |
| 451 | guard !offLine else { return false } | |
| 452 | return min(along.max()!, span) - max(along.min()!, 0) > tolerance | |
| 453 | } | |
| 454 | ||
| 455 | /// Whether faces `f` and `g` lie on the same side of the line through `edge`, within their plane. | |
| 456 | func onSameSide(of edge: [Int], _ f: Int, _ g: Int) -> Bool { | |
| 457 | let a = points[edge[0]] | |
| 458 | let across = cross(normals[f], points[edge[1]] - a) | |
| 459 | return dot(centroid(f) - a, across) * dot(centroid(g) - a, across) > 0 | |
| 460 | } | |
| 461 | ||
| 462 | /// Whether the segment `edge` runs through the interior of face `h` for longer than `tolerance`. | |
| 463 | func segmentCrossesInterior(_ edge: [Int], face h: Int) -> Bool { | |
| 464 | let a = points[edge[0]], b = points[edge[1]] | |
| 465 | let polygon = faces[h].map { points[$0] } | |
| 466 | let n = normals[h] | |
| 467 | guard let corner = polygon.first, | |
| 468 | abs(dot(a - corner, n)) <= tolerance, abs(dot(b - corner, n)) <= tolerance else { return false } | |
| 469 | let d = b - a | |
| 470 | var (t0, t1) = (0.0, 1.0) | |
| 471 | for i in polygon.indices { | |
| 472 | let p = polygon[i], side = polygon[(i + 1) % polygon.count] - p | |
| 473 | guard length(side) > tolerance else { continue } | |
| 474 | // counterclockwise about n, so cross(n, side) points inward; keep points deeper than tolerance | |
| 475 | let inward = normalize(cross(n, side)) | |
| 476 | let start = dot(a - p, inward) - tolerance, rate = dot(d, inward) | |
| 477 | if rate == 0 { | |
| 478 | if start < 0 { return false } | |
| 479 | continue | |
| 480 | } | |
| 481 | let t = -start / rate | |
| 482 | if rate > 0 { t0 = max(t0, t) } else { t1 = min(t1, t) } | |
| 483 | if t0 >= t1 { return false } | |
| 484 | } | |
| 485 | return (t1 - t0) * length(d) > tolerance | |
| 486 | } | |
| 487 | } | |
Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift added +98
| @@ -0,0 +1,98 @@ | ||
| 1 | import Foundation | |
| 2 | import Testing | |
| 3 | import FoldFormat | |
| 4 | import FoldKitTestSupport | |
| 5 | ||
| 6 | @Test(arguments: ["square.fold", "half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", | |
| 7 | "letter-staggered.fold", "quarters.fold", "occlusion.fold"]) | |
| 8 | func acceptsAValidModel(_ name: String) throws { | |
| 9 | #expect(validate(try FoldFile(contentsOf: fixture(name))).isEmpty) | |
| 10 | } | |
| 11 | ||
| 12 | @Test func oppositeNormalsMakeAMutualAboveValid() { | |
| 13 | // [f, g, +1] and [g, f, +1] agree when the faces face opposite ways | |
| 14 | let pairs = normalisedFaceOrders([[0, 1, 1], [1, 0, 1]], | |
| 15 | normals: [SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) | |
| 16 | #expect(Set(pairs.map { [$0.below, $0.above] }) == [[0, 1]]) | |
| 17 | } | |
| 18 | ||
| 19 | @Test func rejectsAnOrderTheCreaseMakesImpossible() throws { | |
| 20 | #expect(validate(try FoldFile(contentsOf: fixture("order-against-crease.fold"))) | |
| 21 | .contains(.orderDisagreesWithCrease(frame: 1, edge: 6))) | |
| 22 | } | |
| 23 | ||
| 24 | @Test func rejectsInterleavedFolds() throws { | |
| 25 | let defects = validate(try FoldFile(contentsOf: fixture("interleaved-folds.fold"))) | |
| 26 | #expect(defects.contains { if case .interleavedFolds(frame: 3, _) = $0 { return true }; return false }) | |
| 27 | } | |
| 28 | ||
| 29 | @Test func rejectsAFaceInsideAFoldItCrosses() throws { | |
| 30 | let defects = validate(try FoldFile(contentsOf: fixture("face-inside-fold.fold"))) | |
| 31 | #expect(defects.contains(.faceInsideFold(frame: 2, face: 2, edge: 8))) | |
| 32 | } | |
| 33 | ||
| 34 | @Test func rejectsAFoldAndUnfoldWithoutItsPeakOrder() throws { | |
| 35 | var file = try FoldFile(contentsOf: fixture("quarters.fold")) | |
| 36 | file.frames[1].faceOrdersMidFold = nil | |
| 37 | #expect(validate(file).contains(.foldAndUnfoldWithoutPeakOrder(step: 1))) | |
| 38 | } | |
| 39 | ||
| 40 | @Test func rejectsANonConvexFace() throws { | |
| 41 | #expect(validate(try FoldFile(contentsOf: fixture("nonconvex.fold"))) == [.nonConvexFace(face: 0)]) | |
| 42 | } | |
| 43 | ||
| 44 | @Test func rejectsAFrameThatChangesTheVertexCount() throws { | |
| 45 | let defects = validate(try FoldFile(contentsOf: fixture("retopologised.fold"))) | |
| 46 | #expect(defects.contains(.vertexCountChanged(frame: 2))) | |
| 47 | } | |
| 48 | ||
| 49 | @Test func rejectsOverlappingMovingSetsWithNoMidFoldOrder() throws { | |
| 50 | let defects = validate(try FoldFile(contentsOf: fixture("letter-no-midfold.fold"))) | |
| 51 | #expect(defects == [.overlappingMovingSetsWithoutMidFoldOrder(step: 1)]) | |
| 52 | } | |
| 53 | ||
| 54 | @Test func rejectsStartAndEndOrderDisagreementOnStillFaces() throws { | |
| 55 | let defects = validate(try FoldFile(contentsOf: fixture("still-face-reorder.fold"))) | |
| 56 | #expect(defects.contains { | |
| 57 | if case .startAndEndOrderDisagreeOnStillFaces(step: 2, _, _) = $0 { return true }; return false }) | |
| 58 | } | |
| 59 | ||
| 60 | @Test func rejectsCyclicFaceOrder() throws { | |
| 61 | let defects = validate(try FoldFile(contentsOf: fixture("cyclic-order.fold"))) | |
| 62 | #expect(defects.contains { if case .cyclicFaceOrder(frame: 2, _) = $0 { return true }; return false }) | |
| 63 | } | |
| 64 | ||
| 65 | @Test func rejectsNonIsometricTransition() throws { | |
| 66 | let defects = validate(try FoldFile(contentsOf: fixture("stretched-step.fold"))) | |
| 67 | #expect(defects.contains { if case .nonIsometricTransition(step: 1, _, _, _) = $0 { return true }; return false }) | |
| 68 | } | |
| 69 | ||
| 70 | @Test func rejectsFoldAngleOutsideRange() throws { | |
| 71 | #expect(validate(try FoldFile(contentsOf: fixture("angle-200.fold"))) | |
| 72 | == [.foldAngleOutOfRange(frame: 1, edge: 6, degrees: 200)]) | |
| 73 | } | |
| 74 | ||
| 75 | @Test func rejectsAFoldAngleWhoseSignDisagreesWithItsAssignment() throws { | |
| 76 | #expect(validate(try FoldFile(contentsOf: fixture("angle-sign.fold"))) | |
| 77 | == [.foldAngleSignDisagreesWithAssignment(frame: 1, edge: 6)]) | |
| 78 | } | |
| 79 | ||
| 80 | @Test func rejectsAFoldedBoundaryEdge() throws { | |
| 81 | let defects = validate(try FoldFile(contentsOf: fixture("folded-boundary.fold"))) | |
| 82 | #expect(defects.contains(.boundaryEdgeFolded(frame: 1, edge: 0))) | |
| 83 | } | |
| 84 | ||
| 85 | @Test func rejectsAStepWithoutAnInstruction() throws { | |
| 86 | #expect(validate(try FoldFile(contentsOf: fixture("no-instruction.fold"))) | |
| 87 | == [.missingInstruction(step: 1)]) | |
| 88 | } | |
| 89 | ||
| 90 | @Test func rejectsANonTraditionalAuthor() throws { | |
| 91 | #expect(validate(try FoldFile(contentsOf: fixture("designed-model.fold"))) | |
| 92 | == [.authorNotTraditional("A. Designer")]) | |
| 93 | } | |
| 94 | ||
| 95 | @Test func rejectsEdgeReferencingMissingVertex() throws { | |
| 96 | #expect(validate(try FoldFile(contentsOf: fixture("bad-index.fold"))) | |
| 97 | == [.vertexIndexOutOfRange(edge: 0)]) | |
| 98 | } | |