Commit a9bce7ca7d

a9bce7ca7d23c88735bc7d2ba9ee06eba7ae61b1

parent: e8111179c5

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-19 20:36 UTC

Non-rigid steps spike: petal fold rigid, reverse fold open-pop-close

Reads the bird base from Origami Simulator's flat crane and finds the
petal fold rigid with solved curves. Measures as-rigid-as-possible
bending for the inside reverse fold: opening the flap to 30° from flat
keeps the pop's strain under 8%.

Ref #8

Layout: unified · split

docs/decisions/0001-interpolation-model.md +4
@@ -97,6 +97,10 @@ sheet.
9797
9898### Case 5 in detail
9999
100Superseded by 0002's case 7, which uses the bird base read from Origami
101Simulator's flat crane and finds the petal fold rigid. The pattern below
102included creases the bird base does not have.
103
100104The crease pattern is Origami Simulator's `assets/Bases/birdBase.svg`
101105(midlines, the diagonal the preliminary base folds, eight 22.5° kite
102106creases), made exact, plus the petal hinge between the kite creases' ends.
docs/decisions/0002-non-rigid-steps.md added +204
@@ -0,0 +1,204 @@
1# 0002 — Non-rigid steps and the remaining coupled steps
2
3**Status:** measured. Two choices are the author's before the plan is
4amended: the strain bound (with the flap opening it implies) and how to
5classify the sampan's and the masu's last steps. Task 1 waits on them.
6
7Follows `0001-interpolation-model.md` (option A). Spike:
8`swift run -c release --package-path spikes/interpolation bending` (case 6) and
9`… petal2` (case 7).
10
11## Case 7 — the petal fold is rigid
12
13**Source.** The bird base inside Origami Simulator's
14`assets/Origami/flat_crane.svg` (github.com/amandaghassaei/OrigamiSimulator,
15MIT). The file's coordinates are hand-drawn to about 1e-3, so the pattern was
16rebuilt exactly from its structure rather than snapped:
17
18- the midline cross from the centre to the four kite ends, mountain;
19- the diagonal the preliminary base folds, valley;
20- the eight 22.5° kite creases from the corners, mountain;
21- the two petal hinges joining the kite ends, valley.
22
23The outer midline segments and the other diagonal are **not** creases of the
24bird base. 0001's case 5 assumed they were, which is why it found no petal
25fold.
26
27**Checks.** The preliminary base (full midlines mountain, diagonal valley)
28and the bird base after the front petal fold are both flat-foldable:
29Kawasaki and Maekawa hold at every interior vertex, and both close with gap
30under 4e-16.
31
32**Motion.** The hinge is driven 0° → 180°, the four kite creases and the two
33outer midline segments are solved, and every other crease is held on the
34spanning tree:
35
36- rigid: gap 1e-12, and it reaches the bird base exactly;
37- no collisions between t = 0.05 and 0.95;
38- the outer midline segments *unfold* (−180° → 0°) while the hinge and
39 kites fold;
40- the angles are coupled nonlinearly: at hinge 45°, 90° and 135°, the kites
41 are at −18.0°, −41.9° and −85.5°. Linear angles tear it by 0.18 on a unit
42 sheet;
43- the traced points behave like a petal fold: the front point swings up past
44 the centre, the side corners come to the centre line, and the leg corners
45 stay down.
46
47**Classification:** rigid, M2 with solved curves. Not flagged.
48
49Two lessons for the code:
50
51- Creases that should hold still must be on the spanning tree. A crease off
52 the tree is held only by vertex closure, so a static region whose tree
53 path runs through moving creases can rotate. With the tree built first
54 from static creases, the spurious collisions disappeared. `foldc`'s
55 region tree (plan, Task 7) already holds static creases rigidly.
56- The one collision reported, at exactly t = 1, is two faces landing
57 coincident to within the solver's tolerance, not a crossing. Task 6's
58 coplanar test must allow for solver error, and `foldc` should set the last
59 sample to the end frame exactly.
60
61## Case 6 — the reverse fold needs the flap opened nearly flat
62
63Case 4's two-layer flap (4×2, spine y = 1). The end pose is the reverse
64fold's coordinates. Inside, outside and folded-over reverse folds share
65those coordinates, so the path decides which one it is.
66
67**Extra straight creases do not help.** Any straight crease that meets the
68spine makes another degree-4 vertex with a straight pair, which has the same
69obstruction as case 4. Bending has to come from a model that lets faces
70deform.
71
72**Direct ARAP interpolation** (each small triangle's rotation slerped from
73the closed flap to the reverse fold, positions by least squares, mesh
74spacing 0.25 and 0.125): strain 68–82%, collision at s = 0.03. Rotations
75near 180° make slerp ill-posed; this is not a usable model.
76
77**Open, pop, close.** Three phases:
78
791. Open the flap rigidly to angle φ on its spine, with the tip still
80 pointing out.
812. Pop the tip inside with the flap held at φ. This is the only non-rigid
82 phase, ARAP between two rigid poses.
833. Close rigidly on the reverse-fold branch.
84
85Closing is rigid (gap 1e-13) and collision-free in every run, and just
86before landing the tip lies between the body's layers: an inside reverse
87fold. The pop's largest edge strain:
88
89| flap opened to φ | mesh 0.25 | mesh 0.125 | pop collision |
90|---|---|---|---|
91| 170° (nearly closed) | 64% | 76% | yes |
92| 150° | 53% | 62% | yes |
93| 120° | 58% | 58% | none |
94| 90° | 49% | 56% | none |
95| 60° | 25% | 29% | none |
96| 30° | 6.8% | 7.9% | none |
97| 10° (nearly flat) | 0.8% | 0.9% | none |
98
99The strain is the same within 0.25, within 0.5 and everywhere, so it is not
100concentrated at the vertex; it runs along the tip, because each tip face is
101moved as a whole. Iterative ARAP with only the tip's far corners guided gave
102the same figures for φ ≤ 120°, since the guided corners carry the
103distortion. A pop optimised for least strain was not measured, and might do
104better at moderate openings.
105
106Opening the flap to about 30° from flat is how beginners' diagrams teach
107the inside reverse fold: open the layers, push the point in, flatten.
108
109## Cases 8 and 9 — not measured
110
111- **Sampan, turning inside out.** No crease pattern was found for the
112 traditional sampan with its mountain and valley assignment, and the
113 published sequences differ. The inversion has no spine for a flap to
114 open on, so open–pop–close does not obviously apply.
115- **Masu, raising the walls.** Not built. The pattern is well known, but the
116 wall-raising step would take its own construction and was left out to
117 report the bound question first.
118
119`foldc` already tells a rigid step from a non-rigid one when the model is
120authored: a loop that does not close fails the step (plan, Task 7). That
121answers "rigid or not" for both, but not "which non-rigid model", if the
122answer is not rigid.
123
124## Recommendation
125
1261. **Petal folds are rigid** (M2). Only reverse folds and sinks are flagged.
127 Sinks have the same structure as reverse folds and are expected to use
128 the same model; that is not measured.
1292. **Non-rigid model: open, pop, close**, with φ authored per step and
130 defaulting to 30° from flat. `krz:step` gains, for a flagged step:
131 - the crease the flap opens on;
132 - φ;
133 - the two phase boundaries on *t* (default ⅓, ⅔);
134 - the popped pose's angles;
135 - the closing phase's axes and curves, as for a rigid step.
136
137 The pop runs ARAP on a render mesh subdividing each face to 1/32 of the
138 model's size. The subdivision is the renderer's, not the file's; the FOLD
139 topology is unchanged.
1403. **Bound:** the largest relative change in any render-mesh edge length
141 during a flagged step, at most **10%**. Measured 7.9% at the default φ.
142 Task 8 checks it for every flagged step, alongside the interpenetration
143 check.
1444. **Sampan and masu:** classify each when it is authored in Task 15, using
145 `foldc`'s closure test. If either is not rigid and open–pop–close does
146 not fit it, stop there for a model of its own. Measuring them now needs a
147 crease pattern for the sampan that has not been found.
148
149## Decisions for the author
150
151- **The bound and the opening.** 10% at φ = 30° (recommended); or a smaller
152 opening with more visible stretching, e.g. φ = 60° at about 30% strain;
153 or nearly flat (φ = 10°, under 1%), which is close to option B from 0001.
154- **Sampan and masu:** classify at authoring time (recommended), or build
155 both cases now. The sampan first needs a source for its crease pattern.
156- **Still open from 0001:** removing the overlapping-moving-sets rule for
157 `krz:faceOrders_midFold`.
158
159## Appendix: spike output
160
161```
162## Case 6 — inside reverse fold with bending (as-rigid-as-possible interpolation)
163- end pose gap 4.44e-16: the reverse fold's coordinates; inside, outside and folded-over share them, so the path decides which
164- mesh spacing 0.25: 153 vertices, 256 triangles
165 - direct, closed flap → reverse fold: max strain 68.37%; collision at s = 0.033; at s = 0.97 the tip is between the body's layers (inside)
166 - open to 170.0°, pop, close: iterative ARAP pop strain 41.47%; pop strain 63.69% (beyond 0.25 of the vertex 63.69%, beyond 0.5 63.69%), pop collision at s = 0.067; closing gap 2.49e-13, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
167 - open to 150.0°, pop, close: iterative ARAP pop strain 43.1%; pop strain 52.71% (beyond 0.25 of the vertex 52.71%, beyond 0.5 52.71%), pop collision at s = 0.233; closing gap 9.76e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
168 - open to 120.0°, pop, close: iterative ARAP pop strain 58.18%; pop strain 58.18% (beyond 0.25 of the vertex 58.18%, beyond 0.5 58.18%), pop collision none; closing gap 9.26e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
169 - open to 90.0°, pop, close: iterative ARAP pop strain 48.97%; pop strain 48.97% (beyond 0.25 of the vertex 48.97%, beyond 0.5 48.97%), pop collision none; closing gap 9.97e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
170 - open to 60.0°, pop, close: iterative ARAP pop strain 25.34%; pop strain 25.34% (beyond 0.25 of the vertex 25.34%, beyond 0.5 25.34%), pop collision none; closing gap 9.63e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
171 - open to 30.0°, pop, close: iterative ARAP pop strain 6.81%; pop strain 6.81% (beyond 0.25 of the vertex 6.81%, beyond 0.5 6.81%), pop collision none; closing gap 9.67e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
172 - open to 10.0°, pop, close: iterative ARAP pop strain 0.91%; pop strain 0.77% (beyond 0.25 of the vertex 0.77%, beyond 0.5 0.77%), pop collision none; closing gap 9.66e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
173- mesh spacing 0.125: 561 vertices, 1024 triangles
174 - direct, closed flap → reverse fold: max strain 81.63%; collision at s = 0.033; at s = 0.97 the tip is between the body's layers (inside)
175 - open to 170.0°, pop, close: pop strain 75.84% (beyond 0.25 of the vertex 75.84%, beyond 0.5 75.84%), pop collision at s = 0.05; closing gap 2.49e-13, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
176 - open to 150.0°, pop, close: pop strain 62.27% (beyond 0.25 of the vertex 62.27%, beyond 0.5 62.27%), pop collision at s = 0.15; closing gap 9.76e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
177 - open to 120.0°, pop, close: pop strain 58.47% (beyond 0.25 of the vertex 58.47%, beyond 0.5 58.47%), pop collision none; closing gap 9.26e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
178 - open to 90.0°, pop, close: pop strain 55.89% (beyond 0.25 of the vertex 55.89%, beyond 0.5 55.89%), pop collision none; closing gap 9.97e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
179 - open to 60.0°, pop, close: pop strain 29.3% (beyond 0.25 of the vertex 29.3%, beyond 0.5 29.3%), pop collision none; closing gap 9.63e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
180 - open to 30.0°, pop, close: pop strain 7.88% (beyond 0.25 of the vertex 7.88%, beyond 0.5 7.88%), pop collision none; closing gap 9.67e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
181 - open to 10.0°, pop, close: pop strain 0.89% (beyond 0.25 of the vertex 0.89%, beyond 0.5 0.89%), pop collision none; closing gap 9.66e-14, collision none, reaches the end pose true; just before landing the tip is between the body's layers (inside)
182
183## Case 7 — petal fold on the bird base from Origami Simulator's flat crane
184- tree: 10 of 13 static creases, 4 of 6 moving creases solved, the rest measured
185- preliminary base: gap 1.57e-16; Kawasaki and Maekawa hold at every interior vertex
186- after the front petal fold: gap 3.34e-16; Kawasaki and Maekawa hold at every interior vertex
187- M2, hinge 0 → 180 driven, 4 creases solved (kites seeded mountain): max gap 9.96e-13; collision at t = 1.0; front kites -180.0…0, -180.0…0; inner kites -180.0…0, -180.0…0; outer midline segments -180.0…0, -180.0…0; reaches the bird base: true
188 - collisions with t in 0.05…0.95, away from the coincident start and end: none
189 - first colliding faces at t = 1.0, by centroid on the sheet: (0.67, 0.07)×(0.76, 0.33), (0.67, 0.07)×(0.67, 0.24), (0.67, 0.07)×(0.76, 0.76), (0.07, 0.33)×(0.24, 0.67), (0.07, 0.33)×(0.33, 0.76), (0.07, 0.33)×(0.24, 0.24)
190 - front kite, inner kite, outer segment at t = 0.25: -18.0, -18.0, -135.0; 0.5: -41.9, -41.9, -90.0; 0.75: -85.5, -85.5, -45.0
191 - M1, every angle linear to the same end: max gap 1.82e-1
192 - front point (0,0): (1.0, 1.0, 0) → (0.646, 0.646, -0.5) → (0.293, 0.293, 0)
193 - side corner (0.5,0): (1.0, 0.5, 0) → (0.955, 0.519, -0.128) → (0.646, 0.646, 0)
194 - leg corner (1,0): (1.0, 1.0, 0) → (1.0, 1.0, 0) → (1.0, 1.0, 0)
195- M2, hinge 0 → 180 driven, 4 creases solved (kites seeded valley): max gap 9.96e-13; collision at t = 1.0; front kites -180.0…0, -180.0…0; inner kites -180.0…0, -180.0…0; outer midline segments -180.0…0, -180.0…0; reaches the bird base: true
196 - collisions with t in 0.05…0.95, away from the coincident start and end: none
197 - first colliding faces at t = 1.0, by centroid on the sheet: (0.67, 0.07)×(0.76, 0.33), (0.67, 0.07)×(0.67, 0.24), (0.67, 0.07)×(0.76, 0.76), (0.07, 0.33)×(0.24, 0.67), (0.07, 0.33)×(0.33, 0.76), (0.07, 0.33)×(0.24, 0.24)
198 - front kite, inner kite, outer segment at t = 0.25: -18.0, -18.0, -135.0; 0.5: -41.9, -41.9, -90.0; 0.75: -85.5, -85.5, -45.0
199 - M1, every angle linear to the same end: max gap 1.82e-1
200 - front point (0,0): (1.0, 1.0, 0) → (0.646, 0.646, -0.5) → (0.293, 0.293, 0)
201 - side corner (0.5,0): (1.0, 0.5, 0) → (0.955, 0.519, -0.128) → (0.646, 0.646, 0)
202 - leg corner (1,0): (1.0, 1.0, 0) → (1.0, 1.0, 0) → (1.0, 1.0, 0)
203
204```
spikes/interpolation/Sources/Spike/Bending.swift added +181
@@ -0,0 +1,181 @@
1import simd
2
3/// As-rigid-as-possible interpolation between rigid poses, on a mesh finer
4/// than the crease pattern. Each small triangle's rotation is interpolated
5/// (slerp) from one pose to the next, and the vertex positions that best fit
6/// those rotated edges are solved by least squares. Where the poses cannot be
7/// joined rigidly, the paper bends and stretches; the strain is the largest
8/// relative change in an edge's length.
9struct Bending {
10 let coarse: Sheet
11 let kinematics: Kinematics
12 let fine: Sheet
13 /// The coarse face each fine face lies in.
14 let parent: [Int]
15 let triangles: [(Int, Int, Int)]
16 let pinned: [Int]
17 let factor: [[Double]] // Cholesky factor of the normal matrix
18
19 init(_ coarse: Sheet, _ kinematics: Kinematics, spacing: Double, creases: [(V2, V2)], pinFace: Int) {
20 self.coarse = coarse
21 self.kinematics = kinematics
22 let xs = coarse.verts.map(\.x), ys = coarse.verts.map(\.y)
23 var grid: [(V2, V2)] = []
24 var x = xs.min()! + spacing
25 while x < xs.max()! - 1e-9 { grid.append((V2(x, ys.min()!), V2(x, ys.max()!))); x += spacing }
26 var y = ys.min()! + spacing
27 while y < ys.max()! - 1e-9 { grid.append((V2(xs.min()!, y), V2(xs.max()!, y))); y += spacing }
28 let boundary = [V2(xs.min()!, ys.min()!), V2(xs.max()!, ys.min()!), V2(xs.max()!, ys.max()!), V2(xs.min()!, ys.max()!)]
29 let fine = Sheet(boundary: boundary, creases: creases + grid)
30 self.fine = fine
31 let parent = fine.faces.map { f in
32 let c = f.map { fine.verts[$0] }.reduce(V2.zero, +) / Double(f.count)
33 return coarse.face(containing: c)
34 }
35 self.parent = parent
36 var tris: [(Int, Int, Int)] = []
37 for f in fine.faces { for k in 1..<(f.count - 1) { tris.append((f[0], f[k], f[k + 1])) } }
38 self.triangles = tris
39 let pinnedSet = Set(fine.faces.indices.filter { parent[$0] == pinFace }.flatMap { fine.faces[$0] })
40 self.pinned = Array(pinnedSet)
41
42 // Normal matrix of Σ |x_j − x_i − d_ij|² + w Σ |x_p − target|², one per coordinate.
43 let n = fine.verts.count
44 var A = Array(repeating: [Double](repeating: 0, count: n), count: n)
45 for (a, b, c) in tris {
46 for (i, j) in [(a, b), (b, c), (c, a)] {
47 A[i][i] += 1; A[j][j] += 1; A[i][j] -= 1; A[j][i] -= 1
48 }
49 }
50 for p in pinnedSet { A[p][p] += 1e6 }
51 self.factor = cholesky(A)
52 }
53
54 /// Fine-vertex positions of a rigid coarse pose.
55 func pose(_ angles: [Double]) -> [V3] {
56 let T = kinematics.transforms(angles)
57 var out = [V3](repeating: .zero, count: fine.verts.count)
58 for (f, face) in fine.faces.enumerated() {
59 for v in face { out[v] = T[parent[f]].apply(V3(fine.verts[v], 0)) }
60 }
61 return out
62 }
63
64 /// Each coarse face's rotation in a pose.
65 func rotations(_ angles: [Double]) -> [simd_quatd] { kinematics.transforms(angles).map(\.q) }
66
67 /// Positions at s in 0…1 between two rigid poses.
68 func interpolate(from a: [Double], to b: [Double], at s: Double) -> [V3] {
69 let qa = rotations(a), qb = rotations(b)
70 let rest = pose(a)
71 let target = pose(b)
72 let pinTarget = rest.indices.map { simd_mix(rest[$0], target[$0], V3(repeating: s)) }
73 let n = fine.verts.count
74 var rhs = [V3](repeating: .zero, count: n)
75 var faceOfTriangle: [Int] = []
76 for (f, face) in fine.faces.enumerated() { for _ in 1..<(face.count - 1) { faceOfTriangle.append(f) } }
77 for (t, (a0, b0, c0)) in triangles.enumerated() {
78 let f = parent[faceOfTriangle[t]]
79 var q1 = qb[f] * qa[f].inverse
80 if q1.real < 0 { q1 = simd_quatd(vector: -q1.vector) }
81 let q = simd_slerp(simd_quatd(ix: 0, iy: 0, iz: 0, r: 1), q1, s)
82 for (i, j) in [(a0, b0), (b0, c0), (c0, a0)] {
83 let d = q.act(rest[j] - rest[i])
84 rhs[j] += d; rhs[i] -= d
85 }
86 }
87 for p in pinned { rhs[p] += 1e6 * pinTarget[p] }
88 var out = [V3](repeating: .zero, count: n)
89 for k in 0..<3 {
90 let col = cholSolve(factor, rhs.map { $0[k] })
91 for i in 0..<n { out[i][k] = col[i] }
92 }
93 return out
94 }
95
96 /// Largest relative change in an edge's length, over edges at least
97 /// `outside` from `center` on the sheet.
98 func strain(_ x: [V3], outside: Double = 0, center: V2 = .zero) -> Double {
99 var worst = 0.0
100 for (a, b, c) in triangles {
101 for (i, j) in [(a, b), (b, c), (c, a)] {
102 if outside > 0, simd_distance((fine.verts[i] + fine.verts[j]) / 2, center) < outside { continue }
103 let rest = simd_distance(fine.verts[i], fine.verts[j])
104 worst = max(worst, abs(simd_distance(x[i], x[j]) - rest) / rest)
105 }
106 }
107 return worst
108 }
109
110 func triangleSoup(_ x: [V3]) -> [[V3]] { triangles.map { [x[$0.0], x[$0.1], x[$0.2]] } }
111}
112
113func cholesky(_ A: [[Double]]) -> [[Double]] {
114 let n = A.count
115 var L = Array(repeating: [Double](repeating: 0, count: n), count: n)
116 for j in 0..<n {
117 var s = A[j][j]
118 for k in 0..<j { s -= L[j][k] * L[j][k] }
119 L[j][j] = s.squareRoot()
120 for i in (j + 1)..<n {
121 var t = A[i][j]
122 for k in 0..<j { t -= L[i][k] * L[j][k] }
123 L[i][j] = t / L[j][j]
124 }
125 }
126 return L
127}
128
129func cholSolve(_ L: [[Double]], _ b: [Double]) -> [Double] {
130 let n = b.count
131 var y = b
132 for i in 0..<n { for k in 0..<i { y[i] -= L[i][k] * y[k] }; y[i] /= L[i][i] }
133 for i in stride(from: n - 1, through: 0, by: -1) { for k in (i + 1)..<n { y[i] -= L[k][i] * y[k] }; y[i] /= L[i][i] }
134 return y
135}
136
137extension Bending {
138 /// Iterative as-rigid-as-possible deformation: hold `handles` at their
139 /// targets and find the least-strained positions for the rest, alternating
140 /// a best-fit rotation per triangle with a least-squares solve.
141 func deform(start x0: [V3], handles: [Int: V3], iterations: Int = 40) -> [V3] {
142 let n = fine.verts.count
143 var A = Array(repeating: [Double](repeating: 0, count: n), count: n)
144 for (a, b, c) in triangles {
145 for (i, j) in [(a, b), (b, c), (c, a)] {
146 A[i][i] += 1; A[j][j] += 1; A[i][j] -= 1; A[j][i] -= 1
147 }
148 }
149 for (h, _) in handles { A[h][h] += 1e6 }
150 let L = cholesky(A)
151 let rest = fine.verts.map { V3($0, 0) }
152 var x = x0
153 for _ in 0..<iterations {
154 var rhs = [V3](repeating: .zero, count: n)
155 for (a, b, c) in triangles {
156 // Best rotation taking the rest triangle to the current one.
157 let p = [rest[a], rest[b], rest[c]], q = [x[a], x[b], x[c]]
158 var M = simd_double3x3()
159 for (i, j) in [(0, 1), (1, 2), (2, 0)] {
160 let dq = q[j] - q[i], dp = p[j] - p[i]
161 M += simd_double3x3(columns: (dq * dp.x, dq * dp.y, dq * dp.z))
162 }
163 let nq = simd_normalize(simd_cross(q[1] - q[0], q[2] - q[0]))
164 let scale = simd_length(simd_cross(p[1] - p[0], p[2] - p[0]))
165 M += simd_double3x3(columns: (.zero, .zero, nq * scale))
166 var R = M
167 for _ in 0..<30 { R = 0.5 * (R + R.inverse.transpose) }
168 for (i, j) in [(a, b), (b, c), (c, a)] {
169 let d = R * (rest[j] - rest[i])
170 rhs[j] += d; rhs[i] -= d
171 }
172 }
173 for (h, target) in handles { rhs[h] += 1e6 * target }
174 for k in 0..<3 {
175 let col = cholSolve(L, rhs.map { $0[k] })
176 for i in 0..<n { x[i][k] = col[i] }
177 }
178 }
179 return x
180 }
181}
spikes/interpolation/Sources/Spike/main.swift +228
@@ -245,3 +245,231 @@ if only == nil || only == "petal" {
245245 line("- control, every crease outside the back quadrant free (\(free.count) unknowns): \(row(loose))")
246246 line("")
247247}
248
249// MARK: 7 — petal fold on the bird base read from a crane
250
251if only == nil || only == "petal2" {
252 // The bird base inside Origami Simulator's assets/Origami/flat_crane.svg, made
253 // exact: the midline cross from the centre to the four kite ends, the
254 // diagonal the preliminary base folds, the eight 22.5° kite creases, and the
255 // two petal hinges. The outer midline segments and the other diagonal are
256 // not creases of the bird base; the preliminary base folds the outer
257 // segments, so the petal fold unfolds them.
258 let h = 0.5 * (2.0.squareRoot() - 1)
259 let L = V2(h, 0.5), B = V2(0.5, h), R = V2(1 - h, 0.5), T = V2(0.5, 1 - h), O = V2(0.5, 0.5)
260 let c00 = V2(0, 0), c10 = V2(1, 0), c11 = V2(1, 1), c01 = V2(0, 1)
261 let mL = V2(0, 0.5), mB = V2(0.5, 0), mR = V2(1, 0.5), mT = V2(0.5, 1)
262 let sheet = Sheet(boundary: rect(0, 0, 1, 1), creases: [
263 (mL, L), (L, O), (O, R), (R, mR), (mB, B), (B, O), (O, T), (T, mT), (c10, c01),
264 (c00, B), (c00, L), (c10, B), (c10, R), (c11, R), (c11, T), (c01, T), (c01, L),
265 (L, B), (R, T),
266 ])
267 func e(_ p: V2, _ q: V2) -> Int { sheet.edges(on: p, q)[0] }
268 let outer = [e(mL, L), e(mB, B)], backOuter = [e(R, mR), e(T, mT)]
269 let cross = [e(L, O), e(O, R), e(B, O), e(O, T)]
270 let diagonal = sheet.edges(on: c10, c01)
271 let hinge = e(L, B)
272 let kites = [e(c00, B), e(c00, L)], innerKites = [e(c10, B), e(c01, L)]
273 var start = [Double](repeating: 0, count: sheet.edges.count)
274 for x in outer + backOuter + cross { start[x] = -180 } // mountain
275 for x in diagonal { start[x] = 180 } // valley
276 var end = start
277 end[hinge] = 180
278 for x in kites + innerKites { end[x] = -180 }
279 for x in outer { end[x] = 0 }
280 let root = sheet.face(containing: V2(0.6, 0.6))
281 // Static creases go on the tree first, so the regions they join are held
282 // still by the tree, not only by closure; the moving creases fill the rest.
283 let moving = Set([hinge] + kites + innerKites + outer)
284 let fixed = sheet.interiorEdges.filter { !moving.contains($0) }
285 let k = Kinematics(sheet, root: root, prefer: fixed + [hinge] + kites + innerKites + outer)
286 precondition(k.treeEdges.contains(hinge))
287 line("## Case 7 — petal fold on the bird base from Origami Simulator's flat crane")
288 line("- tree: \(fixed.filter(k.treeEdges.contains).count) of \(fixed.count) static creases, \((kites + innerKites + outer).filter(k.treeEdges.contains).count) of 6 moving creases solved, the rest measured")
289 // Flat-foldability of both end states, vertex by vertex.
290 func check(_ a: [Double]) -> String {
291 var bad: [String] = []
292 for v in sheet.verts.indices {
293 let es = sheet.interiorEdges.filter { [sheet.edges[$0].0, sheet.edges[$0].1].contains(v) }
294 let onBoundary = sheet.edges.indices.contains { sheet.edgeFaces[$0].count == 1 && [sheet.edges[$0].0, sheet.edges[$0].1].contains(v) }
295 if onBoundary { continue }
296 let folded = es.filter { abs(abs(a[$0]) - 180) < 1e-9 }
297 guard !folded.isEmpty else { continue }
298 let dirs = folded.map { x -> Double in
299 let w = sheet.edges[x].0 == v ? sheet.edges[x].1 : sheet.edges[x].0
300 let d = sheet.verts[w] - sheet.verts[v]
301 return atan2(d.y, d.x) * 180 / .pi
302 }.sorted()
303 let sectors = dirs.indices.map { i in i + 1 < dirs.count ? dirs[i + 1] - dirs[i] : dirs[0] + 360 - dirs[i] }
304 let alt = stride(from: 0, to: sectors.count, by: 2).map { sectors[$0] }.reduce(0, +)
305 let m = folded.filter { a[$0] < 0 }.count, vv = folded.count - m
306 if folded.count % 2 != 0 || abs(alt - 180) > 1e-9 || abs(m - vv) != 2 {
307 bad.append("(\(fmt(sheet.verts[v].x, 3)), \(fmt(sheet.verts[v].y, 3))) degree \(folded.count), M \(m) V \(vv), alternate sum \(fmt(alt, 3))")
308 }
309 }
310 return bad.isEmpty ? "Kawasaki and Maekawa hold at every interior vertex" : bad.joined(separator: "; ")
311 }
312 line("- preliminary base: gap \(sci(k.gap(start))); \(check(start))")
313 line("- after the front petal fold: gap \(sci(k.gap(end))); \(check(end))")
314 let free = (kites + innerKites + outer).filter(k.treeEdges.contains)
315 for (name, seedSign) in [("kites seeded mountain", -1.0), ("kites seeded valley", 1.0)] {
316 var seed: [Int: Double] = [:]
317 for x in kites + innerKites where free.contains(x) { seed[x] = 180 * seedSign }
318 for x in outer where free.contains(x) { seed[x] = 180 }
319 let s = continuation(k, start: start, drivers: [hinge: { 180 * $0 }], free: free, seed: seed, steps: 400)
320 func r(_ es: [Int]) -> String { es.map { let (lo, hi) = s.range($0); return "\(fmt(lo))…\(fmt(hi))" }.joined(separator: ", ") }
321 var details: [String] = []
322 let reached = sheet.interiorEdges.allSatisfy { x in
323 let d = (s.end[x] - end[x]).truncatingRemainder(dividingBy: 360)
324 return min(abs(d), 360 - abs(d)) < 1e-3
325 }
326 let away = s.samples.filter { $0.t >= 0.05 && $0.t <= 0.95 }.first { sample in
327 var a = start
328 for x in k.treeEdges { a[x] = sample.angles[x] }
329 return !intersectingPairs(k.positions(a)).isEmpty
330 }
331 details.append(" - collisions with t in 0.05…0.95, away from the coincident start and end: \(away.map { "first at t = \(fmt($0.t, 3))" } ?? "none")")
332 if let t0 = s.firstCollision {
333 var a = start
334 let sample = s.samples.min { abs($0.t - t0) < abs($1.t - t0) }!
335 for x in k.treeEdges { a[x] = sample.angles[x] }
336 let centroid = { (f: Int) -> String in
337 let c = sheet.faces[f].map { sheet.verts[$0] }.reduce(V2.zero, +) / Double(sheet.faces[f].count)
338 return "(\(fmt(c.x, 2)), \(fmt(c.y, 2)))"
339 }
340 let pairs = intersectingPairs(k.positions(a)).map { "\(centroid($0.0))×\(centroid($0.1))" }
341 details.append(" - first colliding faces at t = \(fmt(t0, 3)), by centroid on the sheet: \(pairs.joined(separator: ", "))")
342 }
343 line("- M2, hinge 0 → 180 driven, \(free.count) creases solved (\(name)): max gap \(sci(s.maxGap)); collision \(s.firstCollision.map { "at t = \(fmt($0, 3))" } ?? "none"); front kites \(r(kites)); inner kites \(r(innerKites)); outer midline segments \(r(outer)); reaches the bird base: \(reached)")
344 details.forEach(line)
345 let at = { (t: Double) in [kites[0], innerKites[0], outer[0]].map { fmt(s.angle($0, at: t)) }.joined(separator: ", ") }
346 line(" - front kite, inner kite, outer segment at t = 0.25: \(at(0.25)); 0.5: \(at(0.5)); 0.75: \(at(0.75))")
347 let linear = prescribed(k, steps: 400, collisions: false) { t in
348 var a = start
349 for x in k.treeEdges { a[x] = start[x] + t * (s.end[x] - start[x]) }
350 return a
351 }
352 line(" - M1, every angle linear to the same end: max gap \(sci(linear.maxGap))")
353 if reached {
354 for (pname, p) in [("front point (0,0)", c00), ("side corner (0.5,0)", mB), ("leg corner (1,0)", c10)] {
355 let f = sheet.faces.indices.first { sheet.faces[$0].contains { simd_distance(sheet.verts[$0], p) < 1e-9 } }!
356 let i = sheet.faces[f].firstIndex { simd_distance(sheet.verts[$0], p) < 1e-9 }!
357 let path = [0.0, 0.5, 1.0].map { t -> String in
358 var a = start
359 let sample = s.samples.min { abs($0.t - t) < abs($1.t - t) }!
360 for x in k.treeEdges { a[x] = sample.angles[x] }
361 let q = k.positions(a)[f][i]
362 return "(\(fmt(q.x, 3)), \(fmt(q.y, 3)), \(fmt(q.z, 3)))"
363 }
364 line(" - \(pname): \(path.joined(separator: " → "))")
365 }
366 }
367 }
368 line("")
369}
370
371// MARK: 6 — inside reverse fold with bending
372
373if only == nil || only == "bending" {
374 let creases = [(V2(0, 1), V2(2, 1)), (V2(2, 1), V2(4, 1)), (V2(2, 1), V2(3, 2)), (V2(2, 1), V2(3, 0))]
375 let sheet = Sheet(boundary: rect(0, 0, 4, 2), creases: creases)
376 let root = sheet.face(containing: V2(0.5, 0.5)), bodyTop = sheet.face(containing: V2(0.5, 1.5))
377 let body = sheet.edges(on: V2(0, 1), V2(2, 1))[0], tip = sheet.edges(on: V2(2, 1), V2(4, 1))[0]
378 let b = sheet.edges(on: V2(2, 1), V2(3, 0))[0]
379 let k = Kinematics(sheet, root: root, prefer: [body, tip, b])
380 func pose(_ bodyAngle: Double, _ tipAngle: Double, _ bAngle: Double) -> [Double] {
381 var a = [Double](repeating: 0, count: sheet.edges.count)
382 a[body] = bodyAngle; a[tip] = tipAngle; a[b] = bAngle
383 return a
384 }
385 let start = pose(180, 180, 0), end = pose(180, -180, 180)
386 line("## Case 6 — inside reverse fold with bending (as-rigid-as-possible interpolation)")
387 line("- end pose gap \(sci(k.gap(end))): the reverse fold's coordinates; inside, outside and folded-over share them, so the path decides which")
388 for spacing in [0.25, 0.125] {
389 let mesh = Bending(sheet, k, spacing: spacing, creases: creases, pinFace: root)
390 line("- mesh spacing \(spacing): \(mesh.fine.verts.count) vertices, \(mesh.triangles.count) triangles")
391 // Which layer is the tip between, just before it lands? Compare a tip point's
392 // height with the body's two layers at the same place.
393 func side(_ x: [V3]) -> String {
394 let probe = mesh.fine.verts.indices.min { simd_distance(mesh.fine.verts[$0], V2(2.75, 0.75)) < simd_distance(mesh.fine.verts[$1], V2(2.75, 0.75)) }!
395 let p = x[probe]
396 var zTop: Double? = nil
397 var t = 0
398 for (f, face) in mesh.fine.faces.enumerated() {
399 for kk in 1..<(face.count - 1) {
400 defer { t += 1 }
401 guard mesh.parent[f] == bodyTop else { continue }
402 let (a0, b0, c0) = (x[face[0]], x[face[kk]], x[face[kk + 1]])
403 let v0 = V2(b0.x - a0.x, b0.y - a0.y), v1 = V2(c0.x - a0.x, c0.y - a0.y), v2 = V2(p.x - a0.x, p.y - a0.y)
404 let d = v0.x * v1.y - v0.y * v1.x
405 guard abs(d) > 1e-12 else { continue }
406 let u = (v2.x * v1.y - v2.y * v1.x) / d, w = (v0.x * v2.y - v0.y * v2.x) / d
407 if u >= 0, w >= 0, u + w <= 1 { zTop = a0.z + u * (b0.z - a0.z) + w * (c0.z - a0.z) }
408 }
409 }
410 guard let top = zTop else { return "tip not over the body yet" }
411 if p.z > min(0, top) && p.z < max(0, top) { return "between the body's layers (inside)" }
412 return "outside the body's layers (z \(fmt(p.z, 3)), layers at 0 and \(fmt(top, 3)))"
413 }
414 func run(_ name: String, from a: [Double], to bPose: [Double]) {
415 var worst = 0.0
416 var collision: Double? = nil
417 for i in 0...60 {
418 let s = Double(i) / 60
419 let x = mesh.interpolate(from: a, to: bPose, at: s)
420 worst = max(worst, mesh.strain(x))
421 if collision == nil, s > 0.02, s < 0.98, !intersectingPairs(mesh.triangleSoup(x)).isEmpty { collision = s }
422 }
423 let near = mesh.interpolate(from: a, to: bPose, at: 0.97)
424 line(" - \(name): max strain \(fmt(100 * worst, 2))%; collision \(collision.map { "at s = \(fmt($0, 3))" } ?? "none"); at s = 0.97 the tip is \(side(near))")
425 }
426 run("direct, closed flap → reverse fold", from: start, to: end)
427 // Open, pop, close: open the flap rigidly to φ with the tip still pointing
428 // out; pop the tip inside with the flap held at φ (the only bending); close
429 // rigidly along the reverse-fold branch. At φ = 0 the pop is free: that is
430 // the fully unfolded rigid path.
431 for phi in [170.0, 150, 120, 90, 60, 30, 10] {
432 var popped = pose(phi, -phi, phi)
433 k.solve(&popped, free: [b])
434 let closing = continuation(k, start: popped,
435 drivers: [body: { phi + (180 - phi) * $0 }, tip: { -(phi + (180 - phi) * $0) }],
436 free: [b], collisions: false)
437 var worst = 0.0, beyondQuarter = 0.0, beyondHalf = 0.0
438 var collision: Double? = nil
439 for i in 0...60 {
440 let s = Double(i) / 60
441 let x = mesh.interpolate(from: pose(phi, phi, 0), to: popped, at: s)
442 worst = max(worst, mesh.strain(x))
443 beyondQuarter = max(beyondQuarter, mesh.strain(x, outside: 0.25, center: V2(2, 1)))
444 beyondHalf = max(beyondHalf, mesh.strain(x, outside: 0.5, center: V2(2, 1)))
445 if collision == nil, s > 0.02, s < 0.98, !intersectingPairs(mesh.triangleSoup(x)).isEmpty { collision = s }
446 }
447 let closeCollision = closing.samples.dropLast(3).first { sample in
448 var a = sample.angles
449 a[body] = sample.angles[body]
450 return !intersectingPairs(mesh.triangleSoup(mesh.pose(a))).isEmpty
451 }
452 // The same pop with iterative ARAP: the body held at φ, only the tip's
453 // far corners moved along the pop, everything else left to the solver.
454 var bent = 0.0
455 if spacing == 0.25 {
456 let bodyFaces = Set([root, bodyTop])
457 let held = Set(mesh.fine.faces.indices.filter { bodyFaces.contains(mesh.parent[$0]) }.flatMap { mesh.fine.faces[$0] })
458 let corners = mesh.fine.verts.indices.filter { mesh.fine.verts[$0].x > 4 - 1e-9 }
459 var x = mesh.pose(pose(phi, phi, 0))
460 for i in 1...12 {
461 let s = Double(i) / 12
462 let guide = mesh.interpolate(from: pose(phi, phi, 0), to: popped, at: s)
463 var handles: [Int: V3] = [:]
464 for h in held { handles[h] = guide[h] }
465 for c in corners { handles[c] = guide[c] }
466 x = mesh.deform(start: x, handles: handles)
467 bent = max(bent, mesh.strain(x))
468 }
469 }
470 let nearEnd = closing.samples.min { abs($0.t - 0.97) < abs($1.t - 0.97) }!.angles
471 line(" - open to \(fmt(phi, 0))°, pop, close: \(spacing == 0.25 ? "iterative ARAP pop strain \(fmt(100 * bent, 2))%; " : "")pop strain \(fmt(100 * worst, 2))% (beyond 0.25 of the vertex \(fmt(100 * beyondQuarter, 2))%, beyond 0.5 \(fmt(100 * beyondHalf, 2))%), pop collision \(collision.map { "at s = \(fmt($0, 3))" } ?? "none"); closing gap \(sci(closing.maxGap)), collision \(closeCollision.map { "at t = \(fmt($0.t, 3))" } ?? "none"), reaches the end pose \(abs(closing.end[b] - 180) < 1e-3); just before landing the tip is \(side(mesh.pose(nearEnd)))")
472 }
473 }
474 line("")
475}