import FoldFormat import Foundation import simd public enum LayerError: Error, Equatable, Sendable { /// One source's order has a cycle: the faces along it, each above the next, starting at the /// smallest face index. case cyclic(cycle: [Int]) } /// A connected group of nearly coplanar faces whose interiors overlap, sorted back to front for /// the view it was computed for. public struct CoplanarCluster: Equatable, Sendable { public let faces: [Int] public init(faces: [Int]) { self.faces = faces } } /// Faces closer than this to one line, in degrees, can be linked into a cluster. private let clusterAngle = 2.0 /// Lengths are compared to within this fraction of the bounding-box diagonal. private let relativeTolerance = 1e-6 /// Two unit normals whose dot product's magnitude reaches this lie on one line. private let parallelCosine = 1 - 1e-9 /// The stacking order of faces in one state of a step, kept as raw `faceOrders` triples so that /// each is read against its `g`'s normal wherever the faces are. public struct LayerOrder: Sendable { struct Triple: Sendable { let f: Int, g: Int, s: Int } let triples: [Triple] /// Each pair's relation in the form `rigidInvariantFaceOrders` gives, from the source that /// supplied the pair. private let invariant: [SIMD2: Int] /// Each source is a set of triples with the face normals of the state it describes. Earlier /// sources win for a pair present in several. /// /// - Throws: `LayerError.cyclic` when one source's triples, normalised with its normals, /// form a cycle. public init(sources: [(faceOrders: [[Int]], normals: [SIMD3])]) throws { var triples: [Triple] = [] var invariant: [SIMD2: Int] = [:] for source in sources { let pairs = normalisedFaceOrders(source.faceOrders, normals: source.normals) if let cycle = faceOrderCycle(pairs, faceCount: source.normals.count) { throw LayerError.cyclic(cycle: cycle) } let claimed = Set(invariant.keys) for (pair, s) in rigidInvariantFaceOrders(source.faceOrders, normals: source.normals) where !claimed.contains(pair) && invariant[pair] == nil { invariant[pair] = s } let faces = source.normals.indices for t in source.faceOrders where t.count == 3 && faces.contains(t[0]) && faces.contains(t[1]) && t[0] != t[1] && (t[2] == 1 || t[2] == -1) && !claimed.contains(SIMD2(min(t[0], t[1]), max(t[0], t[1]))) { triples.append(Triple(f: t[0], g: t[1], s: t[2])) } } self.triples = triples self.invariant = invariant } public init(faceOrders: [[Int]], normals: [SIMD3]) throws { try self.init(sources: [(faceOrders: faceOrders, normals: normals)]) } /// The order that applies throughout step n: frame n's `krz:faceOrders_midFold` (with the /// normals at the peak for a `foldAndUnfold`, else frame n's), or without one frame n's /// `faceOrders`; then frame n − 1's `faceOrders` for the pairs the first lacks, such as a flap /// leaving a stack. /// /// A triple whose `g` moves in the step and whose `f` does not is replaced, with its source's /// normals, by its reverse, so that the pair is read against the still face's normal, which /// does not turn during the step. A face moves when it is in `step.allMovingFaces`. public static func active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder { let start = file.frames[step.index - 1], end = file.frames[step.index] let first: (faceOrders: [[Int]], normals: [SIMD3]) if let midFold = end.faceOrdersMidFold { let normals = step.kind == .foldAndUnfold ? faceNormals(positions: FoldInterpolator(file: file, step: step).positions(at: 0.5), faces: file.facesVertices) : faceNormals(end, file) first = (midFold, normals) } else { first = (end.faceOrders, faceNormals(end, file)) } let moving = step.allMovingFaces let sources = [first, (start.faceOrders, faceNormals(start, file))].map { source in (faceOrders: source.faceOrders.map { t -> [Int] in guard t.count == 3, source.normals.indices.contains(t[0]), source.normals.indices.contains(t[1]), moving.contains(t[1]), !moving.contains(t[0]) else { return t } return [t[1], t[0], dot(source.normals[t[0]], source.normals[t[1]]) > 0 ? -t[2] : t[2]] }, normals: source.normals) } return try LayerOrder(sources: sources) } /// The faces grouped into clusters, each sorted back to front as seen looking along /// `viewDirection`, ordered by their smallest face index. Every face is in exactly one. /// /// Two faces are linked when, projected onto the first's plane, their interiors overlap, their /// normals are within 2° of one line, and each one's vertices lie within sin 2° × the /// bounding-box diagonal of `positions` from the other's plane. A cluster is a connected group /// of linked faces. Within a cluster each triple is read against its `g`'s normal at /// `positions`; faces the order leaves unrelated keep index order. public func clusters(positions: [SIMD3], faces: [[Int]], viewDirection: SIMD3) -> [CoplanarCluster] { let normals = faceNormals(positions: positions, faces: faces) return clusterMembers(positions: positions, faces: faces).map { members in CoplanarCluster(faces: backToFront(members, normals: normals, viewDirection: viewDirection)) } } /// Whether the two orders relate every pair they share the same way, in the form a rigid /// motion leaves unchanged, ignoring pairs with a face in `movingFaces`. public func agreesWith(_ other: LayerOrder, ignoring movingFaces: Set) -> Bool { invariant.allSatisfy { pair, s in movingFaces.contains(pair[0]) || movingFaces.contains(pair[1]) || (other.invariant[pair] ?? s) == s } } /// `members`, in index order, topologically sorted so that every face comes after the faces /// behind it, taking the smallest ready face first. The triples are read against one normal for /// the whole cluster, its smallest face's, so that faces a little off parallel cannot disagree /// about which side the camera is on. private func backToFront(_ members: [Int], normals: [SIMD3], viewDirection: SIMD3) -> [Int] { guard members.count > 1 else { return members } let reference = normals[members[0]] let cameraOnReferenceSide = dot(reference, viewDirection) < 0 let inCluster = Set(members) var inFront: [Int: Set] = [:] for t in triples where inCluster.contains(t.f) && inCluster.contains(t.g) { let gAlongReference = dot(normals[t.g], reference) > 0 let fOnReferenceSide = (t.s > 0) == gAlongReference let (back, front) = fOnReferenceSide == cameraOnReferenceSide ? (t.g, t.f) : (t.f, t.g) inFront[back, default: []].insert(front) } var behind = Dictionary(uniqueKeysWithValues: members.map { ($0, 0) }) for fronts in inFront.values { for f in fronts { behind[f]! += 1 } } var remaining = members var sorted: [Int] = [] while !remaining.isEmpty { // two sources can together order a cluster in a cycle; the smallest remaining face breaks it let i = remaining.firstIndex { behind[$0] == 0 } ?? 0 let face = remaining.remove(at: i) sorted.append(face) for f in inFront[face] ?? [] { behind[f]! -= 1 } } return sorted } } /// The most faces whose open interiors cover one point, over each group of coincident faces. A /// flat sheet is 1. /// /// Each group's outlines are projected onto its plane and every outline is cut by the edge lines /// of the others, so each piece lies wholly inside or outside every face; the count is taken at /// each piece's centroid. public func stackDepth(positions: [SIMD3], faces: [[Int]]) -> Int { let normals = faceNormals(positions: positions, faces: faces) let tolerance = boundingBoxDiagonal(positions) * relativeTolerance func coincident(_ a: Int, _ b: Int) -> Bool { guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= parallelCosine else { return false } let corner = positions[faces[a][0]] return faces[b].allSatisfy { abs(dot(positions[$0] - corner, normals[a])) <= tolerance } } var deepest = 0 for group in components(faces.count, linked: coincident) where normals[group[0]] != .zero { let (u, v) = planeBasis(normals[group[0]]) let outlines = group.map { face in counterclockwise(faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) }) } let lines = outlines.flatMap { outline in outline.indices.map { (outline[$0], outline[($0 + 1) % outline.count]) } } for outline in outlines { var pieces = [outline] for (a, b) in lines where length(b - a) > tolerance { pieces = pieces.flatMap { split($0, along: a, b, tolerance: tolerance) } } for piece in pieces where area(piece) > tolerance * tolerance { let c = centroid(piece) deepest = max(deepest, outlines.filter { contains($0, c) }.count) } } } return deepest } // MARK: - Helpers /// The faces of each near-coplanar cluster, in index order, ordered by their smallest face, as /// `LayerOrder.clusters` links them: normals within 2° of one line, each face's vertices within /// sin 2° × the positions' bounding-box diagonal of the other's plane, and interiors overlapping. func clusterMembers(positions: [SIMD3], faces: [[Int]]) -> [[Int]] { let normals = faceNormals(positions: positions, faces: faces) let diagonal = boundingBoxDiagonal(positions) let tolerance = diagonal * relativeTolerance let offPlane = diagonal * sin(clusterAngle * .pi / 180) let cosine = cos(clusterAngle * .pi / 180) func withinPlane(_ face: Int, of other: Int) -> Bool { let corner = positions[faces[other][0]] return faces[face].allSatisfy { abs(dot(positions[$0] - corner, normals[other])) <= offPlane } } func linked(_ a: Int, _ b: Int) -> Bool { guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= cosine, withinPlane(a, of: b), withinPlane(b, of: a) else { return false } let (u, v) = planeBasis(normals[a]) let project = { (face: Int) in faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } } return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance) } return components(faces.count, linked: linked) } /// The connected components of `linked` over `0.. Bool) -> [[Int]] { var component = Array(repeating: nil, count: count) var result: [[Int]] = [] for start in 0..]) -> Double { guard let first = points.first else { return 0 } return length(points.reduce(first, simd_max) - points.reduce(first, simd_min)) } /// Two unit vectors spanning the plane with unit normal `n`. package func planeBasis(_ n: SIMD3) -> (SIMD3, SIMD3) { let helper: SIMD3 = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0) let u = normalize(cross(n, helper)) return (u, cross(n, u)) } private func signedArea(_ p: [SIMD2]) -> Double { p.indices.reduce(0) { sum, i in let a = p[i], b = p[(i + 1) % p.count] return sum + (a.x * b.y - b.x * a.y) / 2 } } private func area(_ p: [SIMD2]) -> Double { abs(signedArea(p)) } func counterclockwise(_ p: [SIMD2]) -> [SIMD2] { signedArea(p) < 0 ? p.reversed() : p } /// The area centroid of a polygon, or its corners' mean when it has no area. func centroid(_ p: [SIMD2]) -> SIMD2 { let area = signedArea(p) guard abs(area) > 0 else { return p.reduce(.zero, +) / Double(max(p.count, 1)) } var sum = SIMD2.zero for i in p.indices { let a = p[i], b = p[(i + 1) % p.count] sum += (a + b) * (a.x * b.y - b.x * a.y) } return sum / (6 * area) } /// Whether `point` is in the open interior of the counterclockwise convex polygon `p`. private func contains(_ p: [SIMD2], _ point: SIMD2) -> Bool { p.indices.allSatisfy { i in let a = p[i], b = p[(i + 1) % p.count] let side = b - a, offset = point - a return side.x * offset.y - side.y * offset.x > 0 } } /// The convex polygon `p` cut in two by the line through `a` and `b`, or `p` alone when no /// corner lies more than `tolerance` to each side. private func split(_ p: [SIMD2], along a: SIMD2, _ b: SIMD2, tolerance: Double) -> [[SIMD2]] { let d = normalize(b - a) let side = p.map { q in d.x * (q.y - a.y) - d.y * (q.x - a.x) } guard let low = side.min(), let high = side.max(), low < -tolerance, high > tolerance else { return [p] } var left: [SIMD2] = [], right: [SIMD2] = [] for i in p.indices { let j = (i + 1) % p.count if side[i] >= 0 { left.append(p[i]) } if side[i] <= 0 { right.append(p[i]) } if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) { let crossing = p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j])) left.append(crossing) right.append(crossing) } } return [left, right] }