Commit 1f6104968e

1f6104968eed54736b1cd9a14dd8044b2cac2d3e

parent: a9bce7ca7d

Verified · cmc

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

Apply decision 0002: open, pop, close for reverse folds and sinks

Records the decision (10% strain, flap opened to 30° from flat), adds
Task 7b for the non-rigid path, amends Tasks 1, 3, 6, 7, 8, 10, 11, 12
and 15, adds the test-helper table, and corrects 0002's claims after
review.

Closes #8

Layout: unified · split

docs/decisions/0001-interpolation-model.md +9 −5
@@ -1,11 +1,15 @@
11# 0001 — Interpolation model
22
33**Status:** decided 2026-10-19 — **option A**. Rigid steps use M2 with
4per-axis windows on *t*. Reverse folds, sinks and inversions are flagged
5non-rigid and animated by a model Task 0b chooses, which also settles the
6petal fold, the sampan's inversion and the masu's wall-raising. Task 0's stop
7condition was met (the crane's reverse folds have no rigid model that matches
8the fold); this choice resolves it.
4per-axis windows on *t*. Steps with no rigid motion are flagged non-rigid
5and animated by a model Task 0b chooses. Task 0's stop condition was met
6(the crane's reverse folds have no rigid model that matches the fold); this
7choice resolves it.
8
9**Amended by `0002-non-rigid-steps.md`:** the petal fold is rigid; reverse
10folds and sinks are flagged and open, pop, close; inversions (the sampan's)
11and the masu's wall-raising are classified when authored, not flagged in
12advance.
913
1014## Question
1115
docs/decisions/0002-non-rigid-steps.md +104 −65
@@ -1,8 +1,15 @@
11# 0002 — Non-rigid steps and the remaining coupled steps
22
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.
3**Status:** decided 2026-10-19, as recommended:
4
5- the petal fold is rigid (M2);
6- reverse folds and sinks are flagged and use open, pop, close, with the flap
7 opened to 30° from flat by default;
8- the bound is 10% largest edge strain on the render mesh;
9- the sampan's and the masu's last steps, and the crane's preliminary base,
10 are classified when they are authored (Task 15).
11
12The plan is amended accordingly; the non-rigid path is Task 7b.
613
714Follows `0001-interpolation-model.md` (option A). Spike:
815`swift run -c release --package-path spikes/interpolation bending` (case 6) and
@@ -20,20 +27,25 @@ rebuilt exactly from its structure rather than snapped:
2027- the eight 22.5° kite creases from the corners, mountain;
2128- the two petal hinges joining the kite ends, valley.
2229
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.
30The outer midline segments, from each kite end to the edge, are folded in
31the preliminary base and flat in the bird base, so they are edges of the
32pattern, unfolded by the petal fold. The other diagonal is not creased at
33all. 0001's case 5 used a different pattern — no unfolding of the outer
34segments, plus an inner square — and its petal lifted the inner layers'
35corners too.
2636
2737**Checks.** The preliminary base (full midlines mountain, diagonal valley)
2838and the bird base after the front petal fold are both flat-foldable:
2939Kawasaki and Maekawa hold at every interior vertex, and both close with gap
3040under 4e-16.
3141
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:
42**Motion.** The hinge is driven 0° → 180°. Ten of the thirteen static
43creases go on the spanning tree first; the other three are off it and held
44by closure. Of the six moving creases (four kites, two outer segments),
45four are solved on the tree and two measured. Every crease, static ones
46included, ends within 1e-3° of the bird base.
3547
36- rigid: gap 1e-12, and it reaches the bird base exactly;
48- rigid: gap 1e-12, and it reaches the bird base;
3749- no collisions between t = 0.05 and 0.95;
3850- the outer midline segments *unfold* (−180° → 0°) while the hinge and
3951 kites fold;
@@ -48,15 +60,16 @@ spanning tree:
4860
4961Two lessons for the code:
5062
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.
63- Creases that should hold still must be on the spanning tree where
64 possible. A crease off the tree is held only by vertex closure, so a
65 static region whose tree path runs through moving creases can rotate. With
66 the static creases put on the tree first, the spurious mid-motion
67 collisions disappeared. `foldc`'s region tree (plan, Task 7) holds static
68 creases rigidly.
69- Collisions are still reported at exactly t = 1, six pairs, where faces
70 land on stacks; they were not examined further. The plan sets each step's
71 last sample to the end frame exactly, and makes Task 6's coplanar
72 tolerance as wide as the isometry tolerance.
6073
6174## Case 6 — the reverse fold needs the flap opened nearly flat
6275
@@ -64,10 +77,11 @@ Case 4's two-layer flap (4×2, spine y = 1). The end pose is the reverse
6477fold's coordinates. Inside, outside and folded-over reverse folds share
6578those coordinates, so the path decides which one it is.
6679
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.
80**Extra straight creases** were argued against, not measured. A straight
81crease that meets the spine elsewhere makes another degree-4 vertex with a
82straight pair, with the same obstruction as case 4. A fan of creases from
83the existing vertex raises its degree and adds freedom that this argument
84does not cover. The spike went to bending instead.
7185
7286**Direct ARAP interpolation** (each small triangle's rotation slerped from
7387the closed flap to the reverse fold, positions by least squares, mesh
@@ -82,9 +96,10 @@ near 180° make slerp ill-posed; this is not a usable model.
8296 phase, ARAP between two rigid poses.
83973. Close rigidly on the reverse-fold branch.
8498
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:
99Closing is rigid (gap 1e-13). No collision was found in it, checking every
100sample except the last three, where faces land. Just before landing, the
101tip lies between the body's layers: an inside reverse fold. The pop's
102largest edge strain:
88103
89104| flap opened to φ | mesh 0.25 | mesh 0.125 | pop collision |
90105|---|---|---|---|
@@ -96,65 +111,89 @@ fold. The pop's largest edge strain:
96111| 30° | 6.8% | 7.9% | none |
97112| 10° (nearly flat) | 0.8% | 0.9% | none |
98113
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.
114The largest strain beyond 0.25 and beyond 0.5 of the vertex equals the
115largest overall, so it is not concentrated at the vertex. It runs along the
116tip, because each tip face is moved as a whole.
117
118Iterative ARAP, with only the tip's far corners guided and only on the 0.25
119mesh, gave lower strain at 170° and 150° (41%, 43%), the same at 120°–30°,
120and 0.91% against 0.77% at 10°. The guided corners carry the distortion. A
121pop optimised for least strain was not measured, and might do better at
122moderate openings.
105123
106124Opening the flap to about 30° from flat is how beginners' diagrams teach
107125the inside reverse fold: open the layers, push the point in, flatten.
108126
109## Cases 8 and 9 — not measured
127**Limits.**
128
129- One two-layer 4×2 flap, at two resolutions; strain rose with refinement
130 (6.8% → 7.9% at 30°).
131- The crane's flaps are narrower and several layers deep, and the render
132 mesh's spacing is 1/32 of the whole sheet, so a neck flap gets few cells
133 across.
134- Opening a multi-layer flap to 30° may disturb earlier layers; that is
135 0001's "not measured on the crane's geometry" again.
136- Only the inside reverse fold was measured; outside reverse folds and sinks
137 are expected to fit the same model.
138
139Task 15 records each flagged step's strain.
140
141## Not measured
110142
111143- **Sampan, turning inside out.** No crease pattern was found for the
112144 traditional sampan with its mountain and valley assignment, and the
113145 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.
146 open on, so open, pop, close does not obviously apply.
147- **Masu, raising the walls.** Not built. The pattern is well known; the
148 wall-raising step would need its own construction.
149- **The crane's preliminary base.** 0001 listed its collapse (or the squash
150 folds that can replace it) as coupled. Not measured. A squash fold opens a
151 flap on a spine, as a reverse fold does, so the plan has the crane collapse
152 the preliminary base from a pre-creased square instead.
153
154When a model is authored, classifying a step uses:
155
156- `foldc`'s closure test — a loop that does not close fails the step;
157- the interpenetration check;
158- the validator's layer rules;
159- a look in the app.
160
161Closure alone is not enough: a solver that fails to converge does not prove
162there is no rigid motion, and case 4(a) shows closure succeeding on a branch
163with the wrong layering. That is why a reverse fold is flagged by its script
164naming a spine, not by the solver.
123165
124166## Recommendation
125167
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.
1681. **Petal folds are rigid** (M2). Only reverse folds and sinks are flagged,
169 by naming the spine their flap opens on. Sinks have the same structure as
170 reverse folds and are expected to use the same model; that is not
171 measured.
1291722. **Non-rigid model: open, pop, close**, with φ authored per step and
130173 defaulting to 30° from flat. `krz:step` gains, for a flagged step:
131 - the crease the flap opens on;
174 - the spine;
132175 - φ;
133176 - 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.
177 - the opening axes;
178 - the popped pose;
179 - the closing axes and curves, as for a rigid step.
136180
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.
181 The pop runs ARAP on a render mesh built as the spike built it: frame 0's
182 creases plus lines every 1/32 of its longer side in each direction. The
183 mesh is the renderer's, not the file's; the FOLD topology is unchanged.
1401843. **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.
185 during the pop, at most **10%**. Measured 7.9% at the default φ, on the
186 case 6 flap only. Task 8 checks it for every flagged step, alongside the
187 interpenetration check on the mesh.
1884. **Sampan, masu and the crane's preliminary base:** classify each when it
189 is authored in Task 15, as above. If one is not rigid and open, pop, close
190 does not fit it, stop there for a model of its own.
148191
149192## Decisions for the author
150193
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`.
194All three made on 2026-10-19: 10% at φ = 30°; sampan and masu classified at
195authoring time. Removing the overlapping-moving-sets rule for
196`krz:faceOrders_midFold` (from 0001) is still open.
158197
159198## Appendix: spike output
160199
docs/superpowers/plans/2026-10-19-fold.md +263 −40
@@ -4,7 +4,7 @@
44
55**Goal:** An iOS app that folds traditional origami models under your finger and generates their Yoshizawa–Randlett diagrams from the same data, so the diagram and the model cannot disagree.
66
7**Architecture:** A model is one FOLD file whose `file_frames` are its steps, sharing one topology: frame 0 is the sheet already subdivided by every crease the sequence will use. Each frame carries an authored `krz:step` naming its kind, technique, instruction, axes, moving sets and viewpoint. Intermediate geometry is rigid rotation of the moving facets on one parameter the finger drives: a step's axes form a tree, each with its own window on that parameter and, where faces form loops, an angle curve `foldc` solves (decision 0001). Reverse folds, sinks and inversions have no rigid path and are flagged non-rigid, moving by the model Task 0b chooses. Draw order is hybrid — the depth buffer between clusters of near-coplanar overlapping faces, the active `faceOrders` within each. The frames are produced by a macOS fold-script compiler that ships with the repo but not in the app.
7**Architecture:** A model is one FOLD file whose `file_frames` are its steps, sharing one topology: frame 0 is the sheet already subdivided by every crease the sequence will use. Each frame carries an authored `krz:step` naming its kind, technique, instruction, axes, moving sets and viewpoint. Intermediate geometry is rigid rotation of the moving facets on one parameter the finger drives: a step's axes form a tree, each with its own window on that parameter and, where faces form loops, an angle curve `foldc` solves (decision 0001). Reverse folds and sinks have no rigid path with the flap closed; they are flagged non-rigid and open, pop and close (decision 0002), the pop held to 10% strain on a render mesh. Draw order is hybrid — the depth buffer between clusters of near-coplanar overlapping faces, the active `faceOrders` within each. The frames are produced by a macOS fold-script compiler that ships with the repo but not in the app.
88
99**Tech Stack:** Swift 6, iOS 26, SwiftUI, Metal, `simd`, Swift Testing, XcodeGen. No third-party runtime dependencies in the app.
1010
@@ -27,7 +27,7 @@
2727- **Steps are authored, never derived from a frame diff.** That includes `instruction`, which is the accessibility label.
2828- **`turnOver` and `rotate` change the coordinates.** Frame n is frame n − 1 rotated about its bounding-box centre; the camera does not move.
2929- Paper is rigid flat facets hinged at straight creases, except during a step flagged `nonRigid`. No stiffness, self-collision response or crumpling.
30- **Interpolation (decision 0001, option A).** A step's axes form a tree: an axis may name a parent axis whose motion carries it. Each axis has a window on *t* (default 0…1) and either a linear angle or a solved curve of 257 samples, rebuilt by cubic Hermite interpolation. Steps whose technique has no rigid path — inside and outside reverse folds, sinks, inversions — carry `nonRigid: true`; the isometry gate does not apply to them and Task 0b's strain bound does.
30- **Interpolation (decision 0001, option A).** A step's axes form a tree: an axis may name a parent axis whose motion carries it. Each axis has a window on *t* (default 0…1) and either a linear angle or a solved curve of 257 samples, rebuilt by cubic Hermite interpolation. Steps whose technique has no rigid path — inside and outside reverse folds, sinks — carry `nonRigid: true` and a `pop` record, and move by open, pop, close (decision 0002, Task 7b): the flap opens rigidly to 30° from flat by default, the tip pops through on the render mesh, and the flap closes rigidly. The isometry gate does not apply to the pop; the bound does: at most 10% largest edge strain on the render mesh. A step with no rigid motion that is not a reverse fold or sink stops compilation and goes to the author.
3131- Layer order is authored, never computed. Corrections to the compiler's guess live in the fold script.
3232- v1 ships **four** traditional models: the cup, the crane, the sampan and the box (the masu). Every `file_author` is exactly `"Traditional"`, enforced by the validator.
3333- Every shipped model is produced by `foldc` from a committed crease pattern and fold script, and recompiling them reproduces the shipped file (structurally, coordinates within 1e-12). Hand-edited `.fold` files are not shipped.
@@ -39,12 +39,13 @@
3939
4040## Review Focus
4141
421. **A step with several simultaneous axes.** A petal fold moves several facet sets about several creases at once on one shared parameter; where faces form closed loops around interior vertices the angles are coupled nonlinearly, and some axes are carried by others. Decision 0001 settled the model; the axis tree, windows and curves are read in Task 3, applied in Task 4 and solved in Task 7. Steps with no rigid path are Task 0b's.
432. **Two facets that are both moving.** The end frame's ordering does not order two simultaneously moving sets against each other during the motion. Such a step must carry `krz:faceOrders_midFold` or be rejected. Test in Task 2. Task 0 also reports whether this rule has a consumer the clusters do not already cover.
421. **A step with several simultaneous axes.** A petal fold moves several facet sets about several creases at once on one shared parameter; where faces form closed loops around interior vertices the angles are coupled nonlinearly, and some axes are carried by others. Decision 0001 settled the model; the axis tree, windows and curves are read in Task 3, applied in Task 4 and solved in Task 7. The petal fold is one of these (decision 0002).
432. **Two facets that are both moving.** The end frame's ordering does not order two simultaneously moving sets against each other during the motion. Such a step must carry `krz:faceOrders_midFold` or be rejected. Test in Task 2. Decision 0001 found no case for this rule that staggered windows and the clusters do not cover; removing it is the author's call.
44443. **Coplanar stacked facets, and orbiting underneath.** The depth buffer cannot order coplanar or nearly coplanar facets, and `faceOrders`'s `s` sign reverses when the view crosses `g`'s plane. Stacked facets must not z-fight at any orbit angle or at the start and end of a fold, and the stack must not invert when you orbit under it. Test in Tasks 5 and 10.
45454. **A degenerate drag direction.** When the moving facet's centroid travels nearly along the view direction the drag projection approaches zero and the fold becomes uncontrollable. Test in Task 12.
46465. **A crease the reader has not met yet.** Because frame 0 carries every crease in the sequence, a crease not yet made must not be drawn, and an occluded crease must not be drawn either. Test in Task 9.
47476. **A crease through several layers.** One crease in the script is several coincident edges, one per layer, possibly with opposite fold-angle signs on a flipped layer. Test in Tasks 4 and 7.
487. **A step with no rigid motion.** An inside reverse fold cannot be made rigidly with the flap closed. It opens, pops and closes, the pop held to 10% strain, the tip landing between the flap's layers. Test in Task 7b.
4849
4950## Synthetic fixtures
5051
@@ -77,6 +78,7 @@ Defect fixtures, each a copy of one above with one change:
7778| `folded-boundary.fold` | `half.fold`, frame 1's e0 at 90 |
7879| `no-instruction.fold` | `half.fold`, step 1 without `instruction` |
7980| `rotate-no-degrees.fold` | `half.fold`, step 3 without `rotateDegrees` |
81| `nonrigid-no-pop.fold` | `half.fold`, step 1 with `nonRigid: true` and no `pop` |
8082| `bad-moving-face.fold` | `half.fold`, step 1's `movingFaces` is `[7]` |
8183| `letter-no-midfold.fold` | `letter.fold` without `krz:faceOrders_midFold` |
8284| `letter-technique.fold` | `letter.fold` with `technique: "insideReverse"` (notation test only) |
@@ -87,6 +89,28 @@ Defect fixtures, each a copy of one above with one change:
8789| `face-inside-fold.fold` | `occlusion.fold`, frame 2 puts the strip f2 between f1 and f0, inside the fold at e8 whose line crosses f2's interior |
8890| `nonconvex.fold` | an L-shaped sheet as one face, no frames |
8991
92### Test helpers
93
94Each task adds the helpers its tests use to `Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift`, and adds `FoldKitTestSupport`'s target dependencies in `Package.swift` as they appear: `FoldFormat` from Task 1, `Folding` from Task 3, `FoldCompiler` from Task 7.
95
96**Units.** Lengths are in the sheet's units. Every length tolerance below 1e-9 is absolute. The isometry tolerances (1e-6) are relative to the sheet's longer side: `sheetSize(file)` times 1e-6.
97
98| Task | Helpers |
99|---|---|
100| 1 | `fixture(_ name: String) -> URL` |
101| 2 | — |
102| 3 | `degreeFourVertex(linear: Bool = false) -> FoldFile`, `degreeFourExactAngle(_ edge: Int, at t: Double) -> Double` |
103| 4 | `interpolator(_ fixture: String, step: Int) throws -> (FoldFile, FoldInterpolator)`, `maxEdgeLengthDrift(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Double` (largest change in a FOLD edge's length against frame 0), `pairwiseDistancesAgree(_ a: [SIMD3<Double>], _ b: [SIMD3<Double>]) -> Bool`, `gridSheet(cells: Int) -> FoldFile`, `sheetSize(_ file: FoldFile) -> Double` |
104| 5 | `interpolatorWithStep(_ fixture: String, step: Int) throws -> (FoldFile, FoldStep, FoldInterpolator)`; `stackedSquarePositions()`, `separatedSquarePositions()`, `threeStackedPositions()` (unit squares at z = 0 and 0, 0 and 1, 0, 0 and 0); `twoSquares()`, `threeSquares()` (their faces) |
105| 6 | `interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator)`, `interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator)` — both built in code as the tests describe |
106| 7 | `compiled(_ name: String) throws -> FoldFile` (compiles `<name>.foldscript` against `<name>-cp.fold`), `structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool`, `degreeFourPattern() -> FoldFile` and `degreeFourScript() -> FoldScript` (the same vertex, edge numbering identical to `degreeFourVertex()`'s) |
107| 7b | `tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool` (the spike's probe at sheet point (2.75, 0.75)), `FoldScript.withOpenAngle(_:step:)`, `FoldScript.withoutSpine(step:)` |
108| 8 | `script(_ name: String) -> URL`, `pattern(_ name: String) -> URL` (`Models/<name>.foldscript`, `Models/<name>-cp.fold`), `runFoldlint(on: URL) throws -> (exitCode: Int32, output: String)` |
109| 9 | `diagram(_ fixture: String, step: Int) throws -> Diagram`, `visibleSegmentsOf(_ fixture: String, edge: Int, inFrame: Int) throws -> [(SIMD2<Double>, SIMD2<Double>)]`, `segmentLength(_:)`, `render(_ diagram: Diagram) -> CGImage`, `expectSnapshot(_ image: CGImage, named: String) throws` |
110| 10 | `renderToPixels(_ scene: Scene, clusters: [CoplanarCluster]? = nil, camera: Camera, faceColours: [SIMD4<Float>]? = nil) throws -> [SIMD4<Float>]`, `renderStackWithComputedClusters(camera:faceColours:)`, the scene builders the tests name (`Scene` is positions, faces, normals and their `RenderMesh`), `uniqueColours`, `dominantColour`, `cameraAbove()`, `cameraBelow()` |
111| 12 | `mapping(_ fixture: String, step: Int) throws -> FoldParameterMapping`, `mappingForFoldTowardTheCamera() throws -> FoldParameterMapping` |
112| 15 | `authoringDoc(_ name: String) -> URL` |
113
90114---
91115
92116### Setup: repository
@@ -95,7 +119,7 @@ Done once, before Task 0.
95119
961201. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`.
971212. Add `.gitignore` (`.build/`, `.swiftpm/`, `App/*.xcodeproj/`, `DerivedData/`, `.DS_Store`) and `LICENSE` (0BSD). Commit them with `docs/`, and push to `main`. `CLAUDE.md` is excluded by the author's global gitignore, as in the other krz repos, and stays local; edits to it are not part of any merge request. This first push is the one direct push to `main`; every later change goes through a merge request.
983. Work is batched into seven merge requests, each with one gitbay issue:
1223. Work is batched into eight merge requests, each with one gitbay issue:
99123
100124 | Batch | Tasks | Branch |
101125 |---|---|---|
@@ -103,7 +127,7 @@ Done once, before Task 0.
103127 | A2 | 0b — non-rigid steps, petal fold, sampan, masu | `spike-non-rigid` |
104128 | B | 1–3 — decoding, validator, steps | `format-and-steps` |
105129 | C | 4–6 — interpolation, layer order, interpenetration | `folding-engine` |
106 | D | 7–8 — `foldc`, `foldlint`, the cup | `compiler-and-cup` |
130 | D | 7, 7b, 8 — `foldc`, non-rigid steps, `foldlint`, the cup | `compiler-and-cup` |
107131 | E | 9–10 — diagram, renderer | `diagram-and-renderer` |
108132 | F | 11–14 — the app | `app` |
109133 | G | 15 — crane, sampan, box | `models` |
@@ -195,23 +219,25 @@ git commit -m "Interpolation model spike and decision record"
195219- In the same merge request, apply the result:
196220 - the design doc's *Interpolation* section;
197221 - Task 1 (the non-rigid step's data) and Task 3;
198 - Task 4 (the non-rigid path and its tests);
222 - Task 4, or a task after `foldc` if the path needs its data (it became Task 7b);
199223 - Task 7 (how `foldc` produces a non-rigid step);
200224 - Task 8 (the bound's test for flagged steps);
201225 - Task 15 (which steps are flagged);
202226 - `CLAUDE.md`.
203227- If a v1 step is neither rigid nor within a bound worth promising: **stop**. The author decides, as after Task 0.
204228
229Applied (decision 0002): the petal fold is rigid; reverse folds and sinks use open, pop, close, which is Task 7b, with the flap opened to 30° from flat by default and a 10% strain bound; the sampan's and the masu's last steps are classified when authored (Task 15).
230
205231This is a measurement, not TDD.
206232
207- [ ] **Step 1: Find the bird base and the sampan's crease patterns, and record their sources**
208- [ ] **Step 2: Add cases 6–9 to the spike**
209- [ ] **Step 3: Run and record**
233- [x] **Step 1: Find the bird base and the sampan's crease patterns, and record their sources**
234- [x] **Step 2: Add cases 6–9 to the spike**
235- [x] **Step 3: Run and record**
210236
211237Run: `swift run -c release --package-path spikes/interpolation`
212238
213- [ ] **Step 4: Write the decision record and apply the exit criteria**
214- [ ] **Step 5: Commit**
239- [x] **Step 4: Write the decision record and apply the exit criteria**
240- [x] **Step 5: Commit**
215241
216242```bash
217243git add spikes docs
@@ -241,7 +267,8 @@ git commit -m "Non-rigid steps: model, bound and the remaining coupled steps"
241267 - `enum TurnOverAxis: String, Codable, Sendable { case vertical, horizontal }`
242268 - `struct AxisRecord: Codable, Equatable, Sendable { let edge: Int; let movingFaces: [Int]; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: [Double]?; let angles: [Double]? }` — `parent` is the index, in the same step's `axes`, of the axis whose motion carries this one; `window` is `[t0, t1]`, default `[0, 1]`; `angles` is a solved curve, the fold angle at 257 evenly spaced points of the window, absent for a linear axis
243269 - `struct Viewpoint: Codable, Equatable, Sendable { let eye: SIMD3<Double>; let up: SIMD3<Double> }` — `eye` is the unit direction toward the viewer
244 - `struct StepRecord: Codable, Equatable, Sendable { let kind: StepKind; let technique: StepTechnique; let instruction: String?; let axes: [AxisRecord]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let viewpoint: Viewpoint }` — `nonRigid` decodes to `false` when absent; Task 0b adds the data a non-rigid step carries
270 - `struct StepRecord: Codable, Equatable, Sendable { let kind: StepKind; let technique: StepTechnique; let instruction: String?; let axes: [AxisRecord]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let pop: PopRecord?; let viewpoint: Viewpoint }` — `nonRigid` decodes to `false` when absent; a non-rigid step's `axes` still list its creases with their start and end angles, for the diagram and the validator, and its motion is `pop`
271 - `struct PopRecord: Codable, Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: [Double]; let openAxes: [AxisRecord]; let popped: [SIMD3<Double>]; let closeAxes: [AxisRecord] }` — decision 0002's open, pop, close: `spine` is the flap's spine edges; `openAngle` the spine's fold angle when open (default 30); `phases` the two boundaries on *t* (default `[1/3, 2/3]`); `openAxes` open the flap on `[0, phases[0]]`; `popped` is every vertex's position after the pop; `closeAxes`, relative to `popped`, close it on `[phases[1], 1]`
245272 - `struct FoldFrame: Codable, Sendable { var verticesCoords: [SIMD3<Double>]; var edgesAssignment: [EdgeAssignment]; var edgesFoldAngle: [Double]; var faceOrders: [[Int]]; var faceOrdersMidFold: [[Int]]?; var step: StepRecord? }`
246273 - `struct FoldFile: Codable, Sendable { var fileSpec: Double; var fileCreator: String?; var fileTitle: String?; var fileAuthor: String?; var fileClasses: [String]; var edgesVertices: [[Int]]; var facesVertices: [[Int]]; var edgesFirstCreasedAtStep: [Int?]; var frames: [FoldFrame] }` — `frames[0]` is the key frame, `frames[n]` is frame n
247274 - `var (FoldFile).stepCount: Int { get }` — `frames.count − 1`
@@ -308,6 +335,14 @@ Package manifest: swift-tools-version 6.2, platforms `.iOS(.v26)`, `.macOS(.v26)
308335 #expect(axis.angles == [0, 90, 180])
309336}
310337
338@Test func decodesAPopRecord() throws {
339 let json = #"{"spine": [0, 1], "openAngle": 30, "phases": [0.3333333333333333, 0.6666666666666666],"# +
340 #" "openAxes": [], "popped": [[0, 0, 0], [1, 0, 0]], "closeAxes": []}"#
341 let pop = try JSONDecoder().decode(PopRecord.self, from: Data(json.utf8))
342 #expect(pop.openAngle == 30)
343 #expect(pop.popped.count == 2)
344}
345
311346@Test func windowsDecodeOnAStaggeredStep() throws {
312347 let step = try FoldFile(contentsOf: fixture("letter-staggered.fold")).frames[1].step
313348 #expect(step?.axes.map(\.window) == [[0, 0.5], [0.5, 1]])
@@ -381,7 +416,7 @@ git commit -m "FOLD decoding with krz extension keys and synthetic fixtures"
381416 - `func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>]`
382417 - `func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(below: Int, above: Int)]` — each triple as "above" along a canonical normal of the two faces' common plane (the one whose first nonzero component is positive)
383418
384This task owns Review Focus item 2. Isometry tolerance is 1e-6 on edge length between consecutive frames. The validator checks shipped models; it is not run on crease patterns.
419This task owns Review Focus item 2. Isometry tolerance is 1e-6 × the sheet's longer side on edge length between consecutive frames. The validator checks shipped models; it is not run on crease patterns.
385420
386421The interpenetration checker (Task 6) finds faces that collide in motion. It cannot find an ordering that is impossible but collision-free — a flap drawn on the wrong side of a stack moves through exactly the same coordinates. The three **layer-order consistency** rules here find those, in every stack of coincident faces of every frame, and they are what catches a wrong guess from `foldc`:
387422
@@ -523,10 +558,11 @@ git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold o
523558- Produces:
524559 - `struct FoldAxis: Equatable, Sendable { let edge: Int; let origin: SIMD3<Double>; let direction: SIMD3<Double>; let movingFaces: Set<Int>; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: ClosedRange<Double>; let curve: [Double]? }`
525560 - `func (FoldAxis).angle(at t: Double, kind: StepKind) -> Double`
526 - `struct FoldStep: Equatable, Sendable { let index: Int; let kind: StepKind; let technique: StepTechnique; let instruction: String; let axes: [FoldAxis]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let viewpoint: Viewpoint }` — `axes` is ordered so every parent comes before its children
561 - `struct FoldStep: Equatable, Sendable { let index: Int; let kind: StepKind; let technique: StepTechnique; let instruction: String; let axes: [FoldAxis]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let pop: Pop?; let viewpoint: Viewpoint }` — `axes` is ordered so every parent comes before its children
562 - `struct Pop: Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: ClosedRange<Double>; let openAxes: [FoldAxis]; let popped: [SIMD3<Double>]; let closeAxes: [FoldAxis] }` — `closeAxes`' origins and directions come from `popped`, not from frame `index − 1`
527563 - `var (FoldStep).movingFaceUnion: Set<Int> { get }`
528564 - `func readSteps(_ file: FoldFile) throws -> [FoldStep]` — `result[k].index == k + 1`
529 - `enum StepError: Error, Equatable, Sendable { case axisNotAnEdge(step: Int, edge: Int); case axisNotOnMovingSetBoundary(step: Int, edge: Int); case movingFacesOutOfRange(step: Int); case overlappingMovingSetsWithinAStep(step: Int); case rotateWithoutDegrees(step: Int); case turnOverWithoutAxis(step: Int); case foldAndUnfoldWithoutPeak(step: Int); case missingInstruction(step: Int); case axisParentCycle(step: Int); case axisWindowOutOfRange(step: Int); case curveTooShort(step: Int) }`
565 - `enum StepError: Error, Equatable, Sendable { case axisNotAnEdge(step: Int, edge: Int); case axisNotOnMovingSetBoundary(step: Int, edge: Int); case movingFacesOutOfRange(step: Int); case overlappingMovingSetsWithinAStep(step: Int); case rotateWithoutDegrees(step: Int); case turnOverWithoutAxis(step: Int); case foldAndUnfoldWithoutPeak(step: Int); case missingInstruction(step: Int); case axisParentCycle(step: Int); case axisWindowOutOfRange(step: Int); case curveTooShort(step: Int); case nonRigidWithoutPop(step: Int); case popPhasesOutOfOrder(step: Int) }`
530566
531567`readSteps` **reads** the authored `krz:step`; it does not infer axes or moving sets from a frame diff. Deriving a multi-axis decomposition has genuine ambiguities — which side moved, whether a reorientation is a fold, how to partition simultaneous axes — and the author already knows the answer. This task and Task 4 own Review Focus item 1, in the form Task 0 settles.
532568
@@ -534,7 +570,7 @@ git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold o
534570
535571For an axis with a parent, `origin` and `direction` are still in frame `index − 1`'s coordinates: Task 4 applies the axis's own rotation first and its ancestors' after, so the parent's motion carries it.
536572
537`degreeFourVertex()` builds decision 0001's case 3 in code, since its curves cannot be typed: a 2×2 sheet with creases from the centre at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), and one `fold` step from flat to flat-folded. The face between the 140° and 260° creases holds still. Its axes are the 140° crease, linear 0 → 180; the 260° crease, a curve; and the 0° crease, carried by the 260° axis, linear 0 → 180. The 60° crease is off the tree. The curve is the closed form for a flat-foldable degree-4 vertex, `ρ = 2·atan(k·tan(90°·u))` with `k = cos 70° / cos 10°`, sampled at 257 points; the 60° crease follows as `−ρ`. Frame 1 is the flat-folded sheet. `degreeFourExactAngle(_:at:)` evaluates the closed form directly.
573`degreeFourVertex(linear:)` builds decision 0001's case 3 in code, since its curves cannot be typed: a 2×2 sheet with creases from the centre at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), and one `fold` step from flat to flat-folded. The face between the 140° and 260° creases holds still. Its axes are the 140° crease, linear 0 → 180; the 260° crease, a curve; and the 0° crease, carried by the 260° axis, linear 0 → 180. The 60° crease is off the tree. The curve is the closed form for a flat-foldable degree-4 vertex, `ρ = 2·atan(k·tan(90°·u))` with `k = cos 70° / cos 10°`, sampled at 257 points; the 60° crease follows as `−ρ`. Frame 1 is the flat-folded sheet. `degreeFourExactAngle(_:at:)` evaluates the closed form directly for any of the four creases. With `linear: true` the curves are replaced by straight lines, for Task 4's control test.
538574
539575- [ ] **Step 1: Write the failing tests**
540576
@@ -607,6 +643,12 @@ func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws {
607643 #expect(abs(axis.angle(at: t, kind: .fold) - degreeFourExactAngle(axis.edge, at: t)) < 1e-6)
608644}
609645
646@Test func aNonRigidStepNeedsItsPop() {
647 #expect(throws: StepError.nonRigidWithoutPop(step: 1)) {
648 try readSteps(FoldFile(contentsOf: fixture("nonrigid-no-pop.fold")))
649 }
650}
651
610652@Test func rotateWithoutDegreesThrows() {
611653 #expect(throws: StepError.rotateWithoutDegrees(step: 3)) {
612654 try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold")))
@@ -647,7 +689,7 @@ git commit -m "Read authored fold steps, including multi-axis and reorientation
647689- Create: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift`
648690- Test: `Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift`
649691
650**Interfaces** (decision 0001; Task 0b adds the path for `nonRigid` steps):
692**Interfaces** (decision 0001; rigid steps only — Task 7b adds the path for `nonRigid` steps, whose data only `foldc` can produce):
651693- Consumes: Task 1 and Task 3 types.
652694- Produces:
653695 - `struct FoldInterpolator: Sendable { init(file: FoldFile, step: FoldStep) }` — interpolates from frame `step.index − 1` to frame `step.index`
@@ -765,7 +807,7 @@ Expected: FAIL.
765807
766808- [ ] **Step 3: Implement `positions(at:)`**
767809
768Each axis's own transform is the rotation about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, built with `simd_quatd(angle:axis:)` about the origin-shifted axis. A moving face's transform is its axis's own transform followed by its parent's full transform, and so on up the tree, so a carried axis moves with its parent. A vertex in no moving set is unchanged. A vertex shared by faces of different sets takes its position from the first face in `faces_vertices` order that contains it. `foldc`'s curves keep the copies within the isometry tolerance, and the catalogue test (Task 8) checks this. Reorientation steps rotate every vertex as described above. `degreeFourVertex(linear:)` gains a `linear` flag that replaces the curves with straight lines, for the control test.
810Each axis's own transform is the rotation about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, built with `simd_quatd(angle:axis:)` about the origin-shifted axis. A moving face's transform is its axis's own transform followed by its parent's full transform, and so on up the tree, so a carried axis moves with its parent. A vertex in no moving set is unchanged. A vertex shared by faces of different sets takes its position from the first face in `faces_vertices` order that contains it. `foldc`'s curves keep the copies within the isometry tolerance, and the catalogue test (Task 8) checks this. Reorientation steps rotate every vertex as described above.
769811
770812- [ ] **Step 4: Run tests to verify they pass**
771813
@@ -929,9 +971,9 @@ git commit -m "Near-coplanar clustering and view-relative layer order"
929971- Consumes: Task 1–5 types.
930972- Produces:
931973 - `struct Intersection: Equatable, Sendable { let faceA: Int; let faceB: Int; let t: Double }`
932 - `func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection]` — one result per intersecting pair, at the first sample `t = k / samples` where they intersect
974 - `func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection]` — one result per intersecting pair, at the first sample `t = k / samples` where they intersect. Task 7b adds an overload on the render mesh for non-rigid steps, whose faces bend
933975
934"No facets pass through each other" is a headline anti-goal, so it gets a mechanical check rather than an eye. Coplanar faces are excluded — overlap there is the layer order's business. Otherwise a pair interpenetrates when their intersection reaches the relative interior of both faces; contact along edges or at vertices, shared or merely coincident, does not count. Pairs that share a vertex or an edge are **not** skipped: a flap that swings through a layer it shares a corner with is the error this exists to catch, and skipping every pair that shares a vertex would miss it. This is the function Task 7 runs per step and Task 8's catalogue gate runs over every model.
976"No facets pass through each other" is a headline anti-goal, so it gets a mechanical check rather than an eye. Coplanar faces are excluded — overlap there is the layer order's business. Coplanar means normals within 1e-6 rad and planes within 1e-6 × the sheet's size, so that faces landing on a stack to within the solver's tolerance count as landed. Otherwise a pair interpenetrates when their intersection reaches the relative interior of both faces; contact along edges or at vertices, shared or merely coincident, does not count. Pairs that share a vertex or an edge are **not** skipped: a flap that swings through a layer it shares a corner with is the error this exists to catch, and skipping every pair that shares a vertex would miss it. This is the function Task 7 runs per rigid step and Task 8's catalogue gate runs over every rigid step; non-rigid steps use Task 7b's mesh version.
935977
936978- [ ] **Step 1: Write the failing tests**
937979
@@ -1020,20 +1062,20 @@ git commit -m "Facet interpenetration checker"
10201062- Produces:
10211063 - `struct FoldScript: Codable, Sendable { let creasePattern: String; let title: String; let steps: [ScriptStep] }` — `creasePattern` is relative to the script
10221064 - `init (FoldScript).init(contentsOf url: URL) throws`
1023 - `struct ScriptStep: Codable, Sendable { let kind: StepKind; let technique: StepTechnique?; let instruction: String; let creases: [CreaseRef]; let movingSide: [SIMD2<Double>]; let angles: [Double]?; let peakAngles: [Double]?; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let viewpoint: Viewpoint?; let faceOrders: [OrderOverride]?; let faceOrdersMidFold: [OrderOverride]?; let driver: CreaseRef?; let windows: [[Double]]? }` — `windows` pairs with `creases`
1065 - `struct ScriptStep: Codable, Sendable { let kind: StepKind; let technique: StepTechnique?; let instruction: String; let creases: [CreaseRef]; let movingSide: [SIMD2<Double>]; let angles: [Double]?; let peakAngles: [Double]?; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let viewpoint: Viewpoint?; let faceOrders: [OrderOverride]?; let faceOrdersMidFold: [OrderOverride]?; let driver: CreaseRef?; let windows: [[Double]]?; let spine: CreaseRef?; let openAngle: Double? }` — `windows` pairs with `creases`; `spine` and `openAngle` are for a reverse fold or sink (Task 7b)
10241066 - `enum CreaseRef: Codable, Sendable { case betweenVertices(SIMD2<Double>, SIMD2<Double>); case edgeIndex(Int) }`
10251067 - `struct OrderOverride: Codable, Sendable { let above: SIMD2<Double>; let below: SIMD2<Double> }` — points in crease-pattern coordinates naming two faces, "above" as seen from the step's viewpoint
10261068 - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile`
10271069 - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]`
10281070 - `func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame, viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]]`
1029 - `enum CompileError: Error, Equatable, Sendable { case unresolvedCrease(step: Int); case unresolvedMovingSide(step: Int); case unresolvedFace(step: Int, point: SIMD2<Double>); case stepFailed(step: Int, defects: [FoldDefect]); case interpenetration(step: Int, [Intersection]); case assignmentDisagreesWithPattern(edge: Int) }`
1071 - `enum CompileError: Error, Equatable, Sendable { case unresolvedCrease(step: Int); case unresolvedMovingSide(step: Int); case unresolvedFace(step: Int, point: SIMD2<Double>); case stepFailed(step: Int, defects: [FoldDefect]); case interpenetration(step: Int, [Intersection]); case assignmentDisagreesWithPattern(edge: Int); case noRigidMotion(step: Int); case curveTooCoarse(step: Int) }`
10301072 - `foldc <script.foldscript> -o <model.fold>` — exits 0 on success, 1 naming the first failing step and its defects
10311073
1032**This task is the reason the project is buildable.** No existing FOLD tool authors a multi-frame sequence with folded coordinates, per-frame layer order and per-step moving sets; hand-writing them is hundreds of exact numbers per frame. `foldc` takes a crease pattern exported from an existing editor plus a short script that names each step's creases (by the points they run between), which side moves (by a point inside it), and the step kind, and **computes** every frame by applying the rotations in order. It guesses `faceOrders`, applies the script's overrides, and runs the Task 2 validator and the Task 6 checker after each step.
1074**This task is the reason the project is buildable.** No existing FOLD tool authors a multi-frame sequence with folded coordinates, per-frame layer order and per-step moving sets; hand-writing them is hundreds of exact numbers per frame. `foldc` takes a crease pattern exported from an existing editor plus a short script that names each step's creases (by the points they run between), which side moves (by a point inside it), and the step kind, and **computes** every frame by applying the rotations in order. It guesses `faceOrders`, applies the script's overrides, and runs the Task 2 validator and the Task 6 checker after each step (Task 7b's mesh checker for a non-rigid step).
10331075
10341076Defaults: `angles` are each crease's end fold angle, ±180 by the pattern's assignment; `viewpoint` is the previous step's, or `[0, 0, 1]` / `[0, 1, 0]` for step 1; `technique` is `plain`; `driver` is the first crease; `windows` are all `[0, 1]`.
10351077
1036**Coupled steps (decision 0001).** The step's creases cut the sheet into regions, each connected across edges this step does not fold. The fixed region is the one no `movingSide` point lies in. A spanning tree of regions, grown from the fixed region across the step's creases, gives each moving region its axis and each axis its parent. A step crease left off that tree closes a loop. If there is none, every axis is linear on its window. If there are some, `foldc` holds the driver linear on its window and solves the other tree axes as the spike does: damped Gauss–Newton on the gap between vertex copies, continued along *t*. It writes each solved axis's curve at 257 points. Each curve is then checked at four times that density, and its samples are doubled until the gap stays under 1e-6 × the sheet's size. A loop that does not close (the solver's gap stays above that) fails the step: the step has no rigid motion and needs `nonRigid` (Task 0b).
1078**Coupled steps (decision 0001).** The step's creases cut the sheet into regions, each connected across edges this step does not fold. The fixed region is the one no `movingSide` point lies in. A spanning tree of regions, grown from the fixed region across the step's creases, gives each moving region its axis and each axis its parent. A step crease left off that tree closes a loop. If there is none, every axis is linear on its window. If there are some, `foldc` holds the driver linear on its window and solves the other tree axes as the spike does: damped Gauss–Newton on the gap between vertex copies, continued along *t*. It writes each solved axis's curve at 257 points. A solved angle that is linear to within 1e-9° is written without a curve. Each curve is checked at four times its sample density; if the gap exceeds 1e-6 × the sheet's size between samples, the step fails with `curveTooCoarse` (257 samples is fixed, and decision 0001 measured it sufficient). Regions are grown in the order the script lists the step's creases, driver first, so which crease closes a loop is determined by the script. A loop that does not close (the solver's gap stays above the tolerance) fails the step with `noRigidMotion`. The step then needs a decision (decision 0002); a solver that does not converge is not proof that no rigid motion exists, so check the script first. Reverse folds and sinks never reach this: they name a `spine` and are compiled by Task 7b. The last sample of every step is set to the end frame exactly.
10371079
10381080Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it.
10391081
@@ -1087,10 +1129,11 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th
10871129 // gets a curve, the 0° crease rides on it, the 60° crease closes the loop
10881130 let out = try compile(degreeFourScript(), pattern: degreeFourPattern())
10891131 let axes = try #require(out.frames[1].step?.axes)
1090 #expect(axes.filter { $0.angles != nil }.count == 1)
1132 #expect(axes.contains { $0.angles != nil })
10911133 #expect(axes.contains { $0.parent != nil })
1092 let curved = axes.first { $0.angles != nil }!
1093 #expect(abs(curved.angles![128] - degreeFourExactAngle(curved.edge, at: 0.5)) < 1e-6)
1134 for axis in axes where axis.angles != nil {
1135 #expect(abs(axis.angles![128] - degreeFourExactAngle(axis.edge, at: 0.5)) < 1e-6)
1136 }
10941137}
10951138
10961139@Test func anUnresolvedCreaseNamesItsStep() {
@@ -1137,6 +1180,147 @@ git commit -m "foldc: compile a fold script and crease pattern into a FOLD seque
11371180
11381181---
11391182
1183### Task 7b: Non-rigid steps — open, pop, close
1184
1185**Files:**
1186- Create: `Packages/FoldKit/Sources/Folding/RenderMesh.swift`
1187- Create: `Packages/FoldKit/Sources/Folding/Bending.swift`
1188- Modify: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift`
1189- Modify: `Packages/FoldKit/Sources/Folding/Interpenetration.swift`
1190- Create: `Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift`
1191- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-cp.fold`, `reverse.foldscript` — decision 0001's case 4 flap: a 4×2 sheet, spine y = 1, reverse-fold creases from (2, 1) to (3, 0) and (3, 2); step 1 folds the flap in half on the spine, step 2 is an inside reverse fold naming the spine y = 1
1192- Modify: `Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift` — `tipIsBetweenBodyLayers(_:_:)` and `FoldScript.withOpenAngle(_:step:)` (see *Test helpers*)
1193- Test: `Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift`
1194
1195**Interfaces:**
1196- Consumes: Tasks 1–7.
1197- Produces:
1198 - `struct RenderMesh: Sendable { init(file: FoldFile, spacing: Double); let vertices: [SIMD2<Double>]; let triangles: [(Int, Int, Int)]; let faceOf: [Int]; let meshVertexOf: [Int] }` — built as the spike builds it: the planar arrangement of frame 0's edges plus lines every `spacing` in x and in y, each resulting convex cell fanned into triangles. `faceOf` maps a triangle to its FOLD face, `meshVertexOf` a FOLD vertex to its mesh vertex. The FOLD topology is unchanged; the mesh is the renderer's
1199 - `static func (RenderMesh).spacing(for file: FoldFile) -> Double` — frame 0's bounding box's longer side / 32
1200 - `let (FoldInterpolator).mesh: RenderMesh` — built at `init` with `RenderMesh.spacing(for:)`; for a non-rigid step the pop's least-squares matrix is factored once, at `init`
1201 - `func (FoldInterpolator).meshPositions(at t: Double) -> [SIMD3<Double>]` — for a rigid step, each face's transform applied to its mesh vertices; for a non-rigid step, the three phases below. On a non-rigid step `positions(at:)` returns the mesh positions of the FOLD vertices
1202 - `func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double` — the largest relative change in a mesh edge's length
1203 - `func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection]` — Task 6's test on mesh triangles, reporting FOLD faces; used for non-rigid steps, whose faces bend
1204 - `func compilePop(step: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, file: FoldFile) throws -> PopRecord`
1205 - `CompileError` gains `popTooStrained(step: Int, strain: Double)` and `missingSpine(step: Int)`
1206
1207Decision 0002: an inside reverse fold has no rigid motion with the flap closed. Flagged steps move in three phases on *t*:
1208
12091. **Open**, `[0, phases[0]]`: the flap opens rigidly on its spine from 180° to `openAngle` (default 30°, measured from flat), carrying everything on that side of the spine.
12102. **Pop**, `[phases[0], phases[1]]`: as-rigid-as-possible interpolation on the render mesh, from the open pose to `popped`. Each triangle's rotation is slerped from one pose to the other, the mesh positions are solved by least squares, and the faces that do not move in the step are held.
12113. **Close**, `[phases[1], 1]`: rigid, on the reverse-fold branch, from `popped` to frame n. `closeAxes` are an ordinary axis tree with solved curves, relative to `popped`.
1212
1213**What makes a step non-rigid is its script, not the solver.** A step with technique `insideReverse`, `outsideReverse` or `sink` must name a `spine`, and `foldc` fails it with `missingSpine` otherwise. Closure cannot decide this: with the flap closed, the solver finds a rigid motion to the reverse fold's coordinates with the tip swung outside (decision 0001, case 4(a)), which is the wrong fold. For a step with a spine, `foldc`:
1214
1215- builds `openAxes` (the spine as one linear axis);
1216- builds `popped` (the reverse-fold branch with the spine held at `openAngle`, solved as in Task 7);
1217- builds `closeAxes` (from `popped` to the end frame, with the spine driven and the rest solved);
1218- measures the pop's strain on the step's render mesh, and fails the step above **10%**.
1219
1220Decision 0002 measured 7.9% at 30° and 29% at 60° on this flap, at a mesh spacing of 1/32 of its longer side. Only the inside reverse fold was measured. Outside reverse folds and sinks use the same model until a model of theirs fails the bound; if one does, stop for a decision.
1221
1222- [ ] **Step 1: Write the failing tests**
1223
1224```swift
1225@Test func aReverseFoldCompilesToANonRigidStep() throws {
1226 let out = try compiled("reverse")
1227 let step = try #require(out.frames[2].step)
1228 #expect(step.nonRigid)
1229 #expect(step.pop?.openAngle == 30)
1230 #expect(step.technique == .insideReverse)
1231}
1232
1233@Test func aReverseFoldWithoutASpineIsRejected() {
1234 #expect(throws: CompileError.missingSpine(step: 2)) {
1235 try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withoutSpine(step: 2),
1236 pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
1237 }
1238}
1239
1240@Test func theOpenAndCloseLegsAreRigid() throws {
1241 // checked on the FOLD edges, as rigid steps are; mesh slivers at creases make relative mesh strain noisy
1242 let file = try compiled("reverse")
1243 let step = try readSteps(file)[1]
1244 let i = FoldInterpolator(file: file, step: step)
1245 for n in 0...256 {
1246 let t = Double(n) / 256
1247 guard t <= step.pop!.phases.lowerBound || t >= step.pop!.phases.upperBound else { continue }
1248 #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)")
1249 }
1250}
1251
1252@Test func thePopStaysWithinTheBound() throws {
1253 let file = try compiled("reverse")
1254 let step = try readSteps(file)[1]
1255 let i = FoldInterpolator(file: file, step: step)
1256 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
1257 let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()!
1258 #expect(worst <= 0.10)
1259}
1260
1261@Test func theStepEndsOnItsEndFrame() throws {
1262 let file = try compiled("reverse")
1263 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
1264 #expect(zip(i.positions(at: 1), file.frames[2].verticesCoords).allSatisfy { simd_distance($0, $1) < 1e-9 })
1265}
1266
1267@Test func nothingPassesThroughAnything() throws {
1268 let file = try compiled("reverse")
1269 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
1270 #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty)
1271}
1272
1273@Test func theTipLandsBetweenTheFlapsLayers() throws {
1274 // 97% of the way through the closing phase, a point of the tip lies between the body's two layers
1275 let file = try compiled("reverse")
1276 let step = try readSteps(file)[1]
1277 let i = FoldInterpolator(file: file, step: step)
1278 let upper = step.pop!.phases.upperBound
1279 #expect(tipIsBetweenBodyLayers(i.positions(at: upper + 0.97 * (1 - upper)), file))
1280}
1281
1282@Test func aFlapOpenedOnlyTo60DegreesIsRejected() {
1283 #expect {
1284 try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withOpenAngle(60, step: 2),
1285 pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
1286 } throws: { if case CompileError.popTooStrained(step: 2, _) = $0 { true } else { false } }
1287}
1288
1289@Test func thePopFitsInAFrameBudget() throws {
1290 let file = try compiled("reverse")
1291 let step = try readSteps(file)[1]
1292 let i = FoldInterpolator(file: file, step: step)
1293 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
1294 let elapsed = ContinuousClock().measure {
1295 for n in 0..<100 { _ = i.meshPositions(at: lo + Double(n) / 100 * (hi - lo)) }
1296 }
1297 #expect(elapsed / 100 < .milliseconds(4))
1298}
1299```
1300
1301- [ ] **Step 2: Run tests to verify they fail**
1302
1303Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests`
1304Expected: FAIL.
1305
1306- [ ] **Step 3: Implement `RenderMesh`, the pop in `FoldInterpolator`, `meshInterpenetrations`, and `compilePop`**
1307
1308`spikes/interpolation/Sources/Spike/Bending.swift` is the reference for the mesh and the pop; `main.swift`'s case 6 is the reference for building the popped pose and the closing branch. A dense Cholesky factor is fine at the spike's size (561 vertices); at a full model's 1/32 mesh use a sparse one, since the frame budget test runs per frame.
1309
1310- [ ] **Step 4: Run tests to verify they pass**
1311
1312Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests`
1313Expected: PASS.
1314
1315- [ ] **Step 5: Commit**
1316
1317```bash
1318git add Packages/FoldKit
1319git commit -m "Non-rigid steps: open, pop, close"
1320```
1321
1322---
1323
11401324### Task 8: `foldlint` and the model catalogue gate
11411325
11421326**Files:**
@@ -1149,7 +1333,7 @@ git commit -m "foldc: compile a fold script and crease pattern into a FOLD seque
11491333- Test: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift`
11501334
11511335**Interfaces:**
1152- Consumes: Task 1–7.
1336- Consumes: Tasks 1–7b.
11531337- Produces:
11541338 - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }`
11551339 - `foldlint <path>...` — exits 0 when clean, 1 with one defect per line
@@ -1185,8 +1369,9 @@ Its crease pattern and `.foldscript` are committed next to the generated `.fold`
11851369}
11861370
11871371@Test func noShippedModelInterpenetratesAtAnyStep() throws {
1372 // non-rigid steps bend their faces; everyFlaggedStepStaysWithinTheBound checks them on the mesh
11881373 for file in try ModelLibrary.all() {
1189 for step in try readSteps(file) {
1374 for step in try readSteps(file) where !step.nonRigid {
11901375 let i = FoldInterpolator(file: file, step: step)
11911376 #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty,
11921377 "\(file.fileTitle ?? "?") step \(step.index)")
@@ -1206,6 +1391,19 @@ Its crease pattern and `.foldscript` are committed next to the generated `.fold`
12061391 }
12071392}
12081393
1394@Test func everyFlaggedStepStaysWithinTheBound() throws {
1395 // decision 0002: 10% largest edge strain on the render mesh, and nothing passes through anything
1396 for file in try ModelLibrary.all() {
1397 for step in try readSteps(file) where step.nonRigid {
1398 let i = FoldInterpolator(file: file, step: step)
1399 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
1400 let worst = (0...128).map { strain(i.meshPositions(at: lo + Double($0) / 128 * (hi - lo)), mesh: i.mesh) }.max()!
1401 #expect(worst <= 0.10, "\(file.fileTitle ?? "?") step \(step.index)")
1402 #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty)
1403 }
1404 }
1405}
1406
12091407@Test func theCatalogueContainsTheCup() throws {
12101408 #expect(try ModelLibrary.names() == ["cup"])
12111409}
@@ -1395,13 +1593,13 @@ git commit -m "Diagram generation with layer-aware edge occlusion"
13951593- Test: `Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift`
13961594
13971595**Interfaces:**
1398- Consumes: Task 1–5.
1596- Consumes: Tasks 1–5 and 7b (`RenderMesh`).
13991597- Produces:
14001598 - `struct Camera: Sendable { var eye: SIMD3<Double>; var target: SIMD3<Double>; var up: SIMD3<Double>; var fieldOfView: Double }` — in `Folding`, not `Renderer`: it is plain `simd`, and Task 12's mapping in `Folding` needs it, while `Renderer` already depends on `Folding`
14011599 - `func (Camera).viewProjection(aspect: Double) -> simd_double4x4` — view and perspective projection combined, to clip space
14021600 - `var (Camera).viewDirection: SIMD3<Double> { get }` — unit vector from `eye` toward `target`
14031601 - `final class PaperRenderer { init(device: MTLDevice) throws }`
1404 - `func (PaperRenderer).render(positions: [SIMD3<Double>], faces: [[Int]], clusters: [CoplanarCluster], camera: Camera, faceColours: [SIMD4<Float>]? = nil, into: MTLTexture) throws` — `faceColours`, when given, draws face *i* in one flat unlit colour on both sides; it exists so tests can tell faces apart
1602 - `func (PaperRenderer).render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera, faceColours: [SIMD4<Float>]? = nil, into: MTLTexture) throws` — draws the render mesh (Task 7b), so a bending face in a non-rigid step draws as it bends; `positions` are mesh positions, clusters are of FOLD faces and each triangle draws with its face. `faceColours`, when given, draws FOLD face *i* in one flat unlit colour on both sides; it exists so tests can tell faces apart
14051603
14061604Depth handling is **hybrid**. `faceOrders` is defined only for faces that overlap geometrically, so it says nothing about the facets separated in space that make up most of a folded model, and depth testing off everywhere would be wrong for them:
14071605
@@ -1415,7 +1613,7 @@ SwiftPM compiles `Shaders.metal` with the Metal toolchain; see *Setup* step 4.
14151613
14161614- [ ] **Step 1: Write the failing tests**
14171615
1418The geometry helpers return positions, faces and normals; `red`, `green` and `blue` are the debug colours of faces 0, 1 and 2. `stackedCoplanarSquares()` is two coincident unit squares facing +z with face 0 above face 1 (`[[0, 1, 1]]`).
1616The geometry helpers return positions, faces, normals and a `RenderMesh` over those faces; `red`, `green` and `blue` are the debug colours of faces 0, 1 and 2. `stackedCoplanarSquares()` is two coincident unit squares facing +z with face 0 above face 1 (`[[0, 1, 1]]`).
14191617
14201618```swift
14211619@Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() {
@@ -1484,7 +1682,7 @@ Expected: FAIL.
14841682
14851683- [ ] **Step 3: Implement `Camera`, `PaperRenderer` and the shaders**
14861684
1487One vertex and one fragment function. Triangulate each face as a fan (faces are convex). Flat shading with one directional term, or the debug colour unlit. Two depth-stencil states — test on with writes off for a cluster's colour pass, test and write on for its depth pass — and a pipeline variant with colour writes masked off for the depth pass.
1685One vertex and one fragment function. Draw the render mesh's triangles, grouped by FOLD face for clusters. Flat shading with one directional term, or the debug colour unlit. Two depth-stencil states — test on with writes off for a cluster's colour pass, test and write on for its depth pass — and a pipeline variant with colour writes masked off for the depth pass.
14881686
14891687- [ ] **Step 4: Run tests to verify they pass**
14901688
@@ -1513,12 +1711,12 @@ git commit -m "Metal paper renderer with hybrid depth and cluster ordering"
15131711- Test: `App/UITests/StepNavigationTests.swift`
15141712
15151713**Interfaces:**
1516- Consumes: `ModelLibrary`, `readSteps`, `FoldInterpolator`, `LayerOrder`, `buildDiagram`, `PaperRenderer`.
1714- Consumes: `ModelLibrary`, `readSteps`, `FoldInterpolator` (with `mesh` and `meshPositions(at:)`), `RenderMesh`, `LayerOrder`, `buildDiagram`, `PaperRenderer`, `Camera`.
15171715- Produces:
15181716 - `struct ModelListView: View`
15191717 - `struct StepView: View` — `init(model: FoldFile, step: Int)`, step counted from 1
15201718 - `struct DiagramCanvas: View` — `init(diagram: Diagram, style: DiagramStyle)`
1521 - `struct PaperView: View` — `init(positions: [SIMD3<Double>], faces: [[Int]], clusters: [CoplanarCluster], camera: Camera)`, an `MTKView` wrapped for SwiftUI
1719 - `struct PaperView: View` — `init(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera)`, an `MTKView` wrapped for SwiftUI; positions come from `FoldInterpolator.meshPositions(at:)` and the mesh from `FoldInterpolator.mesh`
15221720
15231721`project.yml` mirrors `krz/moonrise/App/project.yml`. The `.xcodeproj` is generated and ignored by git, as in moonrise: `xcodegen generate --spec App/project.yml`. On iPad the diagram and the model sit side by side; on iPhone they swap. The diagram's caption is the step's `instruction`.
15241722
@@ -1577,7 +1775,7 @@ git commit -m "App shell, model list and step layout"
15771775- Test: `App/UITests/FoldGestureTests.swift`
15781776
15791777**Interfaces:**
1580- Consumes: Task 3, 4 types; `Camera` (in `Folding`) from Task 10.
1778- Consumes: Task 3, 4 and 7b types; `Camera` (in `Folding`) from Task 10.
15811779- Produces:
15821780 - `struct FoldParameterMapping: Sendable { init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) }`
15831781 - `func (FoldParameterMapping).parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double` — clamped to 0...1
@@ -1586,7 +1784,7 @@ git commit -m "App shell, model list and step layout"
15861784
15871785This task owns Review Focus item 4.
15881786
1589The finger drives the facet, not an abstract slider: the parameter is the point on the centroid's screen path nearest the centroid's position when grabbed plus the drag's translation, searched outward from `current` so the parameter cannot jump to a distant part of the path. A linear mapping onto the chord would leave the facet trailing the finger by up to a fifth of the throw on a 180° fold, because the centroid's screen speed is not constant. When the path is degenerate, fall back to vertical drag over a fixed 160-point throw so sensitivity stays bounded. For `foldAndUnfold`, search the outbound half (`t` 0...0.5) until the parameter reaches 0.5, then the return half (0.5...1).
1787The finger drives the facet, not an abstract slider: the parameter is the point on the centroid's screen path nearest the centroid's position when grabbed plus the drag's translation, searched outward from `current` so the parameter cannot jump to a distant part of the path. A linear mapping onto the chord would leave the facet trailing the finger by up to a fifth of the throw on a 180° fold, because the centroid's screen speed is not constant. When the path is degenerate, fall back to vertical drag over a fixed 160-point throw so sensitivity stays bounded. For `foldAndUnfold`, search the outbound half (`t` 0...0.5) until the parameter reaches 0.5, then the return half (0.5...1). A non-rigid step's path doubles back the same way. It follows the centroid of the faces beyond the reverse creases through open, pop and close, and is searched one phase at a time, in order: the parameter enters a phase only once it has reached the end of the one before.
15901788
15911789- [ ] **Step 1: Write the failing tests**
15921790
@@ -1626,6 +1824,20 @@ The finger drives the facet, not an abstract slider: the parameter is the point
16261824 #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2)
16271825}
16281826
1827@Test func aNonRigidStepIsDraggedPhaseByPhase() throws {
1828 // following the path's own samples in order reaches t = 1 without ever going back
1829 let m = try FoldParameterMapping(file: compiled("reverse"), step: readSteps(compiled("reverse"))[1],
1830 camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
1831 viewportSize: SIMD2(800, 600))
1832 var t = 0.0
1833 for p in m.path.dropFirst() {
1834 let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
1835 #expect(next >= t - 1e-9)
1836 t = next
1837 }
1838 #expect(t > 0.99)
1839}
1840
16291841@Test func foldAndUnfoldGoesOutThenBack() throws {
16301842 let m = try mapping("quarters.fold", step: 1)
16311843 let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0)
@@ -1847,7 +2059,7 @@ Authoring, not engineering: three crease patterns, three scripts, and a correcti
18472059
18482060The crane is deliberately last. It is the model that proves multi-axis petal folds and eight-deep wing stacks work, and by this point the compiler, the renderer and the gestures are all known-good against the cup, so a failure here is an authoring error rather than an ambiguity about which layer is at fault.
18492061
1850Each `docs/authoring/*.md` records the crease pattern's provenance, which guessed layer orders had to be overridden and why, which steps use a coupled-step model from Task 0, and that the model regenerates from its script.
2062Each `docs/authoring/*.md` records the crease pattern's provenance, which guessed layer orders had to be overridden and why, which steps are coupled (solved curves, decision 0001) and which are flagged non-rigid with their `openAngle` and measured pop strain (decision 0002), and that the model regenerates from its script.
18512063
18522064- [ ] **Step 1: Write the failing tests**
18532065
@@ -1876,6 +2088,17 @@ Each `docs/authoring/*.md` records the crease pattern's provenance, which guesse
18762088 }
18772089}
18782090
2091@Test func onlyTheCranesReverseFoldsAreFlagged() throws {
2092 // decision 0002: the neck, tail and head reverse folds; nothing else, unless the
2093 // sampan's or the masu's last step was flagged by a later decision
2094 let crane = try readSteps(ModelLibrary.model(named: "crane"))
2095 #expect(crane.filter(\.nonRigid).count == 3)
2096 #expect(crane.filter(\.nonRigid).allSatisfy { $0.technique == .insideReverse })
2097 for name in ["cup", "box", "sampan"] {
2098 #expect(try readSteps(ModelLibrary.model(named: name)).allSatisfy { !$0.nonRigid }, "\(name)")
2099 }
2100}
2101
18792102@Test func everyModelHasAnAuthoringRecord() throws {
18802103 for name in try ModelLibrary.names() {
18812104 #expect(FileManager.default.fileExists(atPath: authoringDoc(name).path))
@@ -1892,7 +2115,7 @@ Expected: FAIL — only the cup is in the catalogue.
18922115
18932116- [ ] **Step 3: Author the three models**
18942117
1895Box and sampan first, then the crane. Neither is shallow: the masu's wall-raising and the sampan's final turn inside out are coupled 3D steps, classified by Task 0b as rigid or flagged. The crane's inside reverse folds (neck, tail, head) are flagged `nonRigid` and use Task 0b's model; its petal folds use whatever 0b found. Run `foldc`, then `foldlint`, correcting guessed orderings with script overrides where the interpenetration checker or the validator's layer-order rules object. Check each in the app before committing: the checks prove no facet passes through another and no ordering is impossible, but only your eye tells you the fold reads correctly.
2118Box and sampan first, then the crane. Neither is shallow: the masu's wall-raising and the sampan's final turn inside out are coupled 3D steps, classified when authored (decision 0002). The classification uses `foldc`'s closure test, the interpenetration check, the validator's layer rules and a look in the app; closure alone can succeed on a branch with the wrong layering. Classify the crane's preliminary base the same way: fold and unfold its diagonals and midlines, then collapse it as one step from the pre-creased square, rather than through squash folds, which have the reverse fold's structure. A step that closes is rigid. One that does not, and is not a reverse fold or sink, stops compilation with `noRigidMotion`. Then stop and ask the author: open, pop, close needs a spine to open on, and an inversion has none. The crane's petal folds are rigid with solved curves (decision 0002, case 7). Its inside reverse folds (neck, tail, head) name their `spine` and use open, pop, close at the default 30°; if one exceeds the 10% bound, its `openAngle` is lowered in the script and the record says why. The bound was measured on a two-layer flap only; the crane's flaps are narrower and several layers deep, so record each flagged step's measured strain, and if opening a flap to its `openAngle` disturbs earlier layers or no `openAngle` meets the bound, stop for a decision. The bird base's crease pattern is the one decision 0002 read from Origami Simulator's flat crane; record that provenance in `docs/authoring/crane.md`. Run `foldc`, then `foldlint`, correcting guessed orderings with script overrides where the interpenetration checker or the validator's layer-order rules object. Check each in the app before committing: the checks prove no facet passes through another and no ordering is impossible, but only your eye tells you the fold reads correctly.
18962119
18972120- [ ] **Step 4: Run tests to verify they pass**
18982121
docs/superpowers/specs/2026-10-19-fold-design.md +52 −25
@@ -225,6 +225,7 @@ Each frame's `krz:step` carries it explicitly:
225225 "turnOverAxis": "vertical" | "horizontal",
226226 "repeatOf": 4,
227227 "nonRigid": false,
228 "pop": null,
228229 "viewpoint": { "eye": [0, 0, 1], "up": [0, 1, 0] } }
229230```
230231
@@ -233,8 +234,10 @@ Each frame's `krz:step` carries it explicitly:
233234 `parent` is the index of the axis whose motion carries this one,
234235 `window` its span of *t*, and `angles` a solved curve (see
235236 *Interpolation*); `foldc` writes all three.
236- `nonRigid`: the step has no rigid motion and moves by the non-rigid model
237 (see *Interpolation*). Reverse folds, sinks and inversions.
237- `nonRigid` and `pop`: the step has no rigid motion and opens, pops and
238 closes (see *Interpolation*). Reverse folds and sinks. `pop` holds the
239 flap's spine, the angle it opens to, the two phase boundaries on *t*, the
240 opening axes, the popped pose and the closing axes; `foldc` writes it.
238241- `technique`: drives the notation and the instruction's wording; geometry
239242 ignores it. `plain` for anything that is not a named technique.
240243- `instruction`: the step in words, written by the author in the fold
@@ -312,14 +315,36 @@ parameter *t* in 0...1, and carries its children with it:
312315- `turnOver` and `rotate` rotate every vertex about the start frame's
313316 bounding-box centre by *t* times the step's angle.
314317
315**Non-rigid steps.** An inside reverse fold has no rigid motion with the flap
316closed. The only rigid path unfolds the flap flat and refolds it, which on
317the crane would undo earlier steps on screen. Reverse folds, sinks and
318inversions are therefore flagged `nonRigid`. They move by a designed
319non-rigid motion, chosen by Task 0b, and are held to a strain bound that
3200b sets instead of the isometry gate. The interpenetration check still
321applies to them. Task 0b also settles the petal fold, the sampan's
322inversion and the masu's wall-raising.
318**Non-rigid steps** (`docs/decisions/0002-non-rigid-steps.md`). An inside
319reverse fold has no rigid motion with the flap closed; the only rigid path
320unfolds the flap flat and refolds it, which on the crane would undo earlier
321steps on screen. Reverse folds and sinks are flagged `nonRigid` and move in
322three phases on *t*:
323
3241. **Open**, rigid: the flap opens on its spine to 30° from flat (authored
325 per step).
3262. **Pop**: the tip passes from outside the flap to inside it, by
327 as-rigid-as-possible interpolation on a render mesh: frame 0's creases
328 plus lines every 1/32 of its longer side in each direction. The render
329 mesh is the renderer's; the FOLD topology is unchanged.
3303. **Close**, rigid: the flap closes on the reverse-fold branch, with solved
331 curves, and the tip lands between its layers.
332
333The isometry gate does not apply to the pop. The **bound** does: no
334render-mesh edge changes length by more than 10%. On a two-layer flap the
335pop measured 7.9% opened to 30° and 29% opened to 60°. That is one flap at
336one resolution; the crane's flaps are narrower and several layers deep, so
337each flagged step's strain is measured when it is authored. The
338interpenetration check applies to all three phases. A step is non-rigid
339because its script says so — a reverse fold or sink names the spine its
340flap opens on — not because a solver failed: with the flap closed the
341solver finds a rigid motion to the right coordinates with the wrong
342layering. The petal fold is rigid (it has solved curves) and is not
343flagged. The sampan's inversion and the masu's wall-raising are classified
344when they are authored, by `foldc`'s closure test together with the
345interpenetration check, the layer rules and a look in the app. If either
346has no rigid motion it needs a decision, since open, pop, close needs a
347spine to open on.
323348
324349### Layer ordering during a fold
325350
@@ -351,12 +376,12 @@ Two rules make this safe rather than merely convenient:
351376 every pair **not involving a moving facet**. A step where this
352377 simplification would be visible in the still part of the model fails
353378 authoring.
3542. When a step's moving sets overlap in projection — the petal and reverse
355 fold case — the end frame's ordering does not determine their order
356 relative to each other, because both are moving. Such a step **must**
3792. When a step's moving sets overlap in projection, such a step **must**
357380 carry `krz:faceOrders_midFold`, and the validator rejects it if it does
358 not. Without this rule two flaps pass through each other on the models
359 v1 requires.
381 not. Decision 0001 found that the problem this was meant to prevent, two
382 flaps passing through each other, is a collision. Ordering cannot fix a
383 collision; staggered windows on *t* do. It found no case left for the
384 rule, and removing it is an open decision.
360385
361386When a traditional model has a step that cannot satisfy these, the fix is
362387to split the step into sub-steps until it can. Dropping the model is the
@@ -364,8 +389,9 @@ last resort and needs a decision, not a shrug.
364389
365390### Rendering
366391
367Metal, with a small renderer written for this: the geometry is tens of
368triangles and a few hundred vertices, and both SceneKit (deprecated) and
392Metal, with a small renderer written for this: the geometry is a render
393mesh of a few thousand triangles (see *Non-rigid steps*), and both SceneKit
394(deprecated) and
369395RealityKit (whose dynamic-mesh support is more than this needs) would
370396contribute more risk than they remove.
371397
@@ -578,8 +604,9 @@ The headline bars get mechanical checks rather than judgement:
578604- **No impossible layering.** The validator checks every frame's orders
579605 against the crease, nesting and inside rules (*Layer ordering during a
580606 fold*).
581- **No stretching.** The catalogue test samples every step of every model
582 and checks every edge length against frame 0.
607- **No stretching.** The catalogue test samples every rigid step of every
608 model and checks every edge length against frame 0. Flagged steps are
609 held to the 10% bound on the render mesh instead.
583610- **Correct notation.** The diagram generator is covered by golden-image
584611 snapshot tests. The reference is Randlett's own conventions as set out in
585612 *The Art of Origami* (1961) and the symbol set as summarised by
@@ -591,13 +618,13 @@ The headline bars get mechanical checks rather than judgement:
5916181. **Name.** "Fold" is not going to be available. The repo and bundle ID
592619 use `fold` / `sh.krz.fold` as working names.
5936202. **Authoring tooling, and how many models.** Settled: build the
594 compiler, cup first, four models for v1. The plan is 17 tasks: two
595 interpolation spikes (Tasks 0 and 0b), the engine, the compiler, the app and the
621 compiler, cup first, four models for v1. The plan is 18 tasks: two
622 interpolation spikes (Tasks 0 and 0b), the engine, non-rigid steps (7b), the compiler, the app and the
596623 cup, then the crane, sampan and box as one gated authoring task.
5973. **The interpolation model for coupled steps.** Settled (decision 0001,
598 option A): an axis tree with windows and solved curves for rigid steps,
599 flagged non-rigid steps for reverse folds, sinks and inversions. The
600 non-rigid model and its strain bound are Task 0b's.
6243. **The interpolation model for coupled steps.** Settled (decisions 0001
625 and 0002): an axis tree with windows and solved curves for rigid steps,
626 including the petal fold; open, pop, close for reverse folds and sinks,
627 opened to 30° by default, held to 10% strain.
6016284. **Which boat.** Settled: the sampan (see *Rights*).
6026295. **The overlapping-moving-sets rule.** Decision 0001 found no case it
603630 covers that staggered windows and the near-coplanar clusters do not.