Commit 359d585089

359d5850891e498531387bbcd020996bb8c355e3

parent: 83d69fc779

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-20 02:24 UTC

foldc: solve only the axes on a loop's cycle, keep other windows

Ref #4

Layout: unified · split

Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +35 −14
@@ -27,6 +27,8 @@ public enum CompileError: Error, Equatable, Sendable {
27 case creaseListMismatch(step: Int) 27 case creaseListMismatch(step: Int)
28 /// The step names a `spine`; reverse folds and sinks are compiled by the non-rigid path. 28 /// The step names a `spine`; reverse folds and sinks are compiled by the non-rigid path.
29 case nonRigidStepNotSupported(step: Int) 29 case nonRigidStepNotSupported(step: Int)
30 /// An axis the step solves to close a loop has a scripted window other than the driver's.
31 case solvedAxisWindowConflict(step: Int, edge: Int)
30} 32}
31 33
32/// Samples in a solved curve, evenly spaced over its window. 34/// Samples in a solved curve, evenly spaced over its window.
@@ -99,10 +101,10 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to
99 edgesFoldAngle: previous.edgesFoldAngle, faceOrders: [], step: record)) 101 edgesFoldAngle: previous.edgesFoldAngle, faceOrders: [], step: record))
100 var step = try readStep(n, in: draft) 102 var step = try readStep(n, in: draft)
101 if let plan, !plan.loops.isEmpty { 103 if let plan, !plan.loops.isEmpty {
102 record = try solveLoops(n, record, step, draft) 104 record = try solveLoops(n, record, step, loops: plan.loops, draft)
103 draft.frames[n].step = record 105 draft.frames[n].step = record
104 step = try readStep(n, in: draft) 106 step = try readStep(n, in: draft)
105 try checkClosure(n, step, draft, solved: record.axes.contains { $0.angles != nil }) 107 try checkClosure(n, step, driver: record.axes[0].edge, draft, solved: record.axes.contains { $0.angles != nil })
106 } 108 }
107 let interpolator = FoldInterpolator(file: draft, step: step) 109 let interpolator = FoldInterpolator(file: draft, step: step)
108 110
@@ -366,19 +368,38 @@ func sheetExtent(_ file: FoldFile) -> Double {
366 368
367// MARK: - Loops 369// MARK: - Loops
368 370
369/// Holds the driver (the first axis in `record`) linear on its window and solves every other 371/// Holds the driver (the first axis in `record`) linear on its window and solves the other axes
370/// axis so the loops stay closed: damped Gauss–Newton on the gap between vertex copies, continued 372/// on a loop's cycle, the tree path between the two sides of a loop crease, so the loops stay
371/// along the window from the previous samples. Each solved axis takes the driver's window and a 373/// closed: damped Gauss–Newton on the gap between vertex copies, continued along the window from
372/// curve of 257 samples, or none when it is linear to within 1e-9°; the last sample is the end 374/// the previous samples. Each solved axis takes the driver's window and a curve of 257 samples, or
373/// angle exactly. 375/// none when it is linear to within 1e-9°; the last sample is the end angle exactly. Axes on no
374private func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, _ file: FoldFile) throws -> StepRecord { 376/// cycle stay linear on their own windows.
377///
378/// - Throws: `solvedAxisWindowConflict` when a solved axis is scripted on another window.
379private func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int],
380 _ file: FoldFile) throws -> StepRecord {
375 guard let driver = step.axes.firstIndex(where: { $0.edge == record.axes[0].edge }) else { return record } 381 guard let driver = step.axes.firstIndex(where: { $0.edge == record.axes[0].edge }) else { return record }
376 let free = step.axes.indices.filter { $0 != driver } 382 var axisOfFace: [Int: Int] = [:]
383 for (a, axis) in step.axes.enumerated() {
384 for f in axis.movingFaces { axisOfFace[f] = a }
385 }
386 func carriers(_ f: Int) -> Set<Int> {
387 var result = Set<Int>(), a = axisOfFace[f]
388 while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent }
389 return result
390 }
391 let edgeFaces = edgesFaces(file)
392 let onCycle = loops.reduce(into: Set<Int>()) { cycle, e in
393 cycle.formUnion(carriers(edgeFaces[e][0]).symmetricDifference(carriers(edgeFaces[e][1])))
394 }
395 let free = onCycle.subtracting([driver]).sorted()
377 guard !free.isEmpty else { return record } 396 guard !free.isEmpty else { return record }
397 for a in free where step.axes[a].window != step.axes[driver].window {
398 throw CompileError.solvedAxisWindowConflict(step: n, edge: step.axes[a].edge)
399 }
378 400
379 let kinematics = LoopKinematics(step: step, file: file) 401 let kinematics = LoopKinematics(step: step, file: file)
380 let tolerance = sheetExtent(file) * relativeTolerance 402 let tolerance = sheetExtent(file) * relativeTolerance
381 let window = step.axes[driver].window
382 let fraction = { (k: Int) in Double(k) / Double(curveSamples - 1) } 403 let fraction = { (k: Int) in Double(k) / Double(curveSamples - 1) }
383 func linear(_ axis: FoldAxis, _ u: Double) -> Double { 404 func linear(_ axis: FoldAxis, _ u: Double) -> Double {
384 step.kind == .foldAndUnfold 405 step.kind == .foldAndUnfold
@@ -409,7 +430,7 @@ private func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, _ file
409 let r = axes[i] 430 let r = axes[i]
410 axes[i] = AxisRecord(edge: r.edge, movingFaces: r.movingFaces, startAngle: r.startAngle, 431 axes[i] = AxisRecord(edge: r.edge, movingFaces: r.movingFaces, startAngle: r.startAngle,
411 endAngle: r.endAngle, peakAngle: r.peakAngle, parent: r.parent, 432 endAngle: r.endAngle, peakAngle: r.peakAngle, parent: r.parent,
412 window: window == 0...1 ? nil : [window.lowerBound, window.upperBound], 433 window: r.window,
413 angles: isLinear ? nil : curve) 434 angles: isLinear ? nil : curve)
414 } 435 }
415 return StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, 436 return StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction,
@@ -419,12 +440,12 @@ private func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, _ file
419} 440}
420 441
421/// Checks the step's loops stay closed as its axes move, at four times the curve sample density 442/// Checks the step's loops stay closed as its axes move, at four times the curve sample density
422/// over the driver's window and over the whole step. 443/// over the window of the axis on `driver` and over the whole step.
423private func checkClosure(_ n: Int, _ step: FoldStep, _ file: FoldFile, solved: Bool) throws { 444private func checkClosure(_ n: Int, _ step: FoldStep, driver: Int, _ file: FoldFile, solved: Bool) throws {
424 let kinematics = LoopKinematics(step: step, file: file) 445 let kinematics = LoopKinematics(step: step, file: file)
425 let tolerance = sheetExtent(file) * relativeTolerance 446 let tolerance = sheetExtent(file) * relativeTolerance
426 let intervals = 4 * (curveSamples - 1) 447 let intervals = 4 * (curveSamples - 1)
427 let window = step.axes.first?.window ?? 0...1 448 let window = step.axes.first { $0.edge == driver }?.window ?? 0...1
428 let times = (0...intervals).flatMap { k -> [Double] in 449 let times = (0...intervals).flatMap { k -> [Double] in
429 let u = Double(k) / Double(intervals) 450 let u = Double(k) / Double(intervals)
430 return [u, window.lowerBound + u * (window.upperBound - window.lowerBound)] 451 return [u, window.lowerBound + u * (window.upperBound - window.lowerBound)]
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +41
@@ -168,3 +168,44 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
168 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) 168 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
169 } 169 }
170} 170}
171
172/// `letter-sequential-cp.fold`'s sheet with the x = 1 crease split at (1, 1.5) into e8 (lower)
173/// and e10 (upper), so folding along it closes a loop of two coincident edges.
174private func splitLetterPattern() -> FoldFile {
175 let points: [SIMD3<Double>] = [
176 SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(3, 0, 0),
177 SIMD3(3, 3, 0), SIMD3(2, 3, 0), SIMD3(1, 3, 0), SIMD3(0, 3, 0), SIMD3(1, 1.5, 0),
178 ]
179 let assignment = Array(repeating: EdgeAssignment.boundary, count: 8) + [.valley, .valley, .valley]
180 return FoldFile(fileSpec: 1.2, fileTitle: "Split letter", fileAuthor: "Traditional",
181 fileClasses: ["creasePattern"],
182 edgesVertices: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0],
183 [1, 8], [2, 5], [8, 6]],
184 facesVertices: [[0, 1, 8, 6, 7], [1, 2, 5, 6, 8], [2, 3, 4, 5]],
185 edgesFirstCreasedAtStep: Array(repeating: nil, count: 11),
186 frames: [FoldFrame(verticesCoords: points, edgesAssignment: assignment,
187 edgesFoldAngle: Array(repeating: 0, count: 11), faceOrders: [])])
188}
189
190@Test func anAxisOffEveryLoopKeepsItsWindowAndStaysLinear() throws {
191 let script = FoldScript(creasePattern: "", title: "Split letter", steps: [
192 ScriptStep(kind: .fold, instruction: "Valley fold the left third over, then the right third over the top.",
193 creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1.5)), .betweenVertices(SIMD2(2, 0), SIMD2(2, 3))],
194 movingSide: [SIMD2(0.5, 1.5), SIMD2(2.5, 1.5)], windows: [[0, 0.5], [0.5, 1]]),
195 ])
196 let axes = try #require(try compile(script, pattern: splitLetterPattern()).frames[1].step?.axes)
197 let flap = try #require(axes.first { $0.edge == 9 })
198 #expect(flap.window == [0.5, 1])
199 #expect(flap.angles == nil)
200}
201
202@Test func aSolvedAxisScriptedOnAnotherWindowIsRejected() throws {
203 let step = degreeFourScript().steps[0]
204 let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
205 ScriptStep(kind: .fold, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
206 windows: [[0, 1], [0, 0.5], [0, 1], [0, 1]]),
207 ])
208 #expect(throws: CompileError.solvedAxisWindowConflict(step: 1, edge: 11)) {
209 try compile(script, pattern: degreeFourPattern())
210 }
211}