Commit a3454f9ad1
Verified · cmc
Layout: unified · split
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +54 −33
| @@ -164,6 +164,44 @@ public func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> | |||
| 164 | } | 164 | } |
| 165 | } | 165 | } |
| 166 | 166 | ||
| 167 | /// Each triple `[f, g, s]` with `s ≠ 0` in a form that a rigid motion of both faces together leaves | ||
| 168 | /// unchanged: rewritten with the lower face first, `s` negated when swapping two faces whose | ||
| 169 | /// normals agree (the spec's rule for a reverse triple). Triples with `s = 0`, a repeated face or | ||
| 170 | /// a face outside `normals` are skipped. | ||
| 171 | public func rigidInvariantFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(pair: SIMD2<Int>, s: Int)] { | ||
| 172 | validTriples(orders, faceCount: normals.count).map { f, g, s in | ||
| 173 | if f < g { return (SIMD2(f, g), s) } | ||
| 174 | return (SIMD2(g, f), dot(normals[f], normals[g]) > 0 ? -s : s) | ||
| 175 | } | ||
| 176 | } | ||
| 177 | |||
| 178 | /// A cycle in the stacking relation `pairs` over faces `0..<faceCount`, as the faces along it, | ||
| 179 | /// each above the next, starting at the cycle's smallest face index; nil when there is none. | ||
| 180 | /// Pairs naming a face outside `0..<faceCount` are skipped. | ||
| 181 | public func faceOrderCycle(_ pairs: [(below: Int, above: Int)], faceCount: Int) -> [Int]? { | ||
| 182 | guard let cycle = firstCycle(stackingGraph(pairs, faceCount: faceCount)), | ||
| 183 | let start = cycle.indices.min(by: { cycle[$0] < cycle[$1] }) else { return nil } | ||
| 184 | return Array(cycle[start...] + cycle[..<start]) | ||
| 185 | } | ||
| 186 | |||
| 187 | /// Whether two convex polygons share interior area wider than `tolerance`, by separating axes. | ||
| 188 | /// Polygons that only touch do not. | ||
| 189 | public func convexPolygonsOverlap(_ p: [SIMD2<Double>], _ q: [SIMD2<Double>], tolerance: Double) -> Bool { | ||
| 190 | var tested = false | ||
| 191 | for polygon in [p, q] { | ||
| 192 | for i in polygon.indices { | ||
| 193 | let edge = polygon[(i + 1) % polygon.count] - polygon[i] | ||
| 194 | guard length(edge) > tolerance else { continue } | ||
| 195 | let axis = normalize(SIMD2(-edge.y, edge.x)) | ||
| 196 | let a = p.map { dot($0, axis) }, b = q.map { dot($0, axis) } | ||
| 197 | guard let aMin = a.min(), let aMax = a.max(), let bMin = b.min(), let bMax = b.max() else { return false } | ||
| 198 | if min(aMax, bMax) - max(aMin, bMin) <= tolerance { return false } | ||
| 199 | tested = true | ||
| 200 | } | ||
| 201 | } | ||
| 202 | return tested | ||
| 203 | } | ||
| 204 | |||
| 167 | // MARK: - File-level rules | 205 | // MARK: - File-level rules |
| 168 | 206 | ||
| 169 | private func sheetSize(_ file: FoldFile) -> Double { | 207 | private func sheetSize(_ file: FoldFile) -> Double { |
| @@ -301,14 +339,11 @@ private func layerOrderDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, e | |||
| 301 | signs[SIMD2(f, g)] = s | 339 | signs[SIMD2(f, g)] = s |
| 302 | } | 340 | } |
| 303 | 341 | ||
| 304 | var aboveOf = Array(repeating: Set<Int>(), count: faceCount) | 342 | let pairs = normalisedFaceOrders(frame.faceOrders, normals: normals) |
| 305 | for pair in normalisedFaceOrders(frame.faceOrders, normals: normals) { | 343 | if let cycle = faceOrderCycle(pairs, faceCount: faceCount) { |
| 306 | aboveOf[pair.below].insert(pair.above) | ||
| 307 | } | ||
| 308 | let graph = aboveOf.map { $0.sorted() } | ||
| 309 | if let cycle = firstCycle(graph) { | ||
| 310 | defects.append(.cyclicFaceOrder(frame: n, cycle: cycle)) | 344 | defects.append(.cyclicFaceOrder(frame: n, cycle: cycle)) |
| 311 | } | 345 | } |
| 346 | let graph = stackingGraph(pairs, faceCount: faceCount) | ||
| 312 | 347 | ||
| 313 | // isAbove[x][y]: y lies above x in the stack, directly or through other faces | 348 | // isAbove[x][y]: y lies above x in the stack, directly or through other faces |
| 314 | let isAbove = reachability(graph) | 349 | let isAbove = reachability(graph) |
| @@ -377,18 +412,12 @@ private func isometryDefects(_ file: FoldFile, step n: Int, tolerance: Double) - | |||
| 377 | } | 412 | } |
| 378 | } | 413 | } |
| 379 | 414 | ||
| 380 | /// Frame n − 1 and frame n must order every pair of faces that step n leaves still the same way. | 415 | /// Frame n − 1 and frame n must order every pair of faces that step n leaves still the same way, |
| 381 | /// Each triple is compared in a form a rigid motion leaves unchanged: rewritten with the lower | 416 | /// compared with `rigidInvariantFaceOrders`. |
| 382 | /// face first, `s` negated when swapping two faces whose normals agree. | ||
| 383 | private func stillFaceDefects(_ file: FoldFile, step n: Int, moving: Set<Int>) -> [FoldDefect] { | 417 | private func stillFaceDefects(_ file: FoldFile, step n: Int, moving: Set<Int>) -> [FoldDefect] { |
| 384 | func relations(_ frame: FoldFrame) -> [(pair: SIMD2<Int>, s: Int)] { | 418 | func relations(_ frame: FoldFrame) -> [(pair: SIMD2<Int>, s: Int)] { |
| 385 | let normals = faceNormals(frame, file) | 419 | rigidInvariantFaceOrders(frame.faceOrders, normals: faceNormals(frame, file)) |
| 386 | return validTriples(frame.faceOrders, faceCount: file.facesVertices.count) | 420 | .filter { !moving.contains($0.pair[0]) && !moving.contains($0.pair[1]) } |
| 387 | .filter { f, g, _ in !moving.contains(f) && !moving.contains(g) } | ||
| 388 | .map { f, g, s in | ||
| 389 | if f < g { return (SIMD2(f, g), s) } | ||
| 390 | return (SIMD2(g, f), dot(normals[f], normals[g]) > 0 ? -s : s) | ||
| 391 | } | ||
| 392 | } | 421 | } |
| 393 | var after: [SIMD2<Int>: Int] = [:] | 422 | var after: [SIMD2<Int>: Int] = [:] |
| 394 | for (pair, s) in relations(file.frames[n]) where after[pair] == nil { | 423 | for (pair, s) in relations(file.frames[n]) where after[pair] == nil { |
| @@ -456,6 +485,15 @@ private func firstCycle(_ graph: [[Int]]) -> [Int]? { | |||
| 456 | return nil | 485 | return nil |
| 457 | } | 486 | } |
| 458 | 487 | ||
| 488 | /// For each face, the faces directly above it, in index order. | ||
| 489 | private func stackingGraph(_ pairs: [(below: Int, above: Int)], faceCount: Int) -> [[Int]] { | ||
| 490 | var aboveOf = Array(repeating: Set<Int>(), count: faceCount) | ||
| 491 | for pair in pairs where (0..<faceCount).contains(pair.below) && (0..<faceCount).contains(pair.above) { | ||
| 492 | aboveOf[pair.below].insert(pair.above) | ||
| 493 | } | ||
| 494 | return aboveOf.map { $0.sorted() } | ||
| 495 | } | ||
| 496 | |||
| 459 | private func reachability(_ graph: [[Int]]) -> [[Bool]] { | 497 | private func reachability(_ graph: [[Int]]) -> [[Bool]] { |
| 460 | graph.indices.map { start in | 498 | graph.indices.map { start in |
| 461 | var seen = Array(repeating: false, count: graph.count) | 499 | var seen = Array(repeating: false, count: graph.count) |
| @@ -469,23 +507,6 @@ private func reachability(_ graph: [[Int]]) -> [[Bool]] { | |||
| 469 | } | 507 | } |
| 470 | } | 508 | } |
| 471 | 509 | ||
| 472 | /// Whether two convex polygons share interior area wider than `tolerance`, by separating axes. | ||
| 473 | private func convexPolygonsOverlap(_ p: [SIMD2<Double>], _ q: [SIMD2<Double>], tolerance: Double) -> Bool { | ||
| 474 | var tested = false | ||
| 475 | for polygon in [p, q] { | ||
| 476 | for i in polygon.indices { | ||
| 477 | let edge = polygon[(i + 1) % polygon.count] - polygon[i] | ||
| 478 | guard length(edge) > tolerance else { continue } | ||
| 479 | let axis = normalize(SIMD2(-edge.y, edge.x)) | ||
| 480 | let a = p.map { dot($0, axis) }, b = q.map { dot($0, axis) } | ||
| 481 | guard let aMin = a.min(), let aMax = a.max(), let bMin = b.min(), let bMax = b.max() else { return false } | ||
| 482 | if min(aMax, bMax) - max(aMin, bMin) <= tolerance { return false } | ||
| 483 | tested = true | ||
| 484 | } | ||
| 485 | } | ||
| 486 | return tested | ||
| 487 | } | ||
| 488 | |||
| 489 | private struct FrameGeometry { | 510 | private struct FrameGeometry { |
| 490 | let points: [SIMD3<Double>] | 511 | let points: [SIMD3<Double>] |
| 491 | let faces: [[Int]] | 512 | let faces: [[Int]] |
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +27
| @@ -205,3 +205,30 @@ public func gridSheet(cells: Int) -> FoldFile { | |||
| 205 | ] | 205 | ] |
| 206 | ) | 206 | ) |
| 207 | } | 207 | } |
| 208 | |||
| 209 | /// A fixture file, its step `step` (counted from 1), and the interpolator for that step. | ||
| 210 | public func interpolatorWithStep(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldStep, FoldInterpolator) { | ||
| 211 | let file = try FoldFile(contentsOf: fixture(fixtureName)) | ||
| 212 | let s = try readSteps(file)[step - 1] | ||
| 213 | return (file, s, FoldInterpolator(file: file, step: s)) | ||
| 214 | } | ||
| 215 | |||
| 216 | /// The corners of a unit square in the plane z = `z`, counterclockwise seen from +z. | ||
| 217 | private func unitSquare(z: Double) -> [SIMD3<Double>] { | ||
| 218 | [SIMD3(0, 0, z), SIMD3(1, 0, z), SIMD3(1, 1, z), SIMD3(0, 1, z)] | ||
| 219 | } | ||
| 220 | |||
| 221 | /// Two unit squares, both at z = 0. | ||
| 222 | public func stackedSquarePositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 0) } | ||
| 223 | |||
| 224 | /// Two unit squares, at z = 0 and z = 1. | ||
| 225 | public func separatedSquarePositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 1) } | ||
| 226 | |||
| 227 | /// Three unit squares, all at z = 0. | ||
| 228 | public func threeStackedPositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 0) + unitSquare(z: 0) } | ||
| 229 | |||
| 230 | /// The faces of two squares of four vertices each, facing +z. | ||
| 231 | public func twoSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7]] } | ||
| 232 | |||
| 233 | /// The faces of three squares of four vertices each, facing +z. | ||
| 234 | public func threeSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] } | ||
Packages/FoldKit/Sources/Folding/LayerOrder.swift added +292
| @@ -0,0 +1,292 @@ | |||
| 1 | import FoldFormat | ||
| 2 | import Foundation | ||
| 3 | import simd | ||
| 4 | |||
| 5 | public enum LayerError: Error, Equatable, Sendable { | ||
| 6 | /// One source's order has a cycle: the faces along it, each above the next, starting at the | ||
| 7 | /// smallest face index. | ||
| 8 | case cyclic(cycle: [Int]) | ||
| 9 | } | ||
| 10 | |||
| 11 | /// A connected group of nearly coplanar faces whose interiors overlap, sorted back to front for | ||
| 12 | /// the view it was computed for. | ||
| 13 | public struct CoplanarCluster: Equatable, Sendable { | ||
| 14 | public let faces: [Int] | ||
| 15 | |||
| 16 | public init(faces: [Int]) { | ||
| 17 | self.faces = faces | ||
| 18 | } | ||
| 19 | } | ||
| 20 | |||
| 21 | /// Faces closer than this to one line, in degrees, can be linked into a cluster. | ||
| 22 | private let clusterAngle = 2.0 | ||
| 23 | /// Lengths are compared to within this fraction of the bounding-box diagonal. | ||
| 24 | private let relativeTolerance = 1e-6 | ||
| 25 | /// Two unit normals whose dot product's magnitude reaches this lie on one line. | ||
| 26 | private let parallelCosine = 1 - 1e-9 | ||
| 27 | |||
| 28 | /// The stacking order of faces in one state of a step, kept as raw `faceOrders` triples so that | ||
| 29 | /// each is read against its `g`'s normal wherever the faces are. | ||
| 30 | public struct LayerOrder: Sendable { | ||
| 31 | private struct Triple: Sendable { | ||
| 32 | let f: Int, g: Int, s: Int | ||
| 33 | } | ||
| 34 | |||
| 35 | private let triples: [Triple] | ||
| 36 | /// Each pair's relation in the form `rigidInvariantFaceOrders` gives, from the source that | ||
| 37 | /// supplied the pair. | ||
| 38 | private let invariant: [SIMD2<Int>: Int] | ||
| 39 | |||
| 40 | /// Each source is a set of triples with the face normals of the state it describes. Earlier | ||
| 41 | /// sources win for a pair present in several. | ||
| 42 | /// | ||
| 43 | /// - Throws: `LayerError.cyclic` when one source's triples, normalised with its normals, | ||
| 44 | /// form a cycle. | ||
| 45 | public init(sources: [(faceOrders: [[Int]], normals: [SIMD3<Double>])]) throws { | ||
| 46 | var triples: [Triple] = [] | ||
| 47 | var invariant: [SIMD2<Int>: Int] = [:] | ||
| 48 | for source in sources { | ||
| 49 | let pairs = normalisedFaceOrders(source.faceOrders, normals: source.normals) | ||
| 50 | if let cycle = faceOrderCycle(pairs, faceCount: source.normals.count) { | ||
| 51 | throw LayerError.cyclic(cycle: cycle) | ||
| 52 | } | ||
| 53 | let claimed = Set(invariant.keys) | ||
| 54 | for (pair, s) in rigidInvariantFaceOrders(source.faceOrders, normals: source.normals) | ||
| 55 | where !claimed.contains(pair) && invariant[pair] == nil { | ||
| 56 | invariant[pair] = s | ||
| 57 | } | ||
| 58 | let faces = source.normals.indices | ||
| 59 | for t in source.faceOrders where t.count == 3 && faces.contains(t[0]) && faces.contains(t[1]) | ||
| 60 | && t[0] != t[1] && (t[2] == 1 || t[2] == -1) | ||
| 61 | && !claimed.contains(SIMD2(min(t[0], t[1]), max(t[0], t[1]))) { | ||
| 62 | triples.append(Triple(f: t[0], g: t[1], s: t[2])) | ||
| 63 | } | ||
| 64 | } | ||
| 65 | self.triples = triples | ||
| 66 | self.invariant = invariant | ||
| 67 | } | ||
| 68 | |||
| 69 | public init(faceOrders: [[Int]], normals: [SIMD3<Double>]) throws { | ||
| 70 | try self.init(sources: [(faceOrders: faceOrders, normals: normals)]) | ||
| 71 | } | ||
| 72 | |||
| 73 | /// The order that applies throughout step n: frame n's `krz:faceOrders_midFold` (with the | ||
| 74 | /// normals at the peak for a `foldAndUnfold`, else frame n's), or without one frame n's | ||
| 75 | /// `faceOrders`; then frame n − 1's `faceOrders` for the pairs the first lacks, such as a flap | ||
| 76 | /// leaving a stack. | ||
| 77 | public static func active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder { | ||
| 78 | let start = file.frames[step.index - 1], end = file.frames[step.index] | ||
| 79 | let first: (faceOrders: [[Int]], normals: [SIMD3<Double>]) | ||
| 80 | if let midFold = end.faceOrdersMidFold { | ||
| 81 | let normals = step.kind == .foldAndUnfold | ||
| 82 | ? faceNormals(positions: FoldInterpolator(file: file, step: step).positions(at: 0.5), | ||
| 83 | faces: file.facesVertices) | ||
| 84 | : faceNormals(end, file) | ||
| 85 | first = (midFold, normals) | ||
| 86 | } else { | ||
| 87 | first = (end.faceOrders, faceNormals(end, file)) | ||
| 88 | } | ||
| 89 | return try LayerOrder(sources: [first, (start.faceOrders, faceNormals(start, file))]) | ||
| 90 | } | ||
| 91 | |||
| 92 | /// The faces grouped into clusters, each sorted back to front as seen looking along | ||
| 93 | /// `viewDirection`, ordered by their smallest face index. Every face is in exactly one. | ||
| 94 | /// | ||
| 95 | /// Two faces are linked when, projected onto the first's plane, their interiors overlap, their | ||
| 96 | /// normals are within 2° of one line, and each one's vertices lie within sin 2° of the | ||
| 97 | /// bounding-box diagonal of `positions` from the other's plane. A cluster is a connected group | ||
| 98 | /// of linked faces. Within a cluster each triple is read against its `g`'s normal at | ||
| 99 | /// `positions`; faces the order leaves unrelated keep index order. | ||
| 100 | public func clusters(positions: [SIMD3<Double>], faces: [[Int]], viewDirection: SIMD3<Double>) -> [CoplanarCluster] { | ||
| 101 | let normals = faceNormals(positions: positions, faces: faces) | ||
| 102 | let diagonal = boundingBoxDiagonal(positions) | ||
| 103 | let tolerance = diagonal * relativeTolerance | ||
| 104 | let offPlane = diagonal * sin(clusterAngle * .pi / 180) | ||
| 105 | let cosine = cos(clusterAngle * .pi / 180) | ||
| 106 | |||
| 107 | func withinPlane(_ face: Int, of other: Int) -> Bool { | ||
| 108 | let corner = positions[faces[other][0]] | ||
| 109 | return faces[face].allSatisfy { abs(dot(positions[$0] - corner, normals[other])) <= offPlane } | ||
| 110 | } | ||
| 111 | func linked(_ a: Int, _ b: Int) -> Bool { | ||
| 112 | guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= cosine, | ||
| 113 | withinPlane(a, of: b), withinPlane(b, of: a) else { return false } | ||
| 114 | let (u, v) = planeBasis(normals[a]) | ||
| 115 | let project = { (face: Int) in faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } } | ||
| 116 | return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance) | ||
| 117 | } | ||
| 118 | |||
| 119 | return components(faces.count, linked: linked).map { members in | ||
| 120 | CoplanarCluster(faces: backToFront(members, normals: normals, viewDirection: viewDirection)) | ||
| 121 | } | ||
| 122 | } | ||
| 123 | |||
| 124 | /// Whether the two orders relate every pair they share the same way, in the form a rigid | ||
| 125 | /// motion leaves unchanged, ignoring pairs with a face in `movingFaces`. | ||
| 126 | public func agreesWith(_ other: LayerOrder, ignoring movingFaces: Set<Int>) -> Bool { | ||
| 127 | invariant.allSatisfy { pair, s in | ||
| 128 | movingFaces.contains(pair[0]) || movingFaces.contains(pair[1]) || (other.invariant[pair] ?? s) == s | ||
| 129 | } | ||
| 130 | } | ||
| 131 | |||
| 132 | /// `members`, in index order, topologically sorted so that every face comes after the faces | ||
| 133 | /// behind it, taking the smallest ready face first. The triples are read against one normal for | ||
| 134 | /// the whole cluster, its smallest face's, so that faces a little off parallel cannot disagree | ||
| 135 | /// about which side the camera is on. | ||
| 136 | private func backToFront(_ members: [Int], normals: [SIMD3<Double>], viewDirection: SIMD3<Double>) -> [Int] { | ||
| 137 | guard members.count > 1 else { return members } | ||
| 138 | let reference = normals[members[0]] | ||
| 139 | let cameraOnReferenceSide = dot(reference, viewDirection) < 0 | ||
| 140 | let inCluster = Set(members) | ||
| 141 | |||
| 142 | var inFront: [Int: Set<Int>] = [:] | ||
| 143 | for t in triples where inCluster.contains(t.f) && inCluster.contains(t.g) { | ||
| 144 | let gAlongReference = dot(normals[t.g], reference) > 0 | ||
| 145 | let fOnReferenceSide = (t.s > 0) == gAlongReference | ||
| 146 | let (back, front) = fOnReferenceSide == cameraOnReferenceSide ? (t.g, t.f) : (t.f, t.g) | ||
| 147 | inFront[back, default: []].insert(front) | ||
| 148 | } | ||
| 149 | var behind = Dictionary(uniqueKeysWithValues: members.map { ($0, 0) }) | ||
| 150 | for fronts in inFront.values { | ||
| 151 | for f in fronts { behind[f]! += 1 } | ||
| 152 | } | ||
| 153 | |||
| 154 | var remaining = members | ||
| 155 | var sorted: [Int] = [] | ||
| 156 | while !remaining.isEmpty { | ||
| 157 | // two sources can together order a cluster in a cycle; the smallest remaining face breaks it | ||
| 158 | let i = remaining.firstIndex { behind[$0] == 0 } ?? 0 | ||
| 159 | let face = remaining.remove(at: i) | ||
| 160 | sorted.append(face) | ||
| 161 | for f in inFront[face] ?? [] { behind[f]! -= 1 } | ||
| 162 | } | ||
| 163 | return sorted | ||
| 164 | } | ||
| 165 | } | ||
| 166 | |||
| 167 | /// The most faces whose open interiors cover one point, over each group of coincident faces. A | ||
| 168 | /// flat sheet is 1. | ||
| 169 | /// | ||
| 170 | /// Each group's outlines are projected onto its plane and every outline is cut by the edge lines | ||
| 171 | /// of the others, so each piece lies wholly inside or outside every face; the count is taken at | ||
| 172 | /// each piece's centroid. | ||
| 173 | public func stackDepth(positions: [SIMD3<Double>], faces: [[Int]]) -> Int { | ||
| 174 | let normals = faceNormals(positions: positions, faces: faces) | ||
| 175 | let tolerance = boundingBoxDiagonal(positions) * relativeTolerance | ||
| 176 | |||
| 177 | func coincident(_ a: Int, _ b: Int) -> Bool { | ||
| 178 | guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= parallelCosine else { | ||
| 179 | return false | ||
| 180 | } | ||
| 181 | let corner = positions[faces[a][0]] | ||
| 182 | return faces[b].allSatisfy { abs(dot(positions[$0] - corner, normals[a])) <= tolerance } | ||
| 183 | } | ||
| 184 | |||
| 185 | var deepest = 0 | ||
| 186 | for group in components(faces.count, linked: coincident) where normals[group[0]] != .zero { | ||
| 187 | let (u, v) = planeBasis(normals[group[0]]) | ||
| 188 | let outlines = group.map { face in | ||
| 189 | counterclockwise(faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) }) | ||
| 190 | } | ||
| 191 | let lines = outlines.flatMap { outline in | ||
| 192 | outline.indices.map { (outline[$0], outline[($0 + 1) % outline.count]) } | ||
| 193 | } | ||
| 194 | for outline in outlines { | ||
| 195 | var pieces = [outline] | ||
| 196 | for (a, b) in lines where length(b - a) > tolerance { | ||
| 197 | pieces = pieces.flatMap { split($0, along: a, b, tolerance: tolerance) } | ||
| 198 | } | ||
| 199 | for piece in pieces where area(piece) > tolerance * tolerance { | ||
| 200 | let c = centroid(piece) | ||
| 201 | deepest = max(deepest, outlines.filter { contains($0, c) }.count) | ||
| 202 | } | ||
| 203 | } | ||
| 204 | } | ||
| 205 | return deepest | ||
| 206 | } | ||
| 207 | |||
| 208 | // MARK: - Helpers | ||
| 209 | |||
| 210 | /// The connected components of `linked` over `0..<count`, each in index order, ordered by their | ||
| 211 | /// smallest member. | ||
| 212 | private func components(_ count: Int, linked: (Int, Int) -> Bool) -> [[Int]] { | ||
| 213 | var component = Array<Int?>(repeating: nil, count: count) | ||
| 214 | var result: [[Int]] = [] | ||
| 215 | for start in 0..<count where component[start] == nil { | ||
| 216 | component[start] = result.count | ||
| 217 | var members = [start], stack = [start] | ||
| 218 | while let a = stack.popLast() { | ||
| 219 | for b in 0..<count where component[b] == nil && linked(min(a, b), max(a, b)) { | ||
| 220 | component[b] = result.count | ||
| 221 | members.append(b) | ||
| 222 | stack.append(b) | ||
| 223 | } | ||
| 224 | } | ||
| 225 | result.append(members.sorted()) | ||
| 226 | } | ||
| 227 | return result | ||
| 228 | } | ||
| 229 | |||
| 230 | private func boundingBoxDiagonal(_ points: [SIMD3<Double>]) -> Double { | ||
| 231 | guard let first = points.first else { return 0 } | ||
| 232 | return length(points.reduce(first, simd_max) - points.reduce(first, simd_min)) | ||
| 233 | } | ||
| 234 | |||
| 235 | /// Two unit vectors spanning the plane with unit normal `n`. | ||
| 236 | private func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) { | ||
| 237 | let helper: SIMD3<Double> = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0) | ||
| 238 | let u = normalize(cross(n, helper)) | ||
| 239 | return (u, cross(n, u)) | ||
| 240 | } | ||
| 241 | |||
| 242 | private func signedArea(_ p: [SIMD2<Double>]) -> Double { | ||
| 243 | p.indices.reduce(0) { sum, i in | ||
| 244 | let a = p[i], b = p[(i + 1) % p.count] | ||
| 245 | return sum + (a.x * b.y - b.x * a.y) / 2 | ||
| 246 | } | ||
| 247 | } | ||
| 248 | |||
| 249 | private func area(_ p: [SIMD2<Double>]) -> Double { abs(signedArea(p)) } | ||
| 250 | |||
| 251 | private func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] { | ||
| 252 | signedArea(p) < 0 ? p.reversed() : p | ||
| 253 | } | ||
| 254 | |||
| 255 | private func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> { | ||
| 256 | var sum = SIMD2<Double>.zero | ||
| 257 | for i in p.indices { | ||
| 258 | let a = p[i], b = p[(i + 1) % p.count] | ||
| 259 | sum += (a + b) * (a.x * b.y - b.x * a.y) | ||
| 260 | } | ||
| 261 | return sum / (6 * signedArea(p)) | ||
| 262 | } | ||
| 263 | |||
| 264 | /// Whether `point` is in the open interior of the counterclockwise convex polygon `p`. | ||
| 265 | private func contains(_ p: [SIMD2<Double>], _ point: SIMD2<Double>) -> Bool { | ||
| 266 | p.indices.allSatisfy { i in | ||
| 267 | let a = p[i], b = p[(i + 1) % p.count] | ||
| 268 | let side = b - a, offset = point - a | ||
| 269 | return side.x * offset.y - side.y * offset.x > 0 | ||
| 270 | } | ||
| 271 | } | ||
| 272 | |||
| 273 | /// The convex polygon `p` cut in two by the line through `a` and `b`, or `p` alone when no | ||
| 274 | /// corner lies more than `tolerance` to each side. | ||
| 275 | private func split(_ p: [SIMD2<Double>], along a: SIMD2<Double>, _ b: SIMD2<Double>, | ||
| 276 | tolerance: Double) -> [[SIMD2<Double>]] { | ||
| 277 | let d = normalize(b - a) | ||
| 278 | let side = p.map { q in d.x * (q.y - a.y) - d.y * (q.x - a.x) } | ||
| 279 | guard let low = side.min(), let high = side.max(), low < -tolerance, high > tolerance else { return [p] } | ||
| 280 | var left: [SIMD2<Double>] = [], right: [SIMD2<Double>] = [] | ||
| 281 | for i in p.indices { | ||
| 282 | let j = (i + 1) % p.count | ||
| 283 | if side[i] >= 0 { left.append(p[i]) } | ||
| 284 | if side[i] <= 0 { right.append(p[i]) } | ||
| 285 | if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) { | ||
| 286 | let crossing = p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j])) | ||
| 287 | left.append(crossing) | ||
| 288 | right.append(crossing) | ||
| 289 | } | ||
| 290 | } | ||
| 291 | return [left, right] | ||
| 292 | } | ||
Packages/FoldKit/Tests/FoldingTests/LayerOrderTests.swift added +100
| @@ -0,0 +1,100 @@ | |||
| 1 | import Testing | ||
| 2 | import simd | ||
| 3 | import FoldFormat | ||
| 4 | import Folding | ||
| 5 | import FoldKitTestSupport | ||
| 6 | |||
| 7 | let up2 = [SIMD3<Double>(0, 0, 1), SIMD3(0, 0, 1)] | ||
| 8 | let up3 = up2 + [SIMD3(0, 0, 1)] | ||
| 9 | |||
| 10 | @Test func twoStackedCoplanarFacesFormOneClusterOrderedFarthestFirst() throws { | ||
| 11 | let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2) // 0 above 1 | ||
| 12 | let c = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), | ||
| 13 | viewDirection: SIMD3(0, 0, -1)) | ||
| 14 | #expect(c.count == 1) | ||
| 15 | #expect(c[0].faces == [1, 0]) | ||
| 16 | } | ||
| 17 | |||
| 18 | @Test func orbitingUnderneathReversesTheClusterOrder() throws { | ||
| 19 | let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2) | ||
| 20 | let above = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), | ||
| 21 | viewDirection: SIMD3(0, 0, -1)) | ||
| 22 | let below = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), | ||
| 23 | viewDirection: SIMD3(0, 0, 1)) | ||
| 24 | #expect(above[0].faces == below[0].faces.reversed()) | ||
| 25 | } | ||
| 26 | |||
| 27 | @Test func facesSeparatedInSpaceFormSeparateClusters() throws { | ||
| 28 | let order = try LayerOrder(faceOrders: [], normals: up2) | ||
| 29 | #expect(order.clusters(positions: separatedSquarePositions(), faces: twoSquares(), | ||
| 30 | viewDirection: SIMD3(0, 0, -1)).count == 2) | ||
| 31 | } | ||
| 32 | |||
| 33 | @Test func unorderedCoplanarFacesKeepIndexOrder() throws { | ||
| 34 | let order = try LayerOrder(faceOrders: [], normals: up3) | ||
| 35 | #expect(order.clusters(positions: threeStackedPositions(), faces: threeSquares(), | ||
| 36 | viewDirection: SIMD3(0, 0, -1))[0].faces == [0, 1, 2]) | ||
| 37 | } | ||
| 38 | |||
| 39 | @Test func anArrivingFlapJoinsTheStackItLandsOn() throws { | ||
| 40 | // letter-sequential step 2 at 179.5°: f2 is half a degree above f0 and f1 | ||
| 41 | let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2) | ||
| 42 | let c = try LayerOrder.active(for: step, in: file) | ||
| 43 | .clusters(positions: i.positions(at: 179.5 / 180), faces: file.facesVertices, | ||
| 44 | viewDirection: SIMD3(0, 0, -1)) | ||
| 45 | #expect(c.contains { Set($0.faces) == [0, 1, 2] && $0.faces.last == 2 }) | ||
| 46 | } | ||
| 47 | |||
| 48 | @Test func aFlapAtThirtyDegreesIsItsOwnCluster() throws { | ||
| 49 | let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2) | ||
| 50 | let c = try LayerOrder.active(for: step, in: file) | ||
| 51 | .clusters(positions: i.positions(at: 150.0 / 180), faces: file.facesVertices, | ||
| 52 | viewDirection: SIMD3(0, 0, -1)) | ||
| 53 | #expect(c.contains { $0.faces == [2] }) | ||
| 54 | } | ||
| 55 | |||
| 56 | @Test func aFoldAndUnfoldPeakIsOrderedByItsMidFoldOrder() throws { | ||
| 57 | // quarters step 1 at the peak: f2 lies on f3 and f1 on f0, the moving faces on top | ||
| 58 | let (file, step, i) = try interpolatorWithStep("quarters.fold", step: 1) | ||
| 59 | let c = try LayerOrder.active(for: step, in: file) | ||
| 60 | .clusters(positions: i.positions(at: 0.5), faces: file.facesVertices, | ||
| 61 | viewDirection: SIMD3(0, 0, -1)) | ||
| 62 | let left = try #require(c.first { $0.faces.contains(3) }) | ||
| 63 | #expect(left.faces.firstIndex(of: 2)! > left.faces.firstIndex(of: 3)!) | ||
| 64 | } | ||
| 65 | |||
| 66 | @Test func cyclicOrderThrows() { | ||
| 67 | #expect(throws: LayerError.cyclic(cycle: [0, 1, 2])) { | ||
| 68 | try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: up3) | ||
| 69 | } | ||
| 70 | } | ||
| 71 | |||
| 72 | @Test func aRawCycleThatNormalisesAwayIsAccepted() { | ||
| 73 | // f0 and f2 face down: these triples say f1 < f0, f1 < f2, f2 < f0 | ||
| 74 | #expect(throws: Never.self) { | ||
| 75 | try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], | ||
| 76 | normals: [SIMD3(0, 0, -1), SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) | ||
| 77 | } | ||
| 78 | } | ||
| 79 | |||
| 80 | @Test func consecutiveOrderingsAgreeAwayFromTheMovingFaces() throws { | ||
| 81 | let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) | ||
| 82 | for step in try readSteps(file) { | ||
| 83 | let start = try LayerOrder(faceOrders: file.frames[step.index - 1].faceOrders, | ||
| 84 | normals: faceNormals(file.frames[step.index - 1], file)) | ||
| 85 | let end = try LayerOrder(faceOrders: file.frames[step.index].faceOrders, | ||
| 86 | normals: faceNormals(file.frames[step.index], file)) | ||
| 87 | #expect(start.agreesWith(end, ignoring: step.movingFaceUnion), "step \(step.index)") | ||
| 88 | } | ||
| 89 | } | ||
| 90 | |||
| 91 | @Test func stackDepthCountsTheLayersOverOnePoint() throws { | ||
| 92 | let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) | ||
| 93 | #expect(stackDepth(positions: file.frames[2].verticesCoords, faces: file.facesVertices) == 3) | ||
| 94 | } | ||
| 95 | |||
| 96 | @Test func stackDepthOfAFlatSheetIsOne() throws { | ||
| 97 | // four faces meet at the centre vertex | ||
| 98 | let file = try FoldFile(contentsOf: fixture("quarters.fold")) | ||
| 99 | #expect(stackDepth(positions: file.frames[0].verticesCoords, faces: file.facesVertices) == 1) | ||
| 100 | } | ||