Packages/FoldKit/Sources/Folding/Interpenetration.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/Packages/FoldKit/Sources/Folding/Interpenetration.swift history · blame · raw

177 lines · 8795 bytes

13 symbols in this file
  1import FoldFormat
  2import simd
  3
  4/// Two faces that pass through each other. `t` is the first sample, `k / samples`, at which they
  5/// do; `faceA < faceB`.
  6public struct Intersection: Equatable, Sendable {
  7    public let faceA: Int
  8    public let faceB: Int
  9    public let t: Double
 10
 11    public init(faceA: Int, faceB: Int, t: Double) {
 12        self.faceA = faceA
 13        self.faceB = faceB
 14        self.t = t
 15    }
 16}
 17
 18/// Contact this close to a face's boundary does not count.
 19private let contactTolerance = 1e-9
 20/// Coplanar faces: normals within this many radians (as lines), planes within this fraction of
 21/// the sheet's size.
 22private let coplanarAngle = 1e-6
 23private let coplanarOffset = 1e-6
 24
 25/// The pairs of faces that interpenetrate at some sample `t = k / samples`, `k` in 0...samples,
 26/// each reported once at the first such sample.
 27///
 28/// Faces are convex. A pair interpenetrates when the line where their planes meet cuts both and
 29/// the stretch common to both has its midpoint more than 1e-9 inside every edge of each. Contact
 30/// along an edge or at a vertex, shared or coincident, does not count, but pairs that share a
 31/// vertex or an edge are tested. Coplanar pairs are skipped; their overlap is the layer order's.
 32/// The sheet's size is the longest side of the bounding box of the positions at `t = 0`.
 33public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection] {
 34    intersections(polygons: faces, faceOf: Array(faces.indices), samples: samples, at: interpolator.positions(at:))
 35}
 36
 37/// `interpenetrations` on the render mesh's triangles at `meshPositions(at:)`, reporting the FOLD
 38/// faces they lie in. Triangles of one face are not tested against each other. For non-rigid
 39/// steps, whose faces bend during the pop. During the pop, strictly between its phases, faces in
 40/// one near-coplanar cluster (`LayerOrder.clusters`' rule, at the FOLD vertices' positions) are
 41/// not tested against each other: their overlap is the layer order's.
 42public func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection] {
 43    let mesh = interpolator.mesh
 44    return meshIntersections(triangles: mesh.triangles, faceOf: mesh.faceOf, faces: interpolator.faces,
 45                             samples: samples, meshAt: interpolator.meshPositions(at:),
 46                             foldAt: interpolator.positions(at:), pop: interpolator.popPhases)
 47}
 48
 49/// `meshInterpenetrations` for triangles at `meshAt(t)` lying in the FOLD faces `faceOf`, whose
 50/// vertices are at `foldAt(t)`; `pop` is the bent phase, if any.
 51func meshIntersections(triangles: [(Int, Int, Int)], faceOf: [Int], faces: [[Int]], samples: Int,
 52                       meshAt: (Double) -> [SIMD3<Double>], foldAt: (Double) -> [SIMD3<Double>],
 53                       pop: ClosedRange<Double>?) -> [Intersection] {
 54    intersections(polygons: triangles.map { [$0.0, $0.1, $0.2] }, faceOf: faceOf, samples: samples, at: meshAt) { t in
 55        guard let pop, t > pop.lowerBound, t < pop.upperBound else { return nil }
 56        var cluster = Array(repeating: 0, count: faces.count)
 57        for (c, members) in clusterMembers(positions: foldAt(t), faces: faces).enumerated() {
 58            for f in members { cluster[f] = c }
 59        }
 60        return cluster
 61    }
 62}
 63
 64/// The pairs of faces, `faceOf` each polygon, whose polygons pass through each other at some
 65/// sample, each reported once at the first such sample, in face order within a sample.
 66/// `clusters(t)`, when not nil, gives each face's cluster at `t`; faces in one cluster are not tested.
 67private func intersections(polygons corners: [[Int]], faceOf: [Int], samples: Int,
 68                           at positions: (Double) -> [SIMD3<Double>],
 69                           clusters: (Double) -> [Int]? = { _ in nil }) -> [Intersection] {
 70    precondition(samples > 0, "interpenetrations needs at least one sample")
 71    let size = boundingExtent(positions(0)).max()
 72    let usable = corners.indices.filter { corners[$0].count >= 3 }
 73
 74    var found: [Intersection] = []
 75    var reported = Set<SIMD2<Int>>()
 76    for k in 0...samples {
 77        let t = Double(k) / Double(samples)
 78        let points = positions(t)
 79        let normals = faceNormals(positions: points, faces: corners)
 80        let polygons = corners.map { $0.map { points[$0] } }
 81        let boxes = polygons.map(bounds)
 82        let cluster = clusters(t)
 83        // sweep along x: a pair can meet only when their boxes' x-ranges do
 84        let order = usable.filter { normals[$0] != .zero }.sorted { boxes[$0].lower.x < boxes[$1].lower.x }
 85
 86        var hits = Set<SIMD2<Int>>()
 87        for (n, a) in order.enumerated() {
 88            for b in order[(n + 1)...] {
 89                guard boxes[b].lower.x - contactTolerance <= boxes[a].upper.x else { break }
 90                let pair = SIMD2(min(faceOf[a], faceOf[b]), max(faceOf[a], faceOf[b]))
 91                guard pair.x != pair.y, cluster.map({ $0[pair.x] != $0[pair.y] }) ?? true,
 92                      boxesMeet(boxes[a], boxes[b]), !reported.contains(pair), !hits.contains(pair),
 93                      !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size),
 94                      passThrough(polygons[a], normals[a], polygons[b], normals[b])
 95                else { continue }
 96                hits.insert(pair)
 97            }
 98        }
 99        for pair in hits.sorted(by: { ($0.x, $0.y) < ($1.x, $1.y) }) {
100            reported.insert(pair)
101            found.append(Intersection(faceA: pair.x, faceB: pair.y, t: t))
102        }
103    }
104    return found
105}
106
107private typealias Box = (lower: SIMD3<Double>, upper: SIMD3<Double>)
108
109private func bounds(_ points: [SIMD3<Double>]) -> Box {
110    guard let first = points.first else { return (.zero, .zero) }
111    return points.dropFirst().reduce((first, first)) { (simd_min($0.0, $1), simd_max($0.1, $1)) }
112}
113
114private func boundingExtent(_ points: [SIMD3<Double>]) -> SIMD3<Double> {
115    let box = bounds(points)
116    return box.upper - box.lower
117}
118
119/// Whether the boxes, grown by the contact tolerance, meet. Faces whose boxes do not meet cannot
120/// pass through each other.
121private func boxesMeet(_ a: Box, _ b: Box) -> Bool {
122    all(a.lower - contactTolerance .<= b.upper) && all(b.lower - contactTolerance .<= a.upper)
123}
124
125private func coplanar(_ a: [SIMD3<Double>], _ na: SIMD3<Double>, _ b: [SIMD3<Double>], _ nb: SIMD3<Double>,
126                      size: Double) -> Bool {
127    guard length(cross(na, nb)) <= coplanarAngle else { return false }
128    let centre = b.reduce(.zero, +) / Double(b.count)
129    return abs(dot(na, centre - a[0])) <= coplanarOffset * size
130}
131
132/// The inward unit normal of each edge of a counterclockwise polygon, in its plane, with a corner
133/// on that edge.
134private func edgeInwardNormals(_ polygon: [SIMD3<Double>], _ normal: SIMD3<Double>)
135    -> [(corner: SIMD3<Double>, inward: SIMD3<Double>)] {
136    polygon.indices.compactMap { i in
137        let corner = polygon[i], edge = polygon[(i + 1) % polygon.count] - corner
138        let size = length(edge)
139        return size > 0 ? (corner, cross(normal, edge) / size) : nil
140    }
141}
142
143/// The interval of `s` for which `p + s·d` lies in the polygon, `p` and `d` being in its plane.
144private func clip(_ edges: [(corner: SIMD3<Double>, inward: SIMD3<Double>)], _ p: SIMD3<Double>,
145                  _ d: SIMD3<Double>) -> ClosedRange<Double>? {
146    var low = -Double.infinity, high = Double.infinity
147    for (corner, inward) in edges {
148        let distance = dot(inward, p - corner), rate = dot(inward, d)
149        if abs(rate) < 1e-15 {
150            if distance < 0 { return nil }
151            continue
152        }
153        let s = -distance / rate
154        if rate > 0 { low = max(low, s) } else { high = min(high, s) }
155    }
156    return low <= high ? low...high : nil
157}
158
159private func passThrough(_ a: [SIMD3<Double>], _ na: SIMD3<Double>, _ b: [SIMD3<Double>], _ nb: SIMD3<Double>) -> Bool {
160    let along = cross(na, nb)
161    let squared = dot(along, along)
162    guard squared > 0 else { return false }
163    let d = along / sqrt(squared)
164    // a point on both planes
165    let p = (dot(na, a[0]) * cross(nb, along) + dot(nb, b[0]) * cross(along, na)) / squared
166
167    let edgesA = edgeInwardNormals(a, na), edgesB = edgeInwardNormals(b, nb)
168    guard let inA = clip(edgesA, p, d), let inB = clip(edgesB, p, d) else { return false }
169    let low = max(inA.lowerBound, inB.lowerBound), high = min(inA.upperBound, inB.upperBound)
170    guard low < high else { return false }
171
172    // A convex chord whose midpoint is on a face's boundary lies on it, so the midpoint decides.
173    let middle = p + d * ((low + high) / 2)
174    return [edgesA, edgesB].allSatisfy { edges in
175        edges.allSatisfy { dot($0.inward, middle - $0.corner) > contactTolerance }
176    }
177}