Commit 8d06aa03b7
Verified · cmc
Layout: unified · split
Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +59 −30
| @@ -25,10 +25,12 @@ public enum CompileError: Error, Equatable, Sendable { | ||
| 25 | 25 | case missingAngle(step: Int) |
| 26 | 26 | /// `angles`, `peakAngles` or `windows` does not have one entry per crease. |
| 27 | 27 | case creaseListMismatch(step: Int) |
| 28 | /// The step names a `spine`; reverse folds and sinks are compiled by the non-rigid path. | |
| 29 | case nonRigidStepNotSupported(step: Int) | |
| 30 | 28 | /// An axis the step solves to close a loop has a scripted window other than the driver's. |
| 31 | 29 | case solvedAxisWindowConflict(step: Int, edge: Int) |
| 30 | /// The pop's largest relative change in a render-mesh edge's length exceeds 10%. | |
| 31 | case popTooStrained(step: Int, strain: Double) | |
| 32 | /// A reverse fold or sink names no `spine` to open on. | |
| 33 | case missingSpine(step: Int) | |
| 32 | 34 | } |
| 33 | 35 | |
| 34 | 36 | /// Samples in a solved curve, evenly spaced over its window. |
| @@ -40,7 +42,7 @@ private let creaseMatchTolerance = 1e-6 | ||
| 40 | 42 | /// A solved angle within this many degrees of linear at every sample is written without a curve. |
| 41 | 43 | private let linearTolerance = 1e-9 |
| 42 | 44 | /// A measured end angle within this many degrees of an expected one is taken to be it. |
| 43 | private let angleSnapTolerance = 1e-6 | |
| 45 | let angleSnapTolerance = 1e-6 | |
| 44 | 46 | /// Samples of a step checked for interpenetration. |
| 45 | 47 | private let interpenetrationSamples = 64 |
| 46 | 48 | |
| @@ -48,7 +50,8 @@ private let interpenetrationSamples = 64 | ||
| 48 | 50 | /// |
| 49 | 51 | /// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the |
| 50 | 52 | /// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed |
| 51 | /// and overridden, and the file so far validated and checked for interpenetration. | |
| 53 | /// and overridden, and the file so far validated and checked for interpenetration. A step that | |
| 54 | /// names a `spine` is a reverse fold or sink and moves by `compilePop`'s open, pop and close. | |
| 52 | 55 | public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile { |
| 53 | 56 | let flat = pattern.frames[0] |
| 54 | 57 | for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 { |
| @@ -82,14 +85,18 @@ public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile | ||
| 82 | 85 | /// Compiles step `n` and appends frame n to `file`. |
| 83 | 86 | private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile, |
| 84 | 87 | finalAssignment: [EdgeAssignment]) throws { |
| 85 | if script.spine != nil { throw CompileError.nonRigidStepNotSupported(step: n) } | |
| 88 | let technique = script.technique ?? .plain | |
| 89 | if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) { | |
| 90 | throw CompileError.missingSpine(step: n) | |
| 91 | } | |
| 92 | if script.spine != nil && script.kind != .fold { throw CompileError.unresolvedCrease(step: n) } | |
| 86 | 93 | let previous = file.frames[n - 1] |
| 87 | 94 | |
| 88 | 95 | var plan: FoldPlan? |
| 89 | 96 | if script.kind == .fold || script.kind == .foldAndUnfold { |
| 90 | 97 | plan = try planFolds(n, script, file, finalAssignment) |
| 91 | 98 | } |
| 92 | var record = StepRecord(kind: script.kind, technique: script.technique ?? .plain, | |
| 99 | var record = StepRecord(kind: script.kind, technique: technique, | |
| 93 | 100 | instruction: script.instruction, axes: plan?.axes ?? [], |
| 94 | 101 | rotateDegrees: script.rotateDegrees, turnOverAxis: script.turnOverAxis, |
| 95 | 102 | repeatOf: script.repeatOf, viewpoint: viewpoint) |
| @@ -106,7 +113,7 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to | ||
| 106 | 113 | step = try readStep(n, in: draft) |
| 107 | 114 | try checkClosure(n, step, driver: record.axes[0].edge, draft, solved: record.axes.contains { $0.angles != nil }) |
| 108 | 115 | } |
| 109 | let interpolator = FoldInterpolator(file: draft, step: step) | |
| 116 | var interpolator = FoldInterpolator(file: draft, step: step) | |
| 110 | 117 | |
| 111 | 118 | var angles = previous.edgesFoldAngle |
| 112 | 119 | var assignment = previous.edgesAssignment |
| @@ -123,6 +130,21 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to | ||
| 123 | 130 | |
| 124 | 131 | var frame = FoldFrame(verticesCoords: interpolator.positions(at: 1), edgesAssignment: assignment, |
| 125 | 132 | edgesFoldAngle: angles, faceOrders: [], step: record) |
| 133 | if script.spine != nil { | |
| 134 | // the step's axes give frame n's coordinates; the pop is how the paper gets there | |
| 135 | let pop = try compilePop(step: n, script: script, before: previous, after: frame, file: file) | |
| 136 | record = withPop(record, pop) | |
| 137 | draft.frames[n].step = record | |
| 138 | step = try readStep(n, in: draft) | |
| 139 | interpolator = FoldInterpolator(file: draft, step: step) | |
| 140 | frame.verticesCoords = interpolator.positions(at: 1) | |
| 141 | frame.step = record | |
| 142 | for (e, angle) in popEndAngles(step, interpolator, previous: previous, file: file) { | |
| 143 | frame.edgesFoldAngle[e] = angle | |
| 144 | frame.edgesAssignment[e] = angle > 0 ? .valley : angle < 0 ? .mountain : .flat | |
| 145 | if file.edgesFirstCreasedAtStep[e] == nil { file.edgesFirstCreasedAtStep[e] = n } | |
| 146 | } | |
| 147 | } | |
| 126 | 148 | let guess = guessFaceOrders(previous: previous, next: frame, step: record, file: file) |
| 127 | 149 | frame.faceOrders = try naming(n) { |
| 128 | 150 | try applyOrderOverrides(script.faceOrders ?? [], to: guess, frame: frame, viewpoint: viewpoint, file: file) |
| @@ -149,7 +171,9 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to | ||
| 149 | 171 | |
| 150 | 172 | let defects = validate(file) |
| 151 | 173 | guard defects.isEmpty else { throw CompileError.stepFailed(step: n, defects: defects) } |
| 152 | let collisions = interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples) | |
| 174 | let collisions = step.nonRigid | |
| 175 | ? meshInterpenetrations(interpolator, samples: interpenetrationSamples) | |
| 176 | : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples) | |
| 153 | 177 | guard collisions.isEmpty else { throw CompileError.interpenetration(step: n, collisions) } |
| 154 | 178 | } |
| 155 | 179 | |
| @@ -325,7 +349,7 @@ private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile, | ||
| 325 | 349 | |
| 326 | 350 | /// The edge a crease reference names: by index, or the edge whose endpoints in the crease |
| 327 | 351 | /// pattern are nearest the named points, within 1e-6. Boundary edges are not creases. |
| 328 | private func resolve(_ ref: CreaseRef, _ file: FoldFile, _ edgeFaces: [[Int]]) -> Int? { | |
| 352 | func resolve(_ ref: CreaseRef, _ file: FoldFile, _ edgeFaces: [[Int]]) -> Int? { | |
| 329 | 353 | switch ref { |
| 330 | 354 | case .edgeIndex(let e): |
| 331 | 355 | return edgeFaces.indices.contains(e) && edgeFaces[e].count == 2 ? e : nil |
| @@ -354,7 +378,7 @@ func face(containing point: SIMD2<Double>, _ file: FoldFile) -> Int? { | ||
| 354 | 378 | } |
| 355 | 379 | } |
| 356 | 380 | |
| 357 | private func onLine(_ p: SIMD3<Double>, _ a: SIMD3<Double>, _ b: SIMD3<Double>, _ tolerance: Double) -> Bool { | |
| 381 | func onLine(_ p: SIMD3<Double>, _ a: SIMD3<Double>, _ b: SIMD3<Double>, _ tolerance: Double) -> Bool { | |
| 358 | 382 | length(cross(p - a, normalize(b - a))) <= tolerance |
| 359 | 383 | } |
| 360 | 384 | |
| @@ -376,23 +400,10 @@ func sheetExtent(_ file: FoldFile) -> Double { | ||
| 376 | 400 | /// cycle stay linear on their own windows. |
| 377 | 401 | /// |
| 378 | 402 | /// - Throws: `solvedAxisWindowConflict` when a solved axis is scripted on another window. |
| 379 | private func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int], | |
| 380 | _ file: FoldFile) throws -> StepRecord { | |
| 403 | func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int], | |
| 404 | _ file: FoldFile) throws -> StepRecord { | |
| 381 | 405 | guard let driver = step.axes.firstIndex(where: { $0.edge == record.axes[0].edge }) else { return record } |
| 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() | |
| 406 | let free = axesOnCycles(step, loops: loops, file).subtracting([driver]).sorted() | |
| 396 | 407 | guard !free.isEmpty else { return record } |
| 397 | 408 | for a in free where step.axes[a].window != step.axes[driver].window { |
| 398 | 409 | throw CompileError.solvedAxisWindowConflict(step: n, edge: step.axes[a].edge) |
| @@ -439,9 +450,27 @@ private func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: | ||
| 439 | 450 | viewpoint: record.viewpoint) |
| 440 | 451 | } |
| 441 | 452 | |
| 453 | /// The indices in `step.axes` of the axes on some loop's cycle: the tree path between the two | |
| 454 | /// faces of a loop crease. | |
| 455 | func axesOnCycles(_ step: FoldStep, loops: [Int], _ file: FoldFile) -> Set<Int> { | |
| 456 | var axisOfFace: [Int: Int] = [:] | |
| 457 | for (a, axis) in step.axes.enumerated() { | |
| 458 | for f in axis.movingFaces { axisOfFace[f] = a } | |
| 459 | } | |
| 460 | func carriers(_ f: Int) -> Set<Int> { | |
| 461 | var result = Set<Int>(), a = axisOfFace[f] | |
| 462 | while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent } | |
| 463 | return result | |
| 464 | } | |
| 465 | let edgeFaces = edgesFaces(file) | |
| 466 | return loops.reduce(into: Set<Int>()) { cycle, e in | |
| 467 | cycle.formUnion(carriers(edgeFaces[e][0]).symmetricDifference(carriers(edgeFaces[e][1]))) | |
| 468 | } | |
| 469 | } | |
| 470 | ||
| 442 | 471 | /// Checks the step's loops stay closed as its axes move, at four times the curve sample density |
| 443 | 472 | /// over the window of the axis on `driver` and over the whole step. |
| 444 | private func checkClosure(_ n: Int, _ step: FoldStep, driver: Int, _ file: FoldFile, solved: Bool) throws { | |
| 473 | func checkClosure(_ n: Int, _ step: FoldStep, driver: Int, _ file: FoldFile, solved: Bool) throws { | |
| 445 | 474 | let kinematics = LoopKinematics(step: step, file: file) |
| 446 | 475 | let tolerance = sheetExtent(file) * relativeTolerance |
| 447 | 476 | let intervals = 4 * (curveSamples - 1) |
| @@ -484,8 +513,8 @@ private func loopEndAngles(_ n: Int, _ plan: FoldPlan, _ previous: FoldFrame, _ | ||
| 484 | 513 | /// The fold angle in degrees of an interior edge between faces `faces`, positive for a valley: |
| 485 | 514 | /// the turn from the first face's normal to the second's about the edge, directed as the second |
| 486 | 515 | /// face traverses it. |
| 487 | private func dihedral(_ e: Int, _ faces: [Int], _ positions: [SIMD3<Double>], _ normals: [SIMD3<Double>], | |
| 488 | _ file: FoldFile) -> Double { | |
| 516 | func dihedral(_ e: Int, _ faces: [Int], _ positions: [SIMD3<Double>], _ normals: [SIMD3<Double>], | |
| 517 | _ file: FoldFile) -> Double { | |
| 489 | 518 | let corners = file.facesVertices[faces[1]], ends = Set(file.edgesVertices[e]) |
| 490 | 519 | let i = corners.indices.first { ends == Set([corners[$0], corners[($0 + 1) % corners.count]]) }! |
| 491 | 520 | let d = normalize(positions[corners[(i + 1) % corners.count]] - positions[corners[i]]) |
| @@ -511,7 +540,7 @@ private struct Rigid { | ||
| 511 | 540 | |
| 512 | 541 | /// A step's axes as functions of their angles, and the gap between the copies of each vertex |
| 513 | 542 | /// that faces moving with different axes carry. |
| 514 | private struct LoopKinematics { | |
| 543 | struct LoopKinematics { | |
| 515 | 544 | let axes: [FoldAxis] |
| 516 | 545 | let start: [SIMD3<Double>] |
| 517 | 546 | /// Each vertex shared by faces that move differently, with the axes that move them, −1 for |
Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift added +297
| @@ -0,0 +1,297 @@ | ||
| 1 | import FoldFormat | |
| 2 | import Folding | |
| 3 | import simd | |
| 4 | ||
| 5 | /// The spine's fold angle when the flap is open, in degrees from flat, when the script gives none. | |
| 6 | private let defaultOpenAngle = 30.0 | |
| 7 | /// The boundaries of the pop on the step's t (decision 0002). | |
| 8 | private let phases = [1.0 / 3, 2.0 / 3] | |
| 9 | /// The largest relative change in a render-mesh edge's length the pop may reach (decision 0002). | |
| 10 | private let strainBound = 0.10 | |
| 11 | /// Samples of the pop measured for strain. | |
| 12 | private let popSamples = 64 | |
| 13 | /// Samples of the open and close phases along which end angles are unwrapped. | |
| 14 | private let angleSamples = 256 | |
| 15 | ||
| 16 | /// Decision 0002's open, pop and close for step `n`, whose script names the `spine` its flap opens | |
| 17 | /// on. `before` is frame n − 1; `after` is frame n as the step's axes place it, carrying the step's | |
| 18 | /// record; `file` holds frames 0…n − 1. | |
| 19 | /// | |
| 20 | /// The spine is the named crease and every edge on its line in `before`, each folded flat. The | |
| 21 | /// flap's layer nearer the viewpoint opens: the open axis turns the faces on that side of the | |
| 22 | /// spine, from ±180 to ±`openAngle`. The pop and close move on a tree cut along the spine and the | |
| 23 | /// step's creases, grown from the faces neither the opening nor the step moves, spine first. In | |
| 24 | /// `popped` the spine is held at ±`openAngle`, reversed where both its faces move in the step, and | |
| 25 | /// the other tree axes are solved to keep the paper whole, starting from `openAngle / 180` of | |
| 26 | /// their way. The close axes drive the named spine edge back to ±180 and solve the rest, as for a | |
| 27 | /// rigid step, and must arrive at `after`'s coordinates. | |
| 28 | /// | |
| 29 | /// - Throws: `unresolvedCrease` when the spine names no edge or is not folded flat, | |
| 30 | /// `noRigidMotion` when the flap cannot open on its spine, `popped` does not close or the close | |
| 31 | /// does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%. | |
| 32 | public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, | |
| 33 | file: FoldFile) throws -> PopRecord { | |
| 34 | guard let reference = script.spine, let record = after.step else { | |
| 35 | preconditionFailure("compilePop needs a script step with a spine and a frame with its record") | |
| 36 | } | |
| 37 | let edgeFaces = edgesFaces(file) | |
| 38 | let faceCount = file.facesVertices.count | |
| 39 | let tolerance = sheetExtent(file) * relativeTolerance | |
| 40 | let openAngle = script.openAngle ?? defaultOpenAngle | |
| 41 | ||
| 42 | guard let named = resolve(reference, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n) } | |
| 43 | let ends = file.edgesVertices[named].map { before.verticesCoords[$0] } | |
| 44 | let spine = [named] + edgeFaces.indices.filter { e in | |
| 45 | e != named && edgeFaces[e].count == 2 | |
| 46 | && file.edgesVertices[e].allSatisfy { onLine(before.verticesCoords[$0], ends[0], ends[1], tolerance) } | |
| 47 | } | |
| 48 | guard spine.allSatisfy({ abs(abs(before.edgesFoldAngle[$0]) - 180) <= angleSnapTolerance }) else { | |
| 49 | throw CompileError.unresolvedCrease(step: n) | |
| 50 | } | |
| 51 | ||
| 52 | var group = Array(repeating: -1, count: faceCount) | |
| 53 | for (a, axis) in record.axes.enumerated() { | |
| 54 | for f in axis.movingFaces { group[f] = a } | |
| 55 | } | |
| 56 | let moving = group.map { $0 >= 0 } | |
| 57 | let creased = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && group[edgeFaces[$0][0]] != group[edgeFaces[$0][1]] } | |
| 58 | ||
| 59 | // the layer nearer the viewer opens: of the named edge's faces, the one a valley puts on the | |
| 60 | // first face's normal side, or a mountain on the other | |
| 61 | let (f, g) = (edgeFaces[named][0], edgeFaces[named][1]) | |
| 62 | let normals = faceNormals(before, file) | |
| 63 | let gNearer = (before.edgesFoldAngle[named] > 0) == (dot(normals[f], record.viewpoint.eye) > 0) | |
| 64 | let (near, far) = gNearer ? (g, f) : (f, g) | |
| 65 | let sides = regions(cut: Set(spine), file, edgeFaces) | |
| 66 | let opening = (0..<faceCount).filter { sides[$0] == sides[near] } | |
| 67 | guard sides[far] != sides[near] else { throw CompileError.noRigidMotion(step: n) } | |
| 68 | let openSign = before.edgesFoldAngle[named] > 0 ? 1.0 : -1.0 | |
| 69 | let openAxes = [AxisRecord(edge: named, movingFaces: opening, startAngle: before.edgesFoldAngle[named], | |
| 70 | endAngle: openSign * openAngle, window: [0, phases[0]])] | |
| 71 | ||
| 72 | // the tree the pop and the close move on | |
| 73 | let fixed = Set((0..<faceCount).filter { !moving[$0] && !opening.contains($0) }) | |
| 74 | guard !fixed.isEmpty else { throw CompileError.noRigidMotion(step: n) } | |
| 75 | let order = spine + record.axes.map(\.edge).filter { !spine.contains($0) } | |
| 76 | + creased.filter { e in !spine.contains(e) && !record.axes.contains { $0.edge == e } } | |
| 77 | let tree = growTree(order: order, fixed: fixed, file, edgeFaces) | |
| 78 | ||
| 79 | // popped: the spine held open, reversed beyond the step's creases; the rest solved | |
| 80 | func held(_ e: Int) -> Double { | |
| 81 | let sign = before.edgesFoldAngle[e] > 0 ? 1.0 : -1.0 | |
| 82 | return (edgeFaces[e].allSatisfy { moving[$0] } ? -sign : sign) * openAngle | |
| 83 | } | |
| 84 | func closed(_ e: Int) -> Double { | |
| 85 | spine.contains(e) ? (held(e) > 0 ? 180 : -180) : after.edgesFoldAngle[e] | |
| 86 | } | |
| 87 | var guess: [Int: Double] = [:] | |
| 88 | for axis in tree.axes { | |
| 89 | let start = before.edgesFoldAngle[axis.edge] | |
| 90 | guess[axis.edge] = spine.contains(axis.edge) ? held(axis.edge) | |
| 91 | : start + (closed(axis.edge) - start) * openAngle / 180 | |
| 92 | } | |
| 93 | let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(spine), record, file) | |
| 94 | var poppedFrame = before | |
| 95 | poppedFrame.verticesCoords = popped.positions | |
| 96 | ||
| 97 | let closeAxes = try closing(n, tree, from: poppedFrame, start: popped.angles, end: closed, record, file) | |
| 98 | let pop = PopRecord(spine: spine, openAngle: openAngle, phases: phases, openAxes: openAxes, | |
| 99 | popped: popped.positions, closeAxes: closeAxes) | |
| 100 | var draft = file | |
| 101 | draft.frames.append(FoldFrame(verticesCoords: after.verticesCoords, edgesAssignment: after.edgesAssignment, | |
| 102 | edgesFoldAngle: after.edgesFoldAngle, faceOrders: [], step: withPop(record, pop))) | |
| 103 | let interpolator = FoldInterpolator(file: draft, step: try readStep(n, in: draft)) | |
| 104 | guard zip(interpolator.positions(at: 1), after.verticesCoords).allSatisfy({ simd_distance($0, $1) <= tolerance }) else { | |
| 105 | throw CompileError.noRigidMotion(step: n) | |
| 106 | } | |
| 107 | let worst = (0...popSamples).map { k in | |
| 108 | let t = phases[0] + Double(k) / Double(popSamples) * (phases[1] - phases[0]) | |
| 109 | return strain(interpolator.meshPositions(at: t), mesh: interpolator.mesh) | |
| 110 | }.max() ?? 0 | |
| 111 | guard worst <= strainBound else { throw CompileError.popTooStrained(step: n, strain: worst) } | |
| 112 | return pop | |
| 113 | } | |
| 114 | ||
| 115 | /// `record`, flagged non-rigid, with `pop`. | |
| 116 | func withPop(_ record: StepRecord, _ pop: PopRecord) -> StepRecord { | |
| 117 | StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, axes: record.axes, | |
| 118 | rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis, repeatOf: record.repeatOf, | |
| 119 | nonRigid: true, pop: pop, viewpoint: record.viewpoint) | |
| 120 | } | |
| 121 | ||
| 122 | /// The fold angle at the end of a non-rigid step of every edge its close axes crease, measured | |
| 123 | /// from the faces' normals along the open phase, at `popped` and along the close phase, unwrapped | |
| 124 | /// from frame n − 1's angle and taken to be ±180 or 0 when within 1e-6° of one. A close axis's | |
| 125 | /// edge ends at its end angle exactly. | |
| 126 | func popEndAngles(_ step: FoldStep, _ interpolator: FoldInterpolator, previous: FoldFrame, | |
| 127 | file: FoldFile) -> [Int: Double] { | |
| 128 | guard let pop = step.pop else { return [:] } | |
| 129 | let edgeFaces = edgesFaces(file) | |
| 130 | var axisOfFace = Array(repeating: -1, count: file.facesVertices.count) | |
| 131 | for (a, axis) in pop.closeAxes.enumerated() { | |
| 132 | for f in axis.movingFaces { axisOfFace[f] = a } | |
| 133 | } | |
| 134 | let edges = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && axisOfFace[edgeFaces[$0][0]] != axisOfFace[edgeFaces[$0][1]] } | |
| 135 | ||
| 136 | let (lower, upper) = (pop.phases.lowerBound, pop.phases.upperBound) | |
| 137 | let times = (1...angleSamples).map { lower * Double($0) / Double(angleSamples) } + [upper] | |
| 138 | + (1...angleSamples).map { upper + (1 - upper) * Double($0) / Double(angleSamples) } | |
| 139 | var current = Dictionary(uniqueKeysWithValues: edges.map { ($0, previous.edgesFoldAngle[$0]) }) | |
| 140 | for t in times { | |
| 141 | let positions = interpolator.positions(at: t) | |
| 142 | let normals = faceNormals(positions: positions, faces: file.facesVertices) | |
| 143 | for e in edges { | |
| 144 | let measured = dihedral(e, edgeFaces[e], positions, normals, file) | |
| 145 | current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded() | |
| 146 | } | |
| 147 | } | |
| 148 | for (e, angle) in current { | |
| 149 | current[e] = [180, -180, 0].first { abs(angle - $0) <= angleSnapTolerance } ?? angle | |
| 150 | } | |
| 151 | for axis in pop.closeAxes { current[axis.edge] = axis.endAngle } | |
| 152 | return current | |
| 153 | } | |
| 154 | ||
| 155 | /// A tree of regions over the faces: the faces connected across edges not in `order`, grown from | |
| 156 | /// the regions holding a `fixed` face across the edges in `order`. Each tree edge is an axis | |
| 157 | /// moving its child region's faces; each other edge of `order` between different regions closes | |
| 158 | /// a loop. | |
| 159 | private struct RegionTree { | |
| 160 | var axes: [(edge: Int, movingFaces: [Int], parent: Int?)] | |
| 161 | var loops: [Int] | |
| 162 | } | |
| 163 | ||
| 164 | private func growTree(order: [Int], fixed: Set<Int>, _ file: FoldFile, _ edgeFaces: [[Int]]) -> RegionTree { | |
| 165 | let region = regions(cut: Set(order), file, edgeFaces) | |
| 166 | let regionCount = (region.max() ?? -1) + 1 | |
| 167 | var node = Array(repeating: -1, count: regionCount) | |
| 168 | for f in fixed { node[region[f]] = 0 } | |
| 169 | var nodeCount = 1 | |
| 170 | for r in 0..<regionCount where node[r] < 0 { | |
| 171 | node[r] = nodeCount | |
| 172 | nodeCount += 1 | |
| 173 | } | |
| 174 | let nodeOfFace = region.map { node[$0] } | |
| 175 | ||
| 176 | var component = Array(0..<nodeCount) | |
| 177 | func find(_ x: Int) -> Int { | |
| 178 | var x = x | |
| 179 | while component[x] != x { x = component[x] } | |
| 180 | return x | |
| 181 | } | |
| 182 | var links: [(edge: Int, ends: (Int, Int))] = [] | |
| 183 | var loops: [Int] = [] | |
| 184 | for e in order { | |
| 185 | let a = nodeOfFace[edgeFaces[e][0]], b = nodeOfFace[edgeFaces[e][1]] | |
| 186 | guard a != b else { continue } | |
| 187 | if find(a) != find(b) { | |
| 188 | component[find(a)] = find(b) | |
| 189 | links.append((e, (a, b))) | |
| 190 | } else { | |
| 191 | loops.append(e) | |
| 192 | } | |
| 193 | } | |
| 194 | ||
| 195 | var parentNode = Array<Int?>(repeating: nil, count: nodeCount) | |
| 196 | var linkOfNode = Array<Int?>(repeating: nil, count: nodeCount) | |
| 197 | var reached: Set<Int> = [0] | |
| 198 | var queue = [0] | |
| 199 | while !queue.isEmpty { | |
| 200 | let a = queue.removeFirst() | |
| 201 | for (k, link) in links.enumerated() where link.ends.0 == a || link.ends.1 == a { | |
| 202 | let b = link.ends.0 == a ? link.ends.1 : link.ends.0 | |
| 203 | guard reached.insert(b).inserted else { continue } | |
| 204 | parentNode[b] = a | |
| 205 | linkOfNode[b] = k | |
| 206 | queue.append(b) | |
| 207 | } | |
| 208 | } | |
| 209 | let axes = links.enumerated().map { k, link in | |
| 210 | let child = linkOfNode[link.ends.0] == k ? link.ends.0 : link.ends.1 | |
| 211 | return (edge: link.edge, movingFaces: nodeOfFace.indices.filter { nodeOfFace[$0] == child }, | |
| 212 | parent: parentNode[child].flatMap { linkOfNode[$0] }) | |
| 213 | } | |
| 214 | return RegionTree(axes: axes, loops: loops) | |
| 215 | } | |
| 216 | ||
| 217 | /// The region of each face: faces connected across interior edges not in `cut`. | |
| 218 | private func regions(cut: Set<Int>, _ file: FoldFile, _ edgeFaces: [[Int]]) -> [Int] { | |
| 219 | var region = Array(repeating: -1, count: file.facesVertices.count) | |
| 220 | var count = 0 | |
| 221 | for seed in region.indices where region[seed] < 0 { | |
| 222 | region[seed] = count | |
| 223 | var stack = [seed] | |
| 224 | while let f = stack.popLast() { | |
| 225 | for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) { | |
| 226 | let g = faces[0] == f ? faces[1] : faces[0] | |
| 227 | if region[g] < 0 { | |
| 228 | region[g] = count | |
| 229 | stack.append(g) | |
| 230 | } | |
| 231 | } | |
| 232 | } | |
| 233 | count += 1 | |
| 234 | } | |
| 235 | return region | |
| 236 | } | |
| 237 | ||
| 238 | /// The tree's axes as records from `start` angles to `end` angles, on `window`. | |
| 239 | private func records(_ tree: RegionTree, start: (Int) -> Double, end: (Int) -> Double, | |
| 240 | window: [Double]?) -> [AxisRecord] { | |
| 241 | tree.axes.map { axis in | |
| 242 | AxisRecord(edge: axis.edge, movingFaces: axis.movingFaces, startAngle: start(axis.edge), | |
| 243 | endAngle: end(axis.edge), parent: axis.parent, window: window) | |
| 244 | } | |
| 245 | } | |
| 246 | ||
| 247 | /// `record` with `axes` in place of its own. | |
| 248 | private func withAxes(_ record: StepRecord, _ axes: [AxisRecord]) -> StepRecord { | |
| 249 | StepRecord(kind: .fold, technique: record.technique, instruction: record.instruction, axes: axes, | |
| 250 | viewpoint: record.viewpoint) | |
| 251 | } | |
| 252 | ||
| 253 | /// The pose with the tree's axes at `angles`, the edges in `holding` held there and the axes on a | |
| 254 | /// loop's cycle solved so the loops close. Returns the vertex positions and the solved angles. | |
| 255 | private func solvedPose(_ n: Int, _ tree: RegionTree, from before: FoldFrame, angles: [Int: Double], | |
| 256 | holding: Set<Int>, _ record: StepRecord, _ file: FoldFile) throws | |
| 257 | -> (positions: [SIMD3<Double>], angles: [Int: Double]) { | |
| 258 | func draft(_ angles: [Int: Double]) -> FoldFile { | |
| 259 | var draft = file | |
| 260 | draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment, | |
| 261 | edgesFoldAngle: before.edgesFoldAngle, faceOrders: [], | |
| 262 | step: withAxes(record, records(tree, start: { before.edgesFoldAngle[$0] }, | |
| 263 | end: { angles[$0]! }, window: nil)))) | |
| 264 | return draft | |
| 265 | } | |
| 266 | var solved = angles | |
| 267 | let first = draft(angles) | |
| 268 | let step = try readStep(n, in: first) | |
| 269 | let free = axesOnCycles(step, loops: tree.loops, first).filter { !holding.contains(step.axes[$0].edge) }.sorted() | |
| 270 | var values = step.axes.map(\.endAngle) | |
| 271 | let tolerance = sheetExtent(file) * relativeTolerance | |
| 272 | guard LoopKinematics(step: step, file: first).solve(&values, free: free) <= tolerance else { | |
| 273 | throw CompileError.noRigidMotion(step: n) | |
| 274 | } | |
| 275 | for (a, axis) in step.axes.enumerated() { solved[axis.edge] = values[a] } | |
| 276 | let last = draft(solved) | |
| 277 | return (FoldInterpolator(file: last, step: try readStep(n, in: last)).positions(at: 1), solved) | |
| 278 | } | |
| 279 | ||
| 280 | /// The close axes from `popped`: the named spine edge, first in the tree, linear from its popped | |
| 281 | /// angle to its end; the axes on a loop's cycle solved as for a rigid step; all on | |
| 282 | /// `[phases[1], 1]`. | |
| 283 | private func closing(_ n: Int, _ tree: RegionTree, from popped: FoldFrame, start: [Int: Double], | |
| 284 | end: (Int) -> Double, _ record: StepRecord, _ file: FoldFile) throws -> [AxisRecord] { | |
| 285 | var draft = file | |
| 286 | draft.frames[n - 1] = popped | |
| 287 | var close = withAxes(record, records(tree, start: { start[$0]! }, end: end, window: [phases[1], 1])) | |
| 288 | draft.frames.append(FoldFrame(verticesCoords: popped.verticesCoords, edgesAssignment: popped.edgesAssignment, | |
| 289 | edgesFoldAngle: popped.edgesFoldAngle, faceOrders: [], step: close)) | |
| 290 | var step = try readStep(n, in: draft) | |
| 291 | guard !tree.loops.isEmpty else { return close.axes } | |
| 292 | close = try solveLoops(n, close, step, loops: tree.loops, draft) | |
| 293 | draft.frames[n].step = close | |
| 294 | step = try readStep(n, in: draft) | |
| 295 | try checkClosure(n, step, driver: close.axes[0].edge, draft, solved: close.axes.contains { $0.angles != nil }) | |
| 296 | return close.axes | |
| 297 | } | |
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +10
| @@ -21,6 +21,9 @@ public enum FoldDefect: Equatable, Sendable { | ||
| 21 | 21 | case authorNotTraditional(String?) |
| 22 | 22 | case missingFirstCreasedAtStep(edge: Int) |
| 23 | 23 | case faceDistorted(frame: Int, face: Int) |
| 24 | /// A non-rigid step without a pop, or a pop whose `popped` lacks a position per vertex or | |
| 25 | /// whose phases are not 0 < p0 < p1 < 1. | |
| 26 | case popMalformed(step: Int) | |
| 24 | 27 | } |
| 25 | 28 | |
| 26 | 29 | /// Lengths are compared to within this fraction of the sheet's longer side. |
| @@ -78,6 +81,13 @@ public func validate(_ file: FoldFile) -> [FoldDefect] { | ||
| 78 | 81 | if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil { |
| 79 | 82 | defects.append(.foldAndUnfoldWithoutPeakOrder(step: n)) |
| 80 | 83 | } |
| 84 | if step.nonRigid || step.pop != nil { | |
| 85 | let wellFormed = step.pop.map { pop in | |
| 86 | pop.popped.count == vertexCount && pop.phases.count == 2 | |
| 87 | && 0 < pop.phases[0] && pop.phases[0] < pop.phases[1] && pop.phases[1] < 1 | |
| 88 | } ?? false | |
| 89 | if !wellFormed { defects.append(.popMalformed(step: n)) } | |
| 90 | } | |
| 81 | 91 | guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue } |
| 82 | 92 | if frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) { |
| 83 | 93 | defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n)) |
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-cp.fold added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | { | |
| 2 | "file_spec": 1.2, | |
| 3 | "file_title": "Reverse fold", | |
| 4 | "file_author": "Traditional", | |
| 5 | "file_classes": ["creasePattern"], | |
| 6 | "vertices_coords": [[0, 0], [3, 0], [4, 0], [4, 1], [4, 2], [3, 2], [0, 2], [0, 1], [2, 1]], | |
| 7 | "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], | |
| 8 | [7, 8], [8, 3], [8, 1], [8, 5]], | |
| 9 | "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "M", "V", "V"], | |
| 10 | "faces_vertices": [[0, 1, 8, 7], [1, 2, 3, 8], [8, 3, 4, 5], [7, 8, 5, 6]] | |
| 11 | } | |
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse.foldscript added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | { | |
| 2 | "creasePattern": "reverse-cp.fold", | |
| 3 | "title": "Reverse fold", | |
| 4 | "steps": [ | |
| 5 | { | |
| 6 | "kind": "fold", | |
| 7 | "instruction": "Valley fold the top half down onto the bottom half.", | |
| 8 | "creases": [[[0, 1], [2, 1]]], | |
| 9 | "movingSide": [[1, 1.5]] | |
| 10 | }, | |
| 11 | { | |
| 12 | "kind": "fold", | |
| 13 | "technique": "insideReverse", | |
| 14 | "instruction": "Inside reverse fold the right end down between the layers.", | |
| 15 | "creases": [[[2, 1], [3, 0]], [[2, 1], [3, 2]]], | |
| 16 | "movingSide": [[3.5, 0.5]], | |
| 17 | "spine": [[0, 1], [2, 1]], | |
| 18 | "faceOrders": [{"above": [3.5, 1.5], "below": [3.5, 0.5]}] | |
| 19 | } | |
| 20 | ] | |
| 21 | } | |
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +72
| @@ -380,3 +380,75 @@ private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) - | ||
| 380 | 380 | && (x.angles == nil) == (y.angles == nil) && close(x.angles ?? [], y.angles ?? [], tolerance) |
| 381 | 381 | } |
| 382 | 382 | } |
| 383 | ||
| 384 | /// Whether, in `reverse.fold`'s geometry at `positions`, the tip's point at sheet point | |
| 385 | /// (2.75, 0.75) lies strictly between the body's two layers: the planes of the faces containing | |
| 386 | /// sheet points (0.5, 0.5) and (0.5, 1.5), at the tip point's x and y. False when the tip point is | |
| 387 | /// not over both layers. | |
| 388 | public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool { | |
| 389 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } | |
| 390 | func face(containing p: SIMD2<Double>) -> Int? { | |
| 391 | file.facesVertices.indices.first { f in | |
| 392 | let corners = file.facesVertices[f].map { flat[$0] } | |
| 393 | return corners.indices.allSatisfy { i in | |
| 394 | let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = p - a | |
| 395 | return side.x * offset.y - side.y * offset.x >= 0 | |
| 396 | } | |
| 397 | } | |
| 398 | } | |
| 399 | // the sheet point p of face f, where f's corners are at `positions` | |
| 400 | func place(_ p: SIMD2<Double>, on f: Int) -> SIMD3<Double> { | |
| 401 | let c = file.facesVertices[f] | |
| 402 | let (a, b, d) = (flat[c[0]], flat[c[1]], flat[c[2]]) | |
| 403 | let u = b - a, v = d - a, w = p - a | |
| 404 | let det = u.x * v.y - u.y * v.x | |
| 405 | let s = (w.x * v.y - w.y * v.x) / det, r = (u.x * w.y - u.y * w.x) / det | |
| 406 | return positions[c[0]] + s * (positions[c[1]] - positions[c[0]]) + r * (positions[c[2]] - positions[c[0]]) | |
| 407 | } | |
| 408 | // the height of face f's plane above (x, y), when (x, y) lies over the face | |
| 409 | func height(of f: Int, at q: SIMD2<Double>) -> Double? { | |
| 410 | let corners = file.facesVertices[f].map { positions[$0] } | |
| 411 | let n = faceNormals(positions: positions, faces: [file.facesVertices[f]])[0] | |
| 412 | guard abs(n.z) > 1e-12 else { return nil } | |
| 413 | let outline = corners.map { SIMD2($0.x, $0.y) } | |
| 414 | let turn = n.z > 0 ? 1.0 : -1.0 | |
| 415 | let inside = outline.indices.allSatisfy { i in | |
| 416 | let a = outline[i], side = outline[(i + 1) % outline.count] - a, offset = q - a | |
| 417 | return turn * (side.x * offset.y - side.y * offset.x) >= 0 | |
| 418 | } | |
| 419 | guard inside else { return nil } | |
| 420 | return corners[0].z - (n.x * (q.x - corners[0].x) + n.y * (q.y - corners[0].y)) / n.z | |
| 421 | } | |
| 422 | guard let tip = face(containing: SIMD2(2.75, 0.75)), let lower = face(containing: SIMD2(0.5, 0.5)), | |
| 423 | let upper = face(containing: SIMD2(0.5, 1.5)) else { return false } | |
| 424 | let probe = place(SIMD2(2.75, 0.75), on: tip) | |
| 425 | let q = SIMD2(probe.x, probe.y) | |
| 426 | guard let a = height(of: lower, at: q), let b = height(of: upper, at: q) else { return false } | |
| 427 | return probe.z > min(a, b) && probe.z < max(a, b) | |
| 428 | } | |
| 429 | ||
| 430 | extension FoldScript { | |
| 431 | /// This script with step `step`'s `openAngle` set to `degrees`. Steps count from 1. | |
| 432 | public func withOpenAngle(_ degrees: Double, step: Int) -> FoldScript { | |
| 433 | editing(step) { replacing($0, spine: $0.spine, openAngle: degrees) } | |
| 434 | } | |
| 435 | ||
| 436 | /// This script with step `step`'s `spine` removed. Steps count from 1. | |
| 437 | public func withoutSpine(step: Int) -> FoldScript { | |
| 438 | editing(step) { replacing($0, spine: nil, openAngle: $0.openAngle) } | |
| 439 | } | |
| 440 | ||
| 441 | private func editing(_ step: Int, _ change: (ScriptStep) -> ScriptStep) -> FoldScript { | |
| 442 | var list = steps | |
| 443 | list[step - 1] = change(list[step - 1]) | |
| 444 | return FoldScript(creasePattern: creasePattern, title: title, steps: list) | |
| 445 | } | |
| 446 | } | |
| 447 | ||
| 448 | private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) -> ScriptStep { | |
| 449 | ScriptStep(kind: s.kind, technique: s.technique, instruction: s.instruction, creases: s.creases, | |
| 450 | movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles, rotateDegrees: s.rotateDegrees, | |
| 451 | turnOverAxis: s.turnOverAxis, repeatOf: s.repeatOf, viewpoint: s.viewpoint, faceOrders: s.faceOrders, | |
| 452 | faceOrdersMidFold: s.faceOrdersMidFold, driver: s.driver, windows: s.windows, spine: spine, | |
| 453 | openAngle: openAngle) | |
| 454 | } | |
Packages/FoldKit/Sources/Folding/Bending.swift added +133
| @@ -0,0 +1,133 @@ | ||
| 1 | import Accelerate | |
| 2 | import simd | |
| 3 | ||
| 4 | /// As-rigid-as-possible interpolation on a render mesh between two rigid poses of the FOLD faces | |
| 5 | /// (decision 0002's pop). At `s` each triangle's edges are its edges in the first pose turned by | |
| 6 | /// `s` of its face's rotation from the first pose to the second (slerp), and the mesh vertices | |
| 7 | /// are the least-squares fit to those edges, with the vertices of held faces kept where the first | |
| 8 | /// pose has them. At `s = 0` and `s = 1` the fit is exact, so it reproduces both poses. | |
| 9 | struct Bending: Sendable { | |
| 10 | /// The mesh vertices in the first pose. | |
| 11 | private let rest: [SIMD3<Double>] | |
| 12 | /// Per FOLD face, its rotation from the first pose to the second. | |
| 13 | private let turns: [simd_quatd] | |
| 14 | /// The mesh vertices that move, in the solve's row order. | |
| 15 | private let free: [Int] | |
| 16 | /// Per row and FOLD face, the signed sum of the rest edge vectors of that face's triangles at | |
| 17 | /// the row's vertex; the right-hand side adds each turned by `s` of the face's turn. | |
| 18 | private let terms: [(row: Int, face: Int, vector: SIMD3<Double>)] | |
| 19 | /// Per row, what the held vertices contribute to the normal equation's right-hand side. | |
| 20 | private let held: [SIMD3<Double>] | |
| 21 | private let factor: SparseCholesky | |
| 22 | ||
| 23 | /// - Parameters: | |
| 24 | /// - first, second: the FOLD vertex positions of two rigid poses. | |
| 25 | /// - heldFaces: FOLD faces placed alike in both poses, whose mesh vertices stay put. | |
| 26 | init(mesh: RenderMesh, faces: [[Int]], from first: [SIMD3<Double>], to second: [SIMD3<Double>], | |
| 27 | heldFaces: Set<Int>) { | |
| 28 | rest = mesh.pose(first) | |
| 29 | turns = faces.map { corners in | |
| 30 | // one corner triple for both poses, chosen on the flat sheet so ties cannot split | |
| 31 | let flat = corners.map { mesh.vertices[mesh.meshVertexOf[$0]] } | |
| 32 | let c = widestCorners(flat).map { corners[$0] } | |
| 33 | var q = simd_quatd(frame(c.map { second[$0] }) * frame(c.map { first[$0] }).transpose) | |
| 34 | if q.real < 0 { q = simd_quatd(vector: -q.vector) } | |
| 35 | return q | |
| 36 | } | |
| 37 | ||
| 38 | var isHeld = Array(repeating: false, count: mesh.vertices.count) | |
| 39 | for (t, (a, b, c)) in mesh.triangles.enumerated() where heldFaces.contains(mesh.faceOf[t]) { | |
| 40 | (isHeld[a], isHeld[b], isHeld[c]) = (true, true, true) | |
| 41 | } | |
| 42 | free = mesh.vertices.indices.filter { !isHeld[$0] } | |
| 43 | var row = Array(repeating: -1, count: mesh.vertices.count) | |
| 44 | for (r, v) in free.enumerated() { row[v] = r } | |
| 45 | ||
| 46 | // Σ over triangle edges (i, j) of |x_j − x_i − d_ij|²: the normal matrix is the edge | |
| 47 | // Laplacian; held vertices move to the right-hand side. | |
| 48 | var matrix: [SIMD2<Int>: Double] = [:] | |
| 49 | var sums: [SIMD2<Int>: SIMD3<Double>] = [:] | |
| 50 | var held = Array(repeating: SIMD3<Double>.zero, count: free.count) | |
| 51 | for (t, (a, b, c)) in mesh.triangles.enumerated() { | |
| 52 | let face = mesh.faceOf[t] | |
| 53 | for (i, j) in [(a, b), (b, c), (c, a)] { | |
| 54 | let d = rest[j] - rest[i] | |
| 55 | for (v, other, sign) in [(i, j, -1.0), (j, i, 1.0)] where row[v] >= 0 { | |
| 56 | matrix[SIMD2(row[v], row[v]), default: 0] += 1 | |
| 57 | sums[SIMD2(row[v], face), default: .zero] += sign * d | |
| 58 | if row[other] >= 0 { | |
| 59 | if row[other] < row[v] { matrix[SIMD2(row[v], row[other]), default: 0] -= 1 } | |
| 60 | } else { | |
| 61 | held[row[v]] += rest[other] | |
| 62 | } | |
| 63 | } | |
| 64 | } | |
| 65 | } | |
| 66 | terms = sums.keys.sorted { ($0.x, $0.y) < ($1.x, $1.y) }.map { ($0.x, $0.y, sums[$0]!) } | |
| 67 | self.held = held | |
| 68 | factor = SparseCholesky(size: free.count, lower: matrix) | |
| 69 | } | |
| 70 | ||
| 71 | /// The mesh vertex positions at `s` in 0...1. | |
| 72 | func positions(at s: Double) -> [SIMD3<Double>] { | |
| 73 | let identity = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1) | |
| 74 | let turned = turns.map { simd_slerp(identity, $0, s) } | |
| 75 | let n = free.count | |
| 76 | var rhs = [Double](repeating: 0, count: 3 * n) | |
| 77 | for (r, h) in held.enumerated() { | |
| 78 | rhs[r] = h.x | |
| 79 | rhs[n + r] = h.y | |
| 80 | rhs[2 * n + r] = h.z | |
| 81 | } | |
| 82 | for (r, face, vector) in terms { | |
| 83 | let d = turned[face].act(vector) | |
| 84 | rhs[r] += d.x | |
| 85 | rhs[n + r] += d.y | |
| 86 | rhs[2 * n + r] += d.z | |
| 87 | } | |
| 88 | factor.solve(&rhs, columns: 3) | |
| 89 | var result = rest | |
| 90 | for (r, v) in free.enumerated() { result[v] = SIMD3(rhs[r], rhs[n + r], rhs[2 * n + r]) } | |
| 91 | return result | |
| 92 | } | |
| 93 | } | |
| 94 | ||
| 95 | /// An orthonormal frame fixed to the triangle `p`: along its first side, across it in its plane, | |
| 96 | /// and along its normal. | |
| 97 | private func frame(_ p: [SIMD3<Double>]) -> simd_double3x3 { | |
| 98 | let along = normalize(p[1] - p[0]), normal = normalize(cross(p[1] - p[0], p[2] - p[0])) | |
| 99 | return simd_double3x3(columns: (along, cross(normal, along), normal)) | |
| 100 | } | |
| 101 | ||
| 102 | /// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix. Only read after | |
| 103 | /// `init`, so sharing it across threads is safe. | |
| 104 | private final class SparseCholesky: @unchecked Sendable { | |
| 105 | private let factor: SparseOpaqueFactorization_Double | |
| 106 | private let size: Int | |
| 107 | ||
| 108 | /// `lower` holds the entries on and below the diagonal, keyed by (row, column). | |
| 109 | init(size: Int, lower: [SIMD2<Int>: Double]) { | |
| 110 | self.size = size | |
| 111 | let keys = lower.keys.sorted { ($0.y, $0.x) < ($1.y, $1.x) } | |
| 112 | let rows = keys.map { Int32($0.x) }, columns = keys.map { Int32($0.y) }, values = keys.map { lower[$0]! } | |
| 113 | var attributes = SparseAttributes_t() | |
| 114 | attributes.triangle = SparseLowerTriangle | |
| 115 | attributes.kind = SparseSymmetric | |
| 116 | let matrix = SparseConvertFromCoordinate(Int32(size), Int32(size), keys.count, 1, attributes, | |
| 117 | rows, columns, values) | |
| 118 | defer { SparseCleanup(matrix) } | |
| 119 | factor = SparseFactor(SparseFactorizationCholesky, matrix) | |
| 120 | precondition(factor.status == SparseStatusOK, "the pop's normal matrix is not positive definite") | |
| 121 | } | |
| 122 | ||
| 123 | deinit { SparseCleanup(factor) } | |
| 124 | ||
| 125 | /// Solves in place for `columns` right-hand sides of `size` values each, one after another. | |
| 126 | func solve(_ values: inout [Double], columns: Int) { | |
| 127 | values.withUnsafeMutableBufferPointer { buffer in | |
| 128 | let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size), | |
| 129 | attributes: SparseAttributes_t(), data: buffer.baseAddress!) | |
| 130 | SparseSolve(factor, b) | |
| 131 | } | |
| 132 | } | |
| 133 | } | |
Packages/FoldKit/Sources/Folding/FoldInterpolator.swift +97 −44
| @@ -1,60 +1,109 @@ | ||
| 1 | 1 | import FoldFormat |
| 2 | 2 | import simd |
| 3 | 3 | |
| 4 | /// Interpolates a rigid step from frame `step.index − 1` to frame `step.index`. | |
| 4 | /// Interpolates step `step.index` from frame `step.index − 1` to frame `step.index`. | |
| 5 | 5 | /// |
| 6 | 6 | /// A fold or fold-and-unfold step moves the faces of each axis's moving set about that axis; an |
| 7 | 7 | /// axis with a parent is carried by the parent's motion. A `turnOver` or `rotate` step rotates |
| 8 | /// the whole of the start frame about its bounding-box centre. Steps flagged `nonRigid` are not | |
| 9 | /// handled here. | |
| 8 | /// the whole of the start frame about its bounding-box centre. A step flagged `nonRigid` moves by | |
| 9 | /// its pop (decision 0002): `openAxes` rigidly on `[0, phases.lowerBound]`, the render mesh bent | |
| 10 | /// from the open pose to `popped` on the phases, and `closeAxes` rigidly from `popped` on | |
| 11 | /// `[phases.upperBound, 1]`. | |
| 10 | 12 | public struct FoldInterpolator: Sendable { |
| 13 | /// Rigid motions of the faces about a step's axes, from `start`. | |
| 11 | 14 | private struct Motion: Sendable { |
| 12 | let step: FoldStep | |
| 15 | let axes: [FoldAxis] | |
| 16 | let kind: StepKind | |
| 17 | let start: [SIMD3<Double>] | |
| 13 | 18 | /// Per axis, the vertices that take their position from that axis's face group. |
| 14 | 19 | let vertices: [[Int]] |
| 20 | ||
| 21 | init(axes: [FoldAxis], kind: StepKind, start: [SIMD3<Double>], faces: [[Int]]) { | |
| 22 | self.axes = axes | |
| 23 | self.kind = kind | |
| 24 | self.start = start | |
| 25 | var axisOfFace: [Int: Int] = [:] | |
| 26 | for (a, axis) in axes.enumerated() { | |
| 27 | for f in axis.movingFaces { axisOfFace[f] = a } | |
| 28 | } | |
| 29 | // a vertex takes its position from the first face containing it | |
| 30 | var owner = Array<Int?>(repeating: nil, count: start.count) | |
| 31 | var seen = Array(repeating: false, count: start.count) | |
| 32 | for (f, face) in faces.enumerated() { | |
| 33 | for v in face where !seen[v] { | |
| 34 | seen[v] = true | |
| 35 | owner[v] = axisOfFace[f] | |
| 36 | } | |
| 37 | } | |
| 38 | var groups = Array(repeating: [Int](), count: axes.count) | |
| 39 | for (v, a) in owner.enumerated() { | |
| 40 | if let a { groups[a].append(v) } | |
| 41 | } | |
| 42 | vertices = groups | |
| 43 | } | |
| 44 | ||
| 45 | func positions(at t: Double) -> [SIMD3<Double>] { | |
| 46 | // each axis's full transform: its own rotation, then its parent's | |
| 47 | var full: [Transform] = [] | |
| 48 | full.reserveCapacity(axes.count) | |
| 49 | for axis in axes { | |
| 50 | let degrees = axis.angle(at: t, kind: kind) - axis.startAngle | |
| 51 | let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction) | |
| 52 | let own = Transform(rotation: simd_double3x3(q), about: axis.origin) | |
| 53 | full.append(axis.parent.map { full[$0].after(own) } ?? own) | |
| 54 | } | |
| 55 | var result = start | |
| 56 | for (a, group) in vertices.enumerated() { | |
| 57 | for v in group { result[v] = full[a].apply(start[v]) } | |
| 58 | } | |
| 59 | return result | |
| 60 | } | |
| 15 | 61 | } |
| 16 | 62 | |
| 17 | 63 | private struct Reorientation: Sendable { |
| 64 | let start: [SIMD3<Double>] | |
| 18 | 65 | let centre: SIMD3<Double> |
| 19 | 66 | let axis: SIMD3<Double> |
| 20 | 67 | /// Radians at t = 1. |
| 21 | 68 | let angle: Double |
| 22 | 69 | } |
| 23 | 70 | |
| 71 | private struct NonRigid: Sendable { | |
| 72 | let open: Motion | |
| 73 | let close: Motion | |
| 74 | let phases: ClosedRange<Double> | |
| 75 | let bending: Bending | |
| 76 | } | |
| 77 | ||
| 24 | 78 | private enum Mode: Sendable { |
| 25 | 79 | case folds(Motion) |
| 26 | 80 | case reorient(Reorientation) |
| 81 | case nonRigid(NonRigid) | |
| 27 | 82 | } |
| 28 | 83 | |
| 29 | private let start: [SIMD3<Double>] | |
| 30 | private let kind: StepKind | |
| 84 | /// The render mesh of the file's frame 0, at `RenderMesh.spacing(for:)`. | |
| 85 | public let mesh: RenderMesh | |
| 31 | 86 | private let mode: Mode |
| 32 | 87 | |
| 33 | 88 | public init(file: FoldFile, step: FoldStep) { |
| 34 | precondition(!step.nonRigid, "FoldInterpolator handles rigid steps only; the non-rigid path is added by Task 7b") | |
| 35 | start = file.frames[step.index - 1].verticesCoords | |
| 36 | kind = step.kind | |
| 89 | let start = file.frames[step.index - 1].verticesCoords | |
| 90 | mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file)) | |
| 91 | ||
| 92 | if step.nonRigid { | |
| 93 | guard let pop = step.pop else { preconditionFailure("a non-rigid step has a pop; readStep checks it") } | |
| 94 | let open = Motion(axes: pop.openAxes, kind: .fold, start: start, faces: file.facesVertices) | |
| 95 | let close = Motion(axes: pop.closeAxes, kind: .fold, start: pop.popped, faces: file.facesVertices) | |
| 96 | let moving = step.movingFaceUnion | |
| 97 | let bending = Bending(mesh: mesh, faces: file.facesVertices, | |
| 98 | from: open.positions(at: pop.phases.lowerBound), to: pop.popped, | |
| 99 | heldFaces: Set(file.facesVertices.indices.filter { !moving.contains($0) })) | |
| 100 | mode = .nonRigid(NonRigid(open: open, close: close, phases: pop.phases, bending: bending)) | |
| 101 | return | |
| 102 | } | |
| 37 | 103 | |
| 38 | 104 | switch step.kind { |
| 39 | 105 | case .fold, .foldAndUnfold: |
| 40 | var axisOfFace: [Int: Int] = [:] | |
| 41 | for (a, axis) in step.axes.enumerated() { | |
| 42 | for f in axis.movingFaces { axisOfFace[f] = a } | |
| 43 | } | |
| 44 | // a vertex takes its position from the first face containing it | |
| 45 | var owner = Array<Int?>(repeating: nil, count: start.count) | |
| 46 | var seen = Array(repeating: false, count: start.count) | |
| 47 | for (f, face) in file.facesVertices.enumerated() { | |
| 48 | for v in face where !seen[v] { | |
| 49 | seen[v] = true | |
| 50 | owner[v] = axisOfFace[f] | |
| 51 | } | |
| 52 | } | |
| 53 | var groups = Array(repeating: [Int](), count: step.axes.count) | |
| 54 | for (v, a) in owner.enumerated() { | |
| 55 | if let a { groups[a].append(v) } | |
| 56 | } | |
| 57 | mode = .folds(Motion(step: step, vertices: groups)) | |
| 106 | mode = .folds(Motion(axes: step.axes, kind: step.kind, start: start, faces: file.facesVertices)) | |
| 58 | 107 | |
| 59 | 108 | case .turnOver, .rotate: |
| 60 | 109 | var lower = start[0], upper = start[0] |
| @@ -71,34 +120,38 @@ public struct FoldInterpolator: Sendable { | ||
| 71 | 120 | axis = step.turnOverAxis == .horizontal ? normalize(cross(up, eye)) : up |
| 72 | 121 | degrees = 180 |
| 73 | 122 | } |
| 74 | mode = .reorient(Reorientation(centre: (lower + upper) / 2, axis: axis, | |
| 123 | mode = .reorient(Reorientation(start: start, centre: (lower + upper) / 2, axis: axis, | |
| 75 | 124 | angle: degrees * .pi / 180)) |
| 76 | 125 | } |
| 77 | 126 | } |
| 78 | 127 | |
| 79 | /// The vertex positions at `t` of the step, `t` in 0...1. | |
| 128 | /// The vertex positions at `t` of the step, `t` in 0...1. During a pop, the mesh positions of | |
| 129 | /// the FOLD vertices. | |
| 80 | 130 | public func positions(at t: Double) -> [SIMD3<Double>] { |
| 81 | 131 | switch mode { |
| 82 | 132 | case .reorient(let r): |
| 83 | 133 | let q = simd_quatd(angle: r.angle * t, axis: r.axis) |
| 84 | return start.map { r.centre + q.act($0 - r.centre) } | |
| 134 | return r.start.map { r.centre + q.act($0 - r.centre) } | |
| 85 | 135 | |
| 86 | 136 | case .folds(let motion): |
| 87 | // each axis's full transform: its own rotation, then its parent's | |
| 88 | var full: [Transform] = [] | |
| 89 | full.reserveCapacity(motion.step.axes.count) | |
| 90 | for axis in motion.step.axes { | |
| 91 | let degrees = axis.angle(at: t, kind: kind) - axis.startAngle | |
| 92 | let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction) | |
| 93 | let own = Transform(rotation: simd_double3x3(q), about: axis.origin) | |
| 94 | full.append(axis.parent.map { full[$0].after(own) } ?? own) | |
| 95 | } | |
| 96 | var result = start | |
| 97 | for (a, group) in motion.vertices.enumerated() { | |
| 98 | for v in group { result[v] = full[a].apply(start[v]) } | |
| 99 | } | |
| 100 | return result | |
| 137 | return motion.positions(at: t) | |
| 138 | ||
| 139 | case .nonRigid(let p): | |
| 140 | if t <= p.phases.lowerBound { return p.open.positions(at: t) } | |
| 141 | if t >= p.phases.upperBound { return p.close.positions(at: t) } | |
| 142 | let points = meshPositions(at: t) | |
| 143 | return mesh.meshVertexOf.map { points[$0] } | |
| 144 | } | |
| 145 | } | |
| 146 | ||
| 147 | /// The render mesh's vertex positions at `t` of the step: each face's rigid placement applied | |
| 148 | /// to its mesh vertices, or during a pop the bent mesh. | |
| 149 | public func meshPositions(at t: Double) -> [SIMD3<Double>] { | |
| 150 | if case .nonRigid(let p) = mode, t > p.phases.lowerBound, t < p.phases.upperBound { | |
| 151 | let s = (t - p.phases.lowerBound) / (p.phases.upperBound - p.phases.lowerBound) | |
| 152 | return p.bending.positions(at: s) | |
| 101 | 153 | } |
| 154 | return mesh.pose(positions(at: t)) | |
| 102 | 155 | } |
| 103 | 156 | } |
| 104 | 157 | |
Packages/FoldKit/Sources/Folding/Interpenetration.swift +35 −12
| @@ -31,30 +31,53 @@ private let coplanarOffset = 1e-6 | ||
| 31 | 31 | /// vertex or an edge are tested. Coplanar pairs are skipped; their overlap is the layer order's. |
| 32 | 32 | /// The sheet's size is the longest side of the bounding box of the positions at `t = 0`. |
| 33 | 33 | public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection] { |
| 34 | intersections(polygons: faces, faceOf: Array(faces.indices), samples: samples, at: interpolator.positions(at:)) | |
| 35 | } | |
| 36 | ||
| 37 | /// `interpenetrations` on the render mesh's triangles at `meshPositions(at:)`, reporting the FOLD | |
| 38 | /// faces they lie in. Triangles of one face are not tested against each other. For non-rigid | |
| 39 | /// steps, whose faces bend during the pop. | |
| 40 | public func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection] { | |
| 41 | let mesh = interpolator.mesh | |
| 42 | return intersections(polygons: mesh.triangles.map { [$0.0, $0.1, $0.2] }, faceOf: mesh.faceOf, | |
| 43 | samples: samples, at: interpolator.meshPositions(at:)) | |
| 44 | } | |
| 45 | ||
| 46 | /// The pairs of faces, `faceOf` each polygon, whose polygons pass through each other at some | |
| 47 | /// sample, each reported once at the first such sample, in face order within a sample. | |
| 48 | private func intersections(polygons corners: [[Int]], faceOf: [Int], samples: Int, | |
| 49 | at positions: (Double) -> [SIMD3<Double>]) -> [Intersection] { | |
| 34 | 50 | precondition(samples > 0, "interpenetrations needs at least one sample") |
| 35 | let size = boundingExtent(interpolator.positions(at: 0)).max() | |
| 36 | let usable = faces.indices.filter { faces[$0].count >= 3 } | |
| 51 | let size = boundingExtent(positions(0)).max() | |
| 52 | let usable = corners.indices.filter { corners[$0].count >= 3 } | |
| 37 | 53 | |
| 38 | 54 | var found: [Intersection] = [] |
| 39 | 55 | var reported = Set<SIMD2<Int>>() |
| 40 | 56 | for k in 0...samples { |
| 41 | 57 | let t = Double(k) / Double(samples) |
| 42 | let positions = interpolator.positions(at: t) | |
| 43 | let normals = faceNormals(positions: positions, faces: faces) | |
| 44 | let polygons = faces.map { $0.map { positions[$0] } } | |
| 58 | let points = positions(t) | |
| 59 | let normals = faceNormals(positions: points, faces: corners) | |
| 60 | let polygons = corners.map { $0.map { points[$0] } } | |
| 45 | 61 | let boxes = polygons.map(bounds) |
| 46 | ||
| 47 | for (n, a) in usable.enumerated() where normals[a] != .zero { | |
| 48 | for b in usable[(n + 1)...] where normals[b] != .zero { | |
| 49 | let pair = SIMD2(a, b) | |
| 50 | guard !reported.contains(pair), boxesMeet(boxes[a], boxes[b]), | |
| 62 | // sweep along x: a pair can meet only when their boxes' x-ranges do | |
| 63 | let order = usable.filter { normals[$0] != .zero }.sorted { boxes[$0].lower.x < boxes[$1].lower.x } | |
| 64 | ||
| 65 | var hits = Set<SIMD2<Int>>() | |
| 66 | for (n, a) in order.enumerated() { | |
| 67 | for b in order[(n + 1)...] { | |
| 68 | guard boxes[b].lower.x - contactTolerance <= boxes[a].upper.x else { break } | |
| 69 | let pair = SIMD2(min(faceOf[a], faceOf[b]), max(faceOf[a], faceOf[b])) | |
| 70 | guard pair.x != pair.y, boxesMeet(boxes[a], boxes[b]), !reported.contains(pair), !hits.contains(pair), | |
| 51 | 71 | !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size), |
| 52 | 72 | passThrough(polygons[a], normals[a], polygons[b], normals[b]) |
| 53 | 73 | else { continue } |
| 54 | reported.insert(pair) | |
| 55 | found.append(Intersection(faceA: a, faceB: b, t: t)) | |
| 74 | hits.insert(pair) | |
| 56 | 75 | } |
| 57 | 76 | } |
| 77 | for pair in hits.sorted(by: { ($0.x, $0.y) < ($1.x, $1.y) }) { | |
| 78 | reported.insert(pair) | |
| 79 | found.append(Intersection(faceA: pair.x, faceB: pair.y, t: t)) | |
| 80 | } | |
| 58 | 81 | } |
| 59 | 82 | return found |
| 60 | 83 | } |
Packages/FoldKit/Sources/Folding/RenderMesh.swift added +172
| @@ -0,0 +1,172 @@ | ||
| 1 | import FoldFormat | |
| 2 | import simd | |
| 3 | ||
| 4 | /// The triangles the renderer draws, finer than the FOLD faces: frame 0's faces cut by lines | |
| 5 | /// every `spacing` in x and in y, each resulting convex cell fanned into triangles. Cells on both | |
| 6 | /// sides of an edge share its vertices, so the mesh is one connected sheet. The FOLD topology is | |
| 7 | /// unchanged; a non-rigid step bends this mesh, not the FOLD faces. | |
| 8 | public struct RenderMesh: Sendable { | |
| 9 | /// Frame 0 positions in its plane. | |
| 10 | public let vertices: [SIMD2<Double>] | |
| 11 | public let triangles: [(Int, Int, Int)] | |
| 12 | /// The FOLD face each triangle lies in. | |
| 13 | public let faceOf: [Int] | |
| 14 | /// The mesh vertex at each FOLD vertex. | |
| 15 | public let meshVertexOf: [Int] | |
| 16 | /// Each mesh vertex as a point of one FOLD face, for placing it in a rigid pose. | |
| 17 | private let anchors: [Anchor] | |
| 18 | ||
| 19 | /// A point of a face: `corners[0] + a·(corners[1] − corners[0]) + b·(corners[2] − corners[0])`. | |
| 20 | private struct Anchor: Sendable { | |
| 21 | let corners: SIMD3<Int> | |
| 22 | let a: Double | |
| 23 | let b: Double | |
| 24 | } | |
| 25 | ||
| 26 | public init(file: FoldFile, spacing: Double) { | |
| 27 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } | |
| 28 | let lower = flat.dropFirst().reduce(flat[0], simd_min) | |
| 29 | let upper = flat.dropFirst().reduce(flat[0], simd_max) | |
| 30 | let size = (upper - lower).max() | |
| 31 | let tolerance = size * 1e-9 | |
| 32 | let xs = lines(from: lower.x, to: upper.x, spacing: spacing, tolerance: tolerance) | |
| 33 | let ys = lines(from: lower.y, to: upper.y, spacing: spacing, tolerance: tolerance) | |
| 34 | ||
| 35 | var points = PointSet(tolerance: tolerance) | |
| 36 | var triangles: [(Int, Int, Int)] = [] | |
| 37 | var faceOf: [Int] = [] | |
| 38 | var anchors: [Int: Anchor] = [:] | |
| 39 | for (f, face) in file.facesVertices.enumerated() { | |
| 40 | var cells = [face.map { flat[$0] }] | |
| 41 | for x in xs { cells = cells.flatMap { split($0, at: x, axis: 0, tolerance: tolerance) } } | |
| 42 | for y in ys { cells = cells.flatMap { split($0, at: y, axis: 1, tolerance: tolerance) } } | |
| 43 | let corners = widestCorners(face.map { flat[$0] }) | |
| 44 | let origin = flat[face[corners[0]]] | |
| 45 | let u = flat[face[corners[1]]] - origin, v = flat[face[corners[2]]] - origin | |
| 46 | let det = u.x * v.y - u.y * v.x | |
| 47 | for cell in cells { | |
| 48 | var ids: [Int] = [] | |
| 49 | for p in cell { | |
| 50 | let id = points.index(of: p) | |
| 51 | if ids.last != id && ids.first != id { ids.append(id) } | |
| 52 | if anchors[id] == nil { | |
| 53 | let w = points.points[id] - origin | |
| 54 | anchors[id] = Anchor(corners: SIMD3(face[corners[0]], face[corners[1]], face[corners[2]]), | |
| 55 | a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det) | |
| 56 | } | |
| 57 | } | |
| 58 | guard ids.count >= 3 else { continue } | |
| 59 | for k in 1..<(ids.count - 1) { | |
| 60 | let (p, q, r) = (points.points[ids[0]], points.points[ids[k]], points.points[ids[k + 1]]) | |
| 61 | let area = ((q - p).x * (r - p).y - (q - p).y * (r - p).x) / 2 | |
| 62 | guard area > tolerance * size else { continue } | |
| 63 | triangles.append((ids[0], ids[k], ids[k + 1])) | |
| 64 | faceOf.append(f) | |
| 65 | } | |
| 66 | } | |
| 67 | } | |
| 68 | meshVertexOf = flat.map { points.index(of: $0) } | |
| 69 | vertices = points.points | |
| 70 | self.triangles = triangles | |
| 71 | self.faceOf = faceOf | |
| 72 | self.anchors = vertices.indices.map { anchors[$0]! } | |
| 73 | } | |
| 74 | ||
| 75 | /// Frame 0's bounding box's longer side / 32. | |
| 76 | public static func spacing(for file: FoldFile) -> Double { | |
| 77 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } | |
| 78 | let lower = flat.dropFirst().reduce(flat[0], simd_min) | |
| 79 | let upper = flat.dropFirst().reduce(flat[0], simd_max) | |
| 80 | return (upper - lower).max() / 32 | |
| 81 | } | |
| 82 | ||
| 83 | /// The mesh vertices when the FOLD vertices are at `positions`, each face placed rigidly. | |
| 84 | func pose(_ positions: [SIMD3<Double>]) -> [SIMD3<Double>] { | |
| 85 | anchors.map { anchor in | |
| 86 | let o = positions[anchor.corners.x] | |
| 87 | return o + anchor.a * (positions[anchor.corners.y] - o) + anchor.b * (positions[anchor.corners.z] - o) | |
| 88 | } | |
| 89 | } | |
| 90 | } | |
| 91 | ||
| 92 | /// The largest relative change in a mesh edge's length against frame 0. | |
| 93 | public func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double { | |
| 94 | var worst = 0.0 | |
| 95 | for (a, b, c) in mesh.triangles { | |
| 96 | for (i, j) in [(a, b), (b, c), (c, a)] { | |
| 97 | let rest = simd_distance(mesh.vertices[i], mesh.vertices[j]) | |
| 98 | worst = max(worst, abs(simd_distance(positions[i], positions[j]) - rest) / rest) | |
| 99 | } | |
| 100 | } | |
| 101 | return worst | |
| 102 | } | |
| 103 | ||
| 104 | /// The grid lines strictly inside `low...high`: `low + k·spacing` for k ≥ 1. | |
| 105 | private func lines(from low: Double, to high: Double, spacing: Double, tolerance: Double) -> [Double] { | |
| 106 | var result: [Double] = [] | |
| 107 | var k = 1.0 | |
| 108 | while low + k * spacing < high - tolerance { | |
| 109 | result.append(low + k * spacing) | |
| 110 | k += 1 | |
| 111 | } | |
| 112 | return result | |
| 113 | } | |
| 114 | ||
| 115 | /// A convex polygon cut by the line where coordinate `axis` equals `value`, or the polygon itself | |
| 116 | /// when the line does not cross it. Crossing points lie exactly on the line. | |
| 117 | private func split(_ polygon: [SIMD2<Double>], at value: Double, axis: Int, tolerance: Double) -> [[SIMD2<Double>]] { | |
| 118 | let d = polygon.map { $0[axis] - value } | |
| 119 | guard d.contains(where: { $0 < -tolerance }), d.contains(where: { $0 > tolerance }) else { return [polygon] } | |
| 120 | var below: [SIMD2<Double>] = [], above: [SIMD2<Double>] = [] | |
| 121 | for i in polygon.indices { | |
| 122 | let j = (i + 1) % polygon.count | |
| 123 | if d[i] <= tolerance { below.append(polygon[i]) } | |
| 124 | if d[i] >= -tolerance { above.append(polygon[i]) } | |
| 125 | if (d[i] < -tolerance && d[j] > tolerance) || (d[i] > tolerance && d[j] < -tolerance) { | |
| 126 | var crossing = polygon[i] + (polygon[j] - polygon[i]) * (d[i] / (d[i] - d[j])) | |
| 127 | crossing[axis] = value | |
| 128 | below.append(crossing) | |
| 129 | above.append(crossing) | |
| 130 | } | |
| 131 | } | |
| 132 | return [below, above] | |
| 133 | } | |
| 134 | ||
| 135 | /// The indices of the three corners spanning the largest triangle, the first such in index order. | |
| 136 | func widestCorners(_ corners: [SIMD2<Double>]) -> [Int] { | |
| 137 | var best = [0, 1, 2], largest = -1.0 | |
| 138 | for i in corners.indices { | |
| 139 | for j in corners.indices where j > i { | |
| 140 | for k in corners.indices where k > j { | |
| 141 | let u = corners[j] - corners[i], v = corners[k] - corners[i] | |
| 142 | let area = abs(u.x * v.y - u.y * v.x) | |
| 143 | if area > largest { (best, largest) = ([i, j, k], area) } | |
| 144 | } | |
| 145 | } | |
| 146 | } | |
| 147 | return best | |
| 148 | } | |
| 149 | ||
| 150 | /// Points merged within a tolerance, found through a grid of buckets one tolerance wide. | |
| 151 | private struct PointSet { | |
| 152 | let tolerance: Double | |
| 153 | private(set) var points: [SIMD2<Double>] = [] | |
| 154 | private var buckets: [SIMD2<Int64>: [Int]] = [:] | |
| 155 | ||
| 156 | init(tolerance: Double) { self.tolerance = tolerance } | |
| 157 | ||
| 158 | /// The index of the point within the tolerance of `p`, added when there is none. | |
| 159 | mutating func index(of p: SIMD2<Double>) -> Int { | |
| 160 | let key = SIMD2(Int64((p.x / tolerance).rounded(.down)), Int64((p.y / tolerance).rounded(.down))) | |
| 161 | for dx in -1...1 { | |
| 162 | for dy in -1...1 { | |
| 163 | for i in buckets[key &+ SIMD2(Int64(dx), Int64(dy))] ?? [] where simd_distance(points[i], p) <= tolerance { | |
| 164 | return i | |
| 165 | } | |
| 166 | } | |
| 167 | } | |
| 168 | points.append(p) | |
| 169 | buckets[key, default: []].append(points.count - 1) | |
| 170 | return points.count - 1 | |
| 171 | } | |
| 172 | } | |
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +3 −2
| @@ -133,8 +133,9 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind | ||
| 133 | 133 | } |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | @Test func aStepNamingASpineIsLeftToTheNonRigidPath() throws { | |
| 137 | #expect(throws: CompileError.nonRigidStepNotSupported(step: 1)) { | |
| 136 | @Test func aSpineThatIsNotFoldedIsRejected() throws { | |
| 137 | // a flap opens on a spine folded flat in the frame the step starts from | |
| 138 | #expect(throws: CompileError.unresolvedCrease(step: 1)) { | |
| 138 | 139 | try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) |
| 139 | 140 | } |
| 140 | 141 | } |
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | import Foundation | |
| 2 | import Testing | |
| 3 | import simd | |
| 4 | import FoldCompiler | |
| 5 | import FoldFormat | |
| 6 | import Folding | |
| 7 | import FoldKitTestSupport | |
| 8 | ||
| 9 | @Test func aReverseFoldCompilesToANonRigidStep() throws { | |
| 10 | let out = try compiled("reverse") | |
| 11 | let step = try #require(out.frames[2].step) | |
| 12 | #expect(step.nonRigid) | |
| 13 | #expect(step.pop?.openAngle == 30) | |
| 14 | #expect(step.technique == .insideReverse) | |
| 15 | } | |
| 16 | ||
| 17 | @Test func aReverseFoldWithoutASpineIsRejected() { | |
| 18 | #expect(throws: CompileError.missingSpine(step: 2)) { | |
| 19 | try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withoutSpine(step: 2), | |
| 20 | pattern: FoldFile(contentsOf: fixture("reverse-cp.fold"))) | |
| 21 | } | |
| 22 | } | |
| 23 | ||
| 24 | @Test func theOpenAndCloseLegsAreRigid() throws { | |
| 25 | // checked on the FOLD edges, as rigid steps are; mesh slivers at creases make relative mesh strain noisy | |
| 26 | let file = try compiled("reverse") | |
| 27 | let step = try readSteps(file)[1] | |
| 28 | let i = FoldInterpolator(file: file, step: step) | |
| 29 | for n in 0...256 { | |
| 30 | let t = Double(n) / 256 | |
| 31 | guard t <= step.pop!.phases.lowerBound || t >= step.pop!.phases.upperBound else { continue } | |
| 32 | #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)") | |
| 33 | } | |
| 34 | } | |
| 35 | ||
| 36 | @Test func thePopStaysWithinTheBound() throws { | |
| 37 | let file = try compiled("reverse") | |
| 38 | let step = try readSteps(file)[1] | |
| 39 | let i = FoldInterpolator(file: file, step: step) | |
| 40 | let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) | |
| 41 | let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()! | |
| 42 | #expect(worst <= 0.10) | |
| 43 | } | |
| 44 | ||
| 45 | @Test func theStepEndsOnItsEndFrame() throws { | |
| 46 | let file = try compiled("reverse") | |
| 47 | let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) | |
| 48 | #expect(zip(i.positions(at: 1), file.frames[2].verticesCoords).allSatisfy { simd_distance($0, $1) < 1e-9 }) | |
| 49 | } | |
| 50 | ||
| 51 | @Test func nothingPassesThroughAnything() throws { | |
| 52 | let file = try compiled("reverse") | |
| 53 | let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) | |
| 54 | #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty) | |
| 55 | } | |
| 56 | ||
| 57 | @Test func theTipLandsBetweenTheFlapsLayers() throws { | |
| 58 | // 97% of the way through the closing phase, a point of the tip lies between the body's two layers | |
| 59 | let file = try compiled("reverse") | |
| 60 | let step = try readSteps(file)[1] | |
| 61 | let i = FoldInterpolator(file: file, step: step) | |
| 62 | let upper = step.pop!.phases.upperBound | |
| 63 | #expect(tipIsBetweenBodyLayers(i.positions(at: upper + 0.97 * (1 - upper)), file)) | |
| 64 | } | |
| 65 | ||
| 66 | @Test func aFlapOpenedOnlyTo60DegreesIsRejected() { | |
| 67 | #expect { | |
| 68 | try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withOpenAngle(60, step: 2), | |
| 69 | pattern: FoldFile(contentsOf: fixture("reverse-cp.fold"))) | |
| 70 | } throws: { if case CompileError.popTooStrained(step: 2, _) = $0 { true } else { false } } | |
| 71 | } | |
| 72 | ||
| 73 | @Test func thePopFitsInAFrameBudget() throws { | |
| 74 | let file = try compiled("reverse") | |
| 75 | let step = try readSteps(file)[1] | |
| 76 | let i = FoldInterpolator(file: file, step: step) | |
| 77 | let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) | |
| 78 | let elapsed = ContinuousClock().measure { | |
| 79 | for n in 0..<100 { _ = i.meshPositions(at: lo + Double(n) / 100 * (hi - lo)) } | |
| 80 | } | |
| 81 | #expect(elapsed / 100 < .milliseconds(4)) | |
| 82 | } | |
| 83 | ||
| 84 | @Test func theRenderMeshIsTheSpikes() throws { | |
| 85 | // decision 0002's mesh at spacing 0.125 on this sheet: 561 vertices, 1024 triangles | |
| 86 | let file = try FoldFile(contentsOf: fixture("reverse-cp.fold")) | |
| 87 | let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file)) | |
| 88 | #expect(RenderMesh.spacing(for: file) == 0.125) | |
| 89 | #expect(mesh.vertices.count == 561) | |
| 90 | #expect(mesh.triangles.count == 1024) | |
| 91 | #expect(mesh.meshVertexOf.enumerated().allSatisfy { v, m in | |
| 92 | mesh.vertices[m] == SIMD2(file.frames[0].verticesCoords[v].x, file.frames[0].verticesCoords[v].y) | |
| 93 | }) | |
| 94 | } | |
Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift +20
| @@ -134,3 +134,23 @@ func acceptsAValidModel(_ name: String) throws { | ||
| 134 | 134 | == [SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) |
| 135 | 135 | #expect(edgesFaces(file) == [[0], [1], [1], [1], [0], [0], [0, 1]]) |
| 136 | 136 | } |
| 137 | ||
| 138 | @Test func rejectsAMalformedPop() throws { | |
| 139 | #expect(validate(try FoldFile(contentsOf: fixture("nonrigid-no-pop.fold"))).contains(.popMalformed(step: 1))) | |
| 140 | ||
| 141 | var file = try FoldFile(contentsOf: fixture("nonrigid-no-pop.fold")) | |
| 142 | let record = file.frames[1].step! | |
| 143 | func withPop(popped: Int, phases: [Double]) -> StepRecord { | |
| 144 | StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, axes: record.axes, | |
| 145 | nonRigid: true, | |
| 146 | pop: PopRecord(spine: [6], openAngle: 30, phases: phases, openAxes: [], | |
| 147 | popped: Array(file.frames[0].verticesCoords.prefix(popped)), closeAxes: []), | |
| 148 | viewpoint: record.viewpoint) | |
| 149 | } | |
| 150 | file.frames[1].step = withPop(popped: 5, phases: [1.0 / 3, 2.0 / 3]) | |
| 151 | #expect(validate(file).contains(.popMalformed(step: 1))) | |
| 152 | file.frames[1].step = withPop(popped: 6, phases: [2.0 / 3, 1.0 / 3]) | |
| 153 | #expect(validate(file).contains(.popMalformed(step: 1))) | |
| 154 | file.frames[1].step = withPop(popped: 6, phases: [1.0 / 3, 2.0 / 3]) | |
| 155 | #expect(!validate(file).contains(.popMalformed(step: 1))) | |
| 156 | } | |