Commit aede7e3bbc

aede7e3bbc5180c82e5bff9c405a121cacb2e428

parent: 13265c0964

Unsigned

cmc <hello@cleberg.net> · 2026-10-20 04:57 UTC

Diagram generation and Metal renderer (Tasks 9–10) (!6)

- Notation: `buildDiagram` draws frame n − 1 with step n's creases and arrows. Valley and mountain are classified as seen from the viewpoint. Earlier creases are light and creases not yet made are omitted. Edges are clipped against the union of the faces above them (`visibleSegments`). Arrows and symbols cover plain folds, fold-and-unfold, techniques, turn-over, rotate and repeat.
- `drawDiagram` is the public CoreGraphics drawing, used by the golden-image snapshots: 21 images, with symbol sources in `NOTATION.md`.
- `Camera` in Folding.
- Renderer: `PaperRenderer` uses hybrid depth. Clusters are depth-tested against each other. Within a cluster, faces are drawn back to front with depth writes off, then the cluster is drawn again depth-only. Paper is two-sided through `[[front_facing]]`. The shaders are compiled at init.
- `FoldStep.allMovingFaces` includes faces opening on the spine; `LayerOrder.active` and `layerMotionDefects` use it.
- Pop solves are serialised on their factor.
- The plan is amended for rulings R35–R41 and the carry-overs into Tasks 11, 14 and 15.

`swift test --package-path Packages/FoldKit`: 180 tests pass.

Closes #5

Layout: unified · split

Packages/FoldKit/Package.swift +9 −1
@@ -9,6 +9,8 @@ let package = Package(
9 .library(name: "Folding", targets: ["Folding"]), 9 .library(name: "Folding", targets: ["Folding"]),
10 .library(name: "FoldCompiler", targets: ["FoldCompiler"]), 10 .library(name: "FoldCompiler", targets: ["FoldCompiler"]),
11 .library(name: "Models", targets: ["Models"]), 11 .library(name: "Models", targets: ["Models"]),
12 .library(name: "Notation", targets: ["Notation"]),
13 .library(name: "Renderer", targets: ["Renderer"]),
12 .executable(name: "foldc", targets: ["foldc"]), 14 .executable(name: "foldc", targets: ["foldc"]),
13 .executable(name: "foldlint", targets: ["foldlint"]), 15 .executable(name: "foldlint", targets: ["foldlint"]),
14 ], 16 ],
@@ -17,11 +19,13 @@ let package = Package(
17 .target(name: "Folding", dependencies: ["FoldFormat"]), 19 .target(name: "Folding", dependencies: ["FoldFormat"]),
18 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]), 20 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]),
19 .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]), 21 .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]),
22 .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]),
23 .target(name: "Renderer", dependencies: ["Folding"], resources: [.copy("Shaders.metal")]),
20 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]), 24 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]),
21 .executableTarget(name: "foldlint", dependencies: ["FoldFormat", "Folding"]), 25 .executableTarget(name: "foldlint", dependencies: ["FoldFormat", "Folding"]),
22 .target( 26 .target(
23 name: "FoldKitTestSupport", 27 name: "FoldKitTestSupport",
24 dependencies: ["FoldFormat", "Folding", "FoldCompiler"], 28 dependencies: ["FoldFormat", "Folding", "FoldCompiler", "Notation"],
25 resources: [.copy("Fixtures")] 29 resources: [.copy("Fixtures")]
26 ), 30 ),
27 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]), 31 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]),
@@ -30,6 +34,10 @@ let package = Package(
30 dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]), 34 dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]),
31 .testTarget(name: "ModelsTests", 35 .testTarget(name: "ModelsTests",
32 dependencies: ["Models", "FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport", "foldlint"]), 36 dependencies: ["Models", "FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport", "foldlint"]),
37 .testTarget(name: "NotationTests",
38 dependencies: ["Notation", "Models", "Folding", "FoldFormat", "FoldKitTestSupport"],
39 resources: [.copy("Snapshots")]),
40 .testTarget(name: "RendererTests", dependencies: ["Renderer", "Folding", "FoldFormat"]),
33 ], 41 ],
34 swiftLanguageModes: [.v6] 42 swiftLanguageModes: [.v6]
35) 43)
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +112
@@ -1,8 +1,12 @@
1import CoreGraphics
1import Foundation 2import Foundation
2import FoldCompiler 3import FoldCompiler
3import FoldFormat 4import FoldFormat
4import Folding 5import Folding
6import ImageIO
7import Notation
5import simd 8import simd
9import Testing
6 10
7/// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases 11/// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases
8/// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step. 12/// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step.
@@ -507,3 +511,111 @@ public func runFoldlint(on url: URL) throws -> (exitCode: Int32, output: String)
507 return (process.terminationStatus, String(decoding: output, as: UTF8.self)) 511 return (process.terminationStatus, String(decoding: output, as: UTF8.self))
508} 512}
509#endif 513#endif
514
515/// The diagram for step `step` (counted from 1) of a fixture.
516public func diagram(_ fixtureName: String, step: Int) throws -> Diagram {
517 let file = try FoldFile(contentsOf: fixture(fixtureName))
518 return buildDiagram(file: file, step: try readStep(step, in: file))
519}
520
521/// `visibleSegments` of a fixture's edge in frame `n`, with frame n's order and step n + 1's
522/// viewpoint (the default one after the last step).
523public func visibleSegmentsOf(_ fixtureName: String, edge: Int, inFrame n: Int) throws -> [(SIMD2<Double>, SIMD2<Double>)] {
524 let file = try FoldFile(contentsOf: fixture(fixtureName))
525 let frame = file.frames[n]
526 let order = try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, file))
527 let viewpoint = n + 1 < file.frames.count
528 ? try readStep(n + 1, in: file).viewpoint
529 : Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
530 return visibleSegments(of: edge, frame: frame, file: file, order: order, viewpoint: viewpoint)
531}
532
533public func segmentLength(_ segment: (SIMD2<Double>, SIMD2<Double>)) -> Double {
534 simd_distance(segment.0, segment.1)
535}
536
537/// The canvas is square, this many pixels a side, white.
538private let canvasSide = 480
539
540/// `diagram` drawn by `drawDiagram` with `DiagramStyle.standard` on a white canvas.
541public func render(_ diagram: Diagram) -> CGImage {
542 let side = Double(canvasSide)
543 let context = CGContext(data: nil, width: canvasSide, height: canvasSide, bitsPerComponent: 8, bytesPerRow: 0,
544 space: CGColorSpace(name: CGColorSpace.sRGB)!,
545 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
546 context.setFillColor(gray: 1, alpha: 1)
547 context.fill(CGRect(x: 0, y: 0, width: side, height: side))
548 drawDiagram(diagram, style: .standard, in: context, size: CGSize(width: side, height: side))
549 return context.makeImage()!
550}
551
552/// The number of the image's pixels darker than mid-grey in any channel.
553public func inkedPixels(_ image: CGImage) -> Int {
554 let bytes = rgba(image)
555 return (0..<(image.width * image.height)).count { p in (0..<3).contains { bytes[4 * p + $0] < 128 } }
556}
557
558/// Golden images differ from a render when any channel of any pixel differs by more than this,
559/// out of 255.
560private let snapshotTolerance = 24
561
562public enum SnapshotError: Error {
563 case unreadable(String)
564}
565
566/// Compares `image` with `Snapshots/<name>.png` beside the calling test file. Records the image
567/// there, and fails saying so, when the golden is missing or `FOLD_RECORD_SNAPSHOTS=1`.
568public func expectSnapshot(_ image: CGImage, named name: String, filePath: String = #filePath,
569 sourceLocation: SourceLocation = #_sourceLocation) throws {
570 let url = URL(fileURLWithPath: filePath).deletingLastPathComponent()
571 .appendingPathComponent("Snapshots").appendingPathComponent("\(name).png")
572 let recording = ProcessInfo.processInfo.environment["FOLD_RECORD_SNAPSHOTS"] == "1"
573 if recording || !FileManager.default.fileExists(atPath: url.path) {
574 try writePNG(image, to: url)
575 Issue.record("recorded \(url.path); inspect it and run again", sourceLocation: sourceLocation)
576 return
577 }
578 guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
579 let golden = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw SnapshotError.unreadable(url.path) }
580 guard golden.width == image.width, golden.height == image.height else {
581 Issue.record("\(name): \(image.width)×\(image.height), golden \(golden.width)×\(golden.height)",
582 sourceLocation: sourceLocation)
583 return
584 }
585 let (rendered, expected) = (rgba(image), rgba(golden))
586 var pixels = 0, first: Int?
587 for p in 0..<(image.width * image.height) {
588 let differs = (0..<4).contains { abs(Int(rendered[4 * p + $0]) - Int(expected[4 * p + $0])) > snapshotTolerance }
589 if differs {
590 pixels += 1
591 first = first ?? p
592 }
593 }
594 if let first {
595 let actual = FileManager.default.temporaryDirectory.appendingPathComponent("\(name).png")
596 try writePNG(image, to: actual)
597 let x = first % image.width, y = first / image.width
598 Issue.record("\(name): \(pixels) pixels differ from the golden image, first at (\(x), \(y)); this render is at \(actual.path)",
599 sourceLocation: sourceLocation)
600 }
601}
602
603private func writePNG(_ image: CGImage, to url: URL) throws {
604 guard let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else {
605 throw SnapshotError.unreadable(url.path)
606 }
607 CGImageDestinationAddImage(destination, image, nil)
608 guard CGImageDestinationFinalize(destination) else { throw SnapshotError.unreadable(url.path) }
609}
610
611/// The image's pixels as 8-bit premultiplied RGBA in sRGB, row by row from the top.
612private func rgba(_ image: CGImage) -> [UInt8] {
613 var bytes = [UInt8](repeating: 0, count: image.width * image.height * 4)
614 bytes.withUnsafeMutableBytes { buffer in
615 let context = CGContext(data: buffer.baseAddress, width: image.width, height: image.height, bitsPerComponent: 8,
616 bytesPerRow: image.width * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!,
617 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
618 context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
619 }
620 return bytes
621}
Packages/FoldKit/Sources/Folding/Bending.swift +5 −3
@@ -1,5 +1,6 @@
1import Accelerate 1import Accelerate
2import simd 2import simd
3import Synchronization
3 4
4/// As-rigid-as-possible interpolation on a render mesh between two rigid poses of the FOLD faces 5/// 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/// (decision 0002's pop). At `s` each triangle's edges are its edges in the first pose turned by
@@ -99,11 +100,12 @@ private func frame(_ p: [SIMD3<Double>]) -> simd_double3x3 {
99 return simd_double3x3(columns: (along, cross(normal, along), normal)) 100 return simd_double3x3(columns: (along, cross(normal, along), normal))
100} 101}
101 102
102/// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix. Only read after 103/// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix. Solves are
103/// `init`, so sharing it across threads is safe. 104/// serialised: Accelerate does not document concurrent `SparseSolve` calls on one factor as safe.
104private final class SparseCholesky: @unchecked Sendable { 105private final class SparseCholesky: @unchecked Sendable {
105 private let factor: SparseOpaqueFactorization_Double 106 private let factor: SparseOpaqueFactorization_Double
106 private let size: Int 107 private let size: Int
108 private let lock = Mutex(())
107 109
108 /// `lower` holds the entries on and below the diagonal, keyed by (row, column). 110 /// `lower` holds the entries on and below the diagonal, keyed by (row, column).
109 init(size: Int, lower: [SIMD2<Int>: Double]) { 111 init(size: Int, lower: [SIMD2<Int>: Double]) {
@@ -127,7 +129,7 @@ private final class SparseCholesky: @unchecked Sendable {
127 values.withUnsafeMutableBufferPointer { buffer in 129 values.withUnsafeMutableBufferPointer { buffer in
128 let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size), 130 let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size),
129 attributes: SparseAttributes_t(), data: buffer.baseAddress!) 131 attributes: SparseAttributes_t(), data: buffer.baseAddress!)
130 SparseSolve(factor, b) 132 lock.withLock { _ in SparseSolve(factor, b) }
131 } 133 }
132 } 134 }
133} 135}
Packages/FoldKit/Sources/Folding/Camera.swift added +46
@@ -0,0 +1,46 @@
1import simd
2
3/// A perspective camera at `eye` looking at `target`. `fieldOfView` is vertical, in radians.
4public struct Camera: Sendable {
5 public var eye: SIMD3<Double>
6 public var target: SIMD3<Double>
7 public var up: SIMD3<Double>
8 public var fieldOfView: Double
9
10 public init(eye: SIMD3<Double>, target: SIMD3<Double>, up: SIMD3<Double>, fieldOfView: Double) {
11 self.eye = eye
12 self.target = target
13 self.up = up
14 self.fieldOfView = fieldOfView
15 }
16
17 /// The unit vector from `eye` toward `target`.
18 public var viewDirection: SIMD3<Double> {
19 let d = target - eye
20 return d / length(d)
21 }
22
23 /// World to clip space, Metal's: depth 0 at the near plane and 1 at the far plane, which are
24 /// 1/100 and 100 times the distance from `eye` to `target`.
25 public func viewProjection(aspect: Double) -> simd_double4x4 {
26 let f = viewDirection
27 let s = normalize(cross(f, up))
28 let u = cross(s, f)
29 let view = simd_double4x4(rows: [
30 SIMD4(s.x, s.y, s.z, -dot(s, eye)),
31 SIMD4(u.x, u.y, u.z, -dot(u, eye)),
32 SIMD4(-f.x, -f.y, -f.z, dot(f, eye)),
33 SIMD4(0, 0, 0, 1),
34 ])
35 let distance = length(target - eye)
36 let near = distance / 100, far = distance * 100
37 let y = 1 / tan(fieldOfView / 2), z = far / (near - far)
38 let projection = simd_double4x4(columns: (
39 SIMD4(y / aspect, 0, 0, 0),
40 SIMD4(0, y, 0, 0),
41 SIMD4(0, 0, z, -1),
42 SIMD4(0, 0, z * near, 0)
43 ))
44 return projection * view
45 }
46}
Packages/FoldKit/Sources/Folding/FoldStep.swift +9
@@ -96,9 +96,18 @@ public struct FoldStep: Equatable, Sendable {
96 self.viewpoint = viewpoint 96 self.viewpoint = viewpoint
97 } 97 }
98 98
99 /// The faces the step's axes move. A non-rigid step's pop holds the other faces still.
99 public var movingFaceUnion: Set<Int> { 100 public var movingFaceUnion: Set<Int> {
100 axes.reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) } 101 axes.reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
101 } 102 }
103
104 /// Every face that moves during the step: `movingFaceUnion` and, in a non-rigid step, the faces
105 /// its open and close axes move, which include the faces that open on the spine.
106 public var allMovingFaces: Set<Int> {
107 let pop = nonRigid ? pop : nil
108 return (axes + (pop?.openAxes ?? []) + (pop?.closeAxes ?? []))
109 .reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
110 }
102} 111}
103 112
104public enum StepError: Error, Equatable, Sendable { 113public enum StepError: Error, Equatable, Sendable {
Packages/FoldKit/Sources/Folding/LayerMotion.swift +1 −1
@@ -43,7 +43,7 @@ public func layerMotionDefects(step n: Int, in file: FoldFile) -> [FoldDefect] {
43 let size = sheetExtent(file) 43 let size = sheetExtent(file)
44 let pop = step.nonRigid ? step.pop : nil 44 let pop = step.nonRigid ? step.pop : nil
45 let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes 45 let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes
46 let moving = (step.axes + departing + arriving).reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) } 46 let moving = step.allMovingFaces
47 let interpolator = FoldInterpolator(file: file, step: step) 47 let interpolator = FoldInterpolator(file: file, step: step)
48 let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in 48 let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in
49 crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) }, 49 crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) },
Packages/FoldKit/Sources/Folding/LayerOrder.swift +4 −4
@@ -28,11 +28,11 @@ private let parallelCosine = 1 - 1e-9
28/// The stacking order of faces in one state of a step, kept as raw `faceOrders` triples so that 28/// The stacking order of faces in one state of a step, kept as raw `faceOrders` triples so that
29/// each is read against its `g`'s normal wherever the faces are. 29/// each is read against its `g`'s normal wherever the faces are.
30public struct LayerOrder: Sendable { 30public struct LayerOrder: Sendable {
31 private struct Triple: Sendable { 31 struct Triple: Sendable {
32 let f: Int, g: Int, s: Int 32 let f: Int, g: Int, s: Int
33 } 33 }
34 34
35 private let triples: [Triple] 35 let triples: [Triple]
36 /// Each pair's relation in the form `rigidInvariantFaceOrders` gives, from the source that 36 /// Each pair's relation in the form `rigidInvariantFaceOrders` gives, from the source that
37 /// supplied the pair. 37 /// supplied the pair.
38 private let invariant: [SIMD2<Int>: Int] 38 private let invariant: [SIMD2<Int>: Int]
@@ -77,7 +77,7 @@ public struct LayerOrder: Sendable {
77 /// 77 ///
78 /// A triple whose `g` moves in the step and whose `f` does not is replaced, with its source's 78 /// A triple whose `g` moves in the step and whose `f` does not is replaced, with its source's
79 /// normals, by its reverse, so that the pair is read against the still face's normal, which 79 /// normals, by its reverse, so that the pair is read against the still face's normal, which
80 /// does not turn during the step. 80 /// does not turn during the step. A face moves when it is in `step.allMovingFaces`.
81 public static func active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder { 81 public static func active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder {
82 let start = file.frames[step.index - 1], end = file.frames[step.index] 82 let start = file.frames[step.index - 1], end = file.frames[step.index]
83 let first: (faceOrders: [[Int]], normals: [SIMD3<Double>]) 83 let first: (faceOrders: [[Int]], normals: [SIMD3<Double>])
@@ -90,7 +90,7 @@ public struct LayerOrder: Sendable {
90 } else { 90 } else {
91 first = (end.faceOrders, faceNormals(end, file)) 91 first = (end.faceOrders, faceNormals(end, file))
92 } 92 }
93 let moving = step.movingFaceUnion 93 let moving = step.allMovingFaces
94 let sources = [first, (start.faceOrders, faceNormals(start, file))].map { source in 94 let sources = [first, (start.faceOrders, faceNormals(start, file))].map { source in
95 (faceOrders: source.faceOrders.map { t -> [Int] in 95 (faceOrders: source.faceOrders.map { t -> [Int] in
96 guard t.count == 3, source.normals.indices.contains(t[0]), source.normals.indices.contains(t[1]), 96 guard t.count == 3, source.normals.indices.contains(t[0]), source.normals.indices.contains(t[1]),
Packages/FoldKit/Sources/Notation/DiagramBuilder.swift added +249
@@ -0,0 +1,249 @@
1import FoldFormat
2import Folding
3import simd
4
5public enum DiagramLine: Equatable, Sendable {
6 /// `B` edges and creases folded in the drawn frame.
7 case solid
8 /// Creases made in an earlier step and flat again.
9 case light
10 /// The step's valley, as seen.
11 case dashed
12 /// The step's mountain, as seen.
13 case dashDot
14}
15
16/// A diagram symbol in screen coordinates, the drawn frame projected along the step's viewpoint
17/// in the sheet's units. A fold arrow curves from `from`, a point of the moving set before the
18/// step, through `over`, the apex of its arc, to `to`, the same point after the fold (at the peak
19/// for a fold-and-unfold).
20public enum DiagramArrow: Equatable, Sendable {
21 case valleyFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>)
22 case mountainFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>)
23 case foldAndUnfold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>, mountain: Bool)
24 /// The technique's symbol at the midpoint of the step's first crease, pointing toward where
25 /// that axis's moving set ends.
26 case technique(StepTechnique, at: SIMD2<Double>, toward: SIMD2<Double>)
27 case turnOver(TurnOverAxis)
28 /// Counterclockwise as seen when positive.
29 case rotate(degrees: Double)
30 /// The step repeats step `of`.
31 case repeatMark(of: Int)
32}
33
34/// A visible piece of FOLD edge `edge`, in the arrows' screen coordinates.
35public struct DiagramEdge: Equatable, Sendable {
36 public let edge: Int
37 public let from: SIMD2<Double>
38 public let to: SIMD2<Double>
39 public let style: DiagramLine
40
41 public init(edge: Int, from: SIMD2<Double>, to: SIMD2<Double>, style: DiagramLine) {
42 self.edge = edge
43 self.from = from
44 self.to = to
45 self.style = style
46 }
47}
48
49/// Edges in FOLD edge order.
50public struct Diagram: Equatable, Sendable {
51 public let edges: [DiagramEdge]
52 public let arrows: [DiagramArrow]
53
54 public init(edges: [DiagramEdge], arrows: [DiagramArrow]) {
55 self.edges = edges
56 self.arrows = arrows
57 }
58}
59
60/// The arc's apex lies this fraction of the chord from the chord's midpoint.
61private let arcBulge = 0.3
62
63/// The diagram for step `step.index`: frame `step.index − 1` seen orthographically from the
64/// step's viewpoint, with the step's creases and symbols.
65///
66/// Edges whose `edges_krz:firstCreasedAtStep` is later than the step, and subdivision edges, are
67/// not drawn. An edge the step creases (its two faces move differently) is dashed for a valley as
68/// seen and dash-dot for a mountain, whatever its assignment; other `B` edges and folded creases
69/// are solid; earlier creases flat again are light. Each edge is clipped by `visibleSegments`, and
70/// a piece coincident with one already drawn is drawn once, step creases before solid before light.
71///
72/// - Precondition: `validate(file)` is empty.
73public func buildDiagram(file: FoldFile, step: FoldStep) -> Diagram {
74 let n = step.index
75 let frame = file.frames[n - 1]
76 let normals = faceNormals(frame, file)
77 // a validated frame's orders have no cycle
78 let order = try! LayerOrder(faceOrders: frame.faceOrders, normals: normals)
79 let occlusion = Occlusion(frame: frame, file: file, order: order, viewpoint: step.viewpoint)
80 let eye = step.viewpoint.eye
81
82 let valley = step.axes.map { axis -> Bool in
83 let face = occlusion.edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }!
84 let turn = (step.kind == .foldAndUnfold ? axis.peakAngle ?? axis.endAngle : axis.endAngle) - axis.startAngle
85 return turn * dot(normals[face], eye) > 0
86 }
87 let creasing = creasingAxes(step, faceCount: file.facesVertices.count, edgeFaces: occlusion.edgeFaces)
88
89 var candidates: [(edge: Int, style: DiagramLine, rank: Int)] = []
90 for e in file.edgesVertices.indices {
91 let created = file.edgesFirstCreasedAtStep[e]
92 if let created, created > n { continue }
93 if frame.edgesAssignment[e] == .boundary {
94 candidates.append((e, .solid, 1))
95 } else if created == nil {
96 continue
97 } else if let axis = creasing[e] {
98 candidates.append((e, valley[axis] ? .dashed : .dashDot, 0))
99 } else if abs(frame.edgesFoldAngle[e]) > 1e-9 {
100 candidates.append((e, .solid, 1))
101 } else if created! < n {
102 candidates.append((e, .light, 2))
103 }
104 }
105 candidates.sort { ($0.rank, $0.edge) < ($1.rank, $1.edge) }
106
107 var drawn: [DiagramEdge] = []
108 for c in candidates {
109 for (a, b) in occlusion.visibleSegments(of: c.edge) {
110 for (p, q) in uncovered(a, b, by: drawn, tolerance: occlusion.tolerance) {
111 drawn.append(DiagramEdge(edge: c.edge, from: p, to: q, style: c.style))
112 }
113 }
114 }
115 let edges = drawn.enumerated().sorted { ($0.element.edge, $0.offset) < ($1.element.edge, $1.offset) }.map(\.element)
116 let symbols = arrows(file, step, valley: valley, project: ViewProjection(step.viewpoint),
117 edgeFaces: occlusion.edgeFaces)
118 return Diagram(edges: edges, arrows: symbols)
119}
120
121/// For each edge, the index in `step.axes` of the axis whose motion creases it, or nil. Each face
122/// belongs to the axis whose moving set holds it, or to the fixed group; an edge is creased when
123/// its faces' groups differ, by the deeper group's axis.
124private func creasingAxes(_ step: FoldStep, faceCount: Int, edgeFaces: [[Int]]) -> [Int?] {
125 var group = Array<Int?>(repeating: nil, count: faceCount)
126 for (i, axis) in step.axes.enumerated() {
127 for f in axis.movingFaces { group[f] = i }
128 }
129 func depth(_ axis: Int?) -> Int {
130 guard let axis else { return -1 }
131 return 1 + depth(step.axes[axis].parent)
132 }
133 return edgeFaces.map { faces in
134 guard faces.count == 2, group[faces[0]] != group[faces[1]] else { return nil }
135 let (a, b) = (group[faces[0]], group[faces[1]])
136 return depth(a) >= depth(b) ? a : b
137 }
138}
139
140/// The parts of `a`–`b` not lying along an edge already drawn.
141private func uncovered(_ a: SIMD2<Double>, _ b: SIMD2<Double>, by drawn: [DiagramEdge],
142 tolerance: Double) -> [(SIMD2<Double>, SIMD2<Double>)] {
143 let d = b - a, length2 = length_squared(d)
144 let normal = normalize(SIMD2(-d.y, d.x))
145 var covered: [ClosedRange<Double>] = []
146 for e in drawn where abs(dot(e.from - a, normal)) <= tolerance && abs(dot(e.to - a, normal)) <= tolerance {
147 let s = dot(e.from - a, d) / length2, t = dot(e.to - a, d) / length2
148 let low = max(min(s, t), 0), high = min(max(s, t), 1)
149 if high > low { covered.append(low...high) }
150 }
151 var pieces: [ClosedRange<Double>] = []
152 var start = 0.0
153 for range in covered.sorted(by: { $0.lowerBound < $1.lowerBound }) {
154 if range.lowerBound > start { pieces.append(start...range.lowerBound) }
155 start = max(start, range.upperBound)
156 }
157 if start < 1 { pieces.append(start...1) }
158 let minimum = tolerance / length2.squareRoot()
159 return pieces.filter { $0.upperBound - $0.lowerBound > minimum }
160 .map { (a + $0.lowerBound * d, a + $0.upperBound * d) }
161}
162
163private func arrows(_ file: FoldFile, _ step: FoldStep, valley: [Bool], project: ViewProjection,
164 edgeFaces: [[Int]]) -> [DiagramArrow] {
165 var arrows: [DiagramArrow] = []
166 let start = file.frames[step.index - 1].verticesCoords
167 switch step.kind {
168 case .turnOver:
169 if let axis = step.turnOverAxis { arrows.append(.turnOver(axis)) }
170 case .rotate:
171 if let degrees = step.rotateDegrees { arrows.append(.rotate(degrees: degrees)) }
172 case .fold, .foldAndUnfold:
173 let interpolator = step.kind == .foldAndUnfold ? FoldInterpolator(file: file, step: step) : nil
174 // a point of the axis's moving set and where it is at the end of the step, or at the peak
175 func track(_ axis: FoldAxis, _ point: SIMD3<Double>) -> (SIMD2<Double>, SIMD2<Double>) {
176 let end = interpolator?.positions(at: (axis.window.lowerBound + axis.window.upperBound) / 2)
177 ?? file.frames[step.index].verticesCoords
178 let face = edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }!
179 return (project(point), project(carried(point, with: file.facesVertices[face], from: start, to: end)))
180 }
181 if step.technique != .plain {
182 guard let axis = step.axes.first else { break }
183 let ends = file.edgesVertices[axis.edge].map { project(start[$0]) }
184 let toward = track(axis, centroid(of: axis.movingFaces, file, positions: start)).1
185 arrows.append(.technique(step.technique, at: (ends[0] + ends[1]) / 2, toward: toward))
186 break
187 }
188 // simultaneous arrows are spread along their creases, in one screen direction, so that
189 // they do not meet
190 let count = Double(step.axes.count)
191 for (i, axis) in step.axes.enumerated() {
192 let ends = file.edgesVertices[axis.edge].map { start[$0] }
193 let shift = (Double(i) - (count - 1) / 2) / (count + 1) * distance(ends[0], ends[1])
194 let along = project(axis.direction)
195 let sign = along.y < -1e-9 || (abs(along.y) <= 1e-9 && along.x < 0) ? -1.0 : 1.0
196 let point = centroid(of: axis.movingFaces, file, positions: start) + sign * shift * axis.direction
197 let (from, to) = track(axis, point)
198 let over = apex(from, to)
199 if step.kind == .foldAndUnfold {
200 arrows.append(.foldAndUnfold(from: from, over: over, to: to, mountain: !valley[i]))
201 } else if valley[i] {
202 arrows.append(.valleyFold(from: from, over: over, to: to))
203 } else {
204 arrows.append(.mountainFold(from: from, over: over, to: to))
205 }
206 }
207 }
208 if let repeated = step.repeatOf { arrows.append(.repeatMark(of: repeated)) }
209 return arrows
210}
211
212/// The area-weighted mean of the faces' vertex means.
213private func centroid(of faces: Set<Int>, _ file: FoldFile, positions: [SIMD3<Double>]) -> SIMD3<Double> {
214 var sum = SIMD3<Double>.zero, total = 0.0
215 for f in faces.sorted() {
216 let corners = file.facesVertices[f].map { positions[$0] }
217 let area = length(corners.indices.reduce(SIMD3<Double>.zero) { s, i in
218 s + simd.cross(corners[i], corners[(i + 1) % corners.count])
219 }) / 2
220 sum += area * corners.reduce(.zero, +) / Double(corners.count)
221 total += area
222 }
223 return sum / total
224}
225
226/// `point` moved rigidly with the face whose corners are `corners`, from `start` to `end`.
227private func carried(_ point: SIMD3<Double>, with corners: [Int], from start: [SIMD3<Double>],
228 to end: [SIMD3<Double>]) -> SIMD3<Double> {
229 let o = start[corners[0]], u = start[corners[1]] - o
230 // the corner farthest from the line of the first two spans the face's plane best
231 let spread = { (i: Int) in length(cross(u, start[corners[i]] - o)) }
232 let k = corners.indices.dropFirst(2).max { spread($0) < spread($1) }!
233 func basis(_ x: [SIMD3<Double>]) -> simd_double3x3 {
234 let e1 = x[corners[1]] - x[corners[0]], e2 = x[corners[k]] - x[corners[0]]
235 return simd_double3x3(columns: (e1, e2, normalize(cross(e1, e2))))
236 }
237 return end[corners[0]] + basis(end) * (basis(start).inverse * (point - o))
238}
239
240/// The apex of an arc from `from` to `to`, to the side of the chord toward screen-up, or toward
241/// screen-right for a vertical chord.
242private func apex(_ from: SIMD2<Double>, _ to: SIMD2<Double>) -> SIMD2<Double> {
243 let chord = to - from
244 var side = SIMD2(-chord.y, chord.x)
245 if side.y < -1e-12 * length(chord) || (abs(side.y) <= 1e-12 * length(chord) && side.x < 0) {
246 side = -side
247 }
248 return (from + to) / 2 + arcBulge * side
249}
Packages/FoldKit/Sources/Notation/DiagramDrawing.swift added +209
@@ -0,0 +1,209 @@
1import CoreGraphics
2import CoreText
3import Foundation
4import simd
5
6/// The model and its arrows fill the canvas inside these margins, in points; the turn-over and
7/// rotate symbols sit in the bottom one.
8private let sideMargin = 48.0, bottomMargin = 96.0
9
10/// Draws `diagram` into the rectangle from the origin to `size`, the model and its arrows fitted
11/// inside the margins.
12///
13/// The context's user space must be y-up with its origin at the bottom-left of the canvas, as in a
14/// `CGBitmapContext`; a y-down context such as SwiftUI's `GraphicsContext.withCGContext` must be
15/// flipped first (`translateBy(x: 0, y: height)`, `scaleBy(x: 1, y: -1)`). Nothing is drawn
16/// behind the diagram: the caller fills the background, and hollow heads and the push arrow are
17/// filled white. The context's graphics state is restored on return.
18public func drawDiagram(_ diagram: Diagram, style: DiagramStyle, in context: CGContext, size: CGSize) {
19 context.saveGState()
20 defer { context.restoreGState() }
21
22 var points = diagram.edges.flatMap { [$0.from, $0.to] }
23 for arrow in diagram.arrows {
24 switch arrow {
25 case let .valleyFold(from, over, to), let .mountainFold(from, over, to), let .foldAndUnfold(from, over, to, _):
26 points += [from, over, to]
27 case let .technique(_, at, toward):
28 points += [at, toward]
29 case .turnOver, .rotate, .repeatMark:
30 break
31 }
32 }
33 let low = points.reduce(points.first ?? .zero, simd_min)
34 let high = points.reduce(points.first ?? .zero, simd_max)
35 let area = CGRect(x: sideMargin, y: bottomMargin, width: size.width - 2 * sideMargin,
36 height: size.height - bottomMargin - sideMargin)
37 let extent = simd_max(high - low, SIMD2(repeating: 1e-9))
38 let scale = min(area.width / extent.x, area.height / extent.y)
39 let offset = SIMD2(area.midX, area.midY) - scale * (low + high) / 2
40 func pixel(_ p: SIMD2<Double>) -> CGPoint {
41 let q = offset + scale * p
42 return CGPoint(x: q.x, y: q.y)
43 }
44
45 context.setLineJoin(.round)
46 let layers: [(DiagramLine, Double, Double, [Double])] = [
47 (.light, style.lightWidth, style.lightGrey, []),
48 (.solid, style.outlineWidth, 0, []),
49 (.dashed, style.creaseWidth, 0, style.valleyDash),
50 (.dashDot, style.creaseWidth, 0, style.mountainDash),
51 ]
52 for (line, width, grey, dash) in layers {
53 context.setStrokeColor(gray: grey, alpha: 1)
54 context.setLineWidth(width)
55 context.setLineCap(dash.isEmpty ? .round : .butt)
56 context.setLineDash(phase: 0, lengths: dash.map { CGFloat($0) })
57 for edge in diagram.edges where edge.style == line {
58 context.move(to: pixel(edge.from))
59 context.addLine(to: pixel(edge.to))
60 }
61 context.strokePath()
62 }
63 context.setLineDash(phase: 0, lengths: [])
64 context.setLineCap(.round)
65 context.setStrokeColor(gray: 0, alpha: 1)
66 context.setLineWidth(style.arrowWidth)
67
68 let repeated = diagram.arrows.contains { if case .repeatMark = $0 { true } else { false } }
69 let symbolCentre = SIMD2(size.width / 2, bottomMargin / 2)
70 for arrow in diagram.arrows {
71 switch arrow {
72 case let .valleyFold(from, over, to):
73 drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .filled, returnHead: false, tick: repeated)
74 case let .mountainFold(from, over, to):
75 drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowHalf, returnHead: false, tick: repeated)
76 case let .foldAndUnfold(from, over, to, mountain):
77 drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: mountain ? .hollowHalf : .filled,
78 returnHead: true, tick: repeated)
79 case let .technique(technique, at, toward):
80 let tip = vector(pixel(at)), direction = normalize(vector(pixel(toward)) - tip)
81 if technique == .petal {
82 let tail = tip - style.symbolSize * 1.5 * direction
83 let over = (tip + tail) / 2 + 0.3 * SIMD2(direction.y, -direction.x) * style.symbolSize * 1.5
84 drawFoldArrow(context, style, point(tail), point(over), point(tip), head: .filled, returnHead: false,
85 tick: repeated)
86 } else {
87 drawPushArrow(context, style, tip: tip, direction: direction, tick: repeated)
88 }
89 case let .turnOver(axis):
90 drawTurnOver(context, style, centre: symbolCentre, vertical: axis == .vertical)
91 case let .rotate(degrees):
92 drawRotate(context, style, centre: symbolCentre, degrees: degrees)
93 case .repeatMark:
94 break
95 }
96 }
97}
98
99private enum Head { case filled, hollowHalf, hollowFull }
100
101private func vector(_ p: CGPoint) -> SIMD2<Double> { SIMD2(p.x, p.y) }
102private func point(_ v: SIMD2<Double>) -> CGPoint { CGPoint(x: v.x, y: v.y) }
103
104/// A quadratic arc from `from` through `over` to `to`, its head at `to`; with `returnHead` a
105/// hollow head at `from` pointing back; with `tick` a stroke across the shaft near its tail.
106private func drawFoldArrow(_ context: CGContext, _ style: DiagramStyle, _ from: CGPoint, _ over: CGPoint, _ to: CGPoint,
107 head: Head, returnHead: Bool, tick: Bool) {
108 let a = vector(from), m = vector(over), b = vector(to)
109 let control = 2 * m - (a + b) / 2
110 context.move(to: from)
111 context.addQuadCurve(to: to, control: point(control))
112 context.strokePath()
113 // the barb of a half head goes on the outside of the arc
114 let outside = m - (a + b) / 2
115 drawHead(context, style, head, tip: b, direction: normalize(b - control), outside: outside)
116 if returnHead {
117 drawHead(context, style, .hollowFull, tip: a, direction: normalize(a - control), outside: outside)
118 }
119 if tick {
120 let t = 0.25
121 let p = (1 - t) * (1 - t) * a + 2 * t * (1 - t) * control + t * t * b
122 let tangent = normalize(2 * (1 - t) * (control - a) + 2 * t * (b - control))
123 let across = SIMD2(-tangent.y, tangent.x) * style.headLength / 2
124 context.move(to: point(p - across))
125 context.addLine(to: point(p + across))
126 context.strokePath()
127 }
128}
129
130private func drawHead(_ context: CGContext, _ style: DiagramStyle, _ head: Head, tip: SIMD2<Double>,
131 direction: SIMD2<Double>, outside: SIMD2<Double>) {
132 let back = tip - style.headLength * direction
133 var across = SIMD2(-direction.y, direction.x) * style.headWidth / 2
134 if dot(across, outside) < 0 { across = -across }
135 let corners: [SIMD2<Double>]
136 switch head {
137 case .filled, .hollowFull: corners = [tip, back + across, back - across]
138 case .hollowHalf: corners = [tip, back + 2 * across, back]
139 }
140 context.addLines(between: corners.map(point))
141 context.closePath()
142 context.setFillColor(gray: head == .filled ? 0 : 1, alpha: 1)
143 context.drawPath(using: .fillStroke)
144}
145
146/// The hollow push arrow, its tip at `tip`, with a notched tail; with `tick` a stroke across the
147/// shaft near its tail, standing out of the shaft by half a head length on each side.
148private func drawPushArrow(_ context: CGContext, _ style: DiagramStyle, tip: SIMD2<Double>, direction: SIMD2<Double>,
149 tick: Bool) {
150 let s = style.symbolSize
151 let outline: [SIMD2<Double>] = [
152 SIMD2(0, 0), SIMD2(-0.36, 0.3), SIMD2(-0.36, 0.12), SIMD2(-1, 0.12),
153 SIMD2(-0.86, 0), SIMD2(-1, -0.12), SIMD2(-0.36, -0.12), SIMD2(-0.36, -0.3),
154 ]
155 let across = SIMD2(-direction.y, direction.x)
156 context.addLines(between: outline.map { point(tip + s * ($0.x * direction + $0.y * across)) })
157 context.closePath()
158 context.setFillColor(gray: 1, alpha: 1)
159 context.drawPath(using: .fillStroke)
160 if tick {
161 let p = tip - 0.7 * s * direction, half = 0.12 * s + style.headLength / 2
162 context.move(to: point(p - half * across))
163 context.addLine(to: point(p + half * across))
164 context.strokePath()
165 }
166}
167
168/// The loop-the-loop arrow: left to right for a turn about the vertical axis, bottom to top about
169/// the horizontal.
170private func drawTurnOver(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, vertical: Bool) {
171 // a prolate cycloid over one period, its loop above the line of travel, between straight tails
172 let a = style.symbolSize / (3 * .pi), b = 2 * a
173 let loop = (0...64).map { i -> SIMD2<Double> in
174 let u = -Double.pi + 2 * .pi * Double(i) / 64
175 return SIMD2(a * u - b * sin(u), b * cos(u))
176 }
177 let tail = SIMD2(style.symbolSize / 4, 0)
178 let path = [loop[0] - tail] + loop + [loop[64] + tail]
179 let place = { (p: SIMD2<Double>) in centre + (vertical ? p : SIMD2(-p.y, p.x)) }
180 context.addLines(between: path.map { point(place($0)) })
181 context.strokePath()
182 let tip = place(path[path.count - 1])
183 drawHead(context, style, .filled, tip: tip, direction: normalize(tip - place(loop[64])), outside: SIMD2(0, 1))
184}
185
186/// Two arcs around a circle, counterclockwise for positive `degrees`, with the amount at the centre.
187private func drawRotate(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, degrees: Double) {
188 let r = style.symbolSize / 2
189 let turn = degrees >= 0 ? 1.0 : -1.0
190 let headAngle = style.headLength / r
191 for start in [Double.pi * 0.6, Double.pi * 1.6] {
192 let end = start + turn * Double.pi * 0.75, back = end - turn * headAngle
193 context.addArc(center: point(centre), radius: r, startAngle: start, endAngle: back, clockwise: turn < 0)
194 context.strokePath()
195 let tip = centre + r * SIMD2(cos(end), sin(end)), base = centre + r * SIMD2(cos(back), sin(back))
196 drawHead(context, style, .filled, tip: tip, direction: normalize(tip - base), outside: tip - centre)
197 }
198 let label = String(format: "%g°", abs(degrees))
199 let font = CTFontCreateWithName("Helvetica" as CFString, 14, nil)
200 let text = NSAttributedString(string: label, attributes: [
201 NSAttributedString.Key(kCTFontAttributeName as String): font,
202 NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true,
203 ])
204 let line = CTLineCreateWithAttributedString(text)
205 let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds)
206 context.setFillColor(gray: 0, alpha: 1)
207 context.textPosition = CGPoint(x: centre.x - bounds.midX, y: centre.y - bounds.midY)
208 CTLineDraw(line, context)
209}
Packages/FoldKit/Sources/Notation/DiagramStyle.swift added +43
@@ -0,0 +1,43 @@
1/// How a `Diagram` is drawn. Lengths are in points; `lightGrey` is a grey level, 0 black to 1 white.
2///
3/// `NOTATION.md` beside the golden images records the source of each choice.
4public struct DiagramStyle: Sendable {
5 /// `B` edges and creases folded in the drawn frame.
6 public var outlineWidth: Double
7 /// Creases made earlier and flat again.
8 public var lightWidth: Double
9 public var lightGrey: Double
10 /// The step's own creases.
11 public var creaseWidth: Double
12 /// Dash, gap: a valley.
13 public var valleyDash: [Double]
14 /// Dash, gap, dot, gap, dot, gap: a mountain, drawn with butt caps.
15 public var mountainDash: [Double]
16 public var arrowWidth: Double
17 public var headLength: Double
18 /// The full head's width; a half head has one barb of half this.
19 public var headWidth: Double
20 /// The longer side of the push arrow and of the turn-over and rotate symbols.
21 public var symbolSize: Double
22
23 public init(outlineWidth: Double, lightWidth: Double, lightGrey: Double, creaseWidth: Double,
24 valleyDash: [Double], mountainDash: [Double], arrowWidth: Double, headLength: Double,
25 headWidth: Double, symbolSize: Double) {
26 self.outlineWidth = outlineWidth
27 self.lightWidth = lightWidth
28 self.lightGrey = lightGrey
29 self.creaseWidth = creaseWidth
30 self.valleyDash = valleyDash
31 self.mountainDash = mountainDash
32 self.arrowWidth = arrowWidth
33 self.headLength = headLength
34 self.headWidth = headWidth
35 self.symbolSize = symbolSize
36 }
37
38 public static let standard = DiagramStyle(
39 outlineWidth: 2, lightWidth: 1, lightGrey: 0.6, creaseWidth: 1.5,
40 valleyDash: [7, 4], mountainDash: [9, 3, 2, 3, 2, 3],
41 arrowWidth: 1.5, headLength: 14, headWidth: 10, symbolSize: 60
42 )
43}
Packages/FoldKit/Sources/Notation/EdgeOcclusion.swift added +133
@@ -0,0 +1,133 @@
1import FoldFormat
2import Folding
3import simd
4
5/// The parts of `edge`, projected orthographically along `viewpoint`, that are not inside the
6/// union of the faces above either of its faces in `frame`.
7///
8/// A face is above an edge's face when it follows that face in their cluster's back-to-front list,
9/// `order.clusters` read looking along −`eye`; faces in other clusters do not occlude. An edge on
10/// the outer boundary of the union stays visible; one under the seam between two upper faces,
11/// covered on both sides, does not.
12public func visibleSegments(of edge: Int, frame: FoldFrame, file: FoldFile, order: LayerOrder,
13 viewpoint: Viewpoint) -> [(SIMD2<Double>, SIMD2<Double>)] {
14 Occlusion(frame: frame, file: file, order: order, viewpoint: viewpoint).visibleSegments(of: edge)
15}
16
17/// Orthographic projection onto the screen plane of a viewpoint: x along `right`, y along `up`.
18struct ViewProjection {
19 let right: SIMD3<Double>
20 let up: SIMD3<Double>
21
22 init(_ viewpoint: Viewpoint) {
23 let eye = normalize(viewpoint.eye)
24 right = normalize(cross(viewpoint.up, eye))
25 up = cross(eye, right)
26 }
27
28 func callAsFunction(_ p: SIMD3<Double>) -> SIMD2<Double> {
29 SIMD2(dot(p, right), dot(p, up))
30 }
31}
32
33/// One frame projected for a viewpoint, with each face's occluders.
34struct Occlusion {
35 let points: [SIMD2<Double>]
36 let edgesVertices: [[Int]]
37 let edgeFaces: [[Int]]
38 /// Each face's projected outline, counterclockwise.
39 let outlines: [[SIMD2<Double>]]
40 /// Each face's followers in its cluster.
41 let above: [[Int]]
42 let tolerance: Double
43
44 init(frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) {
45 let project = ViewProjection(viewpoint)
46 let points = frame.verticesCoords.map(project.callAsFunction)
47 self.points = points
48 edgesVertices = file.edgesVertices
49 edgeFaces = edgesFaces(file)
50 outlines = file.facesVertices.map { corners in
51 let outline = corners.map { points[$0] }
52 return signedArea(outline) < 0 ? outline.reversed() : outline
53 }
54 var above = Array(repeating: [Int](), count: file.facesVertices.count)
55 let clusters = order.clusters(positions: frame.verticesCoords, faces: file.facesVertices,
56 viewDirection: -viewpoint.eye)
57 for cluster in clusters {
58 for (i, face) in cluster.faces.enumerated() {
59 above[face] = Array(cluster.faces[(i + 1)...])
60 }
61 }
62 self.above = above
63 let low = points.reduce(points.first ?? .zero, simd_min)
64 let high = points.reduce(points.first ?? .zero, simd_max)
65 tolerance = max(length(high - low), 1) * 1e-9
66 }
67
68 func endpoints(of edge: Int) -> (SIMD2<Double>, SIMD2<Double>) {
69 (points[edgesVertices[edge][0]], points[edgesVertices[edge][1]])
70 }
71
72 func visibleSegments(of edge: Int) -> [(SIMD2<Double>, SIMD2<Double>)] {
73 let (a, b) = endpoints(of: edge)
74 guard length(b - a) > tolerance else { return [] }
75 let occluders = Set(edgeFaces[edge].flatMap { above[$0] })
76 let covers = occluders.sorted().compactMap { cover(a, b, by: outlines[$0]) }
77
78 // between consecutive cut points coverage is constant; test each piece's midpoint
79 let cuts = Set([0.0, 1.0] + covers.flatMap { [$0.range.lowerBound, $0.range.upperBound] }).sorted()
80 var visible: [ClosedRange<Double>] = []
81 for (t0, t1) in zip(cuts, cuts.dropFirst()) where t1 > t0 {
82 let t = (t0 + t1) / 2
83 let sides = covers.filter { $0.range.contains(t) }.map(\.side)
84 let hidden = sides.contains(.both) || (sides.contains(.left) && sides.contains(.right))
85 if hidden { continue }
86 if let last = visible.last, last.upperBound == t0 {
87 visible[visible.count - 1] = last.lowerBound...t1
88 } else {
89 visible.append(t0...t1)
90 }
91 }
92 let minimum = tolerance / length(b - a)
93 return visible.filter { $0.upperBound - $0.lowerBound > minimum }
94 .map { (a + $0.lowerBound * (b - a), a + $0.upperBound * (b - a)) }
95 }
96
97 enum Side { case left, right, both }
98
99 /// The parameters of the segment `a`–`b` the counterclockwise convex `polygon` covers, and on
100 /// which side: both sides where the segment crosses its open interior, one side where the
101 /// segment lies along one of its sides.
102 private func cover(_ a: SIMD2<Double>, _ b: SIMD2<Double>,
103 by polygon: [SIMD2<Double>]) -> (range: ClosedRange<Double>, side: Side)? {
104 let d = b - a
105 var low = 0.0, high = 1.0
106 var side = Side.both
107 for i in polygon.indices {
108 let p = polygon[i], s = polygon[(i + 1) % polygon.count] - p
109 let sideLength = length(s)
110 guard sideLength > tolerance else { continue }
111 // distance inside this side's line at parameter t: c0 + c1 t
112 let c0 = perpDot(s, a - p) / sideLength, c1 = perpDot(s, d) / sideLength
113 if abs(c0) <= tolerance && abs(c0 + c1) <= tolerance {
114 side = dot(s, d) > 0 ? .left : .right
115 continue
116 }
117 if c1 == 0 {
118 if c0 <= 0 { return nil }
119 } else if c1 > 0 {
120 low = max(low, -c0 / c1)
121 } else {
122 high = min(high, -c0 / c1)
123 }
124 }
125 return high - low > tolerance / length(d) ? (low...high, side) : nil
126 }
127}
128
129func perpDot(_ u: SIMD2<Double>, _ v: SIMD2<Double>) -> Double { u.x * v.y - u.y * v.x }
130
131func signedArea(_ p: [SIMD2<Double>]) -> Double {
132 p.indices.reduce(0) { sum, i in sum + perpDot(p[i], p[(i + 1) % p.count]) / 2 }
133}
Packages/FoldKit/Sources/Renderer/PaperRenderer.swift added +186
@@ -0,0 +1,186 @@
1import Folding
2import Foundation
3import Metal
4import simd
5
6public enum RendererError: Error, Equatable, Sendable {
7 case shadersMissing
8 case allocationFailed
9}
10
11/// Draws a render mesh with Metal.
12///
13/// Each coplanar cluster is drawn back to front in its order with the depth test on and depth
14/// writes off, so that its stacked faces resolve by layer order, then drawn again depth-only, so
15/// that clusters drawn after it are hidden behind it. Faces in different clusters resolve by depth.
16///
17/// Facets are two-sided. Unless `faceColours` is given, the side a FOLD face's normal points toward
18/// is drawn in `frontColour` and the other in `backColour`, shaded by a light along the view
19/// direction.
20public final class PaperRenderer {
21 public static let frontColour = SIMD4<Float>(0.80, 0.22, 0.18, 1)
22 public static let backColour = SIMD4<Float>(0.96, 0.94, 0.89, 1)
23 /// The clear colour.
24 public static let background = SIMD4<Float>(0, 0, 0, 0)
25 /// The shade of a face seen edge-on; a face square to the view direction has its full colour.
26 private static let edgeOnShade: Float = 0.35
27
28 public let device: MTLDevice
29 /// The queue `render` commits to. Work committed to it afterwards runs after the frame.
30 public let commandQueue: MTLCommandQueue
31 private let vertexFunction: MTLFunction
32 private let fragmentFunction: MTLFunction
33 /// Depth test on, writes off: a cluster's colour pass.
34 private let colourPass: MTLDepthStencilState
35 /// Depth test and writes on: a cluster's depth pass.
36 private let depthPass: MTLDepthStencilState
37 /// Per colour pixel format, the pipeline that draws colour and the one that draws depth only.
38 private var pipelines: [MTLPixelFormat: (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState)] = [:]
39 private var depthTexture: MTLTexture?
40
41 private struct PaperVertex {
42 var position: SIMD3<Float>
43 var normal: SIMD3<Float>
44 }
45
46 private struct Shading {
47 var front: SIMD4<Float>
48 var back: SIMD4<Float>
49 var light: SIMD4<Float>
50 }
51
52 public init(device: MTLDevice) throws {
53 guard let url = Bundle.module.url(forResource: "Shaders", withExtension: "metal") else {
54 throw RendererError.shadersMissing
55 }
56 let library = try device.makeLibrary(source: String(contentsOf: url, encoding: .utf8), options: nil)
57 guard let vertexFunction = library.makeFunction(name: "paperVertex"),
58 let fragmentFunction = library.makeFunction(name: "paperFragment") else {
59 throw RendererError.shadersMissing
60 }
61 let depth = MTLDepthStencilDescriptor()
62 depth.depthCompareFunction = .lessEqual
63 depth.isDepthWriteEnabled = false
64 let colourPass = device.makeDepthStencilState(descriptor: depth)
65 depth.isDepthWriteEnabled = true
66 guard let queue = device.makeCommandQueue(), let colourPass,
67 let depthPass = device.makeDepthStencilState(descriptor: depth) else {
68 throw RendererError.allocationFailed
69 }
70 self.device = device
71 commandQueue = queue
72 self.vertexFunction = vertexFunction
73 self.fragmentFunction = fragmentFunction
74 self.colourPass = colourPass
75 self.depthPass = depthPass
76 }
77
78 /// Draws `mesh` with its vertices at `positions` into `target`, cleared to `background`.
79 /// Faces in no cluster are not drawn. `faceColours`, when given, draws FOLD face i in
80 /// `faceColours[i]`, unlit, on both sides. Commits to `commandQueue` without waiting.
81 public func render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera,
82 faceColours: [SIMD4<Float>]? = nil, into target: MTLTexture) throws {
83 let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh)
84 let pipeline = try pipelines(for: target.pixelFormat)
85 guard let buffer = device.makeBuffer(bytes: vertices, length: vertices.count * MemoryLayout<PaperVertex>.stride),
86 let depth = depthTexture(width: target.width, height: target.height),
87 let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed }
88
89 let pass = MTLRenderPassDescriptor()
90 let b = Self.background
91 pass.colorAttachments[0].texture = target
92 pass.colorAttachments[0].loadAction = .clear
93 pass.colorAttachments[0].clearColor = MTLClearColor(red: Double(b.x), green: Double(b.y),
94 blue: Double(b.z), alpha: Double(b.w))
95 pass.colorAttachments[0].storeAction = .store
96 pass.depthAttachment.texture = depth
97 pass.depthAttachment.loadAction = .clear
98 pass.depthAttachment.clearDepth = 1
99 pass.depthAttachment.storeAction = .dontCare
100 guard let encoder = commands.makeRenderCommandEncoder(descriptor: pass) else {
101 throw RendererError.allocationFailed
102 }
103
104 let d = SIMD3<Float>(camera.viewDirection)
105 let lit = Shading(front: Self.frontColour, back: Self.backColour, light: SIMD4(d, Self.edgeOnShade))
106 let vp = camera.viewProjection(aspect: Double(target.width) / Double(target.height))
107 var viewProjection = simd_float4x4(columns: (SIMD4<Float>(vp.columns.0), SIMD4<Float>(vp.columns.1),
108 SIMD4<Float>(vp.columns.2), SIMD4<Float>(vp.columns.3)))
109 encoder.setFrontFacing(.counterClockwise)
110 encoder.setCullMode(.none)
111 encoder.setVertexBuffer(buffer, offset: 0, index: 0)
112 encoder.setVertexBytes(&viewProjection, length: MemoryLayout<simd_float4x4>.stride, index: 1)
113 func draw(_ face: Int) {
114 guard ranges.indices.contains(face), !ranges[face].isEmpty else { return }
115 encoder.drawPrimitives(type: .triangle, vertexStart: ranges[face].lowerBound,
116 vertexCount: ranges[face].count)
117 }
118 func setShading(_ shading: Shading) {
119 var shading = shading
120 encoder.setFragmentBytes(&shading, length: MemoryLayout<Shading>.stride, index: 0)
121 }
122 if faceColours == nil { setShading(lit) }
123
124 for cluster in clusters {
125 encoder.setRenderPipelineState(pipeline.colour)
126 encoder.setDepthStencilState(colourPass)
127 for face in cluster.faces {
128 if let colour = faceColours?[face] {
129 setShading(Shading(front: colour, back: colour, light: SIMD4(d, 1)))
130 }
131 draw(face)
132 }
133 encoder.setRenderPipelineState(pipeline.depth)
134 encoder.setDepthStencilState(depthPass)
135 for face in cluster.faces { draw(face) }
136 }
137 encoder.endEncoding()
138 commands.commit()
139 }
140
141 /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and
142 /// each FOLD face's range in them.
143 private func groupedVertices(positions: [SIMD3<Double>], mesh: RenderMesh) -> ([PaperVertex], [Range<Int>]) {
144 let faceCount = (mesh.faceOf.max() ?? -1) + 1
145 var start = Array(repeating: 0, count: faceCount + 1)
146 for f in mesh.faceOf { start[f + 1] += 3 }
147 for f in 0..<faceCount { start[f + 1] += start[f] }
148 var next = start
149 var vertices = Array(repeating: PaperVertex(position: .zero, normal: .zero), count: 3 * mesh.triangles.count)
150 for (t, (a, b, c)) in mesh.triangles.enumerated() {
151 let n = cross(positions[b] - positions[a], positions[c] - positions[a])
152 let normal = SIMD3<Float>(length(n) > 0 ? normalize(n) : .zero)
153 let f = mesh.faceOf[t]
154 for v in [a, b, c] {
155 vertices[next[f]] = PaperVertex(position: SIMD3<Float>(positions[v]), normal: normal)
156 next[f] += 1
157 }
158 }
159 return (vertices, (0..<faceCount).map { start[$0]..<start[$0 + 1] })
160 }
161
162 private func pipelines(for format: MTLPixelFormat) throws -> (colour: MTLRenderPipelineState,
163 depth: MTLRenderPipelineState) {
164 if let cached = pipelines[format] { return cached }
165 let descriptor = MTLRenderPipelineDescriptor()
166 descriptor.vertexFunction = vertexFunction
167 descriptor.fragmentFunction = fragmentFunction
168 descriptor.colorAttachments[0].pixelFormat = format
169 descriptor.depthAttachmentPixelFormat = .depth32Float
170 let colour = try device.makeRenderPipelineState(descriptor: descriptor)
171 descriptor.colorAttachments[0].writeMask = []
172 let depth = try device.makeRenderPipelineState(descriptor: descriptor)
173 pipelines[format] = (colour, depth)
174 return (colour, depth)
175 }
176
177 private func depthTexture(width: Int, height: Int) -> MTLTexture? {
178 if let depthTexture, depthTexture.width == width, depthTexture.height == height { return depthTexture }
179 let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width,
180 height: height, mipmapped: false)
181 descriptor.usage = .renderTarget
182 descriptor.storageMode = .private
183 depthTexture = device.makeTexture(descriptor: descriptor)
184 return depthTexture
185 }
186}
Packages/FoldKit/Sources/Renderer/Shaders.metal added +37
@@ -0,0 +1,37 @@
1#include <metal_stdlib>
2using namespace metal;
3
4struct PaperVertex {
5 float3 position;
6 float3 normal;
7};
8
9/// `light.xyz` is the view direction, `light.w` the shade of a face seen edge-on.
10struct Shading {
11 float4 front;
12 float4 back;
13 float4 light;
14};
15
16struct Fragment {
17 float4 position [[position]];
18 float3 normal [[flat]];
19};
20
21vertex Fragment paperVertex(uint id [[vertex_id]],
22 const device PaperVertex *vertices [[buffer(0)]],
23 constant float4x4 &viewProjection [[buffer(1)]]) {
24 Fragment out;
25 out.position = viewProjection * float4(vertices[id].position, 1);
26 out.normal = vertices[id].normal;
27 return out;
28}
29
30fragment float4 paperFragment(Fragment in [[stage_in]],
31 bool front [[front_facing]],
32 constant Shading &shading [[buffer(0)]]) {
33 float facing = abs(dot(in.normal, shading.light.xyz));
34 float shade = 1 - (1 - shading.light.w) * (1 - facing);
35 float4 colour = front ? shading.front : shading.back;
36 return float4(colour.rgb * shade, colour.a);
37}
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift +23
@@ -117,3 +117,26 @@ import FoldKitTestSupport
117 #expect(structurallyEqual(nudged(by: 1e-13), file, tolerance: 1e-12)) 117 #expect(structurallyEqual(nudged(by: 1e-13), file, tolerance: 1e-12))
118 #expect(!structurallyEqual(nudged(by: 1e-9), file, tolerance: 1e-12)) 118 #expect(!structurallyEqual(nudged(by: 1e-9), file, tolerance: 1e-12))
119} 119}
120
121@Test func concurrentPopSolvesAgreeWithSerialOnes() async throws {
122 // one interpolator, so one factor, solved from eight tasks at once
123 let file = try compiled("reverse")
124 let step = try readSteps(file)[1]
125 let i = FoldInterpolator(file: file, step: step)
126 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
127 let times = (1..<64).map { lo + Double($0) / 64 * (hi - lo) }
128 let serial = times.map { i.meshPositions(at: $0) }
129 let mismatches = await withTaskGroup(of: Int.self) { group in
130 for _ in 0..<8 {
131 group.addTask {
132 var count = 0
133 for _ in 0..<20 {
134 for (t, expected) in zip(times, serial) where i.meshPositions(at: t) != expected { count += 1 }
135 }
136 return count
137 }
138 }
139 return await group.reduce(0, +)
140 }
141 #expect(mismatches == 0)
142}
Packages/FoldKit/Tests/FoldingTests/CameraTests.swift added +10
@@ -0,0 +1,10 @@
1import Testing
2import simd
3import Folding
4
5@Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() {
6 let c = Camera(eye: SIMD3(0, 0, 5), target: .zero, up: SIMD3(0, 1, 0), fieldOfView: .pi / 4)
7 let p = c.viewProjection(aspect: 1.5) * SIMD4(0, 0, 0, 1)
8 #expect(abs(p.x / p.w) < 1e-12 && abs(p.y / p.w) < 1e-12)
9 #expect(c.viewDirection == SIMD3(0, 0, -1))
10}
Packages/FoldKit/Tests/FoldingTests/LayerOrderTests.swift +10 −1
@@ -1,7 +1,7 @@
1import Testing 1import Testing
2import simd 2import simd
3import FoldFormat 3import FoldFormat
4import Folding 4@testable import Folding
5import FoldKitTestSupport 5import FoldKitTestSupport
6 6
7let up2 = [SIMD3<Double>(0, 0, 1), SIMD3(0, 0, 1)] 7let up2 = [SIMD3<Double>(0, 0, 1), SIMD3(0, 0, 1)]
@@ -87,6 +87,15 @@ let up3 = up2 + [SIMD3(0, 0, 1)]
87 #expect(c.map(\.faces) == [[1, 0]]) 87 #expect(c.map(\.faces) == [[1, 0]])
88} 88}
89 89
90@Test func aFaceOpeningOnTheSpineIsReadAgainstTheStillFace() throws {
91 // reverse step 2: f3 opens on the spine and closes again while f0 holds; both frames give [0, 3, 1]
92 let file = try compiled("reverse")
93 let step = try readSteps(file)[1]
94 #expect(!step.movingFaceUnion.contains(3))
95 let pairs = try LayerOrder.active(for: step, in: file).triples.map { [$0.f, $0.g] }
96 #expect(pairs.contains([3, 0]) && !pairs.contains([0, 3]))
97}
98
90@Test func cyclicOrderThrows() { 99@Test func cyclicOrderThrows() {
91 #expect(throws: LayerError.cyclic(cycle: [0, 1, 2])) { 100 #expect(throws: LayerError.cyclic(cycle: [0, 1, 2])) {
92 try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: up3) 101 try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: up3)
Packages/FoldKit/Tests/NotationTests/DiagramTests.swift added +109
@@ -0,0 +1,109 @@
1import Testing
2import FoldFormat
3import Folding
4import Models
5import Notation
6import FoldKitTestSupport
7
8@Test func valleyCreaseOfThisStepIsDashed() throws {
9 #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .dashed }.map(\.edge) == [6])
10}
11
12@Test func mountainCreaseOfThisStepIsDashDot() throws {
13 #expect(try diagram("mountain.fold", step: 1).edges.filter { $0.style == .dashDot }.map(\.edge) == [6])
14}
15
16@Test func valleyAndMountainAreAsSeenNotAsAssigned() throws {
17 // quarters step 3 folds both layers; the top layer is flipped, so its edge e9 is
18 // assigned M, but the fold is a valley as seen and nothing is dash-dot
19 let d = try diagram("quarters.fold", step: 3)
20 #expect(d.edges.contains { $0.style == .dashed })
21 #expect(!d.edges.contains { $0.style == .dashDot })
22 #expect(d.arrows.contains { if case .valleyFold = $0 { true } else { false } })
23}
24
25@Test func anEdgeUnderASeamIsHidden() throws {
26 // quarters step 3 draws frame 2: e8 lies under the seam between f3 and f2
27 #expect(try !diagram("quarters.fold", step: 3).edges.contains { $0.edge == 8 })
28 #expect(try diagram("quarters.fold", step: 3).edges.contains { $0.style == .dashed })
29}
30
31@Test func boundaryEdgesAreSolid() throws {
32 #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .solid }.count == 6)
33}
34
35@Test func aCreaseMadeEarlierAndFlatAgainIsLight() throws {
36 // quarters step 2 draws frame 1, after the fold-and-unfold on x = 1
37 #expect(Set(try diagram("quarters.fold", step: 2).edges.filter { $0.style == .light }.map(\.edge)) == [8, 9])
38}
39
40@Test func creasesNotYetMetAreNotDrawnAtAll() throws {
41 // frame 0 carries the y = 1 creases too; step 1's diagram must not show them
42 #expect(try diagram("quarters.fold", step: 1).edges.allSatisfy { ![10, 11].contains($0.edge) })
43 #expect(try diagram("quarters.fold", step: 1).edges.contains { $0.style == .dashed })
44}
45
46@Test func edgesOccludedByLayersAboveThemAreOmitted() throws {
47 // occlusion step 3 draws frame 2: f0's raw edge from (2,2) to (2,0) is under the strip
48 #expect(try !diagram("occlusion.fold", step: 3).edges.contains { $0.edge == 0 })
49 #expect(try diagram("occlusion.fold", step: 3).edges.contains { $0.style == .solid })
50}
51
52@Test func anEdgePartlyOccludedIsClippedNotDropped() throws {
53 // f0's raw edge from (0,2) to (2,2) is covered for x in [1, 2]
54 let segments = try visibleSegmentsOf("occlusion.fold", edge: 7, inFrame: 2)
55 #expect(segments.count == 1)
56 #expect(abs(segmentLength(segments[0]) - 1) < 1e-9)
57}
58
59@Test func aPlainMultiAxisStepGetsOneArrowPerAxis() throws {
60 let arrows = try diagram("letter.fold", step: 1).arrows
61 #expect(arrows.filter { if case .valleyFold = $0 { true } else { false } }.count == 1)
62 #expect(arrows.filter { if case .mountainFold = $0 { true } else { false } }.count == 1)
63}
64
65@Test func aTechniqueStepGetsItsOwnArrowsNotOnePerAxis() throws {
66 let arrows = try diagram("letter-technique.fold", step: 1).arrows
67 #expect(arrows.filter { if case .technique(.insideReverse, _, _) = $0 { true } else { false } }.count == 1)
68 #expect(!arrows.contains { if case .valleyFold = $0 { true } else if case .mountainFold = $0 { true } else { false } })
69}
70
71@Test func foldAndUnfoldStepGetsTheReturnHead() throws {
72 #expect(try diagram("quarters.fold", step: 1).arrows
73 .contains { if case .foldAndUnfold = $0 { true } else { false } })
74}
75
76@Test func turnOverStepCarriesTheTurnOverSymbol() throws {
77 #expect(try diagram("half.fold", step: 2).arrows.contains(.turnOver(.vertical)))
78}
79
80@Test func rotateStepCarriesItsDegrees() throws {
81 #expect(try diagram("half.fold", step: 3).arrows.contains(.rotate(degrees: 90)))
82}
83
84@Test func aRepeatedStepCarriesTheRepeatMark() throws {
85 #expect(try diagram("letter-sequential.fold", step: 2).arrows.contains(.repeatMark(of: 1)))
86}
87
88@Test func aRepeatedPushArrowCarriesTheRepeatStroke() {
89 let square = [SIMD2<Double>(0, 0), SIMD2(1, 0), SIMD2(1, 1), SIMD2(0, 1)]
90 let edges = square.indices.map { DiagramEdge(edge: $0, from: square[$0], to: square[($0 + 1) % 4], style: .solid) }
91 let push = DiagramArrow.technique(.insideReverse, at: SIMD2(0.5, 0.5), toward: SIMD2(1, 0.5))
92 let once = render(Diagram(edges: edges, arrows: [push]))
93 let repeated = render(Diagram(edges: edges, arrows: [push, .repeatMark(of: 1)]))
94 #expect(inkedPixels(repeated) > inkedPixels(once))
95}
96
97@Test func everyStepMatchesItsGoldenImage() throws {
98 for name in ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "letter-technique", "quarters",
99 "occlusion"] {
100 let file = try FoldFile(contentsOf: fixture("\(name).fold"))
101 for step in try readSteps(file) {
102 try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)")
103 }
104 }
105 let cup = try ModelLibrary.model(named: "cup")
106 for step in try readSteps(cup) {
107 try expectSnapshot(render(buildDiagram(file: cup, step: step)), named: "cup-\(step.index)")
108 }
109}
Packages/FoldKit/Tests/NotationTests/Snapshots/NOTATION.md added +36
@@ -0,0 +1,36 @@
1# Notation
2
3Symbols chosen by `buildDiagram` and drawn by `drawDiagram`, with their source. The reference is
4Randlett's conventions in *The Art of Origami* (1961) and the symbol set as summarised by
5OrigamiUSA; where they differ, OrigamiUSA's is used. Sizes are `DiagramStyle.standard`, in
6points.
7
8| Symbol | Drawn as | Source |
9|---|---|---|
10| Edge of the paper, folded edge | solid line, 2 | Randlett and OrigamiUSA agree |
11| Crease made earlier, flat again | thin grey line, 1, grey 0.6 | OrigamiUSA (existing crease) |
12| Valley fold | dashed line, 7 on 4 off | Randlett and OrigamiUSA agree |
13| Mountain fold | dash-dot-dot line, 9 on, dots of 2, gaps of 3 | OrigamiUSA; Randlett uses dash-dot |
14| Hidden edge or crease | not drawn | this project's choice, per the design document; Randlett and OrigamiUSA both define an x-ray (dotted) line, which is not used |
15| Valley-fold arrow | curved arrow, filled full head | OrigamiUSA (filled head) |
16| Mountain-fold arrow | curved arrow, hollow half head, barb on the outside of the arc | Randlett and OrigamiUSA agree |
17| Fold and unfold | curved arrow, fold head at the destination, hollow full head at the start pointing back | OrigamiUSA (double-headed form; the zig-zag form is not used) |
18| Inside and outside reverse fold, sink, squash | hollow push arrow with a notched tail, tip on the crease | OrigamiUSA (push) |
19| Petal fold | valley-fold arrow lifting the flap | OrigamiUSA |
20| Turn over | loop-the-loop arrow: left to right for a vertical axis, bottom to top for a horizontal one | Randlett and OrigamiUSA agree |
21| Rotate | two arcs around a circle with heads in the direction of turn, the amount in degrees at the centre | OrigamiUSA (amount written in the circle) |
22| Repeat | one stroke across the shaft of each fold arrow and push arrow near its tail | OrigamiUSA (strokes count repetitions) |
23
24Valley and mountain are as seen from the step's viewpoint, not FOLD's assignment.
25
26Arrow geometry: a fold arrow runs from the area-weighted centroid of the axis's moving set before
27the step to the same point after it (at the peak for a fold and unfold), its apex 0.3 of the chord
28from the chord's midpoint, toward screen-up or, for a vertical chord, screen-right. Arrows of a
29step with several axes start from points spread along their creases so that they do not meet. A
30technique's symbol sits at the midpoint of the step's first crease, pointing toward where that
31axis's moving set ends.
32
33`drawDiagram` fits the model and its arrows inside 48-point margins, 96 at the bottom, where the
34turn-over and rotate symbols sit. The golden images are 480 × 480, white. A render matches its
35golden image when no channel of any pixel differs by more than 24 of 255. Missing images are
36recorded by the test, which then fails; `FOLD_RECORD_SNAPSHOTS=1` records them all.
Packages/FoldKit/Tests/NotationTests/Snapshots/cup-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/cup-2.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/cup-3.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/cup-4.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/cup-5.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/cup-6.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/half-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/half-2.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/half-3.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/letter-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/letter-sequential-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/letter-sequential-2.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/letter-staggered-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/letter-technique-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/mountain-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/occlusion-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/occlusion-2.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/occlusion-3.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/quarters-1.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/quarters-2.png added

Binary file not shown.

Packages/FoldKit/Tests/NotationTests/Snapshots/quarters-3.png added

Binary file not shown.

Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift added +69
@@ -0,0 +1,69 @@
1import Metal
2import Testing
3import Folding
4import Renderer
5
6@Suite(.enabled(if: MTLCreateSystemDefaultDevice() != nil, "needs a Metal device"))
7struct PaperRendererTests {
8 @Test func coplanarStackedFacesDoNotZFight() throws {
9 let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [1, 0])],
10 camera: cameraAbove(), faceColours: [red, green])
11 #expect(uniqueColours(pixels) == [red])
12 }
13
14 @Test func clusterOrderDeterminesWhichCoplanarFaceIsVisible() throws {
15 let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [0, 1])],
16 camera: cameraAbove(), faceColours: [red, green])
17 #expect(uniqueColours(pixels) == [green])
18 }
19
20 @Test func nearlyCoplanarFacesDoNotZFight() throws {
21 // face 0 tilted 1° about its left edge, resting on face 1, in one cluster
22 let pixels = try renderToPixels(squareOverATiltedSquare(degrees: 1), clusters: [CoplanarCluster(faces: [1, 0])],
23 camera: cameraAbove(), faceColours: [red, green])
24 #expect(uniqueColours(pixels) == [red])
25 }
26
27 @Test func withinAClusterOrderWinsOverDepth() throws {
28 // face 0 crosses face 1 at 1°, half of it behind; ordered above it
29 let pixels = try renderToPixels(squareCrossingASquare(degrees: 1), clusters: [CoplanarCluster(faces: [1, 0])],
30 camera: cameraAbove(), faceColours: [red, green])
31 #expect(uniqueColours(pixels) == [red])
32 }
33
34 @Test func facesSeparatedInSpaceAreResolvedByDepthNotByOrder() throws {
35 // face 0 is nearer the camera but drawn first
36 let pixels = try renderToPixels(separatedSquares(),
37 clusters: [CoplanarCluster(faces: [0]), CoplanarCluster(faces: [1])],
38 camera: cameraAbove(), faceColours: [red, green])
39 #expect(dominantColour(pixels) == red)
40 }
41
42 @Test func aStackDrawnFirstStillHidesAFaceBehindItDrawnLater() throws {
43 // faces 0 and 1 stacked near the camera, face 2 farther away and drawn last
44 let pixels = try renderToPixels(nearStackAndFarSquare(),
45 clusters: [CoplanarCluster(faces: [1, 0]), CoplanarCluster(faces: [2])],
46 camera: cameraAbove(), faceColours: [red, green, blue])
47 #expect(dominantColour(pixels) == red)
48 }
49
50 @Test func orbitingUnderneathShowsTheBottomOfTheStack() throws {
51 // clusters computed by Task 5 for each camera, as the app does
52 let above = try renderStackWithComputedClusters(camera: cameraAbove(), faceColours: [red, green])
53 let below = try renderStackWithComputedClusters(camera: cameraBelow(), faceColours: [red, green])
54 #expect(uniqueColours(above) == [red])
55 #expect(uniqueColours(below) == [green])
56 }
57
58 @Test func backOfPaperRendersInTheBackColour() throws {
59 let pixels = try renderToPixels(singleSquareFacingAway(), clusters: [CoplanarCluster(faces: [0])],
60 camera: cameraAbove())
61 #expect(uniqueColours(pixels) == [backColour])
62 }
63
64 @Test func frontOfPaperRendersInTheFrontColour() throws {
65 let pixels = try renderToPixels(singleSquareFacingTheCamera(), clusters: [CoplanarCluster(faces: [0])],
66 camera: cameraAbove())
67 #expect(uniqueColours(pixels) == [frontColour])
68 }
69}
Packages/FoldKit/Tests/RendererTests/Scenes.swift added +144
@@ -0,0 +1,144 @@
1import Metal
2import Testing
3import simd
4import FoldFormat
5import Folding
6import Renderer
7
8let red = SIMD4<Float>(1, 0, 0, 1)
9let green = SIMD4<Float>(0, 1, 0, 1)
10let blue = SIMD4<Float>(0, 0, 1, 1)
11let frontColour = PaperRenderer.frontColour
12let backColour = PaperRenderer.backColour
13
14/// Faces placed in space, with the render mesh of a frame 0 that lays the same faces apart in its
15/// plane, so that no mesh vertex is shared between faces.
16struct Scene {
17 let positions: [SIMD3<Double>]
18 let faces: [[Int]]
19 let normals: [SIMD3<Double>]
20 let mesh: RenderMesh
21
22 /// Unit squares, each given by where its corners (0, 0), (1, 0), (1, 1) and (0, 1) are.
23 init(squares: [[SIMD3<Double>]]) {
24 positions = squares.flatMap { $0 }
25 faces = squares.indices.map { i in (0..<4).map { 4 * i + $0 } }
26 normals = faceNormals(positions: positions, faces: faces)
27 // square i at x = 2i in frame 0; a spacing wider than the sheet leaves each square two triangles
28 let flat = squares.indices.flatMap { i -> [SIMD3<Double>] in
29 let x = 2 * Double(i)
30 return [SIMD3(x, 0, 0), SIMD3(x + 1, 0, 0), SIMD3(x + 1, 1, 0), SIMD3(x, 1, 0)]
31 }
32 let file = FoldFile(fileSpec: 1.2, fileAuthor: "Traditional", edgesVertices: [], facesVertices: faces,
33 edgesFirstCreasedAtStep: [],
34 frames: [FoldFrame(verticesCoords: flat, edgesAssignment: [], edgesFoldAngle: [],
35 faceOrders: [])])
36 mesh = RenderMesh(file: file, spacing: 2 * Double(squares.count))
37 precondition(mesh.vertices.count == positions.count)
38 }
39
40 var meshPositions: [SIMD3<Double>] {
41 var result = positions
42 for (v, m) in mesh.meshVertexOf.enumerated() { result[m] = positions[v] }
43 return result
44 }
45}
46
47private func unitSquare(z: Double) -> [SIMD3<Double>] {
48 [SIMD3(0, 0, z), SIMD3(1, 0, z), SIMD3(1, 1, z), SIMD3(0, 1, z)]
49}
50
51/// Two coincident unit squares facing +z; with `[[0, 1, 1]]` face 0 is above face 1.
52func stackedCoplanarSquares() -> Scene { Scene(squares: [unitSquare(z: 0), unitSquare(z: 0)]) }
53
54/// Face 0 turned `degrees` up about its left edge, x = 0, off face 1 at z = 0.
55func squareOverATiltedSquare(degrees: Double) -> Scene {
56 let c = cos(degrees * .pi / 180), s = sin(degrees * .pi / 180)
57 return Scene(squares: [[SIMD3(0, 0, 0), SIMD3(c, 0, s), SIMD3(c, 1, s), SIMD3(0, 1, 0)], unitSquare(z: 0)])
58}
59
60/// Face 0 at z = 1, face 1 at z = 0.
61func separatedSquares() -> Scene { Scene(squares: [unitSquare(z: 1), unitSquare(z: 0)]) }
62
63/// Faces 0 and 1 at z = 1, face 2 at z = 0.
64func nearStackAndFarSquare() -> Scene {
65 Scene(squares: [unitSquare(z: 1), unitSquare(z: 1), unitSquare(z: 0)])
66}
67
68/// A unit square at z = 0 facing +z.
69func singleSquareFacingTheCamera() -> Scene { Scene(squares: [unitSquare(z: 0)]) }
70
71/// A unit square at z = 0 turned over about x = 0.5, so it faces −z.
72func singleSquareFacingAway() -> Scene {
73 Scene(squares: [[SIMD3(1, 0, 0), SIMD3(0, 0, 0), SIMD3(0, 1, 0), SIMD3(1, 1, 0)]])
74}
75
76func cameraAbove() -> Camera {
77 Camera(eye: SIMD3(0.5, 0.5, 4), target: SIMD3(0.5, 0.5, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4)
78}
79
80func cameraBelow() -> Camera {
81 Camera(eye: SIMD3(0.5, 0.5, -4), target: SIMD3(0.5, 0.5, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4)
82}
83
84/// Width and height of the offscreen target, in pixels.
85private let size = 64
86
87/// `scene` rendered into a `size` × `size` `rgba32Float` texture, row by row from the top. Without
88/// `clusters`, they are computed with no layer order.
89func renderToPixels(_ scene: Scene, clusters: [CoplanarCluster]? = nil, camera: Camera,
90 faceColours: [SIMD4<Float>]? = nil) throws -> [SIMD4<Float>] {
91 let device = try #require(MTLCreateSystemDefaultDevice())
92 let renderer = try PaperRenderer(device: device)
93 let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba32Float, width: size, height: size,
94 mipmapped: false)
95 descriptor.usage = .renderTarget
96 descriptor.storageMode = .private
97 let texture = try #require(device.makeTexture(descriptor: descriptor))
98 let clusters = try clusters ?? LayerOrder(faceOrders: [], normals: scene.normals)
99 .clusters(positions: scene.positions, faces: scene.faces, viewDirection: camera.viewDirection)
100 try renderer.render(positions: scene.meshPositions, mesh: scene.mesh, clusters: clusters, camera: camera,
101 faceColours: faceColours, into: texture)
102
103 let rowBytes = size * MemoryLayout<SIMD4<Float>>.stride
104 let buffer = try #require(device.makeBuffer(length: rowBytes * size, options: .storageModeShared))
105 let commands = try #require(renderer.commandQueue.makeCommandBuffer())
106 let blit = try #require(commands.makeBlitCommandEncoder())
107 blit.copy(from: texture, sourceSlice: 0, sourceLevel: 0, sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0),
108 sourceSize: MTLSize(width: size, height: size, depth: 1), to: buffer, destinationOffset: 0,
109 destinationBytesPerRow: rowBytes, destinationBytesPerImage: rowBytes * size)
110 blit.endEncoding()
111 commands.commit()
112 commands.waitUntilCompleted()
113 return Array(UnsafeBufferPointer(start: buffer.contents().assumingMemoryBound(to: SIMD4<Float>.self),
114 count: size * size))
115}
116
117/// `stackedCoplanarSquares()` with face 0 above face 1, clustered by `LayerOrder` for `camera`.
118func renderStackWithComputedClusters(camera: Camera, faceColours: [SIMD4<Float>]) throws -> [SIMD4<Float>] {
119 let scene = stackedCoplanarSquares()
120 let clusters = try LayerOrder(faceOrders: [[0, 1, 1]], normals: scene.normals)
121 .clusters(positions: scene.positions, faces: scene.faces, viewDirection: camera.viewDirection)
122 return try renderToPixels(scene, clusters: clusters, camera: camera, faceColours: faceColours)
123}
124
125/// The colours other than the background, in the order they first appear.
126func uniqueColours(_ pixels: [SIMD4<Float>]) -> [SIMD4<Float>] {
127 var seen = Set<SIMD4<Float>>()
128 return pixels.filter { $0 != PaperRenderer.background && seen.insert($0).inserted }
129}
130
131/// The most frequent colour other than the background.
132func dominantColour(_ pixels: [SIMD4<Float>]) -> SIMD4<Float>? {
133 var counts: [SIMD4<Float>: Int] = [:]
134 for p in pixels where p != PaperRenderer.background { counts[p, default: 0] += 1 }
135 return counts.max { $0.value < $1.value }?.key
136}
137
138/// Face 0 turned `degrees` about the line x = 0.5 through face 1 at z = 0, its right half above
139/// face 1 and its left half below.
140func squareCrossingASquare(degrees: Double) -> Scene {
141 let c = 0.5 * cos(degrees * .pi / 180), s = 0.5 * sin(degrees * .pi / 180)
142 return Scene(squares: [[SIMD3(0.5 - c, 0, -s), SIMD3(0.5 + c, 0, s), SIMD3(0.5 + c, 1, s), SIMD3(0.5 - c, 1, -s)],
143 unitSquare(z: 0)])
144}
docs/superpowers/plans/2026-10-19-fold.md +8 −4
@@ -1581,7 +1581,7 @@ Expected: FAIL.
1581 1581
1582- [ ] **Step 3: Implement the types, `buildDiagram` and `visibleSegments`** 1582- [ ] **Step 3: Implement the types, `buildDiagram` and `visibleSegments`**
1583 1583
1584Project through the viewpoint's orthographic matrix. Classify each edge as above. Clip each edge against the **union** of the projected faces `order` places above either of the edge's incident faces, and emit the surviving segments, drawing coincident segments once. Clipping against each face separately would keep an edge lying under the seam between two adjacent upper faces — e8 in quarters frame 2 lies on the boundary of f3 and of f2 but inside their union. An edge on the outer boundary of that union is not hidden. Subdivision edges are never drawn. Golden images are generated once, inspected by eye against the reference, then committed. 1584Project through the viewpoint's orthographic matrix. Classify each edge as above. Clip each edge against the **union** of the projected faces `order` places above either of the edge's incident faces, and emit the surviving segments, drawing coincident segments once. Clipping against each face separately would keep an edge lying under the seam between two adjacent upper faces — e8 in quarters frame 2 lies on the boundary of f3 and of f2 but inside their union. An edge on the outer boundary of that union is not hidden. Subdivision edges are never drawn. A face hides an edge when it follows either of the edge's faces in their shared cluster, from `LayerOrder.clusters` looking along −`eye`; faces in other clusters do not occlude, which holds while every diagram frame is flat. Golden images are recorded when missing or with `FOLD_RECORD_SNAPSHOTS=1` (the test fails when it records), compared at 24/255 per channel, inspected by eye against the reference, then committed. The drawing itself is Notation's, so the app's diagram and the goldens are one drawing.
1585 1585
1586- [ ] **Step 4: Run tests to verify they pass** 1586- [ ] **Step 4: Run tests to verify they pass**
1587 1587
@@ -1623,9 +1623,9 @@ Depth handling is **hybrid**. `faceOrders` is defined only for faces that overla
1623 1623
1624Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3. 1624Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3.
1625 1625
1626During a non-rigid step the faces that open on the spine move, but `FoldStep.movingFaceUnion` holds only the main axes' faces (the pop's held faces depend on that). `LayerOrder.active`'s rewrite of mixed moving/still pairs must use the set `layerMotionDefects` uses — the main, open and close axes' faces — made a named `FoldStep` property here rather than a second copy. The pop's `SparseCholesky` factor is `@unchecked Sendable`; confirm concurrent solves on one factor are safe, or serialise them, before the renderer calls the interpolator from more than one thread. 1626During a non-rigid step the faces that open on the spine move, but `FoldStep.movingFaceUnion` holds only the main axes' faces (the pop's held faces depend on that). `LayerOrder.active`'s rewrite of mixed moving/still pairs must use the set `layerMotionDefects` uses — the main, open and close axes' faces — made a named `FoldStep` property here (`allMovingFaces`) rather than a second copy. The pop's `SparseCholesky` factor is `@unchecked Sendable`; confirm concurrent solves on one factor are safe, or serialise them, before the renderer calls the interpolator from more than one thread.
1627 1627
1628SwiftPM compiles `Shaders.metal` with the Metal toolchain; see *Setup* step 4. 1628`Shaders.metal` is a copied resource compiled at `PaperRenderer.init` with `makeLibrary(source:options:)`: SwiftPM can compile it with the Metal toolchain (*Setup* step 4), but then warns on every build.
1629 1629
1630- [ ] **Step 1: Write the failing tests** 1630- [ ] **Step 1: Write the failing tests**
1631 1631
@@ -1736,6 +1736,8 @@ git commit -m "Metal paper renderer with hybrid depth and cluster ordering"
1736 1736
1737`project.yml` mirrors `krz/moonrise/App/project.yml`. The `.xcodeproj` is generated and ignored by git, as in moonrise: `xcodegen generate --spec App/project.yml`. On iPad the diagram and the model sit side by side; on iPhone they swap. The diagram's caption is the step's `instruction`. 1737`project.yml` mirrors `krz/moonrise/App/project.yml`. The `.xcodeproj` is generated and ignored by git, as in moonrise: `xcodegen generate --spec App/project.yml`. On iPad the diagram and the model sit side by side; on iPhone they swap. The diagram's caption is the step's `instruction`.
1738 1738
1739`DiagramCanvas` draws through Notation's public CoreGraphics drawing function (via `GraphicsContext.withCGContext`), the same one Task 9's golden images are rendered with, so the snapshots hold the diagram the user sees; it adds no glyph geometry of its own. `PaperView` computes cluster membership once per *t* and re-sorts only when the camera moves; `LayerOrder.clusters` computes both together, so add the split there if profiling on device shows the per-frame cost matters. Reuse the vertex buffer between frames, and give the depth texture `.memoryless` storage on iOS.
1740
1739- [ ] **Step 1: Write the failing UI tests** 1741- [ ] **Step 1: Write the failing UI tests**
1740 1742
1741```swift 1743```swift
@@ -1986,6 +1988,8 @@ git commit -m "Drag gesture for turn-over and rotate steps"
1986- Produces: 1988- Produces:
1987 - `struct OrbitGesture` — two-finger drag to `Camera` orbit, pinch to field of view 1989 - `struct OrbitGesture` — two-finger drag to `Camera` orbit, pinch to field of view
1988 1990
1991`Camera.viewProjection` builds its basis from `cross(viewDirection, up)`, which is undefined when `up` is parallel to the view direction; `OrbitGesture` keeps `up` perpendicular to the view direction as it orbits, including past the poles.
1992
1989A folding model cannot be described by a static label, so the paper view's accessibility label is the step's authored `instruction`. `AppStore/rights-basis.md` records that every shipped model is traditional and why that matters. 1993A folding model cannot be described by a static label, so the paper view's accessibility label is the step's authored `instruction`. `AppStore/rights-basis.md` records that every shipped model is traditional and why that matters.
1990 1994
1991- [ ] **Step 1: Write the failing tests** 1995- [ ] **Step 1: Write the failing tests**
@@ -2073,7 +2077,7 @@ git commit -m "Orbit and zoom, accessibility pass and release assets"
2073 2077
2074Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Published sampan sequences differ in their middle steps; `docs/authoring/sampan.md` records which sequence was authored and its source. 2078Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Published sampan sequences differ in their middle steps; `docs/authoring/sampan.md` records which sequence was authored and its source.
2075 2079
2076Carried from batch D, to settle before or while authoring these models: a crease on a named crease's line through another layer with a scripted angle other than ±180 is rejected (the masu's 90° walls need its angle derived instead); `curveTooCoarse` is reported where an unreachable scripted angle is the real cause; the cycle computation has no test for several loops sharing axes (the petal fold); `compilePop` does not assert that held faces sit identically in the open pose and `popped`; a flap whose two layers also join through the body (the crane's neck and tail) fails with `noRigidMotion`, because the opening faces are found by cutting only the spine — rule on "that side of the spine" then; `structurallyEqual` must tolerate solver noise in `pop`. 2080Carried from batch D, to settle before or while authoring these models: a crease on a named crease's line through another layer with a scripted angle other than ±180 is rejected (the masu's 90° walls need its angle derived instead); `curveTooCoarse` is reported where an unreachable scripted angle is the real cause; the cycle computation has no test for several loops sharing axes (the petal fold); `compilePop` does not assert that held faces sit identically in the open pose and `popped`; a flap whose two layers also join through the body (the crane's neck and tail) fails with `noRigidMotion`, because the opening faces are found by cutting only the spine — rule on "that side of the spine" then; `structurallyEqual` must tolerate solver noise in `pop`. From batch E: Notation styles an edge between faces of two sibling axes, or between a carried axis's face and a fixed face, by one axis's turn — check the petal fold's golden for segments of one crease drawn in different styles; a step that unfolds a crease folded in frame n − 1 is drawn as a fold, with no unfold notation — decide it when the crane's petal fold and the sampan need it; occlusion's `cover` assumes faces are not edge-on in the view, which the masu's raised walls may break (R35's revisit).
2077 2081
2078The crane is deliberately last. It is the model that proves multi-axis petal folds and eight-deep wing stacks work, and by this point the compiler, the renderer and the gestures are all known-good against the cup, so a failure here is an authoring error rather than an ambiguity about which layer is at fault. 2082The crane is deliberately last. It is the model that proves multi-axis petal folds and eight-deep wing stacks work, and by this point the compiler, the renderer and the gestures are all known-good against the cup, so a failure here is an authoring error rather than an ambiguity about which layer is at fault.
2079 2083