Packages/FoldKit/Sources/Folding/LayerMotion.swift
180 lines · 9291 bytes
9 symbols in this file
1import FoldFormat
2import simd
3
4/// How long after a face starts moving, and before it stops, its side of a still face is read, as
5/// a fraction of the window of the axis that starts or stops it. The compiler's layer-order guess
6/// reads arrivals at the same moment.
7private let lead = 1e-3
8/// Two unit normals whose dot product's magnitude reaches this lie on one line.
9private let parallelCosine = 1 - 1e-9
10/// Lengths are compared to within this fraction of the sheet's longer side.
11private let relativeTolerance = 1e-6
12/// A face closer than this fraction of the sheet's size to a still face's plane is on neither side.
13private let separationTolerance = 1e-9
14
15/// Faces that pass through a still face as they start or finish moving: the coplanar contact that
16/// the validator, which reads one frame at a time, and the interpenetration checker, which skips
17/// coplanar faces, cannot see.
18///
19/// In step n, a moving face that overlaps a still face in frame n − 1 may not leave toward the
20/// side of it opposite the one frame n − 1's `faceOrders` give, read just after the face starts
21/// moving; a moving face that overlaps a still face in frame n may not arrive from the side
22/// opposite the one frame n's `faceOrders` give, read just before it stops. Pairs the orders do
23/// not relate are not checked. A face is still when none of the step's axes moves it, counting a
24/// non-rigid step's open and close axes, so the faces that open on the spine are moving.
25/// A non-rigid step's departures are read on its open axes and its arrivals on its close axes; the
26/// pop between is not. Turn-over and rotate steps move every face together and have no still face.
27///
28/// Arrivals are read on the last axis to finish, the higher-indexed of axes that finish together,
29/// at the moment the compiler's layer-order guess reads them. In a rigid step the guess places
30/// the arriving face on the side it arrives from, so in a compiled file an arrival disagrees with
31/// frame n's orders only where the script overrides them.
32///
33/// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped.
34public func layerMotionDefects(_ file: FoldFile) -> [FoldDefect] {
35 file.frames.indices.dropFirst().flatMap { layerMotionDefects(step: $0, in: file) }
36}
37
38/// `layerMotionDefects(_:)` for step `n` alone. `file` needs frames 0…n.
39public func layerMotionDefects(step n: Int, in file: FoldFile) -> [FoldDefect] {
40 guard let step = try? readStep(n, in: file), step.kind == .fold || step.kind == .foldAndUnfold else {
41 return []
42 }
43 let size = sheetExtent(file)
44 let pop = step.nonRigid ? step.pop : nil
45 let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes
46 let moving = step.allMovingFaces
47 let interpolator = FoldInterpolator(file: file, step: step)
48 let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in
49 crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) },
50 interpolator: interpolator, file: file, size: size)
51 }
52 var defects: [FoldDefect] = []
53 var reported = Set<SIMD2<Int>>()
54 for (m, s) in check(file.frames[n - 1], departing, true) + check(file.frames[n], arriving, false)
55 where reported.insert(SIMD2(m, s)).inserted {
56 defects.append(.movesThroughStillFace(step: n, moving: m, still: s))
57 }
58 return defects
59}
60
61/// The pairs `(moving, still)` in which a face `axes` move is, just after it starts moving
62/// (`departure`) or just before it stops, on the side of a still face it overlaps in `frame`
63/// opposite the one `frame`'s orders give.
64private func crossings(_ frame: FoldFrame, axes: [FoldAxis], departure: Bool, still: (Int) -> Bool,
65 interpolator: FoldInterpolator, file: FoldFile, size: Double) -> [(Int, Int)] {
66 let tolerance = size * relativeTolerance
67 let faces = file.facesVertices
68 let points = frame.verticesCoords
69 let normals = faceNormals(positions: points, faces: faces)
70 var axisOfFace: [Int: Int] = [:]
71 for (a, axis) in axes.enumerated() {
72 for f in axis.movingFaces { axisOfFace[f] = a }
73 }
74
75 var sampled: [Double: [SIMD3<Double>]] = [:]
76 var result: [(Int, Int)] = []
77 for m in axisOfFace.keys.sorted() where normals[m] != .zero {
78 var carriers: [Int] = [], a = axisOfFace[m]
79 while let axis = a, !carriers.contains(axis) {
80 carriers.append(axis)
81 a = axes[axis].parent
82 }
83 let t: Double
84 if departure {
85 let w = carriers.map { axes[$0].window }.min { $0.lowerBound < $1.lowerBound }!
86 t = w.lowerBound + lead * (w.upperBound - w.lowerBound)
87 } else {
88 let w = axes[carriers.max { (axes[$0].window.upperBound, $0) < (axes[$1].window.upperBound, $1) }!].window
89 t = w.upperBound - lead * (w.upperBound - w.lowerBound)
90 }
91 let near = sampled[t] ?? interpolator.positions(at: t)
92 sampled[t] = near
93
94 for s in faces.indices where s != m && still(s) && normals[s] != .zero
95 && overlap(m, s, points, faces, normals, tolerance: tolerance) {
96 guard let side = side(of: m, from: s, frame.faceOrders, normals) else { continue }
97 let centre = overlapCentre(m, s, inPlaneOf: s, points, faces, normals)
98 let offset = dot(carry(centre, on: faces[m], from: points, to: near) - centre, normals[s])
99 if abs(offset) > size * separationTolerance && (offset > 0) != (side > 0) {
100 result.append((m, s))
101 }
102 }
103 }
104 return result
105}
106
107/// The side of face `s` along its normal on which `orders` put face `m`: +1 the side the normal
108/// points toward, −1 the other, nil when no triple relates them.
109private func side(of m: Int, from s: Int, _ orders: [[Int]], _ normals: [SIMD3<Double>]) -> Int? {
110 for t in orders where t.count == 3 && (t[2] == 1 || t[2] == -1) {
111 if t[0] == m && t[1] == s { return t[2] }
112 if t[0] == s && t[1] == m { return dot(normals[m], normals[s]) > 0 ? -t[2] : t[2] }
113 }
114 return nil
115}
116
117/// Whether faces `a` and `b` lie in one plane and their interiors overlap.
118private func overlap(_ a: Int, _ b: Int, _ points: [SIMD3<Double>], _ faces: [[Int]], _ normals: [SIMD3<Double>],
119 tolerance: Double) -> Bool {
120 guard abs(dot(normals[a], normals[b])) >= parallelCosine else { return false }
121 let corner = points[faces[b][0]]
122 guard faces[a].allSatisfy({ abs(dot(points[$0] - corner, normals[b])) <= tolerance }) else { return false }
123 let (u, v) = planeBasis(normals[b])
124 let project = { (f: Int) in faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) } }
125 return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance)
126}
127
128/// The centroid of the overlap of coplanar faces `a` and `b`, in the plane of `plane`, one of them.
129package func overlapCentre(_ a: Int, _ b: Int, inPlaneOf plane: Int, _ points: [SIMD3<Double>], _ faces: [[Int]],
130 _ normals: [SIMD3<Double>]) -> SIMD3<Double> {
131 let n = normals[plane]
132 let (u, v) = planeBasis(n)
133 let project = { (f: Int) in counterclockwise(faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) }) }
134 var common = project(a)
135 let clip = project(b)
136 for i in clip.indices where !common.isEmpty {
137 common = keepLeft(of: clip[i], clip[(i + 1) % clip.count], common)
138 }
139 let c = centroid(common)
140 return c.x * u + c.y * v + dot(points[faces[plane][0]], n) * n
141}
142
143/// `point`, a point of the face with corners `corners` at `from`, where the same point of paper
144/// is at `to`. Both states place the face rigidly.
145private func carry(_ point: SIMD3<Double>, on corners: [Int], from: [SIMD3<Double>],
146 to: [SIMD3<Double>]) -> SIMD3<Double> {
147 let first = corners[0]
148 let far = corners.max { distance(from[$0], from[first]) < distance(from[$1], from[first]) }!
149 func frame(_ p: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>, SIMD3<Double>) {
150 let u = normalize(p[far] - p[first])
151 let n = faceNormals(positions: p, faces: [corners])[0]
152 return (u, cross(n, u), n)
153 }
154 let (u, v, n) = frame(from), (u2, v2, n2) = frame(to)
155 let d = point - from[first]
156 return to[first] + dot(d, u) * u2 + dot(d, v) * v2 + dot(d, n) * n2
157}
158
159/// The part of convex polygon `p` to the left of the directed line from `a` to `b`.
160private func keepLeft(of a: SIMD2<Double>, _ b: SIMD2<Double>, _ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
161 let d = b - a
162 let side = p.map { d.x * ($0.y - a.y) - d.y * ($0.x - a.x) }
163 var result: [SIMD2<Double>] = []
164 for i in p.indices {
165 let j = (i + 1) % p.count
166 if side[i] >= 0 { result.append(p[i]) }
167 if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) {
168 result.append(p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j])))
169 }
170 }
171 return result
172}
173
174/// The longer side of frame 0's bounding box.
175private func sheetExtent(_ file: FoldFile) -> Double {
176 let points = file.frames[0].verticesCoords
177 let lower = points.dropFirst().reduce(points[0], simd_min)
178 let upper = points.dropFirst().reduce(points[0], simd_max)
179 return (upper - lower).max()
180}