| @@ -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 | } |