# Fold Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **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. **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. **Tech Stack:** Swift 6, iOS 26, SwiftUI, Metal, `simd`, Swift Testing, XcodeGen. No third-party runtime dependencies in the app. **Spec:** `docs/superpowers/specs/2026-10-19-fold-design.md` ## Global Constraints - iOS 26 deployment target; Swift 6 language mode. - `TARGETED_DEVICE_FAMILY = "1,2"`; `PRODUCT_BUNDLE_IDENTIFIER = sh.krz.fold`; `DEVELOPMENT_TEAM = ZCNAX3VL9D`; `bundleIdPrefix: sh.krz`. - `FoldKit` targets must not import UIKit or SwiftUI. `Renderer` may import Metal and MetalKit. `foldc` and `foldlint` are macOS executables and never ship in the app. - Models are FOLD 1.2 files (Demaine, Ku and Lang, 2016; `github.com/edemaine/fold`). Standard keys used: `vertices_coords`, `edges_vertices`, `edges_assignment`, `edges_foldAngle`, `faces_vertices`, `faceOrders`, `file_frames`, `frame_parent`, `frame_inherit`, `file_spec`, `file_creator`, `file_classes`, `file_title`, `file_author`. - `edges_assignment` codes: `B` boundary, `M` mountain, `V` valley, `F` flat, `U` unassigned. `C` and `J` are rejected. - `edges_foldAngle` is degrees in −180...180, positive for valley, negative for mountain, 0 for `F`, `U` and `B`. - `faceOrders` triples are `[f, g, s]`; `s = +1` means `f` is above `g` **on the side `g`'s normal points toward**, so the sign is evaluated against the current view direction, not absolutely, and two triples can only be compared after normalising each by its `g`'s folded-state normal. Cycles (after normalising) are rejected. - Faces are convex. FOLD's alternative, splitting faces with `J` edges, is not supported. A crease that ends inside the sheet (a pinch or partial crease) leaves a nonconvex face around its end; split that face with a **subdivision edge** — assigned `F`, flat in every frame, creased by no step, `edges_krz:firstCreasedAtStep` null, never drawn. A step creases an edge when its two faces move differently in that step: each face belongs to the deepest axis whose moving set contains it, or to the fixed group, and the edge is creased when the groups differ. So every edge a fold-and-unfold crosses is creased, not only its axis edge, and needs `edges_krz:firstCreasedAtStep`. - Extension keys: `edges_krz:firstCreasedAtStep` (key frame, inherited), `krz:step` (frames 1…N), `krz:faceOrders_midFold` (frames 1…N). - **Step numbering.** Frame 0 is the key frame (the unfolded sheet); `file_frames[i]` is frame `i + 1`. Step n, counting from 1, takes frame n − 1 to frame n and is recorded in frame n's `krz:step`. Every index called a step — in the format, the validator's defects, `FoldStep.index`, the UI — is this n. Defects about one frame's state say `frame:`; defects about a transition or a step record say `step:`; frame n and step n share the number. - Every frame in `file_frames` carries `frame_parent: 0` and `frame_inherit: true`, and never overrides `edges_vertices` or `faces_vertices`. - **One topology across every frame.** Enforced by the decoder and the validator. - **Steps are authored, never derived from a frame diff.** That includes `instruction`, which is the accessibility label. - **`turnOver` and `rotate` change the coordinates.** Frame n is frame n − 1 rotated about its bounding-box centre; the camera does not move. - Paper is rigid flat facets hinged at straight creases, except during a step flagged `nonRigid`. No stiffness, self-collision response or crumpling. - **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 20° from flat by default (decision 0003; 30° before it), 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. - Layer order is authored, never computed. Corrections to the compiler's guess live in the fold script. - 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. - 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. - The **cup is compiled first**, the crane last. Before the cup exists, tests use the synthetic fixtures below; model-level assertions live in Tasks 8 and 15. - The app never advances the fold parameter on its own. - No network calls. No analytics. No accounts. - Ships on the App Store: privacy manifest, screenshots, and every screen passing Xcode's accessibility audit at the default and largest text size. - Work lands through gitbay merge requests, one per batch of tasks; see *Setup*. ## Review Focus 1. **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). 2. **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. 3. **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. 4. **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. 5. **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. 6. **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. 7. **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. ## Synthetic fixtures The engine is tested before the compiler exists, so its fixtures are small sheets whose folded coordinates are integers or halves and can be typed exactly. They live in `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/`, alongside the `fixture(_:)` helper, in a target that only test targets depend on. Task 7 compiles a script for each of the model fixtures and checks the output matches the hand-written file, which pins the compiler's conventions to them. Every fixture except where noted has `file_author: "Traditional"`, an `instruction` on every step, and the default viewpoint `eye [0, 0, 1]`, `up [0, 1, 0]`. Vertex, edge and face numbering below is the numbering in the file. | Fixture | Sheet and creases | Steps | |---|---|---| | `square.fold` | unit square; v0–v3 with 2-element coords; edges e0–e3 all `B`; one face; no frames; no `faceOrders` key; `edges_krz:firstCreasedAtStep` four nulls | none | | `half.fold` | 2×2; v0 (0,0), v1 (1,0), v2 (2,0), v3 (2,2), v4 (1,2), v5 (0,2); e0–e5 the boundary in that order, e6 = v1–v4; f0 = [v0,v1,v4,v5], f1 = [v1,v2,v3,v4] | 1: valley fold f1 over f0 about e6, 0 → 180. 2: `turnOver`, vertical. 3: `rotate` 90 | | `mountain.fold` | as `half.fold` | 1: mountain fold f1 behind f0 about e6, 0 → −180 | | `letter.fold` | 3×3; v0 (0,0), v1 (1,0), v2 (2,0), v3 (3,0), v4 (3,3), v5 (2,3), v6 (1,3), v7 (0,3); e0–e7 the boundary, e8 = v1–v6 (x = 1, valley), e9 = v2–v5 (x = 2, mountain); f0 = [v0,v1,v6,v7], f1 = [v1,v2,v5,v6], f2 = [v2,v3,v4,v5] | 1: one step, two axes: f0 valley folds in front of f1, f2 mountain folds behind it. The sets overlap in projection on opposite sides of f1, so frame 1 carries `krz:faceOrders_midFold` | | `letter-sequential.fold` | as `letter.fold`, both creases valley | 1: f0 over f1. 2: f2 over both, `repeatOf: 1` | | `letter-staggered.fold` | as `letter.fold`, both creases valley | 1: one step, two axes: f0 over f1 on window 0…0.5, then f2 over both on 0.5…1. The sets overlap in projection, so frame 1 carries `krz:faceOrders_midFold`, equal to its `faceOrders`. Frame 1 is `letter-sequential.fold`'s frame 2 | | `quarters.fold` | 2×2; v0 (0,0), v1 (1,0), v2 (2,0), v3 (2,1), v4 (2,2), v5 (1,2), v6 (0,2), v7 (0,1), v8 (1,1); e0–e7 the boundary, e8 = v1–v8, e9 = v8–v5 (x = 1), e10 = v7–v8, e11 = v8–v3 (y = 1); f0 = [v0,v1,v8,v7], f1 = [v1,v2,v3,v8], f2 = [v8,v3,v4,v5], f3 = [v7,v8,v5,v6] | 1: `foldAndUnfold` on e8, moving f1 and f2, peak 180; frame 1 carries `krz:faceOrders_midFold` with the order at the peak (f1 on f0, f2 on f3). 2: valley fold the top half (f2, f3) down about e10. 3: valley fold the right half of both layers (f1, f2) over about e8 — e8 and e9 are now coincident; e9 is on the flipped layer and ends at −180, `M` | | `occlusion.fold` | 4×4; v0 (0,0), v1 (2,0), v2 (2.5,0), v3 (4,0), v4 (4,4), v5 (2.5,4), v6 (0,4), v7 (0,2); e0–e7 the boundary, e8 = v7–v1 (diagonal), e9 = v2–v5; f0 = [v0,v1,v7], f1 = [v1,v2,v5,v6,v7], f2 = [v2,v3,v4,v5] | 1: valley fold the corner f0 up about e8 (v0 lands on (2,2)). 2: valley fold the strip f2 over about e9 (it lands on x ∈ [1, 2.5], covering part of f0). 3: `turnOver`, vertical, so that step 3's diagram draws frame 2 | Defect fixtures, each a copy of one above with one change: | Fixture | Change | |---|---| | `bad-index.fold` | `square.fold`, e0 references vertex 9 | | `designed-model.fold` | `square.fold`, `file_author: "A. Designer"` | | `topology-in-frame.fold` | `half.fold`, frame 1 carries `edges_vertices` | | `retopologised.fold` | `half.fold`, frame 2 has a seventh vertex | | `stretched-step.fold` | `half.fold`, frame 1's v2 moved to (0.01, 0, 0) | | `angle-200.fold` | `half.fold`, frame 1's e6 at 200 | | `angle-sign.fold` | `half.fold`, frame 1's e6 assigned `V` at −180 | | `folded-boundary.fold` | `half.fold`, frame 1's e0 at 90 | | `no-instruction.fold` | `half.fold`, step 1 without `instruction` | | `rotate-no-degrees.fold` | `half.fold`, step 3 without `rotateDegrees` | | `nonrigid-no-pop.fold` | `half.fold`, step 1 with `nonRigid: true` and no `pop` | | `bad-moving-face.fold` | `half.fold`, step 1's `movingFaces` is `[7]` | | `letter-no-midfold.fold` | `letter.fold` without `krz:faceOrders_midFold` | | `letter-technique.fold` | `letter.fold` with `technique: "insideReverse"` (notation test only) | | `still-face-reorder.fold` | `letter-sequential.fold`, frame 2 reverses the f0–f1 order (both still in step 2) | | `cyclic-order.fold` | `letter-sequential.fold`, frame 2's orders form a cycle over f0, f1, f2 **after normalising** for their normals (f0 and f2 face −z, f1 faces +z in frame 2; `[0,1,1],[1,2,1],[2,0,1]` is not a cycle there) | | `order-against-crease.fold` | `half.fold`, frame 1 puts f0 above f1, which the valley at e6 makes impossible | | `interleaved-folds.fold` | `quarters.fold`, frame 3 swaps f1 and f2, so the folds at e8 (f0, f1) and e9 (f3, f2), coincident on x = 1, interleave instead of nesting | | `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 | | `nonconvex.fold` | an L-shaped sheet as one face, no frames | ### Test helpers Each 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. **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. | Task | Helpers | |---|---| | 1 | `fixture(_ name: String) -> URL` | | 2 | — | | 3 | `degreeFourVertex(linear: Bool = false) -> FoldFile`, `degreeFourExactAngle(_ edge: Int, at t: Double) -> Double` | | 4 | `interpolator(_ fixture: String, step: Int) throws -> (FoldFile, FoldInterpolator)`, `maxEdgeLengthDrift(_ positions: [SIMD3], _ file: FoldFile) -> Double` (largest change in a FOLD edge's length against frame 0), `pairwiseDistancesAgree(_ a: [SIMD3], _ b: [SIMD3]) -> Bool`, `gridSheet(cells: Int) -> FoldFile`, `sheetSize(_ file: FoldFile) -> Double` | | 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) | | 6 | `interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator)`, `interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator)` — both built in code as the tests describe | | 7 | `compiled(_ name: String) throws -> FoldFile` (compiles `.foldscript` against `-cp.fold`), `structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool`, `degreeFourPattern() -> FoldFile` and `degreeFourScript() -> FoldScript` (the same vertex, edge numbering identical to `degreeFourVertex()`'s) | | 7b | `tipIsBetweenBodyLayers(_ positions: [SIMD3], _ file: FoldFile) -> Bool` (the spike's probe at sheet point (2.75, 0.75)), `FoldScript.withOpenAngle(_:step:)`, `FoldScript.withoutSpine(step:)` | | 8 | `script(_ name: String) -> URL`, `pattern(_ name: String) -> URL` (`Models/.foldscript`, `Models/-cp.fold`), `runFoldlint(on: URL) throws -> (exitCode: Int32, output: String)` | | 9 | `diagram(_ fixture: String, step: Int) throws -> Diagram`, `visibleSegmentsOf(_ fixture: String, edge: Int, inFrame: Int) throws -> [(SIMD2, SIMD2)]`, `segmentLength(_:)`, `render(_ diagram: Diagram) -> CGImage`, `expectSnapshot(_ image: CGImage, named: String) throws` | | 10 | `renderToPixels(_ scene: Scene, clusters: [CoplanarCluster]? = nil, camera: Camera, faceColours: [SIMD4]? = nil) throws -> [SIMD4]`, `renderStackWithComputedClusters(camera:faceColours:)`, the scene builders the tests name (`Scene` is positions, faces, normals and their `RenderMesh`), `uniqueColours`, `dominantColour`, `cameraAbove()`, `cameraBelow()` | | 12 | `mapping(_ fixture: String, step: Int) throws -> FoldParameterMapping`, `mappingForFoldTowardTheCamera() throws -> FoldParameterMapping` | | 15 | `authoringDoc(_ name: String) -> URL` | --- ### Setup: repository Done once, before Task 0. 1. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`. 2. 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. 3. Work is batched into ten merge requests, each with one gitbay issue: | Batch | Tasks | Branch | |---|---|---| | A | 0 — interpolation spike | `spike-interpolation` | | A2 | 0b — non-rigid steps, petal fold, sampan, masu | `spike-non-rigid` | | B | 1–3 — decoding, validator, steps | `format-and-steps` | | C | 4–6 — interpolation, layer order, interpenetration | `folding-engine` | | D | 7, 7b, 8 — `foldc`, non-rigid steps, `foldlint`, the cup | `compiler-and-cup` | | E | 9–10 — diagram, renderer | `diagram-and-renderer` | | F | 11–14 — the app | `app` | | F2 | 14b — step list, dragging back | `step-access` | | G | 15, first part — the box | `models` | | G2 | 15, second part — the crane and the sampan, after decision 0003 | `crane` | Batches A and A2 merge alone, since Tasks 0 and 0b can stop the plan. Each batch commits task by task on its branch, ends with `gitbay mr create --source --target main`, merges when `swift test --package-path Packages/FoldKit` (and, from batch F, the `xcodebuild` test) is green, and the branch is then deleted locally and remotely. Commit messages end with `Ref #N` for the batch's issue; the batch's last commit uses `Closes #N`. 4. If `xcrun metal --version` fails, run `xcodebuild -downloadComponent MetalToolchain`. SwiftPM invokes `metal` for the `.metal` file in Task 10; on 2026-10-19 this machine had no Metal toolchain. --- ### Task 0: Interpolation model spike **Files:** - Create: `spikes/interpolation/Package.swift` — a macOS executable using `simd` only; not part of FoldKit and never linked into anything - Create: `spikes/interpolation/Sources/Spike/main.swift` and whatever else it needs - Create: `docs/decisions/0001-interpolation-model.md` - Modify at the end: the design doc's *Interpolation* section, this plan's Tasks 1, 3, 4 and 7 and Review Focus item 1, and `CLAUDE.md` **Why first.** The design's interpolation — each axis rotates a disjoint moving set about its crease line in the start frame by a linearly interpolated angle — is exact for independent flaps. It is not exact for steps whose faces form closed loops around interior vertices: squash, petal and reverse folds, and the masu's wall-raising step. There the fold angles at a vertex are coupled nonlinearly (at a flat-foldable degree-4 vertex, tan(ρ₁/2) = k·tan(ρ₂/2)), some axes are carried by other moving faces, and vertices shared between moving sets off any axis tear apart partway through the fold even though both end frames are exact. Task 1's `AxisRecord`, Task 3's `FoldAxis`, Task 4's interpolator and Task 7's compiler all encode the answer, so it is measured before any of them exists. The isometry sweep in Task 4 would otherwise only find this in Task 15, on the crane, after everything else is built. **Cases**, each built in code with exact coordinates: 1. **Letter fold, both flaps valley.** 3×3 sheet, creases x = 1 and x = 2, both outer thirds folded in front in one step. Under a linear shared parameter, two flaps of equal reach folding toward each other meet at the midline from about 120° on and pass through each other. Draw order cannot fix a collision; this is the control for per-axis scheduling. 2. **Letter fold, one valley, one mountain** (`letter.fold`'s geometry). The control for the case the current model handles: expected exact and clean. 3. **Generic flat-foldable degree-4 vertex**, sector angles 60°, 80°, 120°, 100° in order, folded from flat to flat-folded in one step. Expected: independent linear angles drift; angles solved for loop closure are exact. 4. **Inside reverse fold of a two-layer flap.** A 4×2 rectangle folded in half along y = 1 (the spine), with reverse-fold creases from (2, 1) to (3, 0) and from (2, 1) to (3, 2), the part left of them held still. Question: does any rigid motion take the tip inside the flap with the left part fixed? Hypothesis: none does. With the spine held at 180° the two layers' creases coincide, and the only rigid motion of the tip is to swing about that line as one closed unit, outside the flap. That ends at the same coordinates as the reverse fold, with the wrong layer order. Getting the tip inside requires the flap's layers to open — the "still" part moves. Measure the smallest spine opening for which a rigid path exists, and the peak strain of a non-rigid path if the spine may not open. 5. **Petal fold** of the front flap of a preliminary base, built in code by applying the base's folds to a unit square. Measure the drift of independent linear angles, whether solved angles close every loop, and whether the side flaps' axes are carried by the lifted flap. **Candidate models:** - **M1** — the current design: disjoint moving sets, each rotated about its axis in the start frame by a linear angle (a tent for `foldAndUnfold`). - **M2** — a kinematic tree with solved angle curves: an axis may name a parent axis whose motion carries it; each axis's angle is a monotone function of *t*, with its own start and end window on *t* so axes can be staggered; `foldc` solves the curves so every loop of faces around an interior vertex closes, and stores them sampled. - **M3** — decomposition: the script splits the step into sub-steps, each M1 or M2, driven by one continuous drag. - **M4** — non-rigid: per-face rigid transforms at solved sub-keyframes, interpolated between them; isometry is exact only at the sub-keyframes. **Measure**, for every case under every model that applies: the maximum edge-length drift over 1,001 samples of *t*; for M2, the maximum loop-closure residual; the minimum distance between faces that share no edge (negative means they intersect); and for case 4, the answer to the rigid-path question. **Also record:** - For each v1 model, every step that is not a single independent fold — the crane's preliminary-base collapse or squash folds, its petal folds and its inside reverse folds (neck, tail, head); the masu's wall-raising; the sampan's final turn inside out; the cup has none — with the case above that stands in for it and the model that covers it. - Whether the overlapping-moving-sets rule for `krz:faceOrders_midFold` covers anything the end frame's ordering and the near-coplanar clusters (design, *Rendering*) do not. Case 1 suggests the problem with overlapping moving sets is that they collide, which ordering cannot fix. The key's other use, the peak order of a `foldAndUnfold`, is not in question. If the rule has no remaining consumer, recommend removing it, with the evidence; that changes a settled decision and goes to the author. **Exit criteria:** - `docs/decisions/0001-interpolation-model.md` holds the measurements, the model chosen and why. - If every v1 step is covered by a rigid model (M1, M2 or M3): in the same merge request, rewrite the design doc's *Interpolation* section; amend Task 1's `AxisRecord` and tests, Task 3's `FoldAxis`, Task 4's interface and tests (add cases 3–5 to the isometry sweep as fixtures), Task 7's script fields and outputs, and Review Focus item 1; and add the result to `CLAUDE.md`'s *Settled* list. - If some v1 step is covered only by M4, or by nothing: **stop**. Splitting the step, dropping it, shipping a different model and relaxing `CLAUDE.md`'s isometry rule for that step are the author's choices. Do not start Task 1. This is a measurement, not TDD. - [x] **Step 1: Build the spike package and the five cases** - [x] **Step 2: Implement M1 and M2, and M3 and M4 as far as case 4 needs them** - [x] **Step 3: Run and record** Run: `swift run --package-path spikes/interpolation` - [x] **Step 4: Write the decision record and apply the exit criteria** - [x] **Step 5: Commit** ```bash git add spikes docs git commit -m "Interpolation model spike and decision record" ``` --- ### Task 0b: Non-rigid steps and the remaining coupled steps **Files:** - Modify: `spikes/interpolation` — cases 6–9 - Create: `docs/decisions/0002-non-rigid-steps.md` - Modify at the end: the design doc's *Interpolation* section, this plan's Tasks 1, 3, 4, 7, 8 and 15, and `CLAUDE.md` **Why.** Decision 0001 found no rigid motion that makes an inside reverse fold with the flap closed, and chose option A: such steps are flagged `nonRigid` and move by a designed non-rigid motion held to a stated strain bound. This task chooses that motion and the bound, and measures the coupled steps 0001 left open. Task 1 encodes the result, so it comes first. **Cases**, continuing 0001's numbering: 6. **Reverse fold with bending**, on case 4's flap. Candidates: - **virtual creases** — extra edges in the flap's layers near the vertex (a fan from it), never drawn, flat in every frame and free to fold during the step. If some number of them gives a rigid path that keeps the flap mostly closed, the step is rigid on a finer mesh: zero gap, and the bend shows as their largest angle. They are subdivision edges in the format, which already allows them. - **pose interpolation** — per-face transforms through solved intermediate poses (the flap opened to φ, the tip swung through), interpolated between them; strain is the gap. Measure for each: the largest gap, the largest opening of the flap, the largest virtual-crease angle, and collisions, across φ and the number of virtual creases. 0001 measured naive schedules at 0.24–1.6 of the flap's height; the question is how far a designed motion gets below that. 7. **Petal fold, verified.** A bird-base crease pattern with its mountain–valley assignment from a citable source — Lang, *Origami Design Secrets*, or the base folded in Oriedita and exported — recorded with its source. Check it is flat-foldable at every vertex (Kawasaki, and Maekawa against the assignment). Then measure the petal fold as 0001's case 5 did, and check that the inner layers' corners stay down. 8. **Sampan, turning inside out.** The crease pattern of the sequence Task 15 will author, with its source. Does any rigid path exist? Rigid (M2), or flagged. 9. **Masu, raising the walls.** The traditional masu's crease pattern, walls ending at 90°. Does M2 find a rigid path? Rigid, or flagged. **Exit criteria:** - `docs/decisions/0002-non-rigid-steps.md` holds: the non-rigid model and the data it adds to `krz:step`; the strain metric and the bound the app promises; and, for every v1 step that is not a single independent fold, whether it is rigid (M2) or flagged, with the case that stands in for it. - In the same merge request, apply the result: - the design doc's *Interpolation* section; - Task 1 (the non-rigid step's data) and Task 3; - Task 4, or a task after `foldc` if the path needs its data (it became Task 7b); - Task 7 (how `foldc` produces a non-rigid step); - Task 8 (the bound's test for flagged steps); - Task 15 (which steps are flagged); - `CLAUDE.md`. - If a v1 step is neither rigid nor within a bound worth promising: **stop**. The author decides, as after Task 0. Applied (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). This is a measurement, not TDD. - [x] **Step 1: Find the bird base and the sampan's crease patterns, and record their sources** - [x] **Step 2: Add cases 6–9 to the spike** - [x] **Step 3: Run and record** Run: `swift run -c release --package-path spikes/interpolation` - [x] **Step 4: Write the decision record and apply the exit criteria** - [x] **Step 5: Commit** ```bash git add spikes docs git commit -m "Non-rigid steps: model, bound and the remaining coupled steps" ``` --- ### Task 1: FOLD decoding, including the extension keys **Files:** - Create: `Packages/FoldKit/Package.swift` - Create: `Packages/FoldKit/Sources/FoldFormat/FoldFile.swift` - Create: `Packages/FoldKit/Sources/FoldFormat/FoldFrame.swift` - Create: `Packages/FoldKit/Sources/FoldFormat/EdgeAssignment.swift` - Create: `Packages/FoldKit/Sources/FoldFormat/StepRecord.swift` - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixture.swift` - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/` — every fixture in *Synthetic fixtures* - Test: `Packages/FoldKit/Tests/FoldFormatTests/DecodingTests.swift` **Interfaces:** - Consumes: nothing. - Produces: - `enum EdgeAssignment: String, Codable, Sendable { case boundary = "B", mountain = "M", valley = "V", flat = "F", unassigned = "U" }` - `enum StepKind: String, Codable, Sendable { case fold, foldAndUnfold, turnOver, rotate }` - `enum StepTechnique: String, Codable, Sendable { case plain, insideReverse, outsideReverse, squash, petal, sink }` - `enum TurnOverAxis: String, Codable, Sendable { case vertical, horizontal }` - `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 - `struct Viewpoint: Codable, Equatable, Sendable { let eye: SIMD3; let up: SIMD3 }` — `eye` is the unit direction toward the viewer - `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` - `struct PopRecord: Codable, Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: [Double]; let openAxes: [AxisRecord]; let popped: [SIMD3]; 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]`. Axis windows are on the step's whole *t*, as for any axis, so `foldc` writes each opening axis's window inside `[0, phases[0]]` and each closing axis's inside `[phases[1], 1]` - `struct FoldFrame: Codable, Sendable { var verticesCoords: [SIMD3]; var edgesAssignment: [EdgeAssignment]; var edgesFoldAngle: [Double]; var faceOrders: [[Int]]; var faceOrdersMidFold: [[Int]]?; var step: StepRecord? }` - `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 - `var (FoldFile).stepCount: Int { get }` — `frames.count − 1` - `init (FoldFile).init(contentsOf url: URL) throws` - `enum FoldError: Error, Equatable, Sendable { case unsupportedAssignment(String); case malformedCoordinate(vertex: Int); case missingStepRecord(step: Int); case topologyInFrame(frame: Int); case missingFrameInheritance(frame: Int) }` - `func fixture(_ name: String) -> URL` in `FoldKitTestSupport` `edgesVertices` and `facesVertices` live on `FoldFile`, not `FoldFrame`, because the spec fixes one topology for every frame. Decoding them per-frame would make the invariant expressible-but-violable; hoisting them makes it structural, and a frame that carries either is a decoding error. `vertices_coords` entries may be 2- or 3-element arrays; decode 2-element as z = 0. The key frame is FOLD's top level, mixed with the `file_` keys, so `FoldFile` needs a hand-written `init(from:)` and `encode(to:)`: frame 0 from the top level, frames 1…N from `file_frames`, each of which must carry `frame_parent: 0` and `frame_inherit: true` and is written with them. Keys an exported crease pattern may lack decode to defaults: `edges_foldAngle` to zeros, `faceOrders` to empty, `edges_krz:firstCreasedAtStep` to nulls, `file_title` and `file_author` to nil, `file_classes` to empty. That lets `foldc` read crease patterns with the same decoder; the validator, not the decoder, decides what a shipped model must have. Package manifest: swift-tools-version 6.2, platforms `.iOS(.v26)`, `.macOS(.v26)`. Library products `FoldFormat`, `Folding`, `Notation`, `Renderer`, `Models`; executables `foldlint` and `foldc`; a test target per library; and `FoldKitTestSupport`, a plain target with `resources: [.copy("Fixtures")]` that only test targets depend on. - [ ] **Step 1: Write the failing tests** ```swift @Test func decodesUnitSquareWithFourBoundaryEdges() throws { let f = try FoldFile(contentsOf: fixture("square.fold")) #expect(f.frames[0].verticesCoords.count == 4) #expect(f.frames[0].edgesAssignment.allSatisfy { $0 == .boundary }) #expect(f.stepCount == 0) } @Test func topologyLivesOnTheFileNotTheFrame() throws { let f = try FoldFile(contentsOf: fixture("square.fold")) #expect(f.edgesVertices.count == 4) #expect(f.facesVertices.count == 1) } @Test func aFrameCarryingTopologyIsRejected() { #expect(throws: FoldError.topologyInFrame(frame: 1)) { try FoldFile(contentsOf: fixture("topology-in-frame.fold")) } } @Test func decodesTwoElementCoordsAsZeroZ() throws { #expect(try FoldFile(contentsOf: fixture("square.fold")).frames[0].verticesCoords .allSatisfy { $0.z == 0 }) } @Test func frameNIsTheResultOfStepN() throws { let f = try FoldFile(contentsOf: fixture("half.fold")) #expect(f.stepCount == 3) #expect(f.frames[0].step == nil) #expect(f.frames[1].step?.kind == .fold) #expect(f.frames[2].step?.kind == .turnOver) #expect(f.frames[3].step?.rotateDegrees == 90) } @Test func decodesTheStepRecordIncludingItsInstructionAndViewpoint() throws { let step = try FoldFile(contentsOf: fixture("half.fold")).frames[1].step #expect(step?.axes.count == 1) #expect(step?.technique == .plain) #expect(step?.instruction?.isEmpty == false) #expect(step?.viewpoint == Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))) } @Test func decodesAnAxisTreeWithWindowsAndACurve() throws { let json = #"{"edge": 3, "movingFaces": [2], "startAngle": 0, "endAngle": 180, "parent": 0,"# + #" "window": [0.25, 1], "angles": [0, 90, 180]}"# let axis = try JSONDecoder().decode(AxisRecord.self, from: Data(json.utf8)) #expect(axis.parent == 0) #expect(axis.window == [0.25, 1]) #expect(axis.angles == [0, 90, 180]) } @Test func decodesAPopRecord() throws { let json = #"{"spine": [0, 1], "openAngle": 30, "phases": [0.3333333333333333, 0.6666666666666666],"# + #" "openAxes": [], "popped": [[0, 0, 0], [1, 0, 0]], "closeAxes": []}"# let pop = try JSONDecoder().decode(PopRecord.self, from: Data(json.utf8)) #expect(pop.openAngle == 30) #expect(pop.popped.count == 2) } @Test func windowsDecodeOnAStaggeredStep() throws { let step = try FoldFile(contentsOf: fixture("letter-staggered.fold")).frames[1].step #expect(step?.axes.map(\.window) == [[0, 0.5], [0.5, 1]]) #expect(step?.nonRigid == false) } @Test func decodesFirstCreasedAtStepWithNullForBoundaries() throws { let f = try FoldFile(contentsOf: fixture("half.fold")) #expect(f.edgesFirstCreasedAtStep == [nil, nil, nil, nil, nil, nil, 1]) } @Test func roundTripsThroughEncodingUnchanged() throws { let f = try FoldFile(contentsOf: fixture("half.fold")) let again = try JSONDecoder().decode(FoldFile.self, from: JSONEncoder().encode(f)) #expect(again.edgesVertices == f.edgesVertices) #expect(again.frames.map(\.verticesCoords) == f.frames.map(\.verticesCoords)) #expect(again.frames.map(\.step) == f.frames.map(\.step)) } @Test func encodedFramesInheritFromTheKeyFrame() throws { let f = try FoldFile(contentsOf: fixture("half.fold")) let json = try JSONSerialization.jsonObject(with: JSONEncoder().encode(f)) as! [String: Any] let frames = json["file_frames"] as! [[String: Any]] #expect(frames.allSatisfy { $0["frame_parent"] as? Int == 0 && $0["frame_inherit"] as? Bool == true }) #expect(frames.allSatisfy { $0["edges_vertices"] == nil }) } @Test(arguments: ["C", "J"]) func rejectsCutAndJoinAssignments(_ code: String) { #expect(throws: FoldError.unsupportedAssignment(code)) { try JSONDecoder().decode(EdgeAssignment.self, from: Data("\"\(code)\"".utf8)) } } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter DecodingTests` Expected: FAIL — no such module `FoldFormat`. - [ ] **Step 3: Write the fixtures, implement the types and `FoldFile`'s coding** `CodingKeys` map the format's spelling exactly: snake_case for standard keys, `faceOrders` camelCase, `edges_krz:firstCreasedAtStep`, `krz:step`, `krz:faceOrders_midFold`. `EdgeAssignment` needs its own `init(from:)` to throw `FoldError` rather than `DecodingError`. Write the fixtures from the tables in *Synthetic fixtures*; their coordinates are exact. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter DecodingTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "FOLD decoding with krz extension keys and synthetic fixtures" ``` --- ### Task 2: The validator **Files:** - Create: `Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift` - Test: `Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift` **Interfaces:** - Consumes: Task 1 types. - Produces: - `enum FoldDefect: Equatable, Sendable { case vertexIndexOutOfRange(edge: Int); case faceVertexOutOfRange(face: Int); case vertexCountChanged(frame: Int); case foldAngleOutOfRange(frame: Int, edge: Int, degrees: Double); case foldAngleSignDisagreesWithAssignment(frame: Int, edge: Int); case boundaryEdgeFolded(frame: Int, edge: Int); case faceOrderNotAntisymmetric(frame: Int, f: Int, g: Int); case cyclicFaceOrder(frame: Int, cycle: [Int]); case nonIsometricTransition(step: Int, edge: Int, from: Double, to: Double); case overlappingMovingSetsWithoutMidFoldOrder(step: Int); case startAndEndOrderDisagreeOnStillFaces(step: Int, f: Int, g: Int); case foldAndUnfoldWithoutPeakOrder(step: Int); case orderDisagreesWithCrease(frame: Int, edge: Int); case interleavedFolds(frame: Int, edges: [Int]); case faceInsideFold(frame: Int, face: Int, edge: Int); case nonConvexFace(face: Int); case missingInstruction(step: Int); case authorNotTraditional(String?); case missingFirstCreasedAtStep(edge: Int) }` - `func validate(_ file: FoldFile) -> [FoldDefect]` - `func movingSetsOverlapInProjection(step: Int, _ file: FoldFile) -> Bool` - `func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3]` - `func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3]) -> [(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) This 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. The 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`: - **crease:** two faces joined at a crease folded to ±180 are ordered as its `edges_assignment` requires — for a valley each face's normal points toward the other, for a mountain away; - **nesting:** where two folded creases coincide, their face pairs nest or are disjoint in the stack, never interleave (FOLD's "taco-taco"); - **inside:** a face whose interior crosses a folded crease's line does not lie between that crease's two faces ("taco-tortilla"). - [ ] **Step 1: Write the failing tests** ```swift @Test(arguments: ["square.fold", "half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", "letter-staggered.fold", "quarters.fold", "occlusion.fold"]) func acceptsAValidModel(_ name: String) throws { #expect(validate(try FoldFile(contentsOf: fixture(name))).isEmpty) } @Test func oppositeNormalsMakeAMutualAboveValid() { // [f, g, +1] and [g, f, +1] agree when the faces face opposite ways let pairs = normalisedFaceOrders([[0, 1, 1], [1, 0, 1]], normals: [SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) #expect(Set(pairs.map { [$0.below, $0.above] }) == [[0, 1]]) } @Test func rejectsAnOrderTheCreaseMakesImpossible() throws { #expect(validate(try FoldFile(contentsOf: fixture("order-against-crease.fold"))) .contains(.orderDisagreesWithCrease(frame: 1, edge: 6))) } @Test func rejectsInterleavedFolds() throws { let defects = validate(try FoldFile(contentsOf: fixture("interleaved-folds.fold"))) #expect(defects.contains { if case .interleavedFolds(frame: 3, _) = $0 { return true }; return false }) } @Test func rejectsAFaceInsideAFoldItCrosses() throws { let defects = validate(try FoldFile(contentsOf: fixture("face-inside-fold.fold"))) #expect(defects.contains(.faceInsideFold(frame: 2, face: 2, edge: 8))) } @Test func rejectsAFoldAndUnfoldWithoutItsPeakOrder() throws { var file = try FoldFile(contentsOf: fixture("quarters.fold")) file.frames[1].faceOrdersMidFold = nil #expect(validate(file).contains(.foldAndUnfoldWithoutPeakOrder(step: 1))) } @Test func rejectsANonConvexFace() throws { #expect(validate(try FoldFile(contentsOf: fixture("nonconvex.fold"))) == [.nonConvexFace(face: 0)]) } @Test func rejectsAFrameThatChangesTheVertexCount() throws { let defects = validate(try FoldFile(contentsOf: fixture("retopologised.fold"))) #expect(defects.contains(.vertexCountChanged(frame: 2))) } @Test func rejectsOverlappingMovingSetsWithNoMidFoldOrder() throws { let defects = validate(try FoldFile(contentsOf: fixture("letter-no-midfold.fold"))) #expect(defects == [.overlappingMovingSetsWithoutMidFoldOrder(step: 1)]) } @Test func rejectsStartAndEndOrderDisagreementOnStillFaces() throws { let defects = validate(try FoldFile(contentsOf: fixture("still-face-reorder.fold"))) #expect(defects.contains { if case .startAndEndOrderDisagreeOnStillFaces(step: 2, _, _) = $0 { return true }; return false }) } @Test func rejectsCyclicFaceOrder() throws { let defects = validate(try FoldFile(contentsOf: fixture("cyclic-order.fold"))) #expect(defects.contains { if case .cyclicFaceOrder(frame: 2, _) = $0 { return true }; return false }) } @Test func rejectsNonIsometricTransition() throws { let defects = validate(try FoldFile(contentsOf: fixture("stretched-step.fold"))) #expect(defects.contains { if case .nonIsometricTransition(step: 1, _, _, _) = $0 { return true }; return false }) } @Test func rejectsFoldAngleOutsideRange() throws { #expect(validate(try FoldFile(contentsOf: fixture("angle-200.fold"))) == [.foldAngleOutOfRange(frame: 1, edge: 6, degrees: 200)]) } @Test func rejectsAFoldAngleWhoseSignDisagreesWithItsAssignment() throws { #expect(validate(try FoldFile(contentsOf: fixture("angle-sign.fold"))) == [.foldAngleSignDisagreesWithAssignment(frame: 1, edge: 6)]) } @Test func rejectsAFoldedBoundaryEdge() throws { let defects = validate(try FoldFile(contentsOf: fixture("folded-boundary.fold"))) #expect(defects.contains(.boundaryEdgeFolded(frame: 1, edge: 0))) } @Test func rejectsAStepWithoutAnInstruction() throws { #expect(validate(try FoldFile(contentsOf: fixture("no-instruction.fold"))) == [.missingInstruction(step: 1)]) } @Test func rejectsANonTraditionalAuthor() throws { #expect(validate(try FoldFile(contentsOf: fixture("designed-model.fold"))) == [.authorNotTraditional("A. Designer")]) } @Test func rejectsEdgeReferencingMissingVertex() throws { #expect(validate(try FoldFile(contentsOf: fixture("bad-index.fold"))) == [.vertexIndexOutOfRange(edge: 0)]) } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests` Expected: FAIL. - [ ] **Step 3: Implement `validate` and `movingSetsOverlapInProjection`** Normals come from the frame's coordinates and the counterclockwise `faces_vertices` order. For cycle detection and the three consistency rules, normalise every triple with `normalisedFaceOrders` first; cycle detection is depth-first search over the resulting below → above graph. The still-face rule must not use normalised pairs, because a turn-over flips every normal and would invert every pair: it compares each pair's relation in a form a rigid motion leaves unchanged — the triple rewritten with the lower face index first, `s` negated when swapping faces whose normals agree (the spec's reverse-triple rule). A raw `s = +1` graph is wrong both ways: `[f, g, +1]` with `[g, f, +1]` is valid for opposite normals, and a raw cycle can be acyclic once normalised. Antisymmetry follows the spec: a present reverse triple `[g, f, t]` has `t = -s` when the two faces' normals agree in the folded state and `t = s` when they oppose. Sign: `V` requires a positive angle, `M` negative, `F`, `U` and `B` zero. Every `foldAndUnfold` needs `krz:faceOrders_midFold`, the order at its peak, since neither end frame orders the moving faces against what they lie on there; the validator checks it is present, and Task 5's `LayerOrder.active`, which can compute the peak positions, checks it for cycles. Every non-boundary edge needs a `edges_krz:firstCreasedAtStep` except a subdivision edge (`F` and flat in every frame). Overlap in projection is tested by polygon intersection of the moving sets' projected outlines at the step's viewpoint, in frame n (where both sets have arrived). - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold ordering" ``` --- ### Task 3: Reading authored steps **Files:** - Create: `Packages/FoldKit/Sources/Folding/FoldStep.swift` - Create: `Packages/FoldKit/Sources/Folding/StepReader.swift` - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/DegreeFourVertex.swift` - Test: `Packages/FoldKit/Tests/FoldingTests/StepReadingTests.swift` **Interfaces:** - Consumes: Task 1 types. - Produces: - `struct FoldAxis: Equatable, Sendable { let edge: Int; let origin: SIMD3; let direction: SIMD3; let movingFaces: Set; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: ClosedRange; let curve: [Double]? }` - `func (FoldAxis).angle(at t: Double, kind: StepKind) -> Double` - `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 - `struct Pop: Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: ClosedRange; let openAxes: [FoldAxis]; let popped: [SIMD3]; let closeAxes: [FoldAxis] }` — `closeAxes`' origins and directions come from `popped`, not from frame `index − 1` - `var (FoldStep).movingFaceUnion: Set { get }` - `func readSteps(_ file: FoldFile) throws -> [FoldStep]` — `result[k].index == k + 1` - `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) }` `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. `FoldAxis.origin` and `direction` come from the axis edge's endpoints in frame `index − 1`. The direction is the way the moving face adjacent to the edge traverses it in `faces_vertices` order, and the origin is the vertex that traversal starts from, so that a positive rotation about it (right-hand rule) turns the moving face toward its normal — a valley — and the rotation for any step is `angle(t) − startAngle` with FOLD's own sign. `angle(at:)` first maps `t` onto the axis's window, `u = clamp((t − t0) / (t1 − t0), 0, 1)`, so an axis waits before its window and holds after it. Then it is `startAngle + u·(endAngle − startAngle)` for `fold`, `startAngle + (peakAngle − startAngle)·(1 − |2u − 1|)` for `foldAndUnfold`, or, when the axis has a curve, the curve at `u` by cubic Hermite interpolation with central-difference tangents (one-sided at the ends). Decision 0001 measured that 257 samples rebuilt this way keep a coupled vertex's tear under 1e-6. For 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. `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. - [ ] **Step 1: Write the failing tests** ```swift @Test func stepIndicesCountFromOne() throws { let steps = try readSteps(FoldFile(contentsOf: fixture("half.fold"))) #expect(steps.map(\.index) == [1, 2, 3]) } @Test func simpleValleyFoldReadsOneAxis() throws { let step = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0] #expect(step.axes.count == 1) #expect(step.axes[0].endAngle == 180) } @Test func letterFoldReadsTwoSimultaneousAxes() throws { let step = try readSteps(FoldFile(contentsOf: fixture("letter.fold")))[0] #expect(step.axes.count == 2) } @Test(arguments: ["half.fold", "letter.fold", "letter-sequential.fold", "quarters.fold", "occlusion.fold"]) func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws { for step in try readSteps(FoldFile(contentsOf: fixture(name))) { let union = step.axes.reduce(into: Set()) { $0.formUnion($1.movingFaces) } #expect(union.count == step.axes.reduce(0) { $0 + $1.movingFaces.count }) } } @Test func turnOverStepHasNoAxesAndAnAxisToTurnAbout() throws { let turn = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[1] #expect(turn.kind == .turnOver) #expect(turn.axes.isEmpty) #expect(turn.turnOverAxis == .vertical) } @Test func rotateStepCarriesItsDegrees() throws { #expect(try readSteps(FoldFile(contentsOf: fixture("half.fold")))[2].rotateDegrees == 90) } @Test func foldAndUnfoldPeaksMidwayAndReturns() throws { let s = try readSteps(FoldFile(contentsOf: fixture("quarters.fold")))[0] #expect(s.kind == .foldAndUnfold) #expect(s.axes[0].angle(at: 0.5, kind: s.kind) == 180) #expect(s.axes[0].angle(at: 1, kind: s.kind) == 0) } @Test func axisIsDirectedAsTheMovingFaceTraversesIt() throws { // f1 = [v1, v2, v3, v4] traverses e6 = [v1, v4] from v4 to v1 let axis = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0].axes[0] #expect(axis.origin == SIMD3(1, 2, 0)) #expect(axis.direction == SIMD3(0, -1, 0)) } @Test func instructionIsReadVerbatim() throws { let f = try FoldFile(contentsOf: fixture("half.fold")) #expect(try readSteps(f)[0].instruction == f.frames[1].step?.instruction) } @Test func aWindowedAxisWaitsAndThenHolds() throws { let s = try readSteps(FoldFile(contentsOf: fixture("letter-staggered.fold")))[0] #expect(s.axes[0].angle(at: 0.25, kind: s.kind) == 90) #expect(s.axes[1].angle(at: 0.25, kind: s.kind) == 0) #expect(s.axes[0].angle(at: 0.75, kind: s.kind) == 180) #expect(s.axes[1].angle(at: 0.75, kind: s.kind) == 90) } @Test func aCurveIsInterpolatedBetweenItsSamples() throws { let axis = try readSteps(degreeFourVertex()).first!.axes.first { $0.curve != nil }! let t = 0.5 + 0.5 / 256 // halfway between two samples #expect(abs(axis.angle(at: t, kind: .fold) - degreeFourExactAngle(axis.edge, at: t)) < 1e-6) } @Test func aNonRigidStepNeedsItsPop() { #expect(throws: StepError.nonRigidWithoutPop(step: 1)) { try readSteps(FoldFile(contentsOf: fixture("nonrigid-no-pop.fold"))) } } @Test func rotateWithoutDegreesThrows() { #expect(throws: StepError.rotateWithoutDegrees(step: 3)) { try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold"))) } } @Test func movingFaceOutOfRangeThrows() { #expect(throws: StepError.movingFacesOutOfRange(step: 1)) { try readSteps(FoldFile(contentsOf: fixture("bad-moving-face.fold"))) } } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests` Expected: FAIL. - [ ] **Step 3: Implement `FoldAxis`, `FoldStep` and `readSteps`** - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "Read authored fold steps, including multi-axis and reorientation kinds" ``` --- ### Task 4: Rigid interpolation **Files:** - Create: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift` - Test: `Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift` **Interfaces** (decision 0001; rigid steps only — Task 7b adds the path for `nonRigid` steps, whose data only `foldc` can produce): - Consumes: Task 1 and Task 3 types. - Produces: - `struct FoldInterpolator: Sendable { init(file: FoldFile, step: FoldStep) }` — interpolates from frame `step.index − 1` to frame `step.index` - `func (FoldInterpolator).positions(at t: Double) -> [SIMD3]` — `t` in 0...1 There is no separate orientation output: a `turnOver` or `rotate` step's end frame already has rotated coordinates, so `positions(at:)` rotates the start frame about its bounding-box centre by `t` times the step's angle — 180° about the viewpoint's up vector or its right vector (`up × eye`) for `turnOver`, `rotateDegrees` about `eye` for `rotate` (right-hand rule, so positive is counterclockwise as seen). - [ ] **Step 1: Write the failing tests** ```swift let modelFixtures = ["half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", "letter-staggered.fold", "quarters.fold", "occlusion.fold"] @Test func tZeroReproducesTheStartFrame() throws { let (file, i) = try interpolator("half.fold", step: 1) #expect(zip(i.positions(at: 0), file.frames[0].verticesCoords) .allSatisfy { simd_distance($0, $1) < 1e-12 }) } @Test(arguments: modelFixtures) func tOneReproducesTheEndFrameForEveryStep(_ name: String) throws { let file = try FoldFile(contentsOf: fixture(name)) for step in try readSteps(file) { let i = FoldInterpolator(file: file, step: step) #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords) .allSatisfy { simd_distance($0, $1) < 1e-9 }, "\(name) step \(step.index)") } } @Test(arguments: modelFixtures) func everyEdgeLengthIsPreservedThroughoutEveryStep(_ name: String) throws { let file = try FoldFile(contentsOf: fixture(name)) for step in try readSteps(file) { let i = FoldInterpolator(file: file, step: step) for t in stride(from: 0.0, through: 1.0, by: 0.05) { #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-9, "\(name) step \(step.index) t \(t)") } } } @Test func verticesOnTheAxisDoNotMove() throws { let (file, i) = try interpolator("half.fold", step: 1) for v in [1, 4] { #expect(simd_distance(i.positions(at: 0.37)[v], file.frames[0].verticesCoords[v]) < 1e-12) } } @Test func aValleyFoldRisesTowardTheViewerAndAMountainFoldFallsAway() throws { let (_, valley) = try interpolator("half.fold", step: 1) let (_, mountain) = try interpolator("mountain.fold", step: 1) #expect(valley.positions(at: 0.5)[2].z > 0) #expect(mountain.positions(at: 0.5)[2].z < 0) } @Test func multiAxisStepMovesEverySetOnTheSharedParameter() throws { let (file, i) = try interpolator("letter.fold", step: 1) let start = file.frames[0].verticesCoords, mid = i.positions(at: 0.5) #expect(simd_distance(mid[0], start[0]) > 0.1) // left flap #expect(simd_distance(mid[3], start[3]) > 0.1) // right flap } @Test func foldAndUnfoldPassesThroughThePeakAndReturns() throws { let (file, i) = try interpolator("quarters.fold", step: 1) #expect(simd_distance(i.positions(at: 0.5)[2], SIMD3(0, 0, 0)) < 1e-9) #expect(zip(i.positions(at: 1), file.frames[0].verticesCoords) .allSatisfy { simd_distance($0, $1) < 1e-9 }) } @Test func aCoupledVertexStaysWholeThroughout() throws { // decision 0001, case 3: curves from the closed form, sampled at 257 points let file = degreeFourVertex() let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) for n in 0...1024 { #expect(maxEdgeLengthDrift(i.positions(at: Double(n) / 1024), file) < 1e-6) } #expect(zip(i.positions(at: 1), file.frames[1].verticesCoords) .allSatisfy { simd_distance($0, $1) < 1e-9 }) } @Test func theSameVertexWithLinearAnglesTears() throws { // the control: drop the curve and the paper does not hold together let file = degreeFourVertex(linear: true) let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) #expect(maxEdgeLengthDrift(i.positions(at: 0.5), file) > 0.1) } @Test func aStaggeredAxisMovesOnlyInItsWindow() throws { let (file, i) = try interpolator("letter-staggered.fold", step: 1) let start = file.frames[0].verticesCoords #expect(simd_distance(i.positions(at: 0.25)[3], start[3]) < 1e-12) // right flap waits #expect(simd_distance(i.positions(at: 0.5)[0], SIMD3(2, 0, 0)) < 1e-9) // left flap down } @Test func turnOverRotatesTheModelRigidly() throws { let (_, i) = try interpolator("half.fold", step: 2) #expect(pairwiseDistancesAgree(i.positions(at: 0.5), i.positions(at: 0))) #expect(i.positions(at: 0.5).contains { $0.z != 0 }) } @Test func interpolationFitsInAFrameBudget() throws { let file = gridSheet(cells: 12) // built in code: a 12×12 grid, one fold down the middle let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) let elapsed = ContinuousClock().measure { for n in 0..<1000 { _ = i.positions(at: Double(n) / 1000) } } #expect(elapsed / 1000 < .milliseconds(1)) } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests` Expected: FAIL. - [ ] **Step 3: Implement `positions(at:)`** Each 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. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "Rigid interpolation on an axis tree with windows and solved curves" ``` --- ### Task 5: Layer order resolution **Files:** - Create: `Packages/FoldKit/Sources/Folding/LayerOrder.swift` - Test: `Packages/FoldKit/Tests/FoldingTests/LayerOrderTests.swift` **Interfaces:** - Consumes: Task 1–4 types; `faceNormals` and `normalisedFaceOrders` from Task 2. - Produces: - `struct LayerOrder: Sendable { init(sources: [(faceOrders: [[Int]], normals: [SIMD3])]) throws }` — each source is a set of triples with the face normals of the state it describes; earlier sources win for a pair present in several. Triples are stored raw; normals are used only to check each source for cycles - `init (LayerOrder).init(faceOrders: [[Int]], normals: [SIMD3]) throws` — one source - `static func (LayerOrder).active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder` — first source frame n's `krz:faceOrders_midFold` (with the normals at the peak, from Task 4's interpolator at `t = 0.5`, for a `foldAndUnfold`, else frame n's) or, without one, frame n's `faceOrders` with frame n's normals; second source frame n − 1's `faceOrders` with frame n − 1's normals, for pairs the first lacks - `struct CoplanarCluster: Equatable, Sendable { let faces: [Int] }` — faces already sorted back-to-front for the given view - `func (LayerOrder).clusters(positions: [SIMD3], faces: [[Int]], viewDirection: SIMD3) -> [CoplanarCluster]` - `func (LayerOrder).agreesWith(_ other: LayerOrder, ignoring movingFaces: Set) -> Bool` - `func stackDepth(positions: [SIMD3], faces: [[Int]]) -> Int` — the most faces whose open interiors cover one point, over coincident faces; a flat sheet is 1 - `enum LayerError: Error, Equatable, Sendable { case cyclic(cycle: [Int]) }` The output is **clusters**, not one global draw order, because the renderer is hybrid: the depth buffer separates clusters and the active ordering orders within them. Two faces are linked when they overlap in projection, their normals are within 2° of each other's line, and each one's vertices lie within sin 2° × the model's bounding-box diagonal of the other's plane — the distance tolerance follows the angular one, since a flap hinged at the edge of a stack and 2° off it rises that far. A cluster is a connected group of linked faces. The tolerance is wide on purpose: a facet just leaving or just arriving on a stack is nearly coplanar with it, and the depth buffer alone would z-fight there. Each triple's `s` is resolved against `viewDirection` using `g`'s normal **at the given positions**, since "above" in FOLD means "on the side `g`'s normal points toward", that reverses when the view crosses `g`'s plane, and a moving stack's normals turn with it. In `active`, a triple whose `g` moves in the step and whose `f` does not is rewritten into its reverse with that source's normals, so a moving/still pair is always read against the still face, whose normal does not turn. The fallback to frame n − 1 covers a flap leaving a stack, whose pairs exist only in the start frame; `foldAndUnfold` carries its peak order in `krz:faceOrders_midFold` (Task 2 requires it). - [ ] **Step 1: Write the failing tests** ```swift let up2 = [SIMD3(0, 0, 1), SIMD3(0, 0, 1)] let up3 = up2 + [SIMD3(0, 0, 1)] @Test func twoStackedCoplanarFacesFormOneClusterOrderedFarthestFirst() throws { let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2) // 0 above 1 let c = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), viewDirection: SIMD3(0, 0, -1)) #expect(c.count == 1) #expect(c[0].faces == [1, 0]) } @Test func orbitingUnderneathReversesTheClusterOrder() throws { let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2) let above = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), viewDirection: SIMD3(0, 0, -1)) let below = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), viewDirection: SIMD3(0, 0, 1)) #expect(above[0].faces == below[0].faces.reversed()) } @Test func facesSeparatedInSpaceFormSeparateClusters() throws { let order = try LayerOrder(faceOrders: [], normals: up2) #expect(order.clusters(positions: separatedSquarePositions(), faces: twoSquares(), viewDirection: SIMD3(0, 0, -1)).count == 2) } @Test func unorderedCoplanarFacesKeepIndexOrder() throws { let order = try LayerOrder(faceOrders: [], normals: up3) #expect(order.clusters(positions: threeStackedPositions(), faces: threeSquares(), viewDirection: SIMD3(0, 0, -1))[0].faces == [0, 1, 2]) } @Test func anArrivingFlapJoinsTheStackItLandsOn() throws { // letter-sequential step 2 at 179.5°: f2 is half a degree above f0 and f1 let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2) let c = try LayerOrder.active(for: step, in: file) .clusters(positions: i.positions(at: 179.5 / 180), faces: file.facesVertices, viewDirection: SIMD3(0, 0, -1)) #expect(c.contains { Set($0.faces) == [0, 1, 2] && $0.faces.last == 2 }) } @Test func aFlapAtThirtyDegreesIsItsOwnCluster() throws { let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2) let c = try LayerOrder.active(for: step, in: file) .clusters(positions: i.positions(at: 150.0 / 180), faces: file.facesVertices, viewDirection: SIMD3(0, 0, -1)) #expect(c.contains { $0.faces == [2] }) } @Test func aFoldAndUnfoldPeakIsOrderedByItsMidFoldOrder() throws { // quarters step 1 at the peak: f2 lies on f3 and f1 on f0, the moving faces on top let (file, step, i) = try interpolatorWithStep("quarters.fold", step: 1) let c = try LayerOrder.active(for: step, in: file) .clusters(positions: i.positions(at: 0.5), faces: file.facesVertices, viewDirection: SIMD3(0, 0, -1)) let left = try #require(c.first { $0.faces.contains(3) }) #expect(left.faces.firstIndex(of: 2)! > left.faces.firstIndex(of: 3)!) } @Test func cyclicOrderThrows() { #expect(throws: LayerError.cyclic(cycle: [0, 1, 2])) { try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: up3) } } @Test func aRawCycleThatNormalisesAwayIsAccepted() { // f0 and f2 face down: these triples say f1 < f0, f1 < f2, f2 < f0 #expect(throws: Never.self) { try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: [SIMD3(0, 0, -1), SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) } } @Test func consecutiveOrderingsAgreeAwayFromTheMovingFaces() throws { let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) for step in try readSteps(file) { let start = try LayerOrder(faceOrders: file.frames[step.index - 1].faceOrders, normals: faceNormals(file.frames[step.index - 1], file)) let end = try LayerOrder(faceOrders: file.frames[step.index].faceOrders, normals: faceNormals(file.frames[step.index], file)) #expect(start.agreesWith(end, ignoring: step.movingFaceUnion), "step \(step.index)") } } @Test func stackDepthCountsTheLayersOverOnePoint() throws { let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) #expect(stackDepth(positions: file.frames[2].verticesCoords, faces: file.facesVertices) == 3) } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests` Expected: FAIL. - [ ] **Step 3: Implement `LayerOrder`, `CoplanarCluster` and `clusters`** `init` normalises each source's triples with that source's normals (`faceNormals(positions:faces:)` from FoldFormat) and throws on a cycle within it, the cycle listed so that each face lies above the next, as the validator reports it, then keeps the raw triples. `agreesWith` compares pairs in the rigid-motion-invariant form Task 2's still-face rule uses. `clusters` links faces by the rule above, then topologically sorts each cluster against `viewDirection`, resolving each triple with `g`'s normal at `positions`, stably on unordered pairs. `stackDepth` overlays the projected outlines of each group of coincident faces, takes one interior point of each cell of that arrangement (its centroid), counts the faces whose open interior contains it, and returns the maximum. Counting at the arrangement's vertices instead would count every face meeting at a crease vertex, so a flat sheet would score its vertex degree. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "Near-coplanar clustering and view-relative layer order" ``` --- ### Task 6: The interpenetration checker **Files:** - Create: `Packages/FoldKit/Sources/Folding/Interpenetration.swift` - Test: `Packages/FoldKit/Tests/FoldingTests/InterpenetrationTests.swift` **Interfaces:** - Consumes: Task 1–5 types. - Produces: - `struct Intersection: Equatable, Sendable { let faceA: Int; let faceB: Int; let t: Double }` - `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 "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. - [ ] **Step 1: Write the failing tests** ```swift @Test func aCleanFoldHasNoIntersections() throws { let (file, i) = try interpolator("half.fold", step: 1) #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) } @Test func twoFlapsFoldingIntoEachOtherAreDetected() throws { // both thirds of the letter sheet valley-folded at once: they meet at the midline from ~120° let (file, i) = try interpolatorForBothThirdsInFront() #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) } @Test func staggeredFlapsDoNotCollide() throws { // the same two flaps on separate windows of t let (file, i) = try interpolator("letter-staggered.fold", step: 1) #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) } @Test func aFaceSwingingThroughAFaceItSharesAVertexWithIsDetected() throws { // built in code: fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4); moving triangle // (0,0,0), (0,2,0), (-1,1,0) hinged on its edge along the y-axis, folding toward +z let (file, i) = try interpolatorForSharedVertexSweep() #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) } @Test func coplanarFacesAreNotReportedAsIntersecting() throws { let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty) } @Test func edgeAdjacentFacesAreNotReportedAsIntersecting() throws { let (file, i) = try interpolator("quarters.fold", step: 3) #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty) } @Test func theReportedParameterIsWhereTheIntersectionBegins() throws { let (file, i) = try interpolatorForBothThirdsInFront() let found = interpenetrations(i, faces: file.facesVertices, samples: 64) #expect(!found.isEmpty) #expect(found.allSatisfy { abs($0.t - 2.0 / 3) <= 1.0 / 64 }) // the flaps meet at 120° } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests` Expected: FAIL. - [ ] **Step 3: Implement `interpenetrations`** At each sample of `t`, triangulate the facets and test triangle-triangle intersection pairwise, skipping coplanar pairs. Discard an intersection that lies within 1e-9 of either face's boundary (the face's, not a triangle's, so the fan's internal edges do not count as boundary). An AABB pre-pass keeps the pairwise cost down; the models are small enough that nothing cleverer is needed. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "Facet interpenetration checker" ``` --- ### Task 7: `foldc`, the fold-script compiler **Files:** - Create: `Packages/FoldKit/Sources/foldc/main.swift` - Create: `Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift` - Create: `Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift` - Create: `Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift` - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,letter-staggered,quarters,occlusion}-cp.fold` — each model fixture's sheet and creases as an editor would export them: no frames, every crease carrying its **final** `M`/`V` assignment from the fixture's last frame (`F` for a crease that ends flat). `compile` resets frame 0 to `F` and 0 - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,letter-staggered,quarters,occlusion}.foldscript` - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{unresolved-crease,angle-out-of-range}.foldscript` - Modify: `Packages/FoldKit/Sources/FoldKitTestSupport/DegreeFourVertex.swift` — `degreeFourPattern()` and `degreeFourScript()`, the same vertex as a crease pattern and a one-step script driven by the 140° crease - Test: `Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift` **Interfaces:** - Consumes: Task 1–6 types. - Produces: - `struct FoldScript: Codable, Sendable { let creasePattern: String; let title: String; let steps: [ScriptStep] }` — `creasePattern` is relative to the script - `init (FoldScript).init(contentsOf url: URL) throws` - `struct ScriptStep: Codable, Sendable { let kind: StepKind; let technique: StepTechnique?; let instruction: String; let creases: [CreaseRef]; let movingSide: [SIMD2]; 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) - `enum CreaseRef: Codable, Sendable { case betweenVertices(SIMD2, SIMD2); case edgeIndex(Int) }` - `struct OrderOverride: Codable, Sendable { let above: SIMD2; let below: SIMD2 }` — points in crease-pattern coordinates naming two faces, "above" as seen from the step's viewpoint - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile` - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]` - `func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame, viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]]` - `enum CompileError: Error, Equatable, Sendable { case unresolvedCrease(step: Int, crease: CreaseRef); case noCreases(step: Int); case unresolvedMovingSide(step: Int); case unresolvedFace(step: Int, point: SIMD2); case stepFailed(step: Int, defects: [FoldDefect]); case interpenetration(step: Int, [Intersection]); case assignmentDisagreesWithPattern(edge: Int); case noRigidMotion(step: Int); case curveTooCoarse(step: Int); case clockwiseFace(face: Int); case missingAngle(step: Int, crease: CreaseRef); case creaseListMismatch(step: Int); case solvedAxisWindowConflict(step: Int, edge: Int); case coincidentAxisAngle(step: Int, edge: Int) }` — Task 7b adds `popTooStrained`, `missingSpine` and `invalidSpine` - `foldc -o ` — exits 0 on success, 1 naming the first failing step and its defects **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). Defaults: `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]`. **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 tree axes on some loop's cycle (the tree path between the two regions a loop crease joins), excluding the driver, as the spike does: damped Gauss–Newton on the gap between vertex copies, continued along *t*. Every other axis stays linear on its scripted window. A solved axis whose scripted window differs from the driver's is rejected rather than ignored. 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. Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it. macOS only. Never linked into the app. - [ ] **Step 1: Write the failing tests** ```swift @Test(arguments: ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"]) func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) throws { let out = try compile(FoldScript(contentsOf: fixture("\(name).foldscript")), pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold"))) #expect(structurallyEqual(out, try FoldFile(contentsOf: fixture("\(name).fold")), tolerance: 1e-12)) #expect(validate(out).isEmpty) } @Test func aCreaseThroughTwoLayersChangesBothEdges() throws { let out = try compiled("quarters") #expect(out.frames[3].edgesFoldAngle[8] == 180) #expect(out.frames[3].edgesFoldAngle[9] == -180) #expect(out.frames[3].edgesAssignment[9] == .mountain) } @Test func firstCreasedAtStepIsTheFirstStepThatMakesTheCrease() throws { // x = 1 is made by the fold-and-unfold in step 1 and refolded in step 3 #expect(try compiled("quarters").edgesFirstCreasedAtStep == [nil, nil, nil, nil, nil, nil, nil, nil, 1, 1, 2, 2]) } @Test func movingSideIsResolvedFromAContainedPoint() throws { #expect(try compiled("half").frames[1].step?.axes[0].movingFaces == [1]) } @Test func creaseGivenByEndpointsResolvesToAnEdgeIndex() throws { #expect(try compiled("half").frames[1].step?.axes[0].edge == 6) } @Test func anOverrideReplacesTheGuessForThatPair() throws { let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) let frame = file.frames[2] // the guess puts f2 (folded last) above f0; the override puts f0 above f2 let swapped = try applyOrderOverrides([OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))], to: frame.faceOrders, frame: frame, viewpoint: frame.step!.viewpoint, file: file) #expect(swapped != frame.faceOrders) #expect(throws: Never.self) { try LayerOrder(faceOrders: swapped, normals: faceNormals(frame, file)) } } @Test func aCoupledStepIsSolvedIntoCurves() throws { // decision 0001's case 3 as a script: the 140° crease drives, the 260° crease // gets a curve, the 0° crease rides on it, the 60° crease closes the loop let out = try compile(degreeFourScript(), pattern: degreeFourPattern()) let axes = try #require(out.frames[1].step?.axes) #expect(axes.contains { $0.angles != nil }) #expect(axes.contains { $0.parent != nil }) for axis in axes where axis.angles != nil { #expect(abs(axis.angles![128] - degreeFourExactAngle(axis.edge, at: 0.5)) < 1e-6) } } @Test func anUnresolvedCreaseNamesItsStep() { #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) { try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")), pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) } } @Test func aStepThatFailsValidationNamesItsStep() { #expect { try compile(FoldScript(contentsOf: fixture("angle-out-of-range.foldscript")), pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) } throws: { if case CompileError.stepFailed(step: 2, _) = $0 { true } else { false } } } @Test func guessedFaceOrdersAreAcyclic() throws { let out = try compiled("occlusion") for frame in out.frames { #expect(throws: Never.self) { try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, out)) } } } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter CompilerTests` Expected: FAIL. - [ ] **Step 3: Implement `FoldScript`, `compile`, `guessFaceOrders`, `applyOrderOverrides` and the `foldc` entry point** Every face of the crease pattern must be counterclockwise with the sheet's top side up; reject a pattern with a clockwise face (`clockwiseFace`) rather than rewinding it, since rewinding a y-down export also swaps which side is up and so swaps valley and mountain. Every solved curve has exactly 257 samples. Resolve each `CreaseRef` to an edge by nearest-endpoint match in crease-pattern coordinates with a 1e-6 tolerance. Resolve `movingSide` to a face by point-in-polygon in the crease pattern, then grow it to its connected component across edges that are not folded this step; the axis edge must lie on that set's boundary. A crease through several layers: every edge that lies on the axis line in the start frame and bounds the moving set is part of the fold, and each gets its own resulting fold angle and assignment. Produce each step's end frame by building the step and calling `FoldInterpolator.positions(at: 1)` on it, so vertex ownership, carried axes and reorientation have one implementation; Folding's `readStep(_ n: Int, in file: FoldFile) throws -> FoldStep` reads one step from frames 0…n and `readSteps` calls it for each n. The departure/arrival rule (a moving face may not have an overlapping still face on the side it departs toward in frame n − 1, or on the side it arrives from in frame n) needs the interpolator, so it is Folding's `layerMotionDefects`, built in Task 8; `foldc` runs it per step from then on. A crease found on a named crease's line through another layer takes its angle from the pattern's assignment, so `foldc` rejects such an edge (`coincidentAxisAngle`) when it becomes an axis while the named crease's scripted angle is not ±180; deriving its angle is left until a model needs it. Guess layer order by placing the moving set on the side of the existing stack it arrived from, its own layers reversed because it has turned over; this is right for plain valley and mountain folds and wrong for anything tucked between layers, which the script corrects with overrides — and the validator's consistency rules (Task 2) report the cases it gets wrong. For a `foldAndUnfold`, compute the order at the peak the same way and write it to `krz:faceOrders_midFold`. Write `faceOrders` and the mid-fold order as every overlapping pair once, `[f, g, s]` with `f < g`, as the fixtures do. After the last step, every crease folded in the last frame must carry the crease pattern's assignment; a mismatch means the script folded something the wrong way. Write JSON with sorted keys so regenerated files diff cleanly. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter CompilerTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "foldc: compile a fold script and crease pattern into a FOLD sequence" ``` --- ### Task 7b: Non-rigid steps — open, pop, close **Files:** - Create: `Packages/FoldKit/Sources/Folding/RenderMesh.swift` - Create: `Packages/FoldKit/Sources/Folding/Bending.swift` - Modify: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift` - Modify: `Packages/FoldKit/Sources/Folding/Interpenetration.swift` - Create: `Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift` - 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 - Modify: `Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift` — `tipIsBetweenBodyLayers(_:_:)` and `FoldScript.withOpenAngle(_:step:)` (see *Test helpers*) - Test: `Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift` **Interfaces:** - Consumes: Tasks 1–7. - Produces: - `struct RenderMesh: Sendable { init(file: FoldFile, spacing: Double); let vertices: [SIMD2]; 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 - `static func (RenderMesh).spacing(for file: FoldFile) -> Double` — frame 0's bounding box's longer side / 32 - `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` - `func (FoldInterpolator).meshPositions(at t: Double) -> [SIMD3]` — 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 - `func strain(_ positions: [SIMD3], mesh: RenderMesh) -> Double` — the largest relative change in a mesh edge's length - `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 - `func compilePop(step: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, file: FoldFile) throws -> PopRecord` - `CompileError` gains `popTooStrained(step: Int, strain: Double)`, `missingSpine(step: Int)` and `invalidSpine(step: Int)` (a spine on a step that is not a fold, or not folded flat) Decision 0002: an inside reverse fold has no rigid motion with the flap closed. Flagged steps move in three phases on *t*: 1. **Open**, `[0, phases[0]]`: the flap opens rigidly on its spine from 180° to `openAngle` (default 30°, measured from flat; 20° since decision 0003), carrying everything on that side of the spine. The layer nearer the step's viewpoint opens; the other holds. A script field to choose the other layer is added when a model needs it. 2. **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. 3. **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`. **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`: - builds `openAxes` (the spine as one linear axis); - builds `popped` (the reverse-fold branch with the spine held at `openAngle`, solved as in Task 7, starting each other crease at `openAngle`/180 of its travel, as the spike does). Closing the loops does not show which branch was found; a wrong branch is caught by the close reaching frame n's coordinates, the final assignment check and the validator's layer rules; - builds `closeAxes` (from `popped` to the end frame, with the spine driven and the rest solved); - checks `popped` has one position per vertex; - writes `openAngle` and `phases` into the file explicitly: 30° (20° since decision 0003) and [⅓, ⅔] are the script's defaults, and the decoder requires both. The validator rejects a pop record with the wrong number of positions, phases outside 0 < p₀ < p₁ < 1, or a non-rigid step without one (`popMalformed`); - measures the pop's strain on the step's render mesh, and fails the step above **10%**. Decision 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. - [ ] **Step 1: Write the failing tests** ```swift @Test func aReverseFoldCompilesToANonRigidStep() throws { let out = try compiled("reverse") let step = try #require(out.frames[2].step) #expect(step.nonRigid) #expect(step.pop?.openAngle == 30) #expect(step.technique == .insideReverse) } @Test func aReverseFoldWithoutASpineIsRejected() { #expect(throws: CompileError.missingSpine(step: 2)) { try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withoutSpine(step: 2), pattern: FoldFile(contentsOf: fixture("reverse-cp.fold"))) } } @Test func theOpenAndCloseLegsAreRigid() throws { // checked on the FOLD edges, as rigid steps are; mesh slivers at creases make relative mesh strain noisy let file = try compiled("reverse") let step = try readSteps(file)[1] let i = FoldInterpolator(file: file, step: step) for n in 0...256 { let t = Double(n) / 256 guard t <= step.pop!.phases.lowerBound || t >= step.pop!.phases.upperBound else { continue } #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)") } } @Test func thePopStaysWithinTheBound() throws { let file = try compiled("reverse") let step = try readSteps(file)[1] let i = FoldInterpolator(file: file, step: step) let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()! #expect(worst <= 0.10) } @Test func theStepEndsOnItsEndFrame() throws { let file = try compiled("reverse") let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) #expect(zip(i.positions(at: 1), file.frames[2].verticesCoords).allSatisfy { simd_distance($0, $1) < 1e-9 }) } @Test func nothingPassesThroughAnything() throws { let file = try compiled("reverse") let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty) } @Test func theTipLandsBetweenTheFlapsLayers() throws { // 97% of the way through the closing phase, a point of the tip lies between the body's two layers let file = try compiled("reverse") let step = try readSteps(file)[1] let i = FoldInterpolator(file: file, step: step) let upper = step.pop!.phases.upperBound #expect(tipIsBetweenBodyLayers(i.positions(at: upper + 0.97 * (1 - upper)), file)) } @Test func aFlapOpenedOnlyTo60DegreesIsRejected() { #expect { try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withOpenAngle(60, step: 2), pattern: FoldFile(contentsOf: fixture("reverse-cp.fold"))) } throws: { if case CompileError.popTooStrained(step: 2, _) = $0 { true } else { false } } } @Test func thePopFitsInAFrameBudget() throws { let file = try compiled("reverse") let step = try readSteps(file)[1] let i = FoldInterpolator(file: file, step: step) let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) let elapsed = ContinuousClock().measure { for n in 0..<100 { _ = i.meshPositions(at: lo + Double(n) / 100 * (hi - lo)) } } #expect(elapsed / 100 < .milliseconds(4)) } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests` Expected: FAIL. - [ ] **Step 3: Implement `RenderMesh`, the pop in `FoldInterpolator`, `meshInterpenetrations`, and `compilePop`** `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. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "Non-rigid steps: open, pop, close" ``` --- ### Task 8: `foldlint` and the model catalogue gate **Files:** - Create: `Packages/FoldKit/Sources/foldlint/main.swift` - Create: `Packages/FoldKit/Sources/Models/ModelLibrary.swift` - Create: `Packages/FoldKit/Sources/Models/Resources/cup.fold` - Create: `Models/cup.foldscript` - Create: `Models/cup-cp.fold` - Create: `docs/authoring/cup.md` - Test: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` **Interfaces:** - Consumes: Tasks 1–7b. - Produces: - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }` - `foldlint ...` — runs `validate` and then `readSteps`, which rejects step records the validator does not check; exits 0 when clean, 1 with one defect per line - `func layerMotionDefects(_ file: FoldFile) -> [FoldDefect]` in Folding, and `FoldDefect.movesThroughStillFace(step:moving:still:)` — the departure/arrival rule. Departure is read just after a face starts moving, against frame n − 1's order; arrival just before it stops, against frame n's. A non-rigid step uses its open axes for departure and its close axes for arrival, and the faces that open on the spine count as moving. `layerMotionDefects(step:in:)` checks one step on frames 0…n; `foldlint`, the catalogue gate and `foldc` (per step, as a `stepFailed`) run it. The arrival read time is the one the layer guess uses, so for a step without overrides the arrival check cannot disagree with the guess; it checks overrides and departures **The cup is the model authored here, not the crane.** Six steps — five folds of one axis each and a turn-over — no reverse folds, six layers where the corner flaps cross and eight in the centre once both top flaps are down. It exercises script, compile, validate, interpolate and the catalogue gate end to end without exercising coupled steps or deep stacks at the same time. The version authored folds the top flaps down — the front one, then after the turn-over the back one — rather than tucking them into the pocket, and it ends flat. Step 1's instruction starts "Valley fold"; Task 14's accessibility test reads it. Its crease pattern and `.foldscript` are committed next to the generated `.fold`, so the model regenerates rather than only being editable. `docs/authoring/cup.md` records the crease pattern's provenance and every layer-order override and why. - [ ] **Step 1: Write the failing tests** ```swift @Test func everyShippedStepEndsOnItsEndFrame() throws { // the step records and the frames must agree: interpolating a step to t = 1 reproduces frame n for file in try ModelLibrary.all() { for step in try readSteps(file) { let i = FoldInterpolator(file: file, step: step) #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords) .allSatisfy { simd_distance($0, $1) < 1e-6 * sheetSize(file) }, "\(file.fileTitle ?? "?") step \(step.index)") } } } @Test func everyShippedModelValidates() throws { for file in try ModelLibrary.all() { #expect(validate(file).isEmpty, "\(file.fileTitle ?? "?")") } } @Test func everyShippedModelReadsItsSteps() throws { for file in try ModelLibrary.all() { #expect(try readSteps(file).count == file.stepCount) } } @Test func noShippedModelStretchesAtAnyStep() throws { // flagged non-rigid steps are held to Task 0b's bound instead for file in try ModelLibrary.all() { for step in try readSteps(file) where !step.nonRigid { let i = FoldInterpolator(file: file, step: step) for t in stride(from: 0.0, through: 1.0, by: 1.0 / 256) { #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6, "\(file.fileTitle ?? "?") step \(step.index) t \(t)") } } } } @Test func noShippedModelInterpenetratesAtAnyStep() throws { // non-rigid steps bend their faces; everyFlaggedStepStaysWithinTheBound checks them on the mesh for file in try ModelLibrary.all() { for step in try readSteps(file) where !step.nonRigid { let i = FoldInterpolator(file: file, step: step) #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty, "\(file.fileTitle ?? "?") step \(step.index)") } } } @Test func everyModelIsAttributedAsTraditional() throws { for file in try ModelLibrary.all() { #expect(file.fileAuthor == "Traditional") } } @Test func everyShippedModelRegeneratesFromItsScript() throws { for name in try ModelLibrary.names() { let recompiled = try compile(FoldScript(contentsOf: script(name)), pattern: FoldFile(contentsOf: pattern(name))) #expect(structurallyEqual(recompiled, try ModelLibrary.model(named: name), tolerance: 1e-12), "\(name)") } } @Test func everyFlaggedStepStaysWithinTheBound() throws { // decision 0002: 10% largest edge strain on the render mesh, and nothing passes through anything for file in try ModelLibrary.all() { for step in try readSteps(file) where step.nonRigid { let i = FoldInterpolator(file: file, step: step) let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) let worst = (0...128).map { strain(i.meshPositions(at: lo + Double($0) / 128 * (hi - lo)), mesh: i.mesh) }.max()! #expect(worst <= 0.10, "\(file.fileTitle ?? "?") step \(step.index)") #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty) } } } @Test func theCatalogueContainsTheCup() throws { #expect(try ModelLibrary.names() == ["cup"]) } @Test func theCupContainsATurnOverStep() throws { #expect(try readSteps(ModelLibrary.model(named: "cup")).contains { $0.kind == .turnOver }) } @Test func foldlintExitsNonZeroOnADefectiveFile() throws { #expect(try runFoldlint(on: fixture("bad-index.fold")).exitCode == 1) } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests` Expected: FAIL. - [ ] **Step 3: Implement `ModelLibrary`, `foldlint`, and author the cup's crease pattern and script** Iterate the cup against `foldc` and `foldlint` until clean, adding `faceOrders` overrides to the script where the interpenetration checker or the validator's layer-order rules object. The cup's turn-over step is what Task 13's gesture will be built against, so it must be present and correct here. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit Models docs/authoring git commit -m "Model library, foldlint and the cup" ``` --- ### Task 9: Diagram generation with layer-aware occlusion **Files:** - Create: `Packages/FoldKit/Sources/Notation/DiagramStyle.swift` - Create: `Packages/FoldKit/Sources/Notation/DiagramBuilder.swift` - Create: `Packages/FoldKit/Sources/Notation/EdgeOcclusion.swift` - Test: `Packages/FoldKit/Tests/NotationTests/DiagramTests.swift` - Test: `Packages/FoldKit/Tests/NotationTests/Snapshots/` (golden images, and `NOTATION.md` recording each symbol choice and its source) **Interfaces:** - Consumes: Task 1–5 and Task 8 (the cup). - Produces: - `enum DiagramLine: Equatable, Sendable { case solid, light, dashed, dashDot }` - `enum DiagramArrow: Equatable, Sendable { case valleyFold(from: SIMD2, over: SIMD2, to: SIMD2); case mountainFold(from: SIMD2, over: SIMD2, to: SIMD2); case foldAndUnfold(from: SIMD2, over: SIMD2, to: SIMD2, mountain: Bool); case technique(StepTechnique, at: SIMD2, toward: SIMD2); case turnOver(TurnOverAxis); case rotate(degrees: Double); case repeatMark(of: Int) }` - `struct DiagramEdge: Equatable, Sendable { let edge: Int; let from: SIMD2; let to: SIMD2; let style: DiagramLine }` - `struct Diagram: Equatable, Sendable { let edges: [DiagramEdge]; let arrows: [DiagramArrow] }` - `func buildDiagram(file: FoldFile, step: FoldStep) -> Diagram` — draws frame `step.index − 1` with step `step.index`'s creases and arrows - `func visibleSegments(of edge: Int, frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) -> [(SIMD2, SIMD2)]` - `struct DiagramStyle: Sendable` The view is orthographic from the step's authored `viewpoint` and does **not** rotate when the model is orbited. This task owns Review Focus item 5. Edge classes, for the diagram of step n drawing frame n − 1: `B` edges and creases folded in frame n − 1 are solid; creases made earlier and flat again are light; step n's creases (every edge coincident with an axis) are dashed for a valley and dash-dot for a mountain **as seen from the viewpoint**: the axis's turn `Δ` (`endAngle − startAngle`, or `peakAngle − startAngle` for `foldAndUnfold`) moves the moving face toward its own normal, so the fold is a valley as seen when `sign(Δ) · sign(n · eye) > 0`, with `n` the moving face's normal in frame n − 1. FOLD's assignment is relative to each face's own normal and cannot be used: on a flipped layer, or after a turn-over, it names the opposite fold, and coincident edges on different layers disagree; creases whose `edges_krz:firstCreasedAtStep` is later than n are not drawn. Arrows: a `plain` step gets one valley-fold or mountain-fold arrow per axis, by the same as-seen rule; a named technique gets that technique's arrows from the reference and no per-axis arrows; reorientation and repeat steps get their symbols. Reference, per the spec: Randlett's conventions in *The Art of Origami* (1961) and the symbol set as summarised by OrigamiUSA; where they differ OrigamiUSA's is used, and the choice is recorded in `Snapshots/NOTATION.md`. - [ ] **Step 1: Write the failing tests** ```swift @Test func valleyCreaseOfThisStepIsDashed() throws { #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .dashed }.map(\.edge) == [6]) } @Test func mountainCreaseOfThisStepIsDashDot() throws { #expect(try diagram("mountain.fold", step: 1).edges.filter { $0.style == .dashDot }.map(\.edge) == [6]) } @Test func valleyAndMountainAreAsSeenNotAsAssigned() throws { // quarters step 3 folds both layers; the top layer is flipped, so its edge e9 is // assigned M, but the fold is a valley as seen and nothing is dash-dot let d = try diagram("quarters.fold", step: 3) #expect(d.edges.contains { $0.style == .dashed }) #expect(!d.edges.contains { $0.style == .dashDot }) #expect(d.arrows.contains { if case .valleyFold = $0 { true } else { false } }) } @Test func anEdgeUnderASeamIsHidden() throws { // quarters step 3 draws frame 2: e8 lies under the seam between f3 and f2 #expect(try !diagram("quarters.fold", step: 3).edges.contains { $0.edge == 8 }) } @Test func boundaryEdgesAreSolid() throws { #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .solid }.count == 6) } @Test func aCreaseMadeEarlierAndFlatAgainIsLight() throws { // quarters step 2 draws frame 1, after the fold-and-unfold on x = 1 #expect(Set(try diagram("quarters.fold", step: 2).edges.filter { $0.style == .light }.map(\.edge)) == [8, 9]) } @Test func creasesNotYetMetAreNotDrawnAtAll() throws { // frame 0 carries the y = 1 creases too; step 1's diagram must not show them #expect(try diagram("quarters.fold", step: 1).edges.allSatisfy { ![10, 11].contains($0.edge) }) } @Test func edgesOccludedByLayersAboveThemAreOmitted() throws { // occlusion step 3 draws frame 2: f0's raw edge from (2,2) to (2,0) is under the strip #expect(try !diagram("occlusion.fold", step: 3).edges.contains { $0.edge == 0 }) } @Test func anEdgePartlyOccludedIsClippedNotDropped() throws { // f0's raw edge from (0,2) to (2,2) is covered for x in [1, 2] let segments = try visibleSegmentsOf("occlusion.fold", edge: 7, inFrame: 2) #expect(segments.count == 1) #expect(abs(segmentLength(segments[0]) - 1) < 1e-9) } @Test func aPlainMultiAxisStepGetsOneArrowPerAxis() throws { let arrows = try diagram("letter.fold", step: 1).arrows #expect(arrows.filter { if case .valleyFold = $0 { true } else { false } }.count == 1) #expect(arrows.filter { if case .mountainFold = $0 { true } else { false } }.count == 1) } @Test func aTechniqueStepGetsItsOwnArrowsNotOnePerAxis() throws { let arrows = try diagram("letter-technique.fold", step: 1).arrows #expect(arrows.filter { if case .technique(.insideReverse, _, _) = $0 { true } else { false } }.count == 1) #expect(!arrows.contains { if case .valleyFold = $0 { true } else if case .mountainFold = $0 { true } else { false } }) } @Test func foldAndUnfoldStepGetsTheReturnHead() throws { #expect(try diagram("quarters.fold", step: 1).arrows .contains { if case .foldAndUnfold = $0 { true } else { false } }) } @Test func turnOverStepCarriesTheTurnOverSymbol() throws { #expect(try diagram("half.fold", step: 2).arrows.contains(.turnOver(.vertical))) } @Test func rotateStepCarriesItsDegrees() throws { #expect(try diagram("half.fold", step: 3).arrows.contains(.rotate(degrees: 90))) } @Test func aRepeatedStepCarriesTheRepeatMark() throws { #expect(try diagram("letter-sequential.fold", step: 2).arrows.contains(.repeatMark(of: 1))) } @Test func everyStepMatchesItsGoldenImage() throws { for name in ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"] { let file = try FoldFile(contentsOf: fixture("\(name).fold")) for step in try readSteps(file) { try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)") } } let cup = try ModelLibrary.model(named: "cup") for step in try readSteps(cup) { try expectSnapshot(render(buildDiagram(file: cup, step: step)), named: "cup-\(step.index)") } } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter DiagramTests` Expected: FAIL. - [ ] **Step 3: Implement the types, `buildDiagram` and `visibleSegments`** Project through the viewpoint's orthographic matrix. Classify each edge as above. Clip each edge against the **union** of the projected faces `order` places above either of the edge's incident faces, and emit the surviving segments, drawing coincident segments once. Clipping against each face separately would keep an edge lying under the seam between two adjacent upper faces — e8 in quarters frame 2 lies on the boundary of f3 and of f2 but inside their union. An edge on the outer boundary of that union is not hidden. Subdivision edges are never drawn. A face hides an edge when it follows either of the edge's faces in their shared cluster, from `LayerOrder.clusters` looking along −`eye`; faces in other clusters do not occlude, which holds while every diagram frame is flat. Golden images are recorded when missing or with `FOLD_RECORD_SNAPSHOTS=1` (the test fails when it records), compared at 24/255 per channel, inspected by eye against the reference, then committed. The drawing itself is Notation's, so the app's diagram and the goldens are one drawing. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter DiagramTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "Diagram generation with layer-aware edge occlusion" ``` --- ### Task 10: The Metal paper renderer **Files:** - Create: `Packages/FoldKit/Sources/Folding/Camera.swift` - Create: `Packages/FoldKit/Sources/Renderer/PaperRenderer.swift` - Create: `Packages/FoldKit/Sources/Renderer/Shaders.metal` - Test: `Packages/FoldKit/Tests/FoldingTests/CameraTests.swift` - Test: `Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift` **Interfaces:** - Consumes: Tasks 1–5 and 7b (`RenderMesh`). - Produces: - `struct Camera: Sendable { var eye: SIMD3; var target: SIMD3; var up: SIMD3; 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` - `func (Camera).viewProjection(aspect: Double) -> simd_double4x4` — view and perspective projection combined, to clip space - `var (Camera).viewDirection: SIMD3 { get }` — unit vector from `eye` toward `target` - `final class PaperRenderer { init(device: MTLDevice) throws }` - `func (PaperRenderer).render(positions: [SIMD3], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera, faceColours: [SIMD4]? = 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 Depth 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: - clusters come from Task 5, already resolved against `camera.viewDirection`, over FOLD faces, never render-mesh triangles; compute membership once per *t* and re-sort only when the camera moves; - each cluster is drawn back-to-front in its order with depth test on (less-or-equal) and depth **writes off**, so stacked faces resolve by order rather than by z; - then the same cluster is drawn again **depth-only** (colour writes off), so that clusters drawn after it are hidden behind it. Without this pass a cluster writes no depth and anything drawn later draws over it. Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3. During a non-rigid step the faces that open on the spine move, but `FoldStep.movingFaceUnion` holds only the main axes' faces (the pop's held faces depend on that). `LayerOrder.active`'s rewrite of mixed moving/still pairs must use the set `layerMotionDefects` uses — the main, open and close axes' faces — made a named `FoldStep` property here (`allMovingFaces`) rather than a second copy. The pop's `SparseCholesky` factor is `@unchecked Sendable`; confirm concurrent solves on one factor are safe, or serialise them, before the renderer calls the interpolator from more than one thread. `Shaders.metal` is a copied resource compiled at `PaperRenderer.init` with `makeLibrary(source:options:)`: SwiftPM can compile it with the Metal toolchain (*Setup* step 4), but then warns on every build. - [ ] **Step 1: Write the failing tests** The 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]]`). ```swift @Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() { let c = Camera(eye: SIMD3(0, 0, 5), target: .zero, up: SIMD3(0, 1, 0), fieldOfView: .pi / 4) let p = c.viewProjection(aspect: 1.5) * SIMD4(0, 0, 0, 1) #expect(abs(p.x / p.w) < 1e-12 && abs(p.y / p.w) < 1e-12) #expect(c.viewDirection == SIMD3(0, 0, -1)) } @Test func coplanarStackedFacesDoNotZFight() throws { let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [1, 0])], camera: cameraAbove(), faceColours: [red, green]) #expect(uniqueColours(pixels) == [red]) } @Test func clusterOrderDeterminesWhichCoplanarFaceIsVisible() throws { let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [0, 1])], camera: cameraAbove(), faceColours: [red, green]) #expect(uniqueColours(pixels) == [green]) } @Test func nearlyCoplanarFacesDoNotZFight() throws { // face 0 tilted 1° about its left edge, resting on face 1, in one cluster let pixels = try renderToPixels(squareOverATiltedSquare(degrees: 1), clusters: [CoplanarCluster(faces: [1, 0])], camera: cameraAbove(), faceColours: [red, green]) #expect(uniqueColours(pixels) == [red]) } @Test func facesSeparatedInSpaceAreResolvedByDepthNotByOrder() throws { // face 0 is nearer the camera but drawn first let pixels = try renderToPixels(separatedSquares(), clusters: [CoplanarCluster(faces: [0]), CoplanarCluster(faces: [1])], camera: cameraAbove(), faceColours: [red, green]) #expect(dominantColour(pixels) == red) } @Test func aStackDrawnFirstStillHidesAFaceBehindItDrawnLater() throws { // faces 0 and 1 stacked near the camera, face 2 farther away and drawn last let pixels = try renderToPixels(nearStackAndFarSquare(), clusters: [CoplanarCluster(faces: [1, 0]), CoplanarCluster(faces: [2])], camera: cameraAbove(), faceColours: [red, green, blue]) #expect(dominantColour(pixels) == red) } @Test func orbitingUnderneathShowsTheBottomOfTheStack() throws { // clusters computed by Task 5 for each camera, as the app does let above = try renderStackWithComputedClusters(camera: cameraAbove(), faceColours: [red, green]) let below = try renderStackWithComputedClusters(camera: cameraBelow(), faceColours: [red, green]) #expect(uniqueColours(above) == [red]) #expect(uniqueColours(below) == [green]) } @Test func backOfPaperRendersInTheBackColour() throws { let pixels = try renderToPixels(singleSquareFacingAway(), clusters: [CoplanarCluster(faces: [0])], camera: cameraAbove()) #expect(uniqueColours(pixels) == [backColour]) } ``` These require a Metal device; the target skips when `MTLCreateSystemDefaultDevice()` is nil. `uniqueColours` ignores the background. - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"` Expected: FAIL. - [ ] **Step 3: Implement `Camera`, `PaperRenderer` and the shaders** One 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. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Packages/FoldKit git commit -m "Metal paper renderer with hybrid depth and cluster ordering" ``` --- ### Task 11: App shell, model list and the step layout **Files:** - Create: `App/project.yml` - Create: `App/Sources/FoldApp.swift` - Create: `App/Sources/ModelListView.swift` - Create: `App/Sources/StepView.swift` - Create: `App/Sources/DiagramCanvas.swift` - Create: `App/Sources/PaperView.swift` - Create: `App/Sources/Info.plist` - Test: `App/UITests/StepNavigationTests.swift` **Interfaces:** - Consumes: `ModelLibrary`, `readSteps`, `FoldInterpolator` (with `mesh` and `meshPositions(at:)`), `RenderMesh`, `LayerOrder`, `buildDiagram`, `PaperRenderer`, `Camera`. - Produces: - `struct ModelListView: View` - `struct StepView: View` — `init(model: FoldFile, step: Int)`, step counted from 1 - `struct DiagramCanvas: View` — `init(diagram: Diagram, style: DiagramStyle)` - `struct PaperView: View` — `init(positions: [SIMD3], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera)`, an `MTKView` wrapped for SwiftUI; positions come from `FoldInterpolator.meshPositions(at:)` and the mesh from `FoldInterpolator.mesh` `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`. `DiagramCanvas` draws through Notation's public CoreGraphics drawing function (via `GraphicsContext.withCGContext`), the same one Task 9's golden images are rendered with, so the snapshots hold the diagram the user sees; it adds no glyph geometry of its own. `PaperView` computes cluster membership once per *t* and re-sorts only when the camera moves; `LayerOrder.clusters` computes both together, so add the split there if profiling on device shows the per-frame cost matters. Reuse the vertex buffer between frames, and give the depth texture `.memoryless` storage on iOS. - [ ] **Step 1: Write the failing UI tests** ```swift func testCupOpensAtStepOne() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() XCTAssertEqual(app.staticTexts["step.index"].label, "1") } func testStepNeverAdvancesWithoutTheUserCompletingTheFold() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() sleep(3) XCTAssertEqual(app.staticTexts["step.index"].label, "1") } func testTheDiagramIsCaptionedWithTheStepsInstruction() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() XCTAssertTrue(app.staticTexts["diagram.caption"].label.hasPrefix("Valley fold")) } ``` Completing a step needs Task 12's gesture and orbiting needs Task 14's; their tests are written there. - [ ] **Step 2: Run tests to verify they fail** Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test` Expected: FAIL — no such project. - [ ] **Step 3: Generate the project and implement the shell, list, step layout and both canvases** - [ ] **Step 4: Run tests to verify they pass** Run: `xcodegen generate --spec App/project.yml`, then as above. Expected: PASS. - [ ] **Step 5: Commit** ```bash git add App git commit -m "App shell, model list and step layout" ``` --- ### Task 12: The fold gesture **Files:** - Create: `App/Sources/FoldGesture.swift` - Create: `Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift` - Test: `Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift` - Test: `App/UITests/FoldGestureTests.swift` **Interfaces:** - Consumes: Task 3, 4 and 7b types; `Camera` (in `Folding`) from Task 10. - Produces: - `struct FoldParameterMapping: Sendable { init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2) }` - `func (FoldParameterMapping).parameter(grabbedAt: SIMD2, translation: SIMD2, current: Double) -> Double` — clamped to 0...1 - `var (FoldParameterMapping).path: [SIMD2] { get }` — the first moving set's centroid in screen points at 129 samples of `t` - `var (FoldParameterMapping).isDegenerate: Bool { get }` — path under 8 points long This task owns Review Focus item 4. The 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. - [ ] **Step 1: Write the failing tests** ```swift @Test func theFacetTracksTheFinger() throws { let m = try mapping("half.fold", step: 1) // viewed from above let target = m.path[32] // t = 0.25 let t = m.parameter(grabbedAt: m.path[0], translation: target - m.path[0], current: 0) #expect(abs(t - 0.25) < 0.01) } @Test func dragPerpendicularToThePathDoesNotAdvanceTheFold() throws { let m = try mapping("half.fold", step: 1) let along = simd_normalize(m.path[1] - m.path[0]) let perp = SIMD2(-along.y, along.x) #expect(m.parameter(grabbedAt: m.path[0], translation: perp * 50, current: 0) < 0.01) } @Test func parameterIsClampedToUnitRange() throws { let m = try mapping("half.fold", step: 1) let along = simd_normalize(m.path[128] - m.path[0]) #expect(m.parameter(grabbedAt: m.path[0], translation: along * 100_000, current: 0) == 1) #expect(m.parameter(grabbedAt: m.path[0], translation: along * -100_000, current: 0) == 0) } @Test func headOnFoldIsReportedDegenerate() throws { #expect(try mappingForFoldTowardTheCamera().isDegenerate) } @Test func degenerateMappingFallsBackToVerticalDrag() throws { let m = try mappingForFoldTowardTheCamera() #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 50), current: 0) > 0.1) } @Test func theMappingIsNeverInfinitelySensitive() throws { let m = try mappingForFoldTowardTheCamera() #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2) } @Test func aNonRigidStepIsDraggedPhaseByPhase() throws { // following the path's own samples in order reaches t = 1 without ever going back let m = try FoldParameterMapping(file: compiled("reverse"), step: readSteps(compiled("reverse"))[1], camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4), viewportSize: SIMD2(800, 600)) var t = 0.0 for p in m.path.dropFirst() { let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) #expect(next >= t - 1e-9) t = next } #expect(t > 0.99) } @Test func foldAndUnfoldGoesOutThenBack() throws { let m = try mapping("quarters.fold", step: 1) let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0) #expect(abs(atPeak - 0.5) < 0.01) let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak) #expect(back > 0.99) } ``` `App/UITests/FoldGestureTests.swift`: ```swift func testCompletingAStepAdvancesToTheNext() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() completeCurrentFold(app) // drag along the moving facet's path to t = 1, then lift XCTAssertEqual(app.staticTexts["step.index"].label, "2") } func testReleasingPartwayLeavesTheStepWhereItIs() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() dragCurrentFold(app, to: 0.5) let released = app.otherElements["fold.paper"].value as? String sleep(2) XCTAssertEqual(app.staticTexts["step.index"].label, "1") XCTAssertEqual(app.otherElements["fold.paper"].value as? String, released) XCTAssertNotEqual(released, "0%") } ``` The paper view's accessibility value is the fold parameter as a percentage. - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests` Expected: FAIL. - [ ] **Step 3: Implement `FoldParameterMapping` and `FoldGesture`** The step completes when the parameter is 1 and the finger lifts; the release position counts as the finger's last position. Releasing below 1 leaves the paper where it is. Screen points are UIKit's (origin top-left, y down); the degenerate fallback advances with a downward drag. The path is projected at the camera target's depth rather than with per-point perspective, because under perspective a flap landing flat overshoots its end on screen; a 0.5-point end tolerance applies along the path, never across it. Segment boundaries are every axis window's ends, each fold-and-unfold's peak and each non-rigid phase's end; each segment follows an axis that moves throughout it, falls back to the vertical drag when its own path is under 8 points, and is one way. Under the launch argument `-UITesting` the app exposes the path as a hidden element `fold.path` for the UI tests' drag helpers; nothing of that is active otherwise. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`, then `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/FoldGestureTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add App Packages git commit -m "Fold gesture tracking the moving facet's screen path" ``` --- ### Task 13: The drag for turn-over and rotate steps **Files:** - Create: `App/Sources/ReorientGesture.swift` - Test: `App/UITests/ReorientGestureTests.swift` **Interfaces:** - Consumes: `FoldStep.kind`, `FoldInterpolator.positions(at:)`. - Produces: - `struct ReorientGesture` — a one-finger horizontal drag across the model drives `t` of a `turnOver` or `rotate` step as the drag's horizontal distance over the model's on-screen width, clamped to 0...1 A `turnOver` has no crease and no fold angle, so the fold drag has nothing to drive — and every one of the v1 models needs turn-overs, the crane most of all. The model reorients, not the camera: the diagram's viewpoint is fixed and the reader's mental model is of turning the paper over in their hands. The parameter follows the finger like a fold does; a flick does not complete the step, because the app never advances `t` on its own. - [ ] **Step 1: Write the failing tests** ```swift func testDraggingAcrossTheModelCompletesATurnOverStep() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() advanceToFirstTurnOverStep(app) let before = app.staticTexts["step.index"].label dragAcross(app.otherElements["fold.paper"]) XCTAssertNotEqual(before, app.staticTexts["step.index"].label) } func testFoldDragDoesNothingOnATurnOverStep() { // a fold drag on a turnOver step must leave step.index unchanged } func testReorientDragDoesNothingOnAFoldStep() { // a horizontal drag that does not follow the fold path must leave step.index unchanged } func testTurnOverReorientsTheModelNotTheCamera() { // midway through the turn-over drag the diagram is unchanged; after it, the paper // shows its back colour } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/ReorientGestureTests` Expected: FAIL. - [ ] **Step 3: Implement `ReorientGesture`** Gate the gesture on the current step's `kind`, so a fold drag and a reorient drag are never both live. A rightward drag advances and a leftward drag turns back; the width is frame n − 1's projected extent at the grab. The UI test checks the diagram and the camera (exposed under `-UITesting` as `paper.camera`) after a partial lift, since XCUITest's drag returns only on lift. - [ ] **Step 4: Run tests to verify they pass** Run: as above. Expected: PASS. - [ ] **Step 5: Commit** ```bash git add App git commit -m "Drag gesture for turn-over and rotate steps" ``` --- ### Task 14: Orbit, zoom, accessibility and release assets **Files:** - Create: `App/Sources/OrbitGesture.swift` - Create: `App/Resources/PrivacyInfo.xcprivacy` - Create: `App/UITests/AccessibilityAuditTests.swift` - Create: `AppStore/rights-basis.md` - Create: `scripts/take-screenshots.sh` **Interfaces:** - Consumes: `Camera`, `PaperView`, `FoldStep.instruction`. - Produces: - `struct OrbitGesture` — two-finger drag to `Camera` orbit, pinch to field of view `Camera.viewProjection` builds its basis from `cross(viewDirection, up)`, which is undefined when `up` is parallel to the view direction; `OrbitGesture` keeps `up` perpendicular to the view direction as it orbits, including past the poles. A folding model cannot be described by a static label, so the paper view's accessibility label is the step's authored `instruction`. `AppStore/rights-basis.md` records that every shipped model is traditional and why that matters. - [ ] **Step 1: Write the failing tests** ```swift func testEveryScreenPassesTheAccessibilityAuditAtDefaultTextSize() throws { let app = XCUIApplication(); app.launch() try app.performAccessibilityAudit() app.buttons["Cup"].tap() try app.performAccessibilityAudit() } func testEveryScreenPassesTheAuditAtTheLargestTextSize() throws { let app = XCUIApplication() app.launchArguments += ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"] app.launch() try app.performAccessibilityAudit() app.buttons["Cup"].tap() try app.performAccessibilityAudit() } func testPaperViewDescribesTheCurrentStepInWords() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() XCTAssertTrue(app.otherElements["fold.paper"].label.hasPrefix("Valley fold")) } func testTwoFingerDragOrbitsWithoutAdvancingTheFold() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() let paper = app.otherElements["fold.paper"] let before = paper.value as? String twoFingerDrag(paper) XCTAssertEqual(app.staticTexts["step.index"].label, "1") XCTAssertEqual(paper.value as? String, before) } func testDiagramDoesNotRotateWhenTheModelIsOrbited() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() let diagram = app.otherElements["diagram"].screenshot().pngRepresentation twoFingerDrag(app.otherElements["fold.paper"]) XCTAssertEqual(app.otherElements["diagram"].screenshot().pngRepresentation, diagram) } ``` - [ ] **Step 2: Run tests to verify they fail** Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/AccessibilityAuditTests` Expected: FAIL. - [ ] **Step 3: Implement `OrbitGesture`, the accessibility labels, the privacy manifest, the rights note and the screenshot script** `take-screenshots.sh` follows `krz/daybyday/scripts/take-screenshots.sh`. `PrivacyInfo.xcprivacy` declares no tracking and no collected data. XCUITest cannot make a two-finger pan, so the orbit and zoom maths are `Camera.orbited(by:)` and `Camera.zoomed(by:within:)` in Folding, unit-tested through the poles, and the UI tests use pinch and rotate. A pan or pinch that begins during a one-finger drag suspends the drag and restores its starting *t*. The paper view has a VoiceOver adjustable action that moves *t* by tenths; reaching 100% completes the step as a lift does. - [ ] **Step 4: Run tests to verify they pass** Run: as above. Expected: PASS. - [ ] **Step 5: Commit** ```bash git add App scripts AppStore git commit -m "Orbit and zoom, accessibility pass and release assets" ``` --- ### Task 14b: The step list and dragging back **Files:** - Create: `App/Sources/StepListView.swift` - Modify: `App/Sources/StepView.swift`, `App/Sources/FoldSession.swift` - Modify: `Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift` - Test: `App/UITests/StepListTests.swift`, `App/Tests/FoldSessionTests.swift`, `Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift`, `App/UITests/AccessibilityAuditTests.swift` **Interfaces:** - Consumes: Tasks 11–14. - Produces: - `struct StepListView: View` — every step's number and `instruction`, the current one marked - `func (FoldSession).open(step: Int)` — step counted from 1; loads that step at *t* = 0 with the camera at its viewpoint, as completing the step before it does **The step list.** A toolbar button (`steps.button`, label "Steps") opens the list on demand: a popover on iPad, a sheet on iPhone. The navigation title reads "Step n of N"; `step.index` stays the bare number. Choosing a step opens it at its start, frame n − 1, whatever was folded before; choosing the current step closes the list and leaves *t* alone. Nothing about the list advances *t*. **Dragging back.** A step's segments — axis windows and non-rigid phases — are crossed in both directions: the search runs outward from `current` across segment boundaries, so dragging the flap back takes *t* back through earlier windows and phases to 0. Where the path doubles back on screen at a boundary (a non-rigid step's open and pop), the segment *t* is in is kept until the finger leaves the overlap, so a finger moving along the retraced stretch neither jumps ahead nor falls back. The 0.5-point end tolerance applies at *t* = 1 only. A `foldAndUnfold` stays one way at its peak: its return half passes through the same poses as its outbound half, so dragging back after the peak is the unfold. - [ ] **Step 1: Write the failing tests** ```swift // FoldParameterTests @Test func aStaggeredStepCanBeDraggedBackPastItsWindowBoundary() throws { // follow letter-staggered's samples to t = 0.75, then back to 0: t tracks k/128 both ways } @Test func aNonRigidStepCanBeDraggedBackThroughItsPhases() throws { // follow the reverse fixture's samples to t = 1, then back: t never increases, and ends below 0.01 } @Test func aFoldAndUnfoldStillUnfoldsAfterItsPeak() throws { // quarters step 1: past 0.5, dragging back toward the start goes to 1 } ``` ```swift // StepListTests func testTheStepListOpensAChosenStepAtItsStart() { let app = XCUIApplication(); app.launch() app.buttons["Cup"].tap() app.buttons["steps.button"].tap() app.buttons["step.5"].tap() XCTAssertEqual(app.staticTexts["step.index"].label, "5") XCTAssertEqual(app.otherElements["fold.paper"].value as? String, "0%") } func testTheStepListNamesEveryStep() { // six rows for the cup, each labelled with its number and instruction } ``` `FoldSessionTests` covers `open(step:)` (the camera resets, *t* is 0, the diagram is step n's) and choosing the current step. The accessibility audit opens the list at both text sizes. - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`, then `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test` Expected: FAIL. - [ ] **Step 3: Implement the step list, `open(step:)` and two-way segments** - [ ] **Step 4: Run tests to verify they pass** Run: as above, then `-only-testing:FoldUITests/FoldGestureTests -test-iterations 100`. Expected: PASS. - [ ] **Step 5: Commit** ```bash git add App Packages git commit -m "Step list and dragging back across segments" ``` --- ### Task 15: The crane, the sampan and the box **Files:** - Create: `Models/crane.foldscript`, `Models/crane-cp.fold` - Create: `Models/sampan.foldscript`, `Models/sampan-cp.fold` - Create: `Models/box.foldscript`, `Models/box-cp.fold` - Create: `Packages/FoldKit/Sources/Models/Resources/{crane,sampan,box}.fold` - Create: `docs/authoring/{crane,sampan,box}.md` - Modify: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` — delete `theCatalogueContainsTheCup`; `theCatalogueContainsFourModels` below replaces it - Modify: `Packages/FoldKit/Tests/NotationTests/DiagramTests.swift` — golden images for every step of the three new models - Test: `Packages/FoldKit/Tests/ModelsTests/FourModelTests.swift` **Interfaces:** - Consumes: everything from Tasks 0–14. No new API. Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Published sampan sequences differ in their middle steps; `docs/authoring/sampan.md` records which sequence was authored and its source. Carried from batch D, to settle before or while authoring these models: a crease on a named crease's line through another layer with a scripted angle other than ±180 is rejected (the masu's 90° walls need its angle derived instead); `curveTooCoarse` is reported where an unreachable scripted angle is the real cause; the cycle computation has no test for several loops sharing axes (the petal fold); `compilePop` does not assert that held faces sit identically in the open pose and `popped`; a flap whose two layers also join through the body (the crane's neck and tail) fails with `noRigidMotion`, because the opening faces are found by cutting only the spine — rule on "that side of the spine" then; `structurallyEqual` must tolerate solver noise in `pop`. From batch E: Notation styles an edge between faces of two sibling axes, or between a carried axis's face and a fixed face, by one axis's turn — check the petal fold's golden for segments of one crease drawn in different styles; a step that unfolds a crease folded in frame n − 1 is drawn as a fold, with no unfold notation — decide it when the crane's petal fold and the sampan need it; occlusion's `cover` assumes faces are not edge-on in the view, which the masu's raised walls may break (R35's revisit). Task 15 ships in two merge requests. The box ships first (batch G). The crane's inside reverse folds have no rigid opening on the real crane — the opening side spans the spine — and the traditional long-form sampan's turn inside out has no rigid motion and no spine; decision 0003 measured bending the opening and found it does not work with the body held; both models ship together after it (batch G2). Decision 0003: a reverse fold opens rigidly — the whole near side turns about the spine's line, with bend lines (edges on that line through the faces crossing it, `F` in every frame, never creased) — the head opens nested on the body's spine (`openOn`), the pop is the banded slerp at a default of 20° from flat, and the render mesh is a Delaunay triangulation. During a pop, faces inside one near-coplanar cluster are left to the layer order (the author's choice), and the two halves' coincident vertices on the spine line are solved as one. The sampan ships in its short form, an open tray with flat ends; the long form with covered ends has no rigid end state as scripted and is a known gap. Shipped `.fold` files come from debug `swift run foldc`; a release build can differ by up to 9e-7° on steps solved by the loop solver's null-space step. The crane's preliminary-base collapse needs `foldc`'s loop solver to steer the free directions of a degree-6 vertex toward the linear angles, and its narrowed legs need the spine gathered only where it separates the two sides. The 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. Each `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. - [ ] **Step 1: Write the failing tests** ```swift @Test func theCatalogueContainsFourModels() throws { #expect(try Set(ModelLibrary.names()) == ["cup", "crane", "sampan", "box"]) } @Test func theCraneContainsAMultiAxisStep() throws { #expect(try readSteps(ModelLibrary.model(named: "crane")).contains { $0.axes.count > 1 }) } @Test func theCraneStacksAtLeastEightLayersSomewhere() throws { let crane = try ModelLibrary.model(named: "crane") let deepest = (0...crane.stepCount).map { stackDepth(positions: crane.frames[$0].verticesCoords, faces: crane.facesVertices) }.max() ?? 0 #expect(deepest >= 8) } @Test func everyModelWithOverlappingMovingSetsCarriesAMidFoldOrder() throws { for file in try ModelLibrary.all() { for n in 1...file.stepCount where movingSetsOverlapInProjection(step: n, file) { #expect(file.frames[n].faceOrdersMidFold != nil, "\(file.fileTitle ?? "?") step \(n)") } } } @Test func onlyTheCranesReverseFoldsAreFlagged() throws { // decision 0002: the neck, tail and head reverse folds; nothing else, unless the // sampan's or the masu's last step was flagged by a later decision let crane = try readSteps(ModelLibrary.model(named: "crane")) #expect(crane.filter(\.nonRigid).count == 3) #expect(crane.filter(\.nonRigid).allSatisfy { $0.technique == .insideReverse }) for name in ["cup", "box", "sampan"] { #expect(try readSteps(ModelLibrary.model(named: name)).allSatisfy { !$0.nonRigid }, "\(name)") } } @Test func everyModelHasAnAuthoringRecord() throws { for name in try ModelLibrary.names() { #expect(FileManager.default.fileExists(atPath: authoringDoc(name).path)) } } ``` The catalogue tests from Task 8 — validation, step reading, isometry, interpenetration, traditional attribution, regeneration from script — now run over four models instead of one and must stay green. - [ ] **Step 2: Run tests to verify they fail** Run: `swift test --package-path Packages/FoldKit --filter ModelsTests` Expected: FAIL — only the cup is in the catalogue. - [ ] **Step 3: Author the three models** Box 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 20° (decision 0003); 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. - [ ] **Step 4: Run tests to verify they pass** Run: `swift test --package-path Packages/FoldKit --filter ModelsTests` Expected: PASS. - [ ] **Step 5: Commit** ```bash git add Models Packages/FoldKit docs/authoring git commit -m "The crane, the sampan and the box" ``` --- ## Open before Task 15 - **Multi-axis steps in the app.** The fold drag's path joins each segment's followed centroid end to end, so on a multi-axis step it can leave the paper view; a short window nested inside a long one falls back to a vertical drag while the paper moves; non-rigid steps follow the axis with the most travel per phase, untested until one ships. Check all three on the crane. The catalogue gate exercises `FoldParameterMapping` on every step but not `ReorientMapping`. - On device: the fold drag's 0.5-point end tolerance is about 14° on the cup's shortest iPhone paths; check it against "the last 10° completes itself". Check that a late second finger orbits rather than folds. Measure the session and mapping build times on the crane. ## After the plan The plan delivers v1 complete: the engine, the compiler, the notation, the renderer, the app and four traditional models. Growing the catalogue needs no further engineering — the frog base, fish base, flapping bird and preliminary base are each a crease pattern, a script and a correction pass, gated by machinery that already exists. What would need new engineering: designed models, which is a permissions project before it is a code one; curved creases and wet folding, which break the rigid-flat-facet premise the whole engine rests on; and deriving layer order rather than authoring it, which is the one place this design knowingly trades authoring effort for runtime correctness and should stay that way.