Commit a11f067734

a11f06773437f729b9505cf28e3fa5d064590a32

parent: aede7e3bbc

Unsigned

cmc <hello@cleberg.net> · 2026-10-20 21:32 UTC

The app: shell, fold and reorient drags, orbit and accessibility (Tasks 11–14) (!7)

- XcodeGen project `App/project.yml` with targets Fold, FoldTests and FoldUITests.
- Model list. Step view: diagram beside the paper on iPad, above it on iPhone.
- `DiagramCanvas` draws through Notation's `drawDiagram`.
- `PaperView` is an MTKView that draws on demand.
- `FoldSession` holds the step, t, the camera and the derived state.
- `FoldParameterMapping` (Folding) and the fold drag: the moving centroid's screen path is searched outward from the current t, with a segment per axis window, fold-and-unfold peak and non-rigid phase. A degenerate path falls back to a vertical drag. The step completes only on lift at t = 1.
- `ReorientMapping` and the drag for turn-over and rotate steps. The model reorients; the camera does not.
- `Camera.orbited(by:)` and `zoomed(by:within:)`. Two-finger orbit and pinch zoom suspend a one-finger drag and restore its t. VoiceOver adjustable action in tenths.
- Accessibility audits at the default and largest text size; the caption scrolls at large sizes.
- `PrivacyInfo.xcprivacy`, `AppStore/rights-basis.md`, `scripts/take-screenshots.sh`.
- The catalogue test builds every shipped step's session inputs. The validator rejects a viewpoint whose up is along its eye.
- Models resources are processed for the app bundle.
- The plan is amended for rulings R42–R57, and lists what is open before Task 15.

Verification:
- `swift test --package-path Packages/FoldKit`: 209 tests pass.
- `xcodebuild … -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test`: 13 unit and 14 UI tests pass.
- FoldGestureTests with `-test-iterations 100`: 200/200 pass.

Closes #6

Layout: unified · split

App/Resources/PrivacyInfo.xcprivacy added +14
@@ -0,0 +1,14 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3<plist version="1.0">
4<dict>
5 <key>NSPrivacyTracking</key>
6 <false/>
7 <key>NSPrivacyTrackingDomains</key>
8 <array/>
9 <key>NSPrivacyCollectedDataTypes</key>
10 <array/>
11 <key>NSPrivacyAccessedAPITypes</key>
12 <array/>
13</dict>
14</plist>
App/Sources/DiagramCanvas.swift added +27
@@ -0,0 +1,27 @@
1import Notation
2import SwiftUI
3
4/// A step's diagram, drawn by Notation's `drawDiagram` on a white ground.
5struct DiagramCanvas: View {
6 let diagram: Diagram
7 let style: DiagramStyle
8
9 init(diagram: Diagram, style: DiagramStyle) {
10 self.diagram = diagram
11 self.style = style
12 }
13
14 var body: some View {
15 Canvas { context, size in
16 context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(.white))
17 context.withCGContext { cg in
18 cg.translateBy(x: 0, y: size.height)
19 cg.scaleBy(x: 1, y: -1)
20 drawDiagram(diagram, style: style, in: cg, size: size)
21 }
22 }
23 .accessibilityElement()
24 .accessibilityAddTraits(.isImage)
25 .accessibilityIdentifier("diagram")
26 }
27}
App/Sources/FoldApp.swift added +10
@@ -0,0 +1,10 @@
1import SwiftUI
2
3@main
4struct FoldApp: App {
5 var body: some Scene {
6 WindowGroup {
7 ModelListView()
8 }
9 }
10}
App/Sources/FoldGesture.swift added +34
@@ -0,0 +1,34 @@
1import FoldFormat
2import SwiftUI
3
4extension View {
5 /// Lets a one-finger drag anywhere on the view drive the session's fold step: the moving faces
6 /// follow the finger along their screen path, and the step completes when the finger lifts at
7 /// t = 1. Releasing below 1 leaves the paper where it is.
8 func foldGesture(_ session: FoldSession) -> some View {
9 modifier(FoldGesture(session: session))
10 }
11}
12
13private struct FoldGesture: ViewModifier {
14 let session: FoldSession
15 @GestureState private var isDragging = false
16
17 func body(content: Content) -> some View {
18 let folds = session.step.kind == .fold || session.step.kind == .foldAndUnfold
19 content
20 .gesture(drag, isEnabled: folds)
21 .onChange(of: isDragging) { _, dragging in if !dragging { session.cancelDrag() } }
22 }
23
24 /// A two-finger gesture during the drag suspends it (`FoldSession.beginOrbit()`).
25 private var drag: some Gesture {
26 DragGesture()
27 .updating($isDragging) { value, isDragging, _ in
28 if !isDragging { session.beginFoldDrag() }
29 isDragging = true
30 session.drag(translation: SIMD2(value.translation.width, value.translation.height))
31 }
32 .onEnded { value in session.endDrag(translation: SIMD2(value.translation.width, value.translation.height)) }
33 }
34}
App/Sources/FoldSession.swift added +231
@@ -0,0 +1,231 @@
1import FoldFormat
2import Folding
3import Foundation
4import Notation
5import Observation
6import simd
7
8/// One model being folded: the current step, its fold parameter `t` in 0...1, and the model
9/// view's orientation. Nothing here changes `t` on its own; the step changes only when the user
10/// completes it.
11@MainActor @Observable
12final class FoldSession {
13 let model: FoldFile
14 private(set) var step: FoldStep
15 private(set) var interpolator: FoldInterpolator
16 private(set) var diagram: Diagram
17 private var order: LayerOrder
18
19 var t = 0.0 {
20 didSet { if t != oldValue { pose() } }
21 }
22 /// The unit vector from the camera's target toward its eye.
23 var eyeDirection: SIMD3<Double> {
24 didSet { if eyeDirection != oldValue { sortClusters(); cachedMapping = nil } }
25 }
26 /// A unit vector perpendicular to `eyeDirection`.
27 var up: SIMD3<Double> {
28 didSet { cachedMapping = nil }
29 }
30 /// The camera's vertical field of view in radians, which a pinch changes.
31 var fieldOfView = FoldSession.defaultFieldOfView {
32 didSet { cachedMapping = nil }
33 }
34 /// The paper view's size in points.
35 var viewportSize = SIMD2(1.0, 1.0) {
36 didSet { cachedMapping = nil }
37 }
38 private var aspect: Double { viewportSize.x / viewportSize.y }
39
40 /// The render mesh at `t`.
41 private(set) var meshPositions: [SIMD3<Double>] = []
42 /// The FOLD faces' clusters at `t`, back to front along the camera's view direction.
43 private(set) var clusters: [CoplanarCluster] = []
44 /// The FOLD vertices at `t`.
45 private var positions: [SIMD3<Double>] = []
46 /// The centre of the bounding box of the frame the step starts from.
47 private var target: SIMD3<Double>
48 @ObservationIgnored private var cachedMapping: FoldParameterMapping?
49 /// Half the flat sheet's diagonal, the radius the camera keeps in view.
50 private let radius: Double
51 private static let defaultFieldOfView = Double.pi / 6
52 /// The fields of view a pinch can reach, from about 2.5 times the default magnification to half of it.
53 static let fieldOfViewRange = 0.21...0.98
54
55 /// `step` counts from 1. The camera starts at the step's authored viewpoint.
56 init(model: FoldFile, step n: Int) throws {
57 self.model = model
58 let step = try readStep(n, in: model)
59 self.step = step
60 interpolator = FoldInterpolator(file: model, step: step)
61 order = try LayerOrder.active(for: step, in: model)
62 diagram = buildDiagram(file: model, step: step)
63 let (low, high) = bounds(model.frames[0].verticesCoords)
64 radius = length(high - low) / 2
65 target = startCentre(model, step)
66 let eye = normalize(step.viewpoint.eye)
67 eyeDirection = eye
68 up = normalize(step.viewpoint.up - dot(step.viewpoint.up, eye) * eye)
69 pose()
70 }
71
72 /// Moves to the next step at t = 0, seen from its viewpoint, once the current step is complete.
73 /// After the last step the finished model stays at t = 1, as it does when the next step cannot
74 /// be read, which stops a Debug build.
75 func completeStep() {
76 guard t == 1, step.index + 1 < model.frames.count else { return }
77 let next: FoldStep, nextOrder: LayerOrder
78 do {
79 next = try readStep(step.index + 1, in: model)
80 nextOrder = try LayerOrder.active(for: next, in: model)
81 } catch {
82 assertionFailure("step \(step.index + 1) of \(model.fileTitle ?? "?"): \(error)")
83 return
84 }
85 step = next
86 interpolator = FoldInterpolator(file: model, step: next)
87 order = nextOrder
88 diagram = buildDiagram(file: model, step: next)
89 target = startCentre(model, next)
90 let eye = normalize(next.viewpoint.eye)
91 eyeDirection = eye
92 up = normalize(next.viewpoint.up - dot(next.viewpoint.up, eye) * eye)
93 fieldOfView = Self.defaultFieldOfView
94 cachedMapping = nil
95 t = 0
96 }
97
98 /// What maps a one-finger drag's translation to `t`.
99 private enum DragMapping {
100 case fold(FoldParameterMapping, grabbedAt: SIMD2<Double>)
101 case reorient(ReorientMapping)
102 }
103
104 /// The current one-finger drag's mapping and `t` when it began, while one is in progress.
105 @ObservationIgnored private var grab: (mapping: DragMapping, start: Double)?
106 /// Two-finger gestures in progress.
107 @ObservationIgnored private var orbits = 0
108 /// Whether a two-finger gesture began during the current drag. The drag then leaves `t` as it
109 /// was when the drag began until the finger lifts, and does not complete the step.
110 @ObservationIgnored private(set) var isDragSuspended = false
111
112 /// Called when a one-finger drag on a fold step begins: the moving faces then follow the
113 /// finger along `mapping`'s path.
114 func beginFoldDrag() {
115 let mapping = self.mapping
116 beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t)))
117 }
118
119 /// Called when a one-finger drag on a turn-over or rotate step begins: its horizontal
120 /// component then turns the model across its on-screen width, measured on the frame the step
121 /// starts from, which a vertical turn-over would otherwise shrink to an edge midway.
122 func beginReorientDrag() {
123 beginDrag(.reorient(ReorientMapping(positions: interpolator.positions(at: 0), camera: camera,
124 viewportSize: viewportSize)))
125 }
126
127 private func beginDrag(_ mapping: DragMapping) {
128 grab = (mapping, t)
129 isDragSuspended = orbits > 0
130 }
131
132 /// Moves `t` to where the drag's `translation` maps it, unless the drag is suspended.
133 func drag(translation: SIMD2<Double>) {
134 guard let grab, !isDragSuspended else { return }
135 switch grab.mapping {
136 case let .fold(mapping, grabbedAt):
137 t = mapping.parameter(grabbedAt: grabbedAt, translation: translation,
138 current: mapping.isDegenerate ? grab.start : t)
139 case let .reorient(mapping):
140 t = mapping.parameter(translation: translation.x, current: grab.start)
141 }
142 }
143
144 /// Called when the drag's finger lifts at `translation`: moves `t` there as `drag(translation:)`
145 /// does, then completes the step unless the drag was suspended.
146 func endDrag(translation: SIMD2<Double>) {
147 drag(translation: translation)
148 if !isDragSuspended { completeStep() }
149 cancelDrag()
150 }
151
152 /// Called when the drag ends by any means, including cancellation.
153 func cancelDrag() {
154 grab = nil
155 isDragSuspended = false
156 }
157
158 /// Called when a two-finger gesture begins. A drag in progress is suspended and its effect on
159 /// `t` undone.
160 func beginOrbit() {
161 orbits += 1
162 if let grab {
163 t = grab.start
164 isDragSuspended = true
165 }
166 }
167
168 func endOrbit() {
169 orbits = max(orbits - 1, 0)
170 }
171
172 /// Turns the view of the model by `angles` radians, as `Camera.orbited(by:)` does.
173 func orbit(by angles: SIMD2<Double>) {
174 let turned = camera.orbited(by: angles)
175 eyeDirection = normalize(turned.eye - turned.target)
176 up = turned.up
177 }
178
179 /// Magnifies the view of the model by `scale`, within `fieldOfViewRange`.
180 func zoom(by scale: Double) {
181 fieldOfView = camera.zoomed(by: scale, within: Self.fieldOfViewRange).fieldOfView
182 }
183
184 /// Moves `t` to the next multiple of 0.1 above it (`direction` 1) or below it (−1), within
185 /// 0...1, for VoiceOver's adjustable action. Reaching 1 completes the step, as lifting the
186 /// finger there does.
187 func adjust(_ direction: Int) {
188 let tenths = direction > 0 ? (t * 10 + 1e-9).rounded(.down) + 1 : (t * 10 - 1e-9).rounded(.up) - 1
189 t = min(max(tenths, 0), 10) / 10
190 if t == 1 { completeStep() }
191 }
192
193 /// Maps drags on the paper view to `t` for the current step, camera and view size.
194 var mapping: FoldParameterMapping {
195 if let cachedMapping { return cachedMapping }
196 let mapping = FoldParameterMapping(file: model, step: step, camera: camera, viewportSize: viewportSize)
197 cachedMapping = mapping
198 return mapping
199 }
200
201 /// Looks at the step's start frame from `eyeDirection`, far enough that a sphere of `radius`
202 /// about it fits the paper view at `aspect` at the default field of view.
203 var camera: Camera {
204 let half = Self.defaultFieldOfView / 2
205 let horizontalHalf = atan(tan(half) * aspect)
206 let distance = radius / sin(min(half, horizontalHalf))
207 return Camera(eye: target + distance * eyeDirection, target: target, up: up, fieldOfView: fieldOfView)
208 }
209
210 private func pose() {
211 positions = interpolator.positions(at: t)
212 meshPositions = interpolator.meshPositions(at: t)
213 sortClusters()
214 }
215
216 /// Membership and order come from one `LayerOrder.clusters` call, so both are recomputed when
217 /// either `t` or the view direction changes.
218 private func sortClusters() {
219 clusters = order.clusters(positions: positions, faces: model.facesVertices, viewDirection: -eyeDirection)
220 }
221}
222
223/// The centre of the bounding box of the frame `step` starts from.
224private func startCentre(_ model: FoldFile, _ step: FoldStep) -> SIMD3<Double> {
225 let (low, high) = bounds(model.frames[step.index - 1].verticesCoords)
226 return (low + high) / 2
227}
228
229private func bounds(_ points: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>) {
230 points.dropFirst().reduce((points[0], points[0])) { (simd_min($0.0, $1), simd_max($0.1, $1)) }
231}
App/Sources/Info.plist added +22
@@ -0,0 +1,22 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3<plist version="1.0">
4<dict>
5 <key>CFBundleDevelopmentRegion</key>
6 <string>$(DEVELOPMENT_LANGUAGE)</string>
7 <key>CFBundleExecutable</key>
8 <string>$(EXECUTABLE_NAME)</string>
9 <key>CFBundleIdentifier</key>
10 <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
11 <key>CFBundleInfoDictionaryVersion</key>
12 <string>6.0</string>
13 <key>CFBundleName</key>
14 <string>$(PRODUCT_NAME)</string>
15 <key>CFBundlePackageType</key>
16 <string>APPL</string>
17 <key>CFBundleShortVersionString</key>
18 <string>$(MARKETING_VERSION)</string>
19 <key>CFBundleVersion</key>
20 <string>$(CURRENT_PROJECT_VERSION)</string>
21</dict>
22</plist>
App/Sources/ModelListView.swift added +34
@@ -0,0 +1,34 @@
1import FoldFormat
2import Models
3import SwiftUI
4
5/// The shipped models by title. Choosing one opens it at step 1.
6struct ModelListView: View {
7 private let models: [FoldFile]
8 @State private var path: [Int]
9
10 init() {
11 let models = (try? ModelLibrary.all()) ?? []
12 self.models = models
13 let cup = ScreenshotScene.requested?.pose == nil ? nil : models.firstIndex { $0.fileTitle == "Cup" }
14 _path = State(initialValue: cup.map { [$0] } ?? [])
15 }
16
17 var body: some View {
18 NavigationStack(path: $path) {
19 Group {
20 if models.isEmpty {
21 ContentUnavailableView("No Models", systemImage: "square.dashed")
22 } else {
23 List(models.indices, id: \.self) { i in
24 NavigationLink(models[i].fileTitle ?? "Untitled", value: i)
25 }
26 }
27 }
28 .navigationTitle("Models")
29 .navigationDestination(for: Int.self) { i in
30 StepView(model: models[i], step: ScreenshotScene.requested?.pose?.step ?? 1)
31 }
32 }
33 }
34}
App/Sources/OrbitGesture.swift added +94
@@ -0,0 +1,94 @@
1import Folding
2import SwiftUI
3import UIKit
4
5extension View {
6 /// Lets a two-finger drag on the view orbit the session's camera around the model, and a pinch
7 /// change its field of view. Neither changes `t` or the diagram: either one beginning suspends
8 /// a one-finger drag in progress and undoes what it did to `t`.
9 func orbitGesture(_ session: FoldSession) -> some View {
10 modifier(OrbitGesture(session: session))
11 }
12}
13
14struct OrbitGesture: ViewModifier {
15 let session: FoldSession
16 /// How far the model turns per point of drag, in radians.
17 static let radiansPerPoint = 0.01
18
19 func body(content: Content) -> some View {
20 content
21 .gesture(TwoFingerPan(session: session) { translation in
22 session.orbit(by: SIMD2(translation.x, translation.y) * Self.radiansPerPoint)
23 })
24 .gesture(Pinch(session: session) { scale in session.zoom(by: scale) })
25 }
26}
27
28/// The names of the two recognizers, which may recognize together.
29private let orbitRecognizers: Set<String> = ["orbit.pan", "orbit.pinch"]
30
31private final class Simultaneous: NSObject, UIGestureRecognizerDelegate {
32 func gestureRecognizer(_ recognizer: UIGestureRecognizer,
33 shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
34 orbitRecognizers.contains(other.name ?? "")
35 }
36}
37
38/// Tells the session when the recognizer begins and ends.
39@MainActor
40private func track(_ state: UIGestureRecognizer.State, _ session: FoldSession) {
41 switch state {
42 case .began: session.beginOrbit()
43 case .ended, .cancelled, .failed: session.endOrbit()
44 default: break
45 }
46}
47
48/// Reports a two-finger drag's translation in points since the last report.
49private struct TwoFingerPan: UIGestureRecognizerRepresentable {
50 let session: FoldSession
51 let changed: (CGPoint) -> Void
52
53 func makeCoordinator(converter: CoordinateSpaceConverter) -> Simultaneous { Simultaneous() }
54
55 func makeUIGestureRecognizer(context: Context) -> UIPanGestureRecognizer {
56 let pan = UIPanGestureRecognizer()
57 pan.name = "orbit.pan"
58 pan.minimumNumberOfTouches = 2
59 pan.maximumNumberOfTouches = 2
60 pan.delegate = context.coordinator
61 return pan
62 }
63
64 func handleUIGestureRecognizerAction(_ recognizer: UIPanGestureRecognizer, context: Context) {
65 track(recognizer.state, session)
66 guard recognizer.state == .began || recognizer.state == .changed else { return }
67 let translation = recognizer.translation(in: recognizer.view)
68 recognizer.setTranslation(.zero, in: recognizer.view)
69 changed(translation)
70 }
71}
72
73/// Reports a pinch's scale since the last report.
74private struct Pinch: UIGestureRecognizerRepresentable {
75 let session: FoldSession
76 let changed: (Double) -> Void
77
78 func makeCoordinator(converter: CoordinateSpaceConverter) -> Simultaneous { Simultaneous() }
79
80 func makeUIGestureRecognizer(context: Context) -> UIPinchGestureRecognizer {
81 let pinch = UIPinchGestureRecognizer()
82 pinch.name = "orbit.pinch"
83 pinch.delegate = context.coordinator
84 return pinch
85 }
86
87 func handleUIGestureRecognizerAction(_ recognizer: UIPinchGestureRecognizer, context: Context) {
88 track(recognizer.state, session)
89 guard recognizer.state == .began || recognizer.state == .changed else { return }
90 let scale = recognizer.scale
91 recognizer.scale = 1
92 changed(scale)
93 }
94}
App/Sources/PaperView.swift added +60
@@ -0,0 +1,60 @@
1import Folding
2import MetalKit
3import Renderer
4import SwiftUI
5
6/// The folding model, drawn by `PaperRenderer` into an `MTKView` that redraws only when its
7/// inputs change. `positions` are render mesh positions, from `FoldInterpolator.meshPositions(at:)`.
8struct PaperView: UIViewRepresentable {
9 let positions: [SIMD3<Double>]
10 let mesh: RenderMesh
11 let clusters: [CoplanarCluster]
12 let camera: Camera
13
14 init(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera) {
15 self.positions = positions
16 self.mesh = mesh
17 self.clusters = clusters
18 self.camera = camera
19 }
20
21 func makeCoordinator() -> Coordinator { Coordinator() }
22
23 func makeUIView(context: Context) -> MTKView {
24 let view = MTKView(frame: .zero, device: context.coordinator.renderer?.device)
25 view.isPaused = true
26 view.enableSetNeedsDisplay = true
27 view.isOpaque = false
28 view.backgroundColor = .clear
29 view.delegate = context.coordinator
30 return view
31 }
32
33 func updateUIView(_ view: MTKView, context: Context) {
34 context.coordinator.paper = self
35 view.setNeedsDisplay()
36 }
37
38 @MainActor
39 final class Coordinator: NSObject, MTKViewDelegate {
40 let renderer = MTLCreateSystemDefaultDevice().flatMap { try? PaperRenderer(device: $0) }
41 var paper: PaperView?
42
43 func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
44 view.setNeedsDisplay()
45 }
46
47 func draw(in view: MTKView) {
48 guard let renderer, let paper, let drawable = view.currentDrawable else { return }
49 do {
50 try renderer.render(positions: paper.positions, mesh: paper.mesh, clusters: paper.clusters,
51 camera: paper.camera, into: drawable.texture)
52 } catch {
53 return
54 }
55 guard let present = renderer.commandQueue.makeCommandBuffer() else { return }
56 present.present(drawable)
57 present.commit()
58 }
59 }
60}
App/Sources/ReorientGesture.swift added +34
@@ -0,0 +1,34 @@
1import FoldFormat
2import SwiftUI
3
4extension View {
5 /// Lets a one-finger horizontal drag drive the session's turn-over or rotate step: a rightward
6 /// drag across the model's on-screen width turns it fully, a leftward drag turns it back, and
7 /// the step completes when the finger lifts at t = 1. Releasing below 1 leaves it where it is.
8 func reorientGesture(_ session: FoldSession) -> some View {
9 modifier(ReorientGesture(session: session))
10 }
11}
12
13struct ReorientGesture: ViewModifier {
14 let session: FoldSession
15 @GestureState private var isDragging = false
16
17 func body(content: Content) -> some View {
18 let reorients = session.step.kind == .turnOver || session.step.kind == .rotate
19 content
20 .gesture(drag, isEnabled: reorients)
21 .onChange(of: isDragging) { _, dragging in if !dragging { session.cancelDrag() } }
22 }
23
24 /// A two-finger gesture during the drag suspends it (`FoldSession.beginOrbit()`).
25 private var drag: some Gesture {
26 DragGesture()
27 .updating($isDragging) { value, isDragging, _ in
28 if !isDragging { session.beginReorientDrag() }
29 isDragging = true
30 session.drag(translation: SIMD2(value.translation.width, value.translation.height))
31 }
32 .onEnded { value in session.endDrag(translation: SIMD2(value.translation.width, value.translation.height)) }
33 }
34}
App/Sources/ScreenshotScene.swift added +32
@@ -0,0 +1,32 @@
1import Foundation
2
3/// App Store screens, opened by `scripts/take-screenshots.sh` with `-UITesting -screenshot <name>`.
4/// Every scene but `models` opens the cup at a step, posed and turned to show the paper in 3D.
5enum ScreenshotScene: String {
6 case models, fold, flap, cup
7
8 static let requested: ScreenshotScene? = {
9 let arguments = ProcessInfo.processInfo.arguments
10 guard arguments.contains("-UITesting"), let i = arguments.firstIndex(of: "-screenshot"),
11 i + 1 < arguments.count else { return nil }
12 return ScreenshotScene(rawValue: arguments[i + 1])
13 }()
14
15 /// The cup's step, its fold parameter, the orbit from the step's viewpoint in radians, and
16 /// the zoom.
17 var pose: (step: Int, t: Double, orbit: SIMD2<Double>, zoom: Double)? {
18 switch self {
19 case .models: nil
20 case .fold: (1, 0.55, SIMD2(0.45, -0.5), 1.2)
21 case .flap: (4, 0.6, SIMD2(0.6, 0.3), 1.6)
22 case .cup: (6, 1, SIMD2(0.5, 0.4), 2.2)
23 }
24 }
25
26 @MainActor func apply(to session: FoldSession) {
27 guard let pose else { return }
28 session.t = pose.t
29 session.orbit(by: pose.orbit)
30 session.zoom(by: pose.zoom)
31 }
32}
App/Sources/StepView.swift added +124
@@ -0,0 +1,124 @@
1import FoldFormat
2import Notation
3import SwiftUI
4
5/// One step of a model: its diagram, captioned with the step's instruction, beside the folding
6/// model on a regular-width screen and above it on a compact one.
7struct StepView: View {
8 private let title: String
9 @State private var session: FoldSession?
10 @Environment(\.horizontalSizeClass) private var horizontalSizeClass
11 @Environment(\.verticalSizeClass) private var verticalSizeClass
12
13 /// `step` counts from 1.
14 init(model: FoldFile, step: Int) {
15 title = model.fileTitle ?? "Untitled"
16 let session = try? FoldSession(model: model, step: step)
17 if let session { ScreenshotScene.requested?.apply(to: session) }
18 _session = State(initialValue: session)
19 }
20
21 var body: some View {
22 Group {
23 if let session {
24 let sideBySide = horizontalSizeClass == .regular || verticalSizeClass == .compact
25 let layout = sideBySide ? AnyLayout(HStackLayout(spacing: 0)) : AnyLayout(VStackLayout(spacing: 0))
26 layout {
27 diagram(session)
28 paper(session)
29 }
30 } else {
31 ContentUnavailableView("This Model Can't Be Shown", systemImage: "exclamationmark.triangle")
32 }
33 }
34 .navigationTitle(title)
35 .navigationBarTitleDisplayMode(.inline)
36 }
37
38 /// The caption takes the height it needs up to `captionShare` of the pane, and scrolls beyond
39 /// that, so the diagram stays in view at large text sizes.
40 private func diagram(_ session: FoldSession) -> some View {
41 GeometryReader { pane in
42 VStack(alignment: .leading, spacing: 0) {
43 DiagramCanvas(diagram: session.diagram, style: .standard)
44 .accessibilityLabel("Diagram of step \(session.step.index)")
45 ScrollView {
46 HStack(alignment: .firstTextBaseline, spacing: 12) {
47 Text("\(session.step.index)")
48 .font(.title.bold())
49 .monospacedDigit()
50 .accessibilityIdentifier("step.index")
51 Text(session.step.instruction)
52 .fixedSize(horizontal: false, vertical: true)
53 .accessibilityIdentifier("diagram.caption")
54 }
55 .frame(maxWidth: .infinity, alignment: .leading)
56 .padding()
57 }
58 .scrollBounceBehavior(.basedOnSize)
59 .frame(maxHeight: pane.size.height * Self.captionShare)
60 .fixedSize(horizontal: false, vertical: true)
61 }
62 }
63 }
64
65 private static let captionShare = 0.45
66
67 private func paper(_ session: FoldSession) -> some View {
68 PaperView(positions: session.meshPositions, mesh: session.interpolator.mesh, clusters: session.clusters,
69 camera: session.camera)
70 .onGeometryChange(for: CGSize.self) { $0.size } action: { size in
71 if size.width > 0 && size.height > 0 { session.viewportSize = SIMD2(size.width, size.height) }
72 }
73 .foldGesture(session)
74 .reorientGesture(session)
75 .orbitGesture(session)
76 .accessibilityElement()
77 .accessibilityLabel(session.step.instruction)
78 .accessibilityValue(session.t.formatted(.percent.precision(.fractionLength(0))))
79 .accessibilityAdjustableAction { direction in
80 switch direction {
81 case .increment: session.adjust(1)
82 case .decrement: session.adjust(-1)
83 @unknown default: break
84 }
85 }
86 .accessibilityIdentifier("fold.paper")
87 .overlay(alignment: .topLeading) {
88 if Self.isUITesting {
89 foldPath(session)
90 cameraValue(session)
91 }
92 }
93 }
94
95 private static let isUITesting = ProcessInfo.processInfo.arguments.contains("-UITesting")
96
97 /// For UI tests: the fold path's samples, each as x,y normalised to the paper view's frame.
98 private func foldPath(_ session: FoldSession) -> some View {
99 let mapping = session.mapping, size = session.viewportSize
100 let value = mapping.path.map { p in
101 String(format: "%.5f,%.5f", p.x / size.x, p.y / size.y)
102 }.joined(separator: " ")
103 return Color.clear
104 .frame(width: 1, height: 1)
105 .allowsHitTesting(false)
106 .accessibilityElement()
107 .accessibilityValue(value)
108 .accessibilityIdentifier("fold.path")
109 }
110
111 /// For UI tests: the camera's eye, up and field of view, to 3 decimals.
112 private func cameraValue(_ session: FoldSession) -> some View {
113 let camera = session.camera
114 let value = [camera.eye, camera.up].map { v in
115 String(format: "%.3f,%.3f,%.3f", v.x, v.y, v.z)
116 }.joined(separator: " ") + String(format: " %.3f", camera.fieldOfView)
117 return Color.clear
118 .frame(width: 1, height: 1)
119 .allowsHitTesting(false)
120 .accessibilityElement()
121 .accessibilityValue(value)
122 .accessibilityIdentifier("paper.camera")
123 }
124}
App/Tests/FoldSessionTests.swift added +162
@@ -0,0 +1,162 @@
1import FoldFormat
2import Models
3import Testing
4import simd
5@testable import Fold
6
7@MainActor
8private func cup(step: Int = 1) throws -> FoldSession {
9 let model = try #require(try ModelLibrary.all().first { $0.fileTitle == "Cup" })
10 return try FoldSession(model: model, step: step)
11}
12
13@MainActor @Test func incrementingMovesToTheNextTenth() throws {
14 let session = try cup()
15 session.adjust(1)
16 #expect(session.t == 0.1)
17 session.adjust(1); session.adjust(1)
18 #expect(session.t == 0.3)
19 session.t = 0.37
20 session.adjust(1)
21 #expect(session.t == 0.4)
22}
23
24@MainActor @Test func decrementingMovesToTheTenthBelowAndStopsAtZero() throws {
25 let session = try cup()
26 session.adjust(-1)
27 #expect(session.t == 0)
28 session.t = 0.37
29 session.adjust(-1)
30 #expect(session.t == 0.3)
31}
32
33@MainActor @Test func incrementingToTheEndCompletesTheStep() throws {
34 let session = try cup()
35 for _ in 0..<9 { session.adjust(1) }
36 #expect(session.step.index == 1 && session.t == 0.9)
37 session.adjust(1)
38 #expect(session.step.index == 2)
39 #expect(session.t == 0)
40}
41
42@MainActor @Test func incrementingOnTheLastStepStaysAtTheEnd() throws {
43 let session = try cup(step: 6)
44 for _ in 0..<12 { session.adjust(1) }
45 #expect(session.step.index == 6)
46 #expect(session.t == 1)
47}
48
49@MainActor @Test func zoomIsClampedAndOrbitAndZoomLeaveTheFoldAlone() throws {
50 let session = try cup()
51 session.t = 0.5
52 session.zoom(by: 100)
53 #expect(session.fieldOfView == FoldSession.fieldOfViewRange.lowerBound)
54 session.zoom(by: 0.001)
55 #expect(session.fieldOfView == FoldSession.fieldOfViewRange.upperBound)
56 session.orbit(by: SIMD2(0.4, -0.7))
57 #expect(session.t == 0.5)
58 #expect(session.step.index == 1)
59}
60
61@MainActor @Test func completingAStepResetsTheCameraToTheNextViewpoint() throws {
62 let session = try cup()
63 let start = session.camera
64 session.orbit(by: SIMD2(0.4, -0.7))
65 session.zoom(by: 2)
66 session.t = 1
67 session.completeStep()
68 #expect(session.step.index == 2)
69 #expect(session.eyeDirection == SIMD3(0, 0, 1))
70 #expect(session.camera.fieldOfView == start.fieldOfView)
71}
72
73/// The translation that takes a fold drag begun at `start` to `t` along the session's path, and
74/// 30 points past its end when `t` is 1.
75@MainActor
76private func translation(_ session: FoldSession, from start: Double = 0, to t: Double) -> SIMD2<Double> {
77 let m = session.mapping
78 let past = t == 1 ? simd_normalize(m.point(at: 1) - m.point(at: 127.0 / 128)) * 30 : .zero
79 return m.point(at: t) - m.point(at: start) + past
80}
81
82@MainActor
83private func cupInView(step: Int = 1) throws -> FoldSession {
84 let session = try cup(step: step)
85 session.viewportSize = SIMD2(400, 400)
86 return session
87}
88
89@MainActor @Test func anOrbitDuringADragRestoresTAndTheDragDoesNotComplete() throws {
90 let session = try cupInView()
91 session.t = 0.2
92 session.beginFoldDrag()
93 session.drag(translation: translation(session, from: 0.2, to: 1))
94 #expect(session.t == 1)
95 session.beginOrbit()
96 #expect(session.t == 0.2)
97 #expect(session.isDragSuspended)
98 session.endOrbit()
99 #expect(session.isDragSuspended)
100 session.endDrag(translation: translation(session, from: 0.2, to: 1))
101 #expect(session.step.index == 1)
102 #expect(session.t == 0.2)
103 #expect(!session.isDragSuspended)
104}
105
106@MainActor @Test func aDragThatStartsDuringAnOrbitIsSuspended() throws {
107 let session = try cupInView()
108 session.beginOrbit()
109 session.beginFoldDrag()
110 #expect(session.isDragSuspended)
111 session.endOrbit()
112 session.endDrag(translation: translation(session, to: 1))
113 #expect(session.step.index == 1)
114 #expect(session.t == 0)
115}
116
117@MainActor @Test func aDragWithoutAnOrbitCompletesAtTheEnd() throws {
118 let session = try cupInView()
119 session.beginFoldDrag()
120 session.drag(translation: translation(session, to: 1))
121 session.endDrag(translation: translation(session, to: 1))
122 #expect(session.step.index == 2)
123}
124
125@MainActor @Test func theReleasePositionIsAppliedBeforeTheLift() throws {
126 // the last movement can arrive only with the lift
127 let session = try cupInView()
128 session.beginFoldDrag()
129 session.drag(translation: translation(session, to: 0.5))
130 #expect(abs(session.t - 0.5) < 0.01)
131 session.endDrag(translation: translation(session, to: 1))
132 #expect(session.step.index == 2)
133 #expect(session.t == 0)
134}
135
136@MainActor @Test func aReleaseShortOfTheEndLeavesTWhereTheFingerLifted() throws {
137 let session = try cupInView()
138 session.beginFoldDrag()
139 session.endDrag(translation: translation(session, to: 0.5))
140 #expect(session.step.index == 1)
141 #expect(abs(session.t - 0.5) < 0.01)
142}
143
144@MainActor @Test func aTurnOverReleasedPastTheModelsWidthCompletes() throws {
145 let session = try cupInView(step: 5)
146 #expect(session.step.kind == .turnOver)
147 session.beginReorientDrag()
148 session.endDrag(translation: SIMD2(1000, 0))
149 #expect(session.step.index == 6)
150}
151
152@MainActor @Test func anOrbitAfterACancelledDragLeavesTAlone() throws {
153 let session = try cupInView()
154 session.t = 0.2
155 session.beginFoldDrag()
156 session.drag(translation: translation(session, from: 0.2, to: 0.6))
157 session.cancelDrag()
158 session.beginOrbit()
159 #expect(abs(session.t - 0.6) < 0.01)
160 #expect(!session.isDragSuspended)
161 session.endOrbit()
162}
App/UITests/AccessibilityAuditTests.swift added +145
@@ -0,0 +1,145 @@
1import XCTest
2
3/// Opens every step of the cup by the labels VoiceOver sees and runs Xcode's accessibility audit
4/// on each screen, at the default text size and at the largest accessibility size. Also checks
5/// that two-finger gestures on the paper change the view without advancing the fold or touching
6/// the diagram. XCUITest has no two-finger drag, so a pinch and a rotation stand in for it.
7final class AccessibilityAuditTests: XCTestCase {
8 static let largestText = "UICTContentSizeCategoryAccessibilityXXXL"
9 /// Elements that exist only under `-UITesting`.
10 static let testHooks: Set<String> = ["fold.path", "paper.camera"]
11
12 private var sizeName = ""
13
14 override func setUp() {
15 continueAfterFailure = true
16 }
17
18 func testEveryScreenPassesTheAccessibilityAuditAtDefaultTextSize() throws {
19 try everyScreen(textSize: nil)
20 }
21
22 func testEveryScreenPassesTheAuditAtTheLargestTextSize() throws {
23 try everyScreen(textSize: Self.largestText)
24 }
25
26 func testPaperViewDescribesTheCurrentStepInWords() {
27 let app = XCUIApplication(); app.launch()
28 app.buttons["Cup"].tap()
29 XCTAssertTrue(app.otherElements["fold.paper"].label.hasPrefix("Valley fold"))
30 }
31
32 func testTwoFingerGesturesChangeTheViewWithoutAdvancingTheFold() {
33 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
34 app.buttons["Cup"].tap()
35 let paper = app.otherElements["fold.paper"]
36 let camera = app.descendants(matching: .any)["paper.camera"]
37 XCTAssertTrue(camera.waitForExistence(timeout: 5))
38 let before = paper.value as? String
39 let cameraBefore = camera.value as? String
40 twoFingerGestures(paper)
41 XCTAssertEqual(app.staticTexts["step.index"].label, "1")
42 XCTAssertEqual(paper.value as? String, before)
43 XCTAssertNotEqual(camera.value as? String, cameraBefore)
44 }
45
46 func testDiagramDoesNotChangeWhenTheModelViewChanges() {
47 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
48 app.buttons["Cup"].tap()
49 let diagram = app.descendants(matching: .any)["diagram"]
50 let camera = app.descendants(matching: .any)["paper.camera"]
51 XCTAssertTrue(diagram.waitForExistence(timeout: 5))
52 XCTAssertTrue(camera.waitForExistence(timeout: 5))
53 let before = diagram.screenshot().pngRepresentation
54 let cameraBefore = camera.value as? String
55 twoFingerGestures(app.otherElements["fold.paper"])
56 XCTAssertNotEqual(camera.value as? String, cameraBefore)
57 XCTAssertEqual(diagram.screenshot().pngRepresentation, before)
58 }
59
60 // MARK: - Helpers
61
62 /// The model list, then every step of the cup, each advanced by the user's own drag.
63 private func everyScreen(textSize: String?) throws {
64 sizeName = textSize == nil ? "default" : "largest"
65 let app = XCUIApplication()
66 app.launchArguments = ["-UITesting"]
67 if let textSize { app.launchArguments += ["-UIPreferredContentSizeCategoryName", textSize] }
68 app.launch()
69 try audit(app, "models")
70 app.buttons["Cup"].tap()
71 let index = app.staticTexts["step.index"]
72 XCTAssertTrue(index.waitForExistence(timeout: 5))
73 while true {
74 let step = index.label
75 try audit(app, "step \(step)")
76 if app.staticTexts["diagram.caption"].label.hasPrefix("Turn over") {
77 dragAcross(app.otherElements["fold.paper"])
78 } else {
79 completeCurrentFold(app)
80 }
81 if index.label == step { break }
82 }
83 // The cup has six steps; stopping earlier means an advance failed.
84 XCTAssertEqual(index.label, "6")
85 }
86
87 private func audit(_ app: XCUIApplication, _ name: String) throws {
88 sleep(1)
89 let shot = XCTAttachment(screenshot: app.screenshot())
90 shot.name = "\(sizeName) \(name)"
91 shot.lifetime = .keepAlways
92 add(shot)
93 let screen = app.windows.firstMatch.frame
94 let navigationBar = app.navigationBars.firstMatch
95 let barFrame = navigationBar.exists ? navigationBar.frame : .null
96 let scrollFrames = app.scrollViews.allElementsBoundByIndex.map(\.frame)
97 var clipped: [String] = []
98 try app.performAccessibilityAudit { issue in
99 if self.isExpected(issue, screen: screen, barFrame: barFrame, scrollFrames: scrollFrames) { return true }
100 // Clipping is re-checked below: it is reported now and then for text that is not clipped.
101 if issue.auditType == .textClipped {
102 clipped.append(issue.element?.label ?? "")
103 return true
104 }
105 self.report(issue, name)
106 return false
107 }
108 guard !clipped.isEmpty else { return }
109 sleep(1)
110 try app.performAccessibilityAudit(for: .textClipped) { issue in
111 guard clipped.contains(issue.element?.label ?? "") else { return true }
112 self.report(issue, name)
113 return false
114 }
115 }
116
117 private func isExpected(_ issue: XCUIAccessibilityAuditIssue, screen: CGRect, barFrame: CGRect,
118 scrollFrames: [CGRect]) -> Bool {
119 if let element = issue.element, Self.testHooks.contains(element.identifier) { return true }
120 // Navigation bar buttons are drawn by the system.
121 if let element = issue.element, barFrame.intersects(element.frame) { return true }
122 // Text growth is checked by the largest-text run, where clipping shows.
123 if sizeName == "default", issue.auditType == .dynamicType { return true }
124 // Contrast is measured from pixels, so text partly off screen measures wrong.
125 if issue.auditType == .contrast, let element = issue.element, !screen.contains(element.frame) { return true }
126 // The same for the caption, which at the largest size runs past the bottom of its scroll view.
127 if issue.auditType == .contrast, let element = issue.element, element.identifier == "diagram.caption",
128 scrollFrames.contains(where: { $0.intersects(element.frame) && !$0.contains(element.frame) }) {
129 return true
130 }
131 return false
132 }
133
134 private func report(_ issue: XCUIAccessibilityAuditIssue, _ name: String) {
135 print("AUDIT [\(sizeName)] [\(name)] \(issue.auditType.rawValue) \(issue.compactDescription) :: \(issue.element?.debugDescription.prefix(200) ?? "-")")
136 }
137}
138
139/// The two-finger gestures XCUITest can make on the element: a pinch out, a pinch in and a
140/// rotation.
141func twoFingerGestures(_ element: XCUIElement) {
142 element.pinch(withScale: 1.6, velocity: 1)
143 element.pinch(withScale: 0.8, velocity: -1)
144 element.rotate(0.6, withVelocity: 1)
145}
App/UITests/FoldGestureTests.swift added +75
@@ -0,0 +1,75 @@
1import XCTest
2
3final class FoldGestureTests: XCTestCase {
4 override func setUp() {
5 continueAfterFailure = false
6 }
7
8 func testCompletingAStepAdvancesToTheNext() {
9 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
10 app.buttons["Cup"].tap()
11 completeCurrentFold(app) // drag along the moving facet's path to t = 1, then lift
12 XCTAssertEqual(app.staticTexts["step.index"].label, "2")
13 }
14
15 func testReleasingPartwayLeavesTheStepWhereItIs() {
16 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
17 app.buttons["Cup"].tap()
18 dragCurrentFold(app, to: 0.5)
19 let released = app.otherElements["fold.paper"].value as? String
20 sleep(2)
21 XCTAssertEqual(app.staticTexts["step.index"].label, "1")
22 XCTAssertEqual(app.otherElements["fold.paper"].value as? String, released)
23 XCTAssertNotEqual(released, "0%")
24 }
25}
26
27/// Drags the current step's moving faces along their path to its end, then lifts.
28func completeCurrentFold(_ app: XCUIApplication) {
29 dragCurrentFold(app, to: 1)
30}
31
32/// Drags the current step's moving faces along their path, read from `fold.path` (the app must be
33/// launched with `-UITesting`), to `fraction` of it, then lifts. Each drag is one straight
34/// press-and-drag through every 32nd sample, with short ones merged so each moves at least
35/// `minimumChord` points: a DragGesture does not begin under 10. A drag to the end continues 30
36/// points past it. Each holds before lifting, so its last position arrives before the lift.
37func dragCurrentFold(_ app: XCUIApplication, to fraction: Double) {
38 let paper = app.otherElements["fold.paper"]
39 let marker = app.descendants(matching: .any)["fold.path"]
40 XCTAssertTrue(marker.waitForExistence(timeout: 5))
41 let samples = (marker.value as? String ?? "").split(separator: " ").map { pair in
42 let xy = pair.split(separator: ",").map { Double($0)! }
43 return CGVector(dx: xy[0], dy: xy[1])
44 }
45 XCTAssertFalse(samples.isEmpty)
46 let size = paper.frame.size
47 func chord(_ a: Int, _ b: Int) -> CGVector {
48 CGVector(dx: (samples[b].dx - samples[a].dx) * size.width, dy: (samples[b].dy - samples[a].dy) * size.height)
49 }
50 func length(_ v: CGVector) -> Double { (v.dx * v.dx + v.dy * v.dy).squareRoot() }
51 let last = Int((fraction * Double(samples.count - 1)).rounded())
52 var stops = [0]
53 for i in stride(from: 32, through: last, by: 32) where length(chord(stops.last!, i)) >= minimumChord {
54 stops.append(i)
55 }
56 if stops.last != last {
57 if stops.count > 1 && length(chord(stops.last!, last)) < minimumChord {
58 stops[stops.count - 1] = last
59 } else {
60 stops.append(last)
61 }
62 }
63 for (a, b) in zip(stops, stops.dropFirst()) {
64 var end = paper.coordinate(withNormalizedOffset: samples[b])
65 if b == samples.count - 1 {
66 let d = chord(a, b), l = max(length(d), 1)
67 end = end.withOffset(CGVector(dx: d.dx / l * 30, dy: d.dy / l * 30))
68 }
69 paper.coordinate(withNormalizedOffset: samples[a])
70 .press(forDuration: 0.1, thenDragTo: end, withVelocity: .default, thenHoldForDuration: 0.3)
71 }
72}
73
74/// The shortest straight drag `dragCurrentFold` makes, in points.
75private let minimumChord = 12.0
App/UITests/ReorientGestureTests.swift added +84
@@ -0,0 +1,84 @@
1import XCTest
2
3final class ReorientGestureTests: XCTestCase {
4 override func setUp() {
5 continueAfterFailure = false
6 }
7
8 func testDraggingAcrossTheModelCompletesATurnOverStep() {
9 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
10 app.buttons["Cup"].tap()
11 advanceToFirstTurnOverStep(app)
12 let before = app.staticTexts["step.index"].label
13 dragAcross(app.otherElements["fold.paper"])
14 XCTAssertNotEqual(before, app.staticTexts["step.index"].label)
15 }
16
17 func testFoldDragDoesNothingOnATurnOverStep() {
18 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
19 app.buttons["Cup"].tap()
20 advanceToFirstTurnOverStep(app)
21 let before = app.staticTexts["step.index"].label
22 let paper = app.otherElements["fold.paper"]
23 // a downward drag longer than the fold drag's 160-point fallback throw
24 drag(paper, from: CGVector(dx: 0.5, dy: 0.05), to: CGVector(dx: 0.5, dy: 0.95))
25 XCTAssertEqual(app.staticTexts["step.index"].label, before)
26 XCTAssertEqual(paper.value as? String, "0%")
27 }
28
29 func testReorientDragDoesNothingOnAFoldStep() {
30 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
31 app.buttons["Cup"].tap()
32 // step 1 folds the bottom corner up; this drag is across that path
33 dragAcross(app.otherElements["fold.paper"])
34 XCTAssertEqual(app.staticTexts["step.index"].label, "1")
35 }
36
37 func testTurnOverReorientsTheModelNotTheCamera() {
38 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
39 app.buttons["Cup"].tap()
40 advanceToFirstTurnOverStep(app)
41 let paper = app.otherElements["fold.paper"]
42 let diagram = app.descendants(matching: .any)["diagram"]
43 let camera = app.descendants(matching: .any)["paper.camera"]
44 XCTAssertTrue(camera.waitForExistence(timeout: 5))
45 let step = app.staticTexts["step.index"].label
46 let diagramBefore = diagram.screenshot().pngRepresentation
47 let cameraBefore = camera.value as? String
48 let paperBefore = paper.screenshot().pngRepresentation
49
50 drag(paper, from: CGVector(dx: 0.3, dy: 0.5), to: CGVector(dx: 0.5, dy: 0.5))
51 let midway = paper.value as? String
52 XCTAssertNotEqual(midway, "0%")
53 XCTAssertNotEqual(midway, "100%")
54 XCTAssertEqual(app.staticTexts["step.index"].label, step)
55 XCTAssertEqual(diagram.screenshot().pngRepresentation, diagramBefore)
56 XCTAssertEqual(camera.value as? String, cameraBefore)
57
58 dragAcross(paper)
59 XCTAssertNotEqual(app.staticTexts["step.index"].label, step)
60 XCTAssertNotEqual(paper.screenshot().pngRepresentation, paperBefore)
61 }
62}
63
64/// Completes the current model's fold steps up to its first turn-over. The app must be launched
65/// with `-UITesting`.
66func advanceToFirstTurnOverStep(_ app: XCUIApplication) {
67 while !app.staticTexts["diagram.caption"].label.hasPrefix("Turn over") {
68 let step = app.staticTexts["step.index"].label
69 completeCurrentFold(app)
70 XCTAssertNotEqual(app.staticTexts["step.index"].label, step)
71 }
72}
73
74/// A rightward drag across most of the element's width, at its middle. It starts clear of the
75/// screen's left edge, where a drag would go back in the navigation stack.
76func dragAcross(_ element: XCUIElement) {
77 drag(element, from: CGVector(dx: 0.1, dy: 0.5), to: CGVector(dx: 0.9, dy: 0.5))
78}
79
80/// A straight drag between two points given as fractions of the element's frame, then a lift.
81func drag(_ element: XCUIElement, from start: CGVector, to end: CGVector) {
82 element.coordinate(withNormalizedOffset: start)
83 .press(forDuration: 0.1, thenDragTo: element.coordinate(withNormalizedOffset: end))
84}
App/UITests/StepNavigationTests.swift added +26
@@ -0,0 +1,26 @@
1import XCTest
2
3final class StepNavigationTests: XCTestCase {
4 override func setUp() {
5 continueAfterFailure = false
6 }
7
8 func testCupOpensAtStepOne() {
9 let app = XCUIApplication(); app.launch()
10 app.buttons["Cup"].tap()
11 XCTAssertEqual(app.staticTexts["step.index"].label, "1")
12 }
13
14 func testStepNeverAdvancesWithoutTheUserCompletingTheFold() {
15 let app = XCUIApplication(); app.launch()
16 app.buttons["Cup"].tap()
17 sleep(3)
18 XCTAssertEqual(app.staticTexts["step.index"].label, "1")
19 }
20
21 func testTheDiagramIsCaptionedWithTheStepsInstruction() {
22 let app = XCUIApplication(); app.launch()
23 app.buttons["Cup"].tap()
24 XCTAssertTrue(app.staticTexts["diagram.caption"].label.hasPrefix("Valley fold"))
25 }
26}
App/project.yml added +77
@@ -0,0 +1,77 @@
1name: Fold
2options:
3 bundleIdPrefix: sh.krz
4 deploymentTarget:
5 iOS: "26.0"
6packages:
7 FoldKit:
8 path: ../Packages/FoldKit
9targets:
10 Fold:
11 type: application
12 platform: iOS
13 scheme:
14 testTargets: [FoldTests, FoldUITests]
15 sources:
16 - Sources
17 - Resources
18 dependencies:
19 - package: FoldKit
20 product: FoldFormat
21 - package: FoldKit
22 product: Folding
23 - package: FoldKit
24 product: Models
25 - package: FoldKit
26 product: Notation
27 - package: FoldKit
28 product: Renderer
29 info:
30 path: Sources/Info.plist
31 properties:
32 CFBundleShortVersionString: $(MARKETING_VERSION)
33 CFBundleVersion: $(CURRENT_PROJECT_VERSION)
34 settings:
35 base:
36 PRODUCT_BUNDLE_IDENTIFIER: sh.krz.fold
37 DEVELOPMENT_TEAM: ZCNAX3VL9D
38 CODE_SIGN_STYLE: Automatic
39 SWIFT_VERSION: "6.0"
40 TARGETED_DEVICE_FAMILY: "1,2"
41 MARKETING_VERSION: "1.0.0"
42 CURRENT_PROJECT_VERSION: "1"
43 GENERATE_INFOPLIST_FILE: YES
44 INFOPLIST_KEY_CFBundleDisplayName: Fold
45 INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO
46 INFOPLIST_KEY_UILaunchScreen_Generation: YES
47 INFOPLIST_KEY_UIApplicationSceneManifest_Generation: YES
48 INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone: UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight
49 INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad: UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight
50 FoldTests:
51 type: bundle.unit-test
52 platform: iOS
53 sources: [Tests]
54 dependencies:
55 - target: Fold
56 settings:
57 base:
58 PRODUCT_BUNDLE_IDENTIFIER: sh.krz.fold.tests
59 DEVELOPMENT_TEAM: ZCNAX3VL9D
60 CODE_SIGN_STYLE: Automatic
61 SWIFT_VERSION: "6.0"
62 TARGETED_DEVICE_FAMILY: "1,2"
63 GENERATE_INFOPLIST_FILE: YES
64 FoldUITests:
65 type: bundle.ui-testing
66 platform: iOS
67 sources: [UITests]
68 dependencies:
69 - target: Fold
70 settings:
71 base:
72 PRODUCT_BUNDLE_IDENTIFIER: sh.krz.fold.uitests
73 DEVELOPMENT_TEAM: ZCNAX3VL9D
74 CODE_SIGN_STYLE: Automatic
75 SWIFT_VERSION: "5.0"
76 TARGETED_DEVICE_FAMILY: "1,2"
77 GENERATE_INFOPLIST_FILE: YES
AppStore/rights-basis.md added +18
@@ -0,0 +1,18 @@
1# Rights basis
2
3Every model the app ships is a traditional origami model: the cup, the crane,
4the sampan and the box (the masu). Traditional models have no known designer
5and are in the public domain, so the app may fold them and publish their
6diagrams.
7
8Each shipped `.fold` file has `file_author` exactly `"Traditional"`, and the
9validator rejects any other value.
10
11Models designed in the modern era are their designers' intellectual property.
12Diagramming one without the designer's permission is a copyright problem and,
13in the origami community, a serious breach. No designed model ships without
14the designer's written permission, and adding one starts with that permission,
15not with a commit.
16
17The app generates its diagrams from each model's data. They are not copied or
18traced from any published diagram.
Packages/FoldKit/Package.swift +3 −2
@@ -18,7 +18,7 @@ let package = Package(
18 .target(name: "FoldFormat"), 18 .target(name: "FoldFormat"),
19 .target(name: "Folding", dependencies: ["FoldFormat"]), 19 .target(name: "Folding", dependencies: ["FoldFormat"]),
20 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]), 20 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]),
21 .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]), 21 .target(name: "Models", dependencies: ["FoldFormat"], resources: [.process("Resources")]),
22 .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]), 22 .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]),
23 .target(name: "Renderer", dependencies: ["Folding"], resources: [.copy("Shaders.metal")]), 23 .target(name: "Renderer", dependencies: ["Folding"], resources: [.copy("Shaders.metal")]),
24 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]), 24 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]),
@@ -33,7 +33,8 @@ let package = Package(
33 .testTarget(name: "FoldCompilerTests", 33 .testTarget(name: "FoldCompilerTests",
34 dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]), 34 dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]),
35 .testTarget(name: "ModelsTests", 35 .testTarget(name: "ModelsTests",
36 dependencies: ["Models", "FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport", "foldlint"]), 36 dependencies: ["Models", "FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport", "Notation",
37 "foldlint"]),
37 .testTarget(name: "NotationTests", 38 .testTarget(name: "NotationTests",
38 dependencies: ["Notation", "Models", "Folding", "FoldFormat", "FoldKitTestSupport"], 39 dependencies: ["Notation", "Models", "Folding", "FoldFormat", "FoldKitTestSupport"],
39 resources: [.copy("Snapshots")]), 40 resources: [.copy("Snapshots")]),
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +8 −1
@@ -27,6 +27,9 @@ public enum FoldDefect: Equatable, Sendable {
27 /// In step `step`, the face `moving` departs toward the still face `still` it overlaps in 27 /// In step `step`, the face `moving` departs toward the still face `still` it overlaps in
28 /// frame n − 1, or arrives from the side of it opposite the one frame n's order gives. 28 /// frame n − 1, or arrives from the side of it opposite the one frame n's order gives.
29 case movesThroughStillFace(step: Int, moving: Int, still: Int) 29 case movesThroughStillFace(step: Int, moving: Int, still: Int)
30 /// Step `step`'s viewpoint has an `eye` or `up` of zero length, or an `up` along its `eye`, so
31 /// it names no screen-up.
32 case viewpointDegenerate(step: Int)
30} 33}
31 34
32/// Lengths are compared to within this fraction of the sheet's longer side. 35/// Lengths are compared to within this fraction of the sheet's longer side.
@@ -84,6 +87,10 @@ public func validate(_ file: FoldFile) -> [FoldDefect] {
84 if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil { 87 if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil {
85 defects.append(.foldAndUnfoldWithoutPeakOrder(step: n)) 88 defects.append(.foldAndUnfoldWithoutPeakOrder(step: n))
86 } 89 }
90 let eye = step.viewpoint.eye, up = step.viewpoint.up
91 let viewpointIsSound = length(eye) > 0 && length(up) > 0
92 && abs(dot(normalize(eye), normalize(up))) < parallelCosine
93 if !viewpointIsSound { defects.append(.viewpointDegenerate(step: n)) }
87 if step.nonRigid || step.pop != nil { 94 if step.nonRigid || step.pop != nil {
88 let wellFormed = step.pop.map { pop in 95 let wellFormed = step.pop.map { pop in
89 pop.popped.count == vertexCount && pop.phases.count == 2 96 pop.popped.count == vertexCount && pop.phases.count == 2
@@ -92,7 +99,7 @@ public func validate(_ file: FoldFile) -> [FoldDefect] {
92 if !wellFormed { defects.append(.popMalformed(step: n)) } 99 if !wellFormed { defects.append(.popMalformed(step: n)) }
93 } 100 }
94 guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue } 101 guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue }
95 if frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) { 102 if viewpointIsSound && frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) {
96 defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n)) 103 defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n))
97 } 104 }
98 defects += isometryDefects(file, step: n, tolerance: tolerance) 105 defects += isometryDefects(file, step: n, tolerance: tolerance)
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +31
@@ -619,3 +619,34 @@ private func rgba(_ image: CGImage) -> [UInt8] {
619 } 619 }
620 return bytes 620 return bytes
621} 621}
622
623/// The fold parameter mapping for step `step` (counted from 1) of a fixture, looking at the step's
624/// start frame from its viewpoint, two sheet sizes away, in an 800 × 600 viewport.
625public func mapping(_ fixtureName: String, step: Int) throws -> FoldParameterMapping {
626 let file = try FoldFile(contentsOf: fixture(fixtureName))
627 let s = try readStep(step, in: file)
628 let points = file.frames[step - 1].verticesCoords
629 let centre = (points.dropFirst().reduce(points[0], simd_min) + points.dropFirst().reduce(points[0], simd_max)) / 2
630 let camera = Camera(eye: centre + normalize(s.viewpoint.eye) * 2 * sheetSize(file), target: centre,
631 up: s.viewpoint.up, fieldOfView: .pi / 4)
632 return FoldParameterMapping(file: file, step: s, camera: camera, viewportSize: SIMD2(800, 600))
633}
634
635/// `half.fold`'s step 1 stopped at 30°, seen along the chord of its moving face's centroid, so the
636/// centroid travels almost along the view direction.
637public func mappingForFoldTowardTheCamera() throws -> FoldParameterMapping {
638 let file = try FoldFile(contentsOf: fixture("half.fold"))
639 let full = try readStep(1, in: file)
640 let a = full.axes[0]
641 let step = FoldStep(index: 1, kind: .fold, instruction: full.instruction,
642 axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction,
643 movingFaces: a.movingFaces, startAngle: 0, endAngle: 30)],
644 viewpoint: full.viewpoint)
645 // f1's centroid turns about x = 1 from (1.5, 1, 0) to (1 + 0.5 cos 30°, 1, 0.5 sin 30°)
646 let start = SIMD3(1.5, 1, 0.0)
647 let end = SIMD3(1 + 0.5 * cos(Double.pi / 6), 1, 0.5 * sin(Double.pi / 6))
648 let middle = (start + end) / 2
649 let camera = Camera(eye: middle + normalize(end - start) * 4, target: middle, up: SIMD3(0, 1, 0),
650 fieldOfView: .pi / 4)
651 return FoldParameterMapping(file: file, step: step, camera: camera, viewportSize: SIMD2(800, 600))
652}
Packages/FoldKit/Sources/Folding/Camera.swift +26
@@ -44,3 +44,29 @@ public struct Camera: Sendable {
44 return projection * view 44 return projection * view
45 } 45 }
46} 46}
47
48extension Camera {
49 /// The camera moved around `target` at its distance so that the scene appears to turn by
50 /// `length(angles)` radians: `angles.x` about the camera's up axis, carrying the near side
51 /// rightward on screen, and `angles.y` about its right axis, carrying the near side downward.
52 /// The returned `up` is a unit vector perpendicular to the view direction, at any angle.
53 public func orbited(by angles: SIMD2<Double>) -> Camera {
54 let f = viewDirection
55 let s = normalize(cross(f, up))
56 let u = cross(s, f)
57 let angle = length(angles)
58 guard angle > 0 else { return Camera(eye: eye, target: target, up: u, fieldOfView: fieldOfView) }
59 // The camera turns the opposite way to the scene.
60 let turn = simd_quatd(angle: -angle, axis: (angles.x * u + angles.y * s) / angle)
61 let turnedF = turn.act(f), turnedU = turn.act(u)
62 return Camera(eye: target + turn.act(eye - target), target: target,
63 up: normalize(turnedU - dot(turnedU, turnedF) * turnedF), fieldOfView: fieldOfView)
64 }
65
66 /// The camera with its field of view narrowed by `scale`, as a pinch of that scale magnifies
67 /// the image, and clamped to `range`.
68 public func zoomed(by scale: Double, within range: ClosedRange<Double>) -> Camera {
69 let fieldOfView = min(max(2 * atan(tan(self.fieldOfView / 2) / scale), range.lowerBound), range.upperBound)
70 return Camera(eye: eye, target: target, up: up, fieldOfView: fieldOfView)
71 }
72}
Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift added +193
@@ -0,0 +1,193 @@
1import FoldFormat
2import simd
3
4/// Maps a drag on the paper view to the fold parameter of a step, so the moving faces follow the
5/// finger. Screen points are UIKit's: origin top left, y down, in a viewport of `viewportSize`.
6///
7/// The step is split into segments at the ends of every axis's window, at the middle of each
8/// window of a fold-and-unfold (its peak), and at a non-rigid step's phases. Within a segment the
9/// drag follows the area centroid of one axis's moving faces: of the axes whose window covers the
10/// segment, the one whose centroid travels furthest on screen, keeping the previous segment's
11/// axis on a tie. A non-rigid step's axes all count as covering every segment. The centroid is
12/// projected at the depth of the camera's target, so that a face nearing the eye as it lands flat
13/// does not overshoot its end on screen and leave t = 1 unreachable by a finger dragged past it.
14public struct FoldParameterMapping: Sendable {
15 /// The drag's path at 129 evenly spaced values of t: the followed centroids, each segment's
16 /// translated to begin where the segment before it ended. A segment along which no covering
17 /// axis's centroid travels 8 points is instead a straight line down, 160 points per unit of t.
18 public let path: [SIMD2<Double>]
19 /// Whether every segment is a straight line down, so a drag cannot follow the fold anywhere.
20 public let isDegenerate: Bool
21
22 /// The search polyline: `path`'s samples with the segment boundaries added.
23 private let ts: [Double]
24 private let points: [SIMD2<Double>]
25 /// Index ranges of `ts` searched one at a time, in order.
26 private let segments: [ClosedRange<Int>]
27
28 private static let samples = 129
29 private static let minimumLength = 8.0
30 /// Points dragged down for the whole step where a segment's path is under `minimumLength`.
31 private static let fallbackThrow = 160.0
32 /// How much further, in points, another axis's centroid must travel to replace the previous
33 /// segment's axis.
34 private static let preference = 0.5
35 /// How far past the best point so far the search continues, in points.
36 private static let slack = 8.0
37 /// How near its segment's end, along the path, a point counts as the end, in points.
38 private static let endTolerance = 0.5
39
40 public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) {
41 var followed: [(faces: [Int], window: ClosedRange<Double>)]
42 var boundaries: Set<Double> = [0, 1]
43 if step.nonRigid, let pop = step.pop {
44 followed = step.axes.map { (Array($0.movingFaces), 0...1) }
45 boundaries.formUnion([pop.phases.lowerBound, pop.phases.upperBound])
46 } else {
47 followed = step.axes.map { (Array($0.movingFaces), $0.window) }
48 for w in step.axes.map(\.window) {
49 boundaries.formUnion([w.lowerBound, w.upperBound])
50 if step.kind == .foldAndUnfold { boundaries.insert((w.lowerBound + w.upperBound) / 2) }
51 }
52 }
53 if followed.isEmpty { followed = [(Array(file.facesVertices.indices), 0...1)] }
54 let bounds = boundaries.sorted()
55
56 let n = Double(Self.samples - 1)
57 let grid = (0..<Self.samples).map { Double($0) / n }
58 let ts = Array(Set(grid + bounds)).sorted()
59 self.ts = ts
60 segments = zip(bounds, bounds.dropFirst()).map { ts.firstIndex(of: $0)!...ts.firstIndex(of: $1)! }
61
62 let projection = Projection(camera: camera, viewportSize: viewportSize)
63 let interpolator = FoldInterpolator(file: file, step: step)
64 let centroids = Centroids(file: file, sets: followed.map(\.faces))
65 let screen = ts.map { t in centroids.points(interpolator.positions(at: t)).map(projection.point) }
66
67 var points = ts.map { _ in SIMD2<Double>.zero }
68 var previous: Int?
69 var fallbacks = 0
70 for segment in segments {
71 func travel(_ c: Int) -> Double {
72 segment.dropLast().reduce(0) { $0 + distance(screen[$1][c], screen[$1 + 1][c]) }
73 }
74 let (a, b) = (ts[segment.lowerBound], ts[segment.upperBound])
75 let covering = followed.indices.filter { followed[$0].window.lowerBound <= a && b <= followed[$0].window.upperBound }
76 var choice: Int?
77 for c in (previous.map { [$0] } ?? []) + covering where covering.contains(c) && travel(c) >= Self.minimumLength {
78 if choice.map({ travel(c) > travel($0) + Self.preference }) ?? true { choice = c }
79 }
80 let start = segment.lowerBound == 0 ? screen[0][choice ?? 0] : points[segment.lowerBound]
81 for i in segment {
82 points[i] = choice.map { start + screen[i][$0] - screen[segment.lowerBound][$0] }
83 ?? start + SIMD2(0, (ts[i] - a) * Self.fallbackThrow)
84 }
85 if choice == nil { fallbacks += 1 }
86 previous = choice ?? previous
87 }
88 self.points = points
89 isDegenerate = fallbacks == segments.count
90 path = grid.map { t in points[ts.firstIndex(of: t)!] }
91 }
92
93 /// The point of `path` at `t`.
94 public func point(at t: Double) -> SIMD2<Double> {
95 let t = min(max(t, 0), 1)
96 let i = min(ts.lastIndex { $0 <= t }!, ts.count - 2)
97 let u = (t - ts[i]) / (ts[i + 1] - ts[i])
98 return points[i] + u * (points[i + 1] - points[i])
99 }
100
101 /// The parameter, in 0...1, whose point of `path` is nearest `grabbedAt + translation`, where
102 /// `grabbedAt` is `point(at:)` of t when the drag began. The search walks the path outward from
103 /// `current`, within the segment `current` is in, the later one at a boundary. Segments are one
104 /// way: once `current` reaches a segment's end, the segments before it are not searched again.
105 /// A point within half a point of its segment's end, measured along the path, is the end, so a
106 /// segment whose path turns back at its end can be finished.
107 ///
108 /// When the path is degenerate the drag's downward component advances the fold over 160
109 /// points from `current`, which is then the parameter when the drag began.
110 public func parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double {
111 let current = min(max(current, 0), 1)
112 if isDegenerate { return min(max(current + translation.y / Self.fallbackThrow, 0), 1) }
113
114 let target = grabbedAt + translation
115 let segment = segments.last { ts[$0.lowerBound] <= current }!
116 // the polyline edge from point i to point i + 1 holding current
117 var start = segment.lowerBound
118 while start + 1 < segment.upperBound && ts[start + 1] <= current { start += 1 }
119
120 func nearest(onEdge i: Int) -> (edge: Int, u: Double, distance: Double) {
121 let a = points[i], d = points[i + 1] - points[i]
122 let lengthSquared = dot(d, d)
123 let u = lengthSquared > 0 ? min(max(dot(target - a, d) / lengthSquared, 0), 1) : 0
124 return (i, u, distance(a + u * d, target))
125 }
126 var best = nearest(onEdge: start)
127 for direction in [1, -1] {
128 var i = start + direction
129 while i >= segment.lowerBound && i < segment.upperBound {
130 let candidate = nearest(onEdge: i)
131 if candidate.distance < best.distance {
132 best = candidate
133 } else if candidate.distance > best.distance + Self.slack {
134 break
135 }
136 i += direction
137 }
138 }
139 let end = segment.upperBound
140 var toEnd = (1 - best.u) * distance(points[best.edge], points[best.edge + 1])
141 for i in best.edge + 1 ..< end { toEnd += distance(points[i], points[i + 1]) }
142 return toEnd <= Self.endTolerance ? ts[end] : (1 - best.u) * ts[best.edge] + best.u * ts[best.edge + 1]
143 }
144}
145
146/// The area centroids of sets of faces.
147private struct Centroids {
148 /// Per set, fan triangles of its faces with their areas in frame 0.
149 let triangles: [[(SIMD3<Int>, Double)]]
150
151 init(file: FoldFile, sets: [[Int]]) {
152 let flat = file.frames[0].verticesCoords
153 triangles = sets.map { faces in
154 faces.flatMap { f in
155 let face = file.facesVertices[f]
156 return (1..<face.count - 1).map { i in
157 (SIMD3(face[0], face[i], face[i + 1]),
158 length(cross(flat[face[i]] - flat[face[0]], flat[face[i + 1]] - flat[face[0]])) / 2)
159 }
160 }
161 }
162 }
163
164 func points(_ positions: [SIMD3<Double>]) -> [SIMD3<Double>] {
165 triangles.map { set in
166 var sum = SIMD3<Double>.zero, area = 0.0
167 for (v, a) in set {
168 sum += a * (positions[v.x] + positions[v.y] + positions[v.z]) / 3
169 area += a
170 }
171 return sum / area
172 }
173 }
174}
175
176/// Projects to screen points at the depth of the camera's target.
177private struct Projection {
178 let viewProjection: simd_double4x4
179 /// Clip-space w of the camera's target.
180 let depth: Double
181 let viewportSize: SIMD2<Double>
182
183 init(camera: Camera, viewportSize: SIMD2<Double>) {
184 viewProjection = camera.viewProjection(aspect: viewportSize.x / viewportSize.y)
185 depth = (viewProjection * SIMD4(camera.target, 1)).w
186 self.viewportSize = viewportSize
187 }
188
189 func point(_ p: SIMD3<Double>) -> SIMD2<Double> {
190 let clip = viewProjection * SIMD4(p, 1)
191 return SIMD2((clip.x / depth + 1) / 2 * viewportSize.x, (1 - clip.y / depth) / 2 * viewportSize.y)
192 }
193}
Packages/FoldKit/Sources/Folding/ReorientMapping.swift added +27
@@ -0,0 +1,27 @@
1import simd
2
3/// Maps a horizontal drag on the paper view to the parameter of a `turnOver` or `rotate` step: the
4/// drag's rightward distance over the model's on-screen width. A leftward drag turns it back.
5/// Screen points are UIKit's, in a viewport of `viewportSize`.
6public struct ReorientMapping: Sendable {
7 /// The width in points of the projected bounding box of `positions`, at least 44 points.
8 public let width: Double
9
10 private static let minimumWidth = 44.0
11
12 /// `positions` are the model's vertices in the frame the step starts from.
13 public init(positions: [SIMD3<Double>], camera: Camera, viewportSize: SIMD2<Double>) {
14 let viewProjection = camera.viewProjection(aspect: viewportSize.x / viewportSize.y)
15 let xs = positions.map { p in
16 let clip = viewProjection * SIMD4(p, 1)
17 return (clip.x / clip.w + 1) / 2 * viewportSize.x
18 }
19 width = max(xs.max()! - xs.min()!, Self.minimumWidth)
20 }
21
22 /// The parameter, in 0...1, after a drag of `translation` points rightward from where the
23 /// parameter was `current`.
24 public func parameter(translation: Double, current: Double) -> Double {
25 min(max(current + translation / width, 0), 1)
26 }
27}
Packages/FoldKit/Sources/Models/ModelLibrary.swift +3 −2
@@ -27,8 +27,9 @@ public enum ModelLibrary {
27 return try FoldFile(contentsOf: url) 27 return try FoldFile(contentsOf: url)
28 } 28 }
29 29
30 /// The resource directory the package copies in. 30 /// The resource bundle's directory, where the package places `Resources/`'s files. A bundle
31 /// holding a directory named `Resources` fails code signing on iOS.
31 private static var directory: URL { 32 private static var directory: URL {
32 Bundle.module.url(forResource: "Resources", withExtension: nil)! 33 Bundle.module.resourceURL!
33 } 34 }
34} 35}
Packages/FoldKit/Sources/Renderer/PaperRenderer.swift +25 −2
@@ -37,6 +37,10 @@ public final class PaperRenderer {
37 /// Per colour pixel format, the pipeline that draws colour and the one that draws depth only. 37 /// Per colour pixel format, the pipeline that draws colour and the one that draws depth only.
38 private var pipelines: [MTLPixelFormat: (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState)] = [:] 38 private var pipelines: [MTLPixelFormat: (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState)] = [:]
39 private var depthTexture: MTLTexture? 39 private var depthTexture: MTLTexture?
40 /// The vertex buffer, reused while it is large enough.
41 private var vertexBuffer: MTLBuffer?
42 /// The last frame's commands, which read `vertexBuffer`.
43 private var lastFrame: MTLCommandBuffer?
40 44
41 private struct PaperVertex { 45 private struct PaperVertex {
42 var position: SIMD3<Float> 46 var position: SIMD3<Float>
@@ -77,12 +81,13 @@ public final class PaperRenderer {
77 81
78 /// Draws `mesh` with its vertices at `positions` into `target`, cleared to `background`. 82 /// Draws `mesh` with its vertices at `positions` into `target`, cleared to `background`.
79 /// Faces in no cluster are not drawn. `faceColours`, when given, draws FOLD face i in 83 /// Faces in no cluster are not drawn. `faceColours`, when given, draws FOLD face i in
80 /// `faceColours[i]`, unlit, on both sides. Commits to `commandQueue` without waiting. 84 /// `faceColours[i]`, unlit, on both sides. Waits for the previous frame to finish, since it
85 /// reuses that frame's vertex buffer, then commits to `commandQueue` without waiting for this one.
81 public func render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera, 86 public func render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera,
82 faceColours: [SIMD4<Float>]? = nil, into target: MTLTexture) throws { 87 faceColours: [SIMD4<Float>]? = nil, into target: MTLTexture) throws {
83 let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh) 88 let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh)
84 let pipeline = try pipelines(for: target.pixelFormat) 89 let pipeline = try pipelines(for: target.pixelFormat)
85 guard let buffer = device.makeBuffer(bytes: vertices, length: vertices.count * MemoryLayout<PaperVertex>.stride), 90 guard let buffer = vertexBuffer(holding: vertices),
86 let depth = depthTexture(width: target.width, height: target.height), 91 let depth = depthTexture(width: target.width, height: target.height),
87 let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed } 92 let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed }
88 93
@@ -136,6 +141,20 @@ public final class PaperRenderer {
136 } 141 }
137 encoder.endEncoding() 142 encoder.endEncoding()
138 commands.commit() 143 commands.commit()
144 lastFrame = commands
145 }
146
147 /// `vertexBuffer` filled with `vertices`, after the last frame has finished reading it; a new
148 /// one when it is too small.
149 private func vertexBuffer(holding vertices: [PaperVertex]) -> MTLBuffer? {
150 let length = vertices.count * MemoryLayout<PaperVertex>.stride
151 lastFrame?.waitUntilCompleted()
152 if (vertexBuffer?.length ?? 0) < length {
153 vertexBuffer = device.makeBuffer(length: length, options: .storageModeShared)
154 }
155 guard let vertexBuffer else { return nil }
156 memcpy(vertexBuffer.contents(), vertices, length)
157 return vertexBuffer
139 } 158 }
140 159
141 /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and 160 /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and
@@ -179,7 +198,11 @@ public final class PaperRenderer {
179 let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width, 198 let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width,
180 height: height, mipmapped: false) 199 height: height, mipmapped: false)
181 descriptor.usage = .renderTarget 200 descriptor.usage = .renderTarget
201 #if os(iOS)
202 descriptor.storageMode = .memoryless
203 #else
182 descriptor.storageMode = .private 204 descriptor.storageMode = .private
205 #endif
183 depthTexture = device.makeTexture(descriptor: descriptor) 206 depthTexture = device.makeTexture(descriptor: descriptor)
184 return depthTexture 207 return depthTexture
185 } 208 }
Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift +19
@@ -154,3 +154,22 @@ func acceptsAValidModel(_ name: String) throws {
154 file.frames[1].step = withPop(popped: 6, phases: [1.0 / 3, 2.0 / 3]) 154 file.frames[1].step = withPop(popped: 6, phases: [1.0 / 3, 2.0 / 3])
155 #expect(!validate(file).contains(.popMalformed(step: 1))) 155 #expect(!validate(file).contains(.popMalformed(step: 1)))
156} 156}
157
158@Test func rejectsAViewpointWhoseUpIsAlongItsEye() throws {
159 var file = try FoldFile(contentsOf: fixture("half.fold"))
160 let record = file.frames[1].step!
161 func viewing(eye: SIMD3<Double>, up: SIMD3<Double>) -> StepRecord {
162 StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, axes: record.axes,
163 viewpoint: Viewpoint(eye: eye, up: up))
164 }
165 file.frames[1].step = viewing(eye: SIMD3(0, 0, 1), up: SIMD3(0, 0, -2))
166 #expect(validate(file).contains(.viewpointDegenerate(step: 1)))
167 file.frames[1].step = viewing(eye: SIMD3(0, 0, 1), up: SIMD3(1e-6, 0, 1))
168 #expect(validate(file).contains(.viewpointDegenerate(step: 1)))
169 file.frames[1].step = viewing(eye: SIMD3(0, 0, 1), up: .zero)
170 #expect(validate(file).contains(.viewpointDegenerate(step: 1)))
171 file.frames[1].step = viewing(eye: .zero, up: SIMD3(0, 1, 0))
172 #expect(validate(file).contains(.viewpointDegenerate(step: 1)))
173 file.frames[1].step = viewing(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 1))
174 #expect(!validate(file).contains(.viewpointDegenerate(step: 1)))
175}
Packages/FoldKit/Tests/FoldingTests/CameraOrbitTests.swift added +85
@@ -0,0 +1,85 @@
1import Testing
2import simd
3import Folding
4
5private let front = Camera(eye: SIMD3(0, 0, 5), target: .zero, up: SIMD3(0, 1, 0), fieldOfView: .pi / 6)
6
7/// The point's position in clip space, divided by w.
8private func screen(_ p: SIMD3<Double>, _ camera: Camera) -> SIMD2<Double> {
9 let clip = camera.viewProjection(aspect: 1) * SIMD4(p, 1)
10 return SIMD2(clip.x, clip.y) / clip.w
11}
12
13private func isPerpendicularUnitUp(_ camera: Camera) -> Bool {
14 let up = camera.up, f = camera.viewDirection
15 return up.x.isFinite && up.y.isFinite && up.z.isFinite
16 && abs(length(up) - 1) < 1e-12 && abs(dot(up, f)) < 1e-12
17}
18
19@Test func orbitingByPositiveXCarriesTheNearSideRight() {
20 let near = SIMD3(0.0, 0, 1)
21 #expect(screen(near, front.orbited(by: SIMD2(0.1, 0))).x > 0.01)
22}
23
24@Test func orbitingByPositiveYCarriesTheNearSideDown() {
25 let near = SIMD3(0.0, 0, 1)
26 #expect(screen(near, front.orbited(by: SIMD2(0, 0.1))).y < -0.01)
27}
28
29@Test func aQuarterTurnAboutUpMovesTheEyeToTheLeftOfTheScene() {
30 let c = front.orbited(by: SIMD2(.pi / 2, 0))
31 #expect(length(c.eye - SIMD3(-5, 0, 0)) < 1e-12)
32 #expect(length(c.up - SIMD3(0, 1, 0)) < 1e-12)
33}
34
35@Test func orbitingKeepsTheTargetDistanceAndFieldOfView() {
36 let c = front.orbited(by: SIMD2(0.7, -1.3))
37 #expect(c.target == front.target)
38 #expect(abs(length(c.eye - c.target) - 5) < 1e-12)
39 #expect(c.fieldOfView == front.fieldOfView)
40}
41
42@Test func upStaysPerpendicularToTheViewDirectionOverThePoles() {
43 var c = front
44 for _ in 0..<200 {
45 c = c.orbited(by: SIMD2(0, 0.1))
46 #expect(isPerpendicularUnitUp(c))
47 let m = c.viewProjection(aspect: 1)
48 #expect((0..<4).allSatisfy { i in (0..<4).allSatisfy { j in m[i][j].isFinite } })
49 }
50 #expect(abs(length(c.eye - c.target) - 5) < 1e-9)
51}
52
53@Test func orbitingExactlyOntoThePoleKeepsAUsableUp() {
54 let c = front.orbited(by: SIMD2(0, .pi / 2))
55 #expect(length(c.eye - SIMD3(0, 5, 0)) < 1e-12)
56 #expect(isPerpendicularUnitUp(c))
57 #expect(length(c.up - SIMD3(0, 0, -1)) < 1e-12)
58}
59
60@Test func manyDiagonalOrbitsDoNotDrift() {
61 var c = front
62 for k in 0..<1000 {
63 c = c.orbited(by: SIMD2(0.031 * Double(k % 7 - 3), 0.017 * Double(k % 5 - 2)))
64 }
65 #expect(isPerpendicularUnitUp(c))
66 #expect(abs(length(c.eye - c.target) - 5) < 1e-9)
67}
68
69@Test func orbitingMakesAnObliqueUpPerpendicular() {
70 let oblique = Camera(eye: SIMD3(0, 0, 5), target: .zero, up: SIMD3(0, 1, 1), fieldOfView: .pi / 6)
71 #expect(isPerpendicularUnitUp(oblique.orbited(by: .zero)))
72 #expect(isPerpendicularUnitUp(oblique.orbited(by: SIMD2(0.2, 0.3))))
73}
74
75@Test func zoomingByTwoHalvesTheTangentOfTheHalfAngle() {
76 let c = front.zoomed(by: 2, within: 0.1...2)
77 #expect(abs(tan(c.fieldOfView / 2) - tan(front.fieldOfView / 2) / 2) < 1e-12)
78 #expect(c.eye == front.eye && c.up == front.up)
79 #expect(front.zoomed(by: 1, within: 0.1...2).fieldOfView == front.fieldOfView)
80}
81
82@Test func zoomingIsClampedToTheRange() {
83 #expect(front.zoomed(by: 100, within: 0.2...1).fieldOfView == 0.2)
84 #expect(front.zoomed(by: 0.01, within: 0.2...1).fieldOfView == 1)
85}
Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift added +128
@@ -0,0 +1,128 @@
1import FoldFormat
2import FoldKitTestSupport
3import Folding
4import simd
5import Testing
6
7@Test func theFacetTracksTheFinger() throws {
8 let m = try mapping("half.fold", step: 1) // viewed from above
9 let target = m.path[32] // t = 0.25
10 let t = m.parameter(grabbedAt: m.path[0], translation: target - m.path[0], current: 0)
11 #expect(abs(t - 0.25) < 0.01)
12}
13
14@Test func dragPerpendicularToThePathDoesNotAdvanceTheFold() throws {
15 let m = try mapping("half.fold", step: 1)
16 let along = simd_normalize(m.path[1] - m.path[0])
17 let perp = SIMD2(-along.y, along.x)
18 #expect(m.parameter(grabbedAt: m.path[0], translation: perp * 50, current: 0) < 0.01)
19}
20
21@Test func parameterIsClampedToUnitRange() throws {
22 let m = try mapping("half.fold", step: 1)
23 let along = simd_normalize(m.path[128] - m.path[0])
24 #expect(m.parameter(grabbedAt: m.path[0], translation: along * 100_000, current: 0) == 1)
25 #expect(m.parameter(grabbedAt: m.path[0], translation: along * -100_000, current: 0) == 0)
26}
27
28@Test func headOnFoldIsReportedDegenerate() throws {
29 #expect(try mappingForFoldTowardTheCamera().isDegenerate)
30}
31
32@Test func degenerateMappingFallsBackToVerticalDrag() throws {
33 let m = try mappingForFoldTowardTheCamera()
34 #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 50), current: 0) > 0.1)
35}
36
37@Test func theMappingIsNeverInfinitelySensitive() throws {
38 let m = try mappingForFoldTowardTheCamera()
39 #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2)
40}
41
42@Test func aNonRigidStepIsDraggedPhaseByPhase() throws {
43 // following the path's own samples in order reaches t = 1 without ever going back
44 let m = try FoldParameterMapping(file: compiled("reverse"), step: readSteps(compiled("reverse"))[1],
45 camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
46 viewportSize: SIMD2(800, 600))
47 var t = 0.0
48 for p in m.path.dropFirst() {
49 let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
50 #expect(next >= t - 1e-9)
51 t = next
52 }
53 #expect(t > 0.99)
54}
55
56@Test func foldAndUnfoldGoesOutThenBack() throws {
57 let m = try mapping("quarters.fold", step: 1)
58 let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0)
59 #expect(abs(atPeak - 0.5) < 0.01)
60 let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak)
61 #expect(back > 0.99)
62}
63
64@Test func aPathThatRetracesItselfOnScreenIsFollowedWithoutJumpingToItsEnd() throws {
65 // seen along (1, 0, 1), the flap's centroid passes the screen point of its end at 90°
66 let file = try FoldFile(contentsOf: fixture("half.fold"))
67 let m = FoldParameterMapping(file: file, step: try readStep(1, in: file),
68 camera: Camera(eye: SIMD3(1, 1, 0) + normalize(SIMD3(1, 0, 1)) * 4, target: SIMD3(1, 1, 0),
69 up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
70 viewportSize: SIMD2(800, 600))
71 var t = 0.0
72 for (k, p) in m.path.enumerated().dropFirst() {
73 t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
74 #expect(abs(t - Double(k) / 128) < 0.01, "sample \(k)")
75 }
76}
77
78@Test func aStaggeredStepIsFollowedAcrossItsWindows() throws {
79 // two axes on windows 0...0.5 and 0.5...1; following the path's samples reaches each in turn.
80 // 0.02 allows the last sample before a slow window end, within the end tolerance, to count as it
81 let m = try mapping("letter-staggered.fold", step: 1)
82 var t = 0.0
83 for (k, p) in m.path.enumerated().dropFirst() {
84 t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
85 #expect(abs(t - Double(k) / 128) < 0.02, "sample \(k)")
86 }
87}
88
89@Test func aLateWindowIsReachedByTheVerticalDragAndThenFollowed() throws {
90 // nothing moves before 0.5, so that half of the path is the vertical fallback
91 let file = try FoldFile(contentsOf: fixture("half.fold"))
92 let full = try readStep(1, in: file)
93 let a = full.axes[0]
94 let step = FoldStep(index: 1, kind: .fold, instruction: full.instruction,
95 axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction,
96 movingFaces: a.movingFaces, startAngle: 0, endAngle: 180, window: 0.5...1)],
97 viewpoint: full.viewpoint)
98 let m = FoldParameterMapping(file: file, step: step,
99 camera: Camera(eye: SIMD3(1, 1, 4), target: SIMD3(1, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
100 viewportSize: SIMD2(800, 600))
101 #expect(!m.isDegenerate)
102 let early = m.parameter(grabbedAt: m.path[0], translation: SIMD2(0, 40), current: 0)
103 #expect(abs(early - 0.25) < 0.01)
104 var t = 0.0
105 for (k, p) in m.path.enumerated().dropFirst() {
106 t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
107 #expect(abs(t - Double(k) / 128) < 0.02, "sample \(k)")
108 }
109}
110
111@Test func aFoldAndUnfoldPeaksAtTheMiddleOfItsWindow() throws {
112 let file = try FoldFile(contentsOf: fixture("quarters.fold"))
113 let full = try readStep(1, in: file)
114 let a = full.axes[0]
115 let step = FoldStep(index: 1, kind: .foldAndUnfold, instruction: full.instruction,
116 axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction, movingFaces: a.movingFaces,
117 startAngle: a.startAngle, endAngle: a.endAngle, peakAngle: a.peakAngle,
118 window: 0...0.6)],
119 viewpoint: full.viewpoint)
120 let m = FoldParameterMapping(file: file, step: step,
121 camera: Camera(eye: SIMD3(1, 1, 4), target: SIMD3(1, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
122 viewportSize: SIMD2(800, 600))
123 let peak = m.point(at: 0.3)
124 let atPeak = m.parameter(grabbedAt: m.path[0], translation: peak - m.path[0], current: 0)
125 #expect(abs(atPeak - 0.3) < 0.01)
126 let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak)
127 #expect(abs(back - 0.6) < 0.01)
128}
Packages/FoldKit/Tests/FoldingTests/ReorientMappingTests.swift added +40
@@ -0,0 +1,40 @@
1import FoldFormat
2import FoldKitTestSupport
3import Folding
4import Testing
5
6/// `half.fold`'s 2 × 2 sheet from 4 units above its centre, with a 90° field of view in an
7/// 800 × 600 viewport: 150 points wide.
8private func sheetFromAbove() throws -> ReorientMapping {
9 let file = try FoldFile(contentsOf: fixture("half.fold"))
10 let camera = Camera(eye: SIMD3(1, 1, 4), target: SIMD3(1, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 2)
11 return ReorientMapping(positions: file.frames[0].verticesCoords, camera: camera, viewportSize: SIMD2(800, 600))
12}
13
14@Test func theWidthIsTheModelsProjectedWidth() throws {
15 #expect(abs(try sheetFromAbove().width - 150) < 1e-9)
16}
17
18@Test func aRightwardDragAcrossTheWidthCompletesTheStep() throws {
19 let m = try sheetFromAbove()
20 #expect(abs(m.parameter(translation: 75, current: 0) - 0.5) < 1e-12)
21 #expect(m.parameter(translation: 150, current: 0) == 1)
22}
23
24@Test func theReorientParameterIsClampedToUnitRange() throws {
25 let m = try sheetFromAbove()
26 #expect(m.parameter(translation: 1000, current: 0.5) == 1)
27 #expect(m.parameter(translation: -1000, current: 0.5) == 0)
28}
29
30@Test func aLeftwardDragTurnsTheModelBack() throws {
31 #expect(abs(try sheetFromAbove().parameter(translation: -37.5, current: 0.5) - 0.25) < 1e-12)
32}
33
34@Test func aModelSeenEdgeOnStillTakesADeliberateDrag() throws {
35 let file = try FoldFile(contentsOf: fixture("half.fold"))
36 let camera = Camera(eye: SIMD3(1, 5, 0), target: SIMD3(1, 1, 0), up: SIMD3(1, 0, 0), fieldOfView: .pi / 2)
37 let m = ReorientMapping(positions: file.frames[0].verticesCoords, camera: camera, viewportSize: SIMD2(800, 600))
38 #expect(m.width == 44)
39 #expect(m.parameter(translation: 0, current: 0) == 0)
40}
Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift +38
@@ -6,6 +6,7 @@ import FoldFormat
6import Folding 6import Folding
7import FoldKitTestSupport 7import FoldKitTestSupport
8import Models 8import Models
9import Notation
9 10
10@Test func everyShippedStepEndsOnItsEndFrame() throws { 11@Test func everyShippedStepEndsOnItsEndFrame() throws {
11 // the step records and the frames must agree: interpolating a step to t = 1 reproduces frame n 12 // the step records and the frames must agree: interpolating a step to t = 1 reproduces frame n
@@ -81,6 +82,43 @@ import Models
81 } 82 }
82} 83}
83 84
85@Test func everyShippedStepBuildsWhatTheAppShowsOfIt() throws {
86 // per step, what the app's session builds, with its camera at the step's authored viewpoint
87 for file in try ModelLibrary.all() {
88 for n in 1..<file.frames.count {
89 let label = "\(file.fileTitle ?? "?") step \(n)"
90 let step = try readStep(n, in: file)
91 let order = try LayerOrder.active(for: step, in: file)
92 _ = buildDiagram(file: file, step: step)
93 let interpolator = FoldInterpolator(file: file, step: step)
94 let camera = sessionCamera(file, step, aspect: 400.0 / 600)
95 for t in [0, 0.5, 1.0] {
96 let clusters = order.clusters(positions: interpolator.positions(at: t), faces: file.facesVertices,
97 viewDirection: camera.target - camera.eye)
98 #expect(clusters.reduce(0) { $0 + $1.faces.count } == file.facesVertices.count, "\(label) t \(t)")
99 }
100 let mapping = FoldParameterMapping(file: file, step: step, camera: camera, viewportSize: SIMD2(400, 600))
101 #expect(mapping.path.allSatisfy { $0.x.isFinite && $0.y.isFinite }, "\(label)")
102 }
103 }
104}
105
106/// The camera FoldSession starts a step with: from the step's viewpoint, at the default field of
107/// view, far enough that the flat sheet's half-diagonal fits about the start frame's centre.
108private func sessionCamera(_ file: FoldFile, _ step: FoldStep, aspect: Double) -> Camera {
109 func bounds(_ p: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>) {
110 (p.dropFirst().reduce(p[0], simd_min), p.dropFirst().reduce(p[0], simd_max))
111 }
112 let (low, high) = bounds(file.frames[0].verticesCoords)
113 let (startLow, startHigh) = bounds(file.frames[step.index - 1].verticesCoords)
114 let target = (startLow + startHigh) / 2
115 let fieldOfView = Double.pi / 6
116 let distance = simd_length(high - low) / 2 / sin(min(fieldOfView / 2, atan(tan(fieldOfView / 2) * aspect)))
117 let eye = simd_normalize(step.viewpoint.eye)
118 let up = simd_normalize(step.viewpoint.up - simd_dot(step.viewpoint.up, eye) * eye)
119 return Camera(eye: target + distance * eye, target: target, up: up, fieldOfView: fieldOfView)
120}
121
84@Test func theCatalogueContainsTheCup() throws { 122@Test func theCatalogueContainsTheCup() throws {
85 #expect(try ModelLibrary.names() == ["cup"]) 123 #expect(try ModelLibrary.names() == ["cup"])
86} 124}
docs/superpowers/plans/2026-10-19-fold.md +14 −7
@@ -1765,7 +1765,7 @@ Completing a step needs Task 12's gesture and orbiting needs Task 14's; their te
1765 1765
1766- [ ] **Step 2: Run tests to verify they fail** 1766- [ ] **Step 2: Run tests to verify they fail**
1767 1767
1768Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test` 1768Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test`
1769Expected: FAIL — no such project. 1769Expected: FAIL — no such project.
1770 1770
1771- [ ] **Step 3: Generate the project and implement the shell, list, step layout and both canvases** 1771- [ ] **Step 3: Generate the project and implement the shell, list, step layout and both canvases**
@@ -1896,11 +1896,11 @@ Expected: FAIL.
1896 1896
1897- [ ] **Step 3: Implement `FoldParameterMapping` and `FoldGesture`** 1897- [ ] **Step 3: Implement `FoldParameterMapping` and `FoldGesture`**
1898 1898
1899The step completes when the parameter is 1 and the finger lifts. Releasing below 1 leaves the paper where it is. 1899The 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.
1900 1900
1901- [ ] **Step 4: Run tests to verify they pass** 1901- [ ] **Step 4: Run tests to verify they pass**
1902 1902
1903Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`, then `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/FoldGestureTests` 1903Run: `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`
1904Expected: PASS. 1904Expected: PASS.
1905 1905
1906- [ ] **Step 5: Commit** 1906- [ ] **Step 5: Commit**
@@ -1953,12 +1953,12 @@ func testTurnOverReorientsTheModelNotTheCamera() {
1953 1953
1954- [ ] **Step 2: Run tests to verify they fail** 1954- [ ] **Step 2: Run tests to verify they fail**
1955 1955
1956Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/ReorientGestureTests` 1956Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/ReorientGestureTests`
1957Expected: FAIL. 1957Expected: FAIL.
1958 1958
1959- [ ] **Step 3: Implement `ReorientGesture`** 1959- [ ] **Step 3: Implement `ReorientGesture`**
1960 1960
1961Gate the gesture on the current step's `kind`, so a fold drag and a reorient drag are never both live. 1961Gate 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.
1962 1962
1963- [ ] **Step 4: Run tests to verify they pass** 1963- [ ] **Step 4: Run tests to verify they pass**
1964 1964
@@ -2039,12 +2039,12 @@ func testDiagramDoesNotRotateWhenTheModelIsOrbited() {
2039 2039
2040- [ ] **Step 2: Run tests to verify they fail** 2040- [ ] **Step 2: Run tests to verify they fail**
2041 2041
2042Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/AccessibilityAuditTests` 2042Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/AccessibilityAuditTests`
2043Expected: FAIL. 2043Expected: FAIL.
2044 2044
2045- [ ] **Step 3: Implement `OrbitGesture`, the accessibility labels, the privacy manifest, the rights note and the screenshot script** 2045- [ ] **Step 3: Implement `OrbitGesture`, the accessibility labels, the privacy manifest, the rights note and the screenshot script**
2046 2046
2047`take-screenshots.sh` follows `krz/daybyday/scripts/take-screenshots.sh`. `PrivacyInfo.xcprivacy` declares no tracking and no collected data. 2047`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.
2048 2048
2049- [ ] **Step 4: Run tests to verify they pass** 2049- [ ] **Step 4: Run tests to verify they pass**
2050 2050
@@ -2153,6 +2153,13 @@ git commit -m "The crane, the sampan and the box"
2153 2153
2154--- 2154---
2155 2155
2156## Open before Task 15
2157
2158- **Reaching an earlier or chosen step.** The app starts each model at step 1 and has no step list; the spec leaves its form open (a visible strip or revealed on demand). On the crane, revisiting a step means refolding from the start.
2159- **Dragging back past a peak, phase or window.** A fold-and-unfold cannot be dragged back once past its peak, a reverse fold past its open phase, or a staggered step past an internal window end, although the spec's first goal says a step can be folded "and back".
2160- **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`.
2161- 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.
2162
2156## After the plan 2163## After the plan
2157 2164
2158The 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. 2165The 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.
scripts/take-screenshots.sh added +76
@@ -0,0 +1,76 @@
1#!/bin/sh
2# Takes the App Store screenshots on the iPhone 18 Pro Max (6.9") and iPad Pro 13-inch (M5)
3# simulators, in light mode at 9:41 with a full status bar. Each screen opens through the
4# -UITesting -screenshot launch arguments (App/Sources/ScreenshotScene.swift). The 6.3" set is
5# resized from the 6.9" one; every PNG is flattened to RGB.
6# Usage: scripts/take-screenshots.sh [scene ...] (default: every scene, in App Store order)
7# TEXT_SIZE=accessibility-extra-extra-extra-large (any simctl content_size) shoots at that text
8# size into AppStore/screenshots-<size> instead.
9set -eu
10
11cd "$(dirname "$0")/.."
12all="fold flap cup models"
13scenes="${*:-$all}"
14size="${TEXT_SIZE:-}"
15out=AppStore/screenshots${size:+-$size}
16derived=.build/screenshots
17app="$derived/Build/Products/Debug-iphonesimulator/Fold.app"
18bundle=sh.krz.fold
19
20xcodegen generate --spec App/project.yml --quiet
21xcodebuild build -project App/Fold.xcodeproj -scheme Fold -configuration Debug \
22 -destination 'generic/platform=iOS Simulator' -derivedDataPath "$derived" -quiet
23
24udid() {
25 xcrun simctl list devices available | grep -F " $1 (" | head -1 | sed 's/.*(\([0-9A-F-]\{36\}\)).*/\1/'
26}
27
28flatten() {
29 # Drops the alpha channel, which App Store Connect rejects.
30 sips -s format jpeg -s formatOptions 100 "$1" --out "$1.jpg" >/dev/null
31 sips -s format png "$1.jpg" --out "$1" >/dev/null
32 rm "$1.jpg"
33}
34
35shoot() { # device name, output folder
36 device="$(udid "$1")"
37 [ -n "$device" ] || { echo "No simulator named $1." >&2; exit 1; }
38 xcrun simctl boot "$device" 2>/dev/null || true
39 xcrun simctl bootstatus "$device" -b >/dev/null
40 xcrun simctl ui "$device" appearance light
41 xcrun simctl ui "$device" content_size "${size:-large}"
42 xcrun simctl install "$device" "$app"
43 mkdir -p "$out/$2"
44 for scene in $scenes; do
45 n="$(printf '%s\n' $all | grep -nx "$scene" | cut -d: -f1)"
46 [ -n "$n" ] || { echo "Unknown scene $scene; one of: $all" >&2; exit 1; }
47 xcrun simctl terminate "$device" "$bundle" 2>/dev/null || true
48 # Set per launch: changing content_size restarts the status bar and drops the override.
49 xcrun simctl status_bar "$device" override --time 9:41 --dataNetwork wifi --wifiMode active \
50 --wifiBars 3 --cellularMode active --cellularBars 4 --batteryState charged --batteryLevel 100
51 xcrun simctl launch "$device" "$bundle" -UITesting -screenshot "$scene" >/dev/null
52 file="$out/$2/$(printf %02d "$n")-$scene.png"
53 # A screen that has not drawn yet is blank white, which compresses to a few KB.
54 tries=0
55 while :; do
56 sleep 3
57 xcrun simctl io "$device" screenshot "$file" >/dev/null 2>&1
58 [ "$(stat -f%z "$file")" -gt 30000 ] && break
59 tries=$((tries + 1))
60 [ "$tries" -lt 10 ] || { echo "$scene stayed blank on $1." >&2; exit 1; }
61 done
62 flatten "$file"
63 echo "$file"
64 done
65 xcrun simctl terminate "$device" "$bundle" 2>/dev/null || true
66 xcrun simctl status_bar "$device" clear
67 xcrun simctl ui "$device" content_size large
68}
69
70shoot "iPhone 18 Pro Max" iphone-6.9
71shoot "iPad Pro 13-inch (M5)" ipad
72
73mkdir -p "$out/iphone-6.3"
74for file in "$out"/iphone-6.9/*.png; do
75 sips -z 2622 1206 "$file" --out "$out/iphone-6.3/$(basename "$file")" >/dev/null
76done