Commit 5da727623b
Verified · cmc
Layout: unified · split
App/Sources/FoldSession.swift +20 −10
| @@ -70,16 +70,23 @@ final class FoldSession { | ||
| 70 | 70 | } |
| 71 | 71 | |
| 72 | 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. | |
| 73 | /// After the last step the finished model stays at t = 1. | |
| 75 | 74 | func completeStep() { |
| 76 | 75 | guard t == 1, step.index + 1 < model.frames.count else { return } |
| 76 | open(step: step.index + 1) | |
| 77 | } | |
| 78 | ||
| 79 | /// Opens step `n`, counting from 1, at t = 0, seen from its viewpoint at the default zoom. | |
| 80 | /// Opening the current step leaves it as it is. A step that cannot be read leaves the session | |
| 81 | /// as it is and stops a Debug build. | |
| 82 | func open(step n: Int) { | |
| 83 | guard n != step.index else { return } | |
| 77 | 84 | let next: FoldStep, nextOrder: LayerOrder |
| 78 | 85 | do { |
| 79 | next = try readStep(step.index + 1, in: model) | |
| 86 | next = try readStep(n, in: model) | |
| 80 | 87 | nextOrder = try LayerOrder.active(for: next, in: model) |
| 81 | 88 | } catch { |
| 82 | assertionFailure("step \(step.index + 1) of \(model.fileTitle ?? "?"): \(error)") | |
| 89 | assertionFailure("step \(n) of \(model.fileTitle ?? "?"): \(error)") | |
| 83 | 90 | return |
| 84 | 91 | } |
| 85 | 92 | step = next |
| @@ -92,12 +99,13 @@ final class FoldSession { | ||
| 92 | 99 | up = normalize(next.viewpoint.up - dot(next.viewpoint.up, eye) * eye) |
| 93 | 100 | fieldOfView = Self.defaultFieldOfView |
| 94 | 101 | cachedMapping = nil |
| 95 | t = 0 | |
| 102 | if t == 0 { pose() } else { t = 0 } | |
| 96 | 103 | } |
| 97 | 104 | |
| 98 | 105 | /// What maps a one-finger drag's translation to `t`. |
| 99 | 106 | private enum DragMapping { |
| 100 | case fold(FoldParameterMapping, grabbedAt: SIMD2<Double>) | |
| 107 | /// `position` is where the latest movement left the drag on the path. | |
| 108 | case fold(FoldParameterMapping, grabbedAt: SIMD2<Double>, position: FoldParameterMapping.Position) | |
| 101 | 109 | case reorient(ReorientMapping) |
| 102 | 110 | } |
| 103 | 111 | |
| @@ -113,7 +121,7 @@ final class FoldSession { | ||
| 113 | 121 | /// finger along `mapping`'s path. |
| 114 | 122 | func beginFoldDrag() { |
| 115 | 123 | let mapping = self.mapping |
| 116 | beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t))) | |
| 124 | beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t), position: mapping.position(at: t))) | |
| 117 | 125 | } |
| 118 | 126 | |
| 119 | 127 | /// Called when a one-finger drag on a turn-over or rotate step begins: its horizontal |
| @@ -133,9 +141,11 @@ final class FoldSession { | ||
| 133 | 141 | func drag(translation: SIMD2<Double>) { |
| 134 | 142 | guard let grab, !isDragSuspended else { return } |
| 135 | 143 | switch grab.mapping { |
| 136 | case let .fold(mapping, grabbedAt): | |
| 137 | t = mapping.parameter(grabbedAt: grabbedAt, translation: translation, | |
| 138 | current: mapping.isDegenerate ? grab.start : t) | |
| 144 | case let .fold(mapping, grabbedAt, position): | |
| 145 | let next = mapping.position(grabbedAt: grabbedAt, translation: translation, | |
| 146 | current: mapping.isDegenerate ? mapping.position(at: grab.start) : position) | |
| 147 | self.grab?.mapping = .fold(mapping, grabbedAt: grabbedAt, position: next) | |
| 148 | t = next.t | |
| 139 | 149 | case let .reorient(mapping): |
| 140 | 150 | t = mapping.parameter(translation: translation.x, current: grab.start) |
| 141 | 151 | } |
App/Sources/StepListView.swift added +42
| @@ -0,0 +1,42 @@ | ||
| 1 | import Folding | |
| 2 | import SwiftUI | |
| 3 | ||
| 4 | /// Every step of the session's model by number and instruction, the current one checked. | |
| 5 | /// Choosing a step opens it at its start; choosing the current step leaves it as it is. Either | |
| 6 | /// closes the list. | |
| 7 | struct StepListView: View { | |
| 8 | let session: FoldSession | |
| 9 | private let steps: [FoldStep] | |
| 10 | @Environment(\.dismiss) private var dismiss | |
| 11 | ||
| 12 | init(session: FoldSession) { | |
| 13 | self.session = session | |
| 14 | steps = (try? readSteps(session.model)) ?? [] | |
| 15 | } | |
| 16 | ||
| 17 | var body: some View { | |
| 18 | List(steps, id: \.index) { step in | |
| 19 | let isCurrent = step.index == session.step.index | |
| 20 | Button { | |
| 21 | session.open(step: step.index) | |
| 22 | dismiss() | |
| 23 | } label: { | |
| 24 | HStack(alignment: .firstTextBaseline, spacing: 12) { | |
| 25 | Text("\(step.index)") | |
| 26 | .font(.headline) | |
| 27 | .monospacedDigit() | |
| 28 | Text(step.instruction) | |
| 29 | .frame(maxWidth: .infinity, alignment: .leading) | |
| 30 | Image(systemName: "checkmark") | |
| 31 | .fontWeight(.semibold) | |
| 32 | .opacity(isCurrent ? 1 : 0) | |
| 33 | } | |
| 34 | } | |
| 35 | .foregroundStyle(.primary) | |
| 36 | .accessibilityLabel("Step \(step.index), \(step.instruction)") | |
| 37 | .accessibilityAddTraits(isCurrent ? .isSelected : []) | |
| 38 | .accessibilityIdentifier("step.\(step.index)") | |
| 39 | } | |
| 40 | .listStyle(.plain) | |
| 41 | } | |
| 42 | } | |
App/Sources/StepView.swift +20 −2
| @@ -3,10 +3,12 @@ import Notation | ||
| 3 | 3 | import SwiftUI |
| 4 | 4 | |
| 5 | 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. | |
| 6 | /// model on a regular-width screen and above it on a compact one. The Steps button lists every | |
| 7 | /// step, in a popover on a regular-width screen and a sheet on a compact one. | |
| 7 | 8 | struct StepView: View { |
| 8 | 9 | private let title: String |
| 9 | 10 | @State private var session: FoldSession? |
| 11 | @State private var isShowingSteps = false | |
| 10 | 12 | @Environment(\.horizontalSizeClass) private var horizontalSizeClass |
| 11 | 13 | @Environment(\.verticalSizeClass) private var verticalSizeClass |
| 12 | 14 | |
| @@ -31,8 +33,24 @@ struct StepView: View { | ||
| 31 | 33 | ContentUnavailableView("This Model Can't Be Shown", systemImage: "exclamationmark.triangle") |
| 32 | 34 | } |
| 33 | 35 | } |
| 34 | .navigationTitle(title) | |
| 36 | .navigationTitle(session.map { "Step \($0.step.index) of \($0.model.frames.count - 1)" } ?? title) | |
| 35 | 37 | .navigationBarTitleDisplayMode(.inline) |
| 38 | .toolbar { | |
| 39 | if let session { | |
| 40 | ToolbarItem(placement: .topBarTrailing) { | |
| 41 | Button("Steps", systemImage: "list.number") { isShowingSteps = true } | |
| 42 | .accessibilityIdentifier("steps.button") | |
| 43 | .popover(isPresented: $isShowingSteps) { | |
| 44 | StepListView(session: session) | |
| 45 | .frame(idealWidth: 360, idealHeight: 480) | |
| 46 | .presentationDetents([.medium, .large]) | |
| 47 | .presentationDragIndicator(.visible) | |
| 48 | // the paper seen through a translucent sheet fails the contrast audit | |
| 49 | .presentationBackground(.background) | |
| 50 | } | |
| 51 | } | |
| 52 | } | |
| 53 | } | |
| 36 | 54 | } |
| 37 | 55 | |
| 38 | 56 | /// The caption takes the height it needs up to `captionShare` of the pane, and scrolls beyond |
App/Tests/FoldSessionTests.swift +54
| @@ -160,3 +160,57 @@ private func cupInView(step: Int = 1) throws -> FoldSession { | ||
| 160 | 160 | #expect(!session.isDragSuspended) |
| 161 | 161 | session.endOrbit() |
| 162 | 162 | } |
| 163 | ||
| 164 | @MainActor @Test func openingAStepStartsItFromTheFrameBeforeIt() throws { | |
| 165 | let session = try cup() | |
| 166 | session.orbit(by: SIMD2(0.4, -0.7)) | |
| 167 | session.zoom(by: 2) | |
| 168 | session.t = 0.6 | |
| 169 | session.open(step: 4) | |
| 170 | let fresh = try cup(step: 4) | |
| 171 | #expect(session.step.index == 4) | |
| 172 | #expect(session.t == 0) | |
| 173 | #expect(session.camera.eye == fresh.camera.eye) | |
| 174 | #expect(session.camera.up == fresh.camera.up) | |
| 175 | #expect(session.camera.fieldOfView == fresh.camera.fieldOfView) | |
| 176 | #expect(session.diagram == fresh.diagram) | |
| 177 | #expect(session.meshPositions == fresh.meshPositions) | |
| 178 | } | |
| 179 | ||
| 180 | @MainActor @Test func openingAnEarlierStepGoesBackToItsStart() throws { | |
| 181 | let session = try cup(step: 4) | |
| 182 | session.t = 1 | |
| 183 | session.completeStep() | |
| 184 | session.open(step: 2) | |
| 185 | #expect(session.step.index == 2) | |
| 186 | #expect(session.t == 0) | |
| 187 | #expect(session.meshPositions == (try cup(step: 2)).meshPositions) | |
| 188 | } | |
| 189 | ||
| 190 | @MainActor @Test func openingTheCurrentStepLeavesItAlone() throws { | |
| 191 | let session = try cup(step: 3) | |
| 192 | session.orbit(by: SIMD2(0.4, -0.7)) | |
| 193 | session.t = 0.4 | |
| 194 | let camera = session.camera | |
| 195 | session.open(step: 3) | |
| 196 | #expect(session.step.index == 3) | |
| 197 | #expect(session.t == 0.4) | |
| 198 | #expect(session.camera.eye == camera.eye) | |
| 199 | } | |
| 200 | ||
| 201 | @MainActor @Test func aDragBackTakesTheFoldBackToItsStart() throws { | |
| 202 | let session = try cupInView() | |
| 203 | session.beginFoldDrag() | |
| 204 | session.drag(translation: translation(session, to: 0.7)) | |
| 205 | session.drag(translation: translation(session, to: 0.3)) | |
| 206 | #expect(abs(session.t - 0.3) < 0.01) | |
| 207 | session.endDrag(translation: .zero) | |
| 208 | #expect(session.step.index == 1) | |
| 209 | #expect(session.t == 0) | |
| 210 | } | |
| 211 | ||
| 212 | @MainActor @Test func openingAStepFromTheStartOfAnotherShowsTheNewStep() throws { | |
| 213 | let session = try cup() | |
| 214 | session.open(step: 4) | |
| 215 | #expect(session.meshPositions == (try cup(step: 4)).meshPositions) | |
| 216 | } | |
App/UITests/AccessibilityAuditTests.swift +10 −3
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | import XCTest |
| 2 | 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 | |
| 3 | /// Opens the step list and every step of the cup by the labels VoiceOver sees and runs Xcode's | |
| 4 | /// accessibility audit on each screen, at the default text size and at the largest accessibility | |
| 5 | /// size. Also checks | |
| 5 | 6 | /// that two-finger gestures on the paper change the view without advancing the fold or touching |
| 6 | 7 | /// the diagram. XCUITest has no two-finger drag, so a pinch and a rotation stand in for it. |
| 7 | 8 | final class AccessibilityAuditTests: XCTestCase { |
| @@ -59,7 +60,8 @@ final class AccessibilityAuditTests: XCTestCase { | ||
| 59 | 60 | |
| 60 | 61 | // MARK: - Helpers |
| 61 | 62 | |
| 62 | /// The model list, then every step of the cup, each advanced by the user's own drag. | |
| 63 | /// The model list, the cup's step list, then every step of the cup, each advanced by the user's | |
| 64 | /// own drag. | |
| 63 | 65 | private func everyScreen(textSize: String?) throws { |
| 64 | 66 | sizeName = textSize == nil ? "default" : "largest" |
| 65 | 67 | let app = XCUIApplication() |
| @@ -70,6 +72,11 @@ final class AccessibilityAuditTests: XCTestCase { | ||
| 70 | 72 | app.buttons["Cup"].tap() |
| 71 | 73 | let index = app.staticTexts["step.index"] |
| 72 | 74 | XCTAssertTrue(index.waitForExistence(timeout: 5)) |
| 75 | app.buttons["steps.button"].tap() | |
| 76 | XCTAssertTrue(app.buttons["step.1"].waitForExistence(timeout: 5)) | |
| 77 | try audit(app, "step list") | |
| 78 | app.buttons["step.1"].tap() | |
| 79 | XCTAssertTrue(app.buttons["step.1"].waitForNonExistence(timeout: 5)) | |
| 73 | 80 | while true { |
| 74 | 81 | let step = index.label |
| 75 | 82 | try audit(app, "step \(step)") |
App/UITests/StepListTests.swift added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | import XCTest | |
| 2 | ||
| 3 | final class StepListTests: XCTestCase { | |
| 4 | override func setUp() { | |
| 5 | continueAfterFailure = false | |
| 6 | } | |
| 7 | ||
| 8 | func testTheStepListOpensAChosenStepAtItsStart() { | |
| 9 | let app = XCUIApplication(); app.launch() | |
| 10 | app.buttons["Cup"].tap() | |
| 11 | app.buttons["steps.button"].tap() | |
| 12 | app.buttons["step.5"].tap() | |
| 13 | XCTAssertEqual(app.staticTexts["step.index"].label, "5") | |
| 14 | XCTAssertEqual(app.otherElements["fold.paper"].value as? String, "0%") | |
| 15 | } | |
| 16 | ||
| 17 | func testTheStepListNamesEveryStep() { | |
| 18 | let app = XCUIApplication(); app.launch() | |
| 19 | app.buttons["Cup"].tap() | |
| 20 | let caption = app.staticTexts["diagram.caption"].label | |
| 21 | app.buttons["steps.button"].tap() | |
| 22 | let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'step.'")) | |
| 23 | XCTAssertTrue(rows.firstMatch.waitForExistence(timeout: 5)) | |
| 24 | XCTAssertEqual(rows.count, 6) | |
| 25 | for n in 1...6 { | |
| 26 | let label = app.buttons["step.\(n)"].label | |
| 27 | XCTAssertTrue(label.hasPrefix("Step \(n), "), label) | |
| 28 | XCTAssertGreaterThan(label.count, "Step \(n), ".count) | |
| 29 | } | |
| 30 | XCTAssertEqual(app.buttons["step.1"].label, "Step 1, \(caption)") | |
| 31 | XCTAssertTrue(app.buttons["step.1"].isSelected) | |
| 32 | XCTAssertFalse(app.buttons["step.2"].isSelected) | |
| 33 | } | |
| 34 | ||
| 35 | func testChoosingTheCurrentStepClosesTheListAndLeavesTheFoldAlone() { | |
| 36 | let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch() | |
| 37 | app.buttons["Cup"].tap() | |
| 38 | dragCurrentFold(app, to: 0.5) | |
| 39 | let released = app.otherElements["fold.paper"].value as? String | |
| 40 | app.buttons["steps.button"].tap() | |
| 41 | app.buttons["step.1"].tap() | |
| 42 | XCTAssertTrue(app.buttons["step.1"].waitForNonExistence(timeout: 5)) | |
| 43 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") | |
| 44 | XCTAssertEqual(app.otherElements["fold.paper"].value as? String, released) | |
| 45 | } | |
| 46 | ||
| 47 | func testTheTitleCountsTheSteps() { | |
| 48 | let app = XCUIApplication(); app.launch() | |
| 49 | app.buttons["Cup"].tap() | |
| 50 | XCTAssertTrue(app.navigationBars["Step 1 of 6"].waitForExistence(timeout: 5)) | |
| 51 | } | |
| 52 | } | |
Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift +103 −26
| @@ -19,11 +19,20 @@ public struct FoldParameterMapping: Sendable { | ||
| 19 | 19 | /// Whether every segment is a straight line down, so a drag cannot follow the fold anywhere. |
| 20 | 20 | public let isDegenerate: Bool |
| 21 | 21 | |
| 22 | /// Where a drag is on the path: its parameter and the segment it is in. At a boundary `t` | |
| 23 | /// alone does not say which: a drag that reaches a boundary has crossed it. | |
| 24 | public struct Position: Sendable, Equatable { | |
| 25 | public let t: Double | |
| 26 | let segment: Int | |
| 27 | } | |
| 28 | ||
| 22 | 29 | /// The search polyline: `path`'s samples with the segment boundaries added. |
| 23 | 30 | private let ts: [Double] |
| 24 | 31 | private let points: [SIMD2<Double>] |
| 25 | /// Index ranges of `ts` searched one at a time, in order. | |
| 32 | /// Index ranges of `ts`, one per segment, in order. | |
| 26 | 33 | private let segments: [ClosedRange<Int>] |
| 34 | /// Per segment, whether a drag can cross back over its start: not at a fold-and-unfold's peak. | |
| 35 | private let reversible: [Bool] | |
| 27 | 36 | |
| 28 | 37 | private static let samples = 129 |
| 29 | 38 | private static let minimumLength = 8.0 |
| @@ -34,12 +43,12 @@ public struct FoldParameterMapping: Sendable { | ||
| 34 | 43 | private static let preference = 0.5 |
| 35 | 44 | /// How far past the best point so far the search continues, in points. |
| 36 | 45 | private static let slack = 8.0 |
| 37 | /// How near its segment's end, along the path, a point counts as the end, in points. | |
| 46 | /// How near the path's end, measured along it, a point counts as the end, in points. | |
| 38 | 47 | private static let endTolerance = 0.5 |
| 39 | 48 | |
| 40 | 49 | public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) { |
| 41 | 50 | var followed: [(faces: [Int], window: ClosedRange<Double>)] |
| 42 | var boundaries: Set<Double> = [0, 1] | |
| 51 | var boundaries: Set<Double> = [0, 1], peaks: Set<Double> = [] | |
| 43 | 52 | if step.nonRigid, let pop = step.pop { |
| 44 | 53 | followed = step.axes.map { (Array($0.movingFaces), 0...1) } |
| 45 | 54 | boundaries.formUnion([pop.phases.lowerBound, pop.phases.upperBound]) |
| @@ -47,11 +56,12 @@ public struct FoldParameterMapping: Sendable { | ||
| 47 | 56 | followed = step.axes.map { (Array($0.movingFaces), $0.window) } |
| 48 | 57 | for w in step.axes.map(\.window) { |
| 49 | 58 | boundaries.formUnion([w.lowerBound, w.upperBound]) |
| 50 | if step.kind == .foldAndUnfold { boundaries.insert((w.lowerBound + w.upperBound) / 2) } | |
| 59 | if step.kind == .foldAndUnfold { peaks.insert((w.lowerBound + w.upperBound) / 2) } | |
| 51 | 60 | } |
| 52 | 61 | } |
| 53 | 62 | if followed.isEmpty { followed = [(Array(file.facesVertices.indices), 0...1)] } |
| 54 | let bounds = boundaries.sorted() | |
| 63 | let bounds = boundaries.union(peaks).sorted() | |
| 64 | reversible = bounds.dropLast().map { $0 > 0 && !peaks.contains($0) } | |
| 55 | 65 | |
| 56 | 66 | let n = Double(Self.samples - 1) |
| 57 | 67 | let grid = (0..<Self.samples).map { Double($0) / n } |
| @@ -98,36 +108,102 @@ public struct FoldParameterMapping: Sendable { | ||
| 98 | 108 | return points[i] + u * (points[i + 1] - points[i]) |
| 99 | 109 | } |
| 100 | 110 | |
| 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. | |
| 111 | /// The position at `t`, clamped to 0...1; at a boundary, in the later segment. | |
| 112 | public func position(at t: Double) -> Position { | |
| 113 | let t = min(max(t, 0), 1) | |
| 114 | return Position(t: t, segment: segments.lastIndex { ts[$0.lowerBound] <= t }!) | |
| 115 | } | |
| 116 | ||
| 117 | /// The parameter `position(grabbedAt:translation:current:)` gives from `position(at: current)`. | |
| 118 | public func parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double { | |
| 119 | position(grabbedAt: grabbedAt, translation: translation, current: position(at: current)).t | |
| 120 | } | |
| 121 | ||
| 122 | /// The position whose point of `path` is nearest `grabbedAt + translation`, where `grabbedAt` | |
| 123 | /// is `point(at:)` of t when the drag began. | |
| 124 | /// | |
| 125 | /// The search walks the path outward from `current` within its segment. It also searches the | |
| 126 | /// segment beyond a boundary when `current` is within one sample of the boundary, or when the | |
| 127 | /// nearest point is the boundary itself, so that the finger has reached it. A neighbour's point | |
| 128 | /// is taken only if strictly nearer. So where the path doubles back on screen at a boundary, a | |
| 129 | /// finger moving along the retraced stretch stays in the segment the drag is in, and changes | |
| 130 | /// segment only at the turnaround. A drag that reaches a boundary crosses it, so the next | |
| 131 | /// movement along a retraced stretch continues into the segment beyond. Boundaries are crossed | |
| 132 | /// both ways, except a fold-and-unfold's peak, which is crossed only forward. A point within | |
| 133 | /// half a point of the path's end, measured along the path, is the end. | |
| 107 | 134 | /// |
| 108 | 135 | /// 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) } | |
| 136 | /// points from `current`, which is then the position when the drag began. | |
| 137 | public func position(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Position) -> Position { | |
| 138 | if isDegenerate { return position(at: current.t + translation.y / Self.fallbackThrow) } | |
| 113 | 139 | |
| 114 | 140 | let target = grabbedAt + translation |
| 115 | let segment = segments.last { ts[$0.lowerBound] <= current }! | |
| 141 | let s = current.segment | |
| 116 | 142 | // 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 } | |
| 143 | var start = segments[s].lowerBound | |
| 144 | while start + 1 < segments[s].upperBound && ts[start + 1] <= current.t { start += 1 } | |
| 119 | 145 | |
| 120 | func nearest(onEdge i: Int) -> (edge: Int, u: Double, distance: Double) { | |
| 146 | let own = nearest(target, in: s, from: start, directions: [1, -1]) | |
| 147 | var best = own | |
| 148 | for direction in [1, -1] { | |
| 149 | let edge = direction > 0 ? segments[s].upperBound - 1 : segments[s].lowerBound + 1 | |
| 150 | var near = direction > 0 ? current.t >= ts[edge] : current.t <= ts[edge] | |
| 151 | var from = own | |
| 152 | while near || from.toBoundary(direction) == 0 { | |
| 153 | let n = from.segment + direction | |
| 154 | guard n >= 0 && n < segments.count && (direction > 0 || reversible[from.segment]) else { break } | |
| 155 | let candidate = nearest(target, in: n, from: direction > 0 ? segments[n].lowerBound : segments[n].upperBound - 1, | |
| 156 | directions: [direction]) | |
| 157 | guard candidate.distance < best.distance else { break } | |
| 158 | best = candidate | |
| 159 | from = candidate | |
| 160 | near = false | |
| 161 | } | |
| 162 | } | |
| 163 | ||
| 164 | if best.segment == segments.count - 1 && best.toBoundary(1) <= Self.endTolerance { | |
| 165 | return Position(t: 1, segment: best.segment) | |
| 166 | } | |
| 167 | let t = (1 - best.u) * ts[best.edge] + best.u * ts[best.edge + 1] | |
| 168 | var segment = best.segment | |
| 169 | if t != current.t { | |
| 170 | if best.toBoundary(1) == 0 && segment + 1 < segments.count { | |
| 171 | segment += 1 | |
| 172 | } else if best.toBoundary(-1) == 0 && reversible[segment] { | |
| 173 | segment -= 1 | |
| 174 | } | |
| 175 | } | |
| 176 | return Position(t: t, segment: segment) | |
| 177 | } | |
| 178 | ||
| 179 | /// A point of the search polyline: `u` of the way along edge `edge` of segment `segment`. | |
| 180 | private struct Nearest { | |
| 181 | let segment: Int | |
| 182 | let edge: Int | |
| 183 | let u: Double | |
| 184 | let distance: Double | |
| 185 | /// Distance along the path to the segment's end (`direction` 1) or start (−1). | |
| 186 | let toEnd: Double | |
| 187 | let toStart: Double | |
| 188 | ||
| 189 | func toBoundary(_ direction: Int) -> Double { direction > 0 ? toEnd : toStart } | |
| 190 | } | |
| 191 | ||
| 192 | /// The point of segment `s` nearest `target`, walking outward from edge `start` in each of | |
| 193 | /// `directions` until an edge is `slack` farther than the best so far. | |
| 194 | private func nearest(_ target: SIMD2<Double>, in s: Int, from start: Int, directions: [Int]) -> Nearest { | |
| 195 | let segment = segments[s] | |
| 196 | func onEdge(_ i: Int) -> (edge: Int, u: Double, distance: Double) { | |
| 121 | 197 | let a = points[i], d = points[i + 1] - points[i] |
| 122 | 198 | let lengthSquared = dot(d, d) |
| 123 | 199 | let u = lengthSquared > 0 ? min(max(dot(target - a, d) / lengthSquared, 0), 1) : 0 |
| 124 | 200 | return (i, u, distance(a + u * d, target)) |
| 125 | 201 | } |
| 126 | var best = nearest(onEdge: start) | |
| 127 | for direction in [1, -1] { | |
| 202 | var best = onEdge(start) | |
| 203 | for direction in directions { | |
| 128 | 204 | var i = start + direction |
| 129 | 205 | while i >= segment.lowerBound && i < segment.upperBound { |
| 130 | let candidate = nearest(onEdge: i) | |
| 206 | let candidate = onEdge(i) | |
| 131 | 207 | if candidate.distance < best.distance { |
| 132 | 208 | best = candidate |
| 133 | 209 | } else if candidate.distance > best.distance + Self.slack { |
| @@ -136,10 +212,11 @@ public struct FoldParameterMapping: Sendable { | ||
| 136 | 212 | i += direction |
| 137 | 213 | } |
| 138 | 214 | } |
| 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] | |
| 215 | let length = distance(points[best.edge], points[best.edge + 1]) | |
| 216 | var toEnd = (1 - best.u) * length, toStart = best.u * length | |
| 217 | for i in best.edge + 1 ..< segment.upperBound { toEnd += distance(points[i], points[i + 1]) } | |
| 218 | for i in segment.lowerBound ..< best.edge { toStart += distance(points[i], points[i + 1]) } | |
| 219 | return Nearest(segment: s, edge: best.edge, u: best.u, distance: best.distance, toEnd: toEnd, toStart: toStart) | |
| 143 | 220 | } |
| 144 | 221 | } |
| 145 | 222 | |
Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift +64
| @@ -126,3 +126,67 @@ import Testing | ||
| 126 | 126 | let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak) |
| 127 | 127 | #expect(abs(back - 0.6) < 0.01) |
| 128 | 128 | } |
| 129 | ||
| 130 | /// The mapping for the reverse fixture's non-rigid step, seen from above. | |
| 131 | private func reverseMapping() throws -> FoldParameterMapping { | |
| 132 | let file = try compiled("reverse") | |
| 133 | return FoldParameterMapping(file: file, step: try readSteps(file)[1], | |
| 134 | camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4), | |
| 135 | viewportSize: SIMD2(800, 600)) | |
| 136 | } | |
| 137 | ||
| 138 | @Test func aNonRigidStepCanBeDraggedBackThroughItsPhases() throws { | |
| 139 | // the pop's path starts back along the open's, so dragging back passes that turnaround too | |
| 140 | let m = try reverseMapping() | |
| 141 | var t = 0.0 | |
| 142 | for p in m.path.dropFirst() { t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) } | |
| 143 | #expect(t == 1) | |
| 144 | for p in m.path.reversed().dropFirst() { | |
| 145 | let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) | |
| 146 | #expect(next <= t + 1e-9) | |
| 147 | t = next | |
| 148 | } | |
| 149 | #expect(t < 0.01) | |
| 150 | } | |
| 151 | ||
| 152 | @Test func aFoldAndUnfoldStillUnfoldsAfterItsPeak() throws { | |
| 153 | // past the peak the return half retraces the outbound half, so moving toward the start unfolds | |
| 154 | let m = try mapping("quarters.fold", step: 1) | |
| 155 | var t = 0.0 | |
| 156 | for p in m.path[1...80] { t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) } | |
| 157 | #expect(abs(t - 0.625) < 0.01) | |
| 158 | for p in m.path[0..<48].reversed() { | |
| 159 | let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) | |
| 160 | #expect(next >= t - 1e-9) | |
| 161 | t = next | |
| 162 | } | |
| 163 | #expect(t == 1) | |
| 164 | } | |
| 165 | ||
| 166 | @Test func aStaggeredStepCanBeDraggedBackPastItsWindowBoundary() throws { | |
| 167 | // seen from above, the second window's path retraces the first's, so samples 63 and 65 are one | |
| 168 | // screen point and only the drag's position says which window it is in | |
| 169 | let m = try mapping("letter-staggered.fold", step: 1) | |
| 170 | var position = m.position(at: 0) | |
| 171 | for k in Array(1...96) + Array((0..<96).reversed()) { | |
| 172 | position = m.position(grabbedAt: m.path[0], translation: m.path[k] - m.path[0], current: position) | |
| 173 | #expect(abs(position.t - Double(k) / 128) < 0.01, "sample \(k)") | |
| 174 | } | |
| 175 | } | |
| 176 | ||
| 177 | @Test func aDragOnARetracedStretchStaysInItsPhase() throws { | |
| 178 | // the pop's samples 44...54 lie within half a point of the open's path; a finger there stays | |
| 179 | // in the phase the drag is in until it reaches the turnaround | |
| 180 | let m = try reverseMapping() | |
| 181 | let phases = try readSteps(compiled("reverse"))[1].pop!.phases | |
| 182 | var opening = m.position(at: 0) | |
| 183 | for k in 1...36 { opening = m.position(grabbedAt: m.path[0], translation: m.path[k] - m.path[0], current: opening) } | |
| 184 | var popping = opening | |
| 185 | for k in 37...54 { popping = m.position(grabbedAt: m.path[0], translation: m.path[k] - m.path[0], current: popping) } | |
| 186 | #expect(popping.t > phases.lowerBound) | |
| 187 | for k in 44...54 { | |
| 188 | let p = m.path[k] - m.path[0] | |
| 189 | #expect(m.position(grabbedAt: m.path[0], translation: p, current: opening).t < phases.lowerBound, "sample \(k)") | |
| 190 | #expect(m.position(grabbedAt: m.path[0], translation: p, current: popping).t > phases.lowerBound, "sample \(k)") | |
| 191 | } | |
| 192 | } | |