Commit e03e518464

e03e518464a85ec56eafa171668b9838ddfcd47b

parent: a3d5346d2c

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 20:43 UTC

Delaunay render mesh

Ref #7

Layout: unified · split

Packages/FoldKit/Sources/Folding/RenderMesh.swift +161 −80
@@ -1,10 +1,12 @@
11import FoldFormat
22import simd
33
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.
4/// The triangles the renderer draws, finer than the FOLD faces (decision 0003). Each side of each
5/// frame 0 face is divided into round(length / `spacing`) equal parts; inside each face, points of
6/// a triangular lattice `spacing` apart are kept at least 0.6 `spacing` from its sides; each face
7/// is triangulated on those points by ear clipping, point insertion and Lawson flips, so it is
8/// Delaunay within the face. Faces sharing a side share its points, so the mesh is one connected
9/// sheet. The FOLD topology is unchanged; a non-rigid step bends this mesh, not the FOLD faces.
810public struct RenderMesh: Sendable {
911 /// Frame 0 positions in its plane.
1012 public let vertices: [SIMD2<Double>]
@@ -27,51 +29,66 @@ public struct RenderMesh: Sendable {
2729 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
2830 let lower = flat.dropFirst().reduce(flat[0], simd_min)
2931 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)
32 let tolerance = (upper - lower).max() * 1e-9
33 let rowSpacing = spacing * 3.0.squareRoot() / 2
3434
3535 var points = PointSet(tolerance: tolerance)
36 let meshVertexOf = flat.map { points.index(of: $0) }
37 // each side's points from its lower-numbered end, so both faces compute the same ones
38 var sides: [SIMD2<Int>: [Int]] = [:]
39 func side(_ a: Int, _ b: Int) -> [Int] {
40 let key = SIMD2(min(a, b), max(a, b))
41 if sides[key] == nil {
42 let p = flat[key.x], q = flat[key.y]
43 let parts = max(1, Int((simd_distance(p, q) / spacing).rounded()))
44 sides[key] = [meshVertexOf[key.x]]
45 + (1..<parts).map { points.index(of: p + Double($0) / Double(parts) * (q - p)) }
46 + [meshVertexOf[key.y]]
47 }
48 return a == key.x ? sides[key]! : sides[key]!.reversed()
49 }
50
3651 var triangles: [(Int, Int, Int)] = []
3752 var faceOf: [Int] = []
3853 var anchors: [Int: Anchor] = [:]
3954 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 func point(_ p: SIMD2<Double>) -> Int {
48 let id = points.index(of: p)
49 if anchors[id] == nil {
50 let w = points.points[id] - origin
51 anchors[id] = Anchor(corners: SIMD3(face[corners[0]], face[corners[1]], face[corners[2]]),
52 a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det)
55 let outline = face.map { flat[$0] }
56 let corners = signedArea(outline) < 0 ? face.reversed() : face
57 let polygon = corners.map { flat[$0] }
58 var boundary: [Int] = []
59 for k in corners.indices { boundary += side(corners[k], corners[(k + 1) % corners.count]).dropLast() }
60
61 var inside: [Int] = []
62 let low = polygon.dropFirst().reduce(polygon[0], simd_min)
63 let high = polygon.dropFirst().reduce(polygon[0], simd_max)
64 var row = Int(((low.y - lower.y) / rowSpacing).rounded(.down))
65 while lower.y + Double(row) * rowSpacing <= high.y {
66 let y = lower.y + Double(row) * rowSpacing
67 let shift = row.isMultiple(of: 2) ? 0 : 0.5
68 var column = Int(((low.x - lower.x) / spacing - shift).rounded(.down))
69 while lower.x + (Double(column) + shift) * spacing <= high.x {
70 let p = SIMD2(lower.x + (Double(column) + shift) * spacing, y)
71 if distanceInside(polygon, p) >= 0.6 * spacing { inside.append(points.index(of: p)) }
72 column += 1
5373 }
54 return id
74 row += 1
5575 }
56 for cell in cells {
57 var ids: [Int] = []
58 for p in cell {
59 let id = point(p)
60 if ids.last != id && ids.first != id { ids.append(id) }
61 }
62 guard ids.count >= 3 else { continue }
63 var fanned = fan(ids, points.points, minimumArea: tolerance * size)
64 if fanned == nil {
65 let centre = ids.reduce(SIMD2<Double>.zero) { $0 + points.points[$1] } / Double(ids.count)
66 fanned = fan(ids, around: point(centre))
67 }
68 for triangle in fanned! {
69 triangles.append(triangle)
70 faceOf.append(f)
71 }
76
77 for triangle in triangulate(boundary: boundary, inside: inside, points.points) {
78 triangles.append(triangle)
79 faceOf.append(f)
80 }
81 let widest = widestCorners(outline)
82 let origin = outline[widest[0]]
83 let u = outline[widest[1]] - origin, v = outline[widest[2]] - origin
84 let det = u.x * v.y - u.y * v.x
85 for id in boundary + inside where anchors[id] == nil {
86 let w = points.points[id] - origin
87 anchors[id] = Anchor(corners: SIMD3(face[widest[0]], face[widest[1]], face[widest[2]]),
88 a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det)
7289 }
7390 }
74 meshVertexOf = flat.map { points.index(of: $0) }
91 self.meshVertexOf = meshVertexOf
7592 vertices = points.points
7693 self.triangles = triangles
7794 self.faceOf = faceOf
@@ -107,56 +124,120 @@ public func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double {
107124 return worst
108125}
109126
110/// The grid lines strictly inside `low...high`: `low + k·spacing` for k ≥ 1.
111private func lines(from low: Double, to high: Double, spacing: Double, tolerance: Double) -> [Double] {
112 var result: [Double] = []
113 var k = 1.0
114 while low + k * spacing < high - tolerance {
115 result.append(low + k * spacing)
116 k += 1
127/// Twice the signed area of a polygon, positive when its corners run counterclockwise.
128private func signedArea(_ polygon: [SIMD2<Double>]) -> Double {
129 polygon.indices.reduce(0) { sum, k in
130 let p = polygon[k], q = polygon[(k + 1) % polygon.count]
131 return sum + p.x * q.y - p.y * q.x
117132 }
118 return result
119133}
120134
121/// A convex polygon cut by the line where coordinate `axis` equals `value`, or the polygon itself
122/// when the line does not cross it. Crossing points lie exactly on the line.
123private func split(_ polygon: [SIMD2<Double>], at value: Double, axis: Int, tolerance: Double) -> [[SIMD2<Double>]] {
124 let d = polygon.map { $0[axis] - value }
125 guard d.contains(where: { $0 < -tolerance }), d.contains(where: { $0 > tolerance }) else { return [polygon] }
126 var below: [SIMD2<Double>] = [], above: [SIMD2<Double>] = []
127 for i in polygon.indices {
128 let j = (i + 1) % polygon.count
129 if d[i] <= tolerance { below.append(polygon[i]) }
130 if d[i] >= -tolerance { above.append(polygon[i]) }
131 if (d[i] < -tolerance && d[j] > tolerance) || (d[i] > tolerance && d[j] < -tolerance) {
132 var crossing = polygon[i] + (polygon[j] - polygon[i]) * (d[i] / (d[i] - d[j]))
133 crossing[axis] = value
134 below.append(crossing)
135 above.append(crossing)
135private func cross(_ u: SIMD2<Double>, _ v: SIMD2<Double>) -> Double { u.x * v.y - u.y * v.x }
136
137/// The distance from `p` to the nearest side of a convex counterclockwise polygon, negative outside.
138private func distanceInside(_ polygon: [SIMD2<Double>], _ p: SIMD2<Double>) -> Double {
139 polygon.indices.map { k in
140 let a = polygon[k], b = polygon[(k + 1) % polygon.count]
141 return cross(b - a, p - a) / simd_distance(a, b)
142 }.min() ?? 0
143}
144
145/// A Delaunay triangulation of a convex polygon whose `boundary` points run counterclockwise
146/// (straight runs allowed), with `inside` points strictly inside, keeping the boundary's edges.
147/// Ear clipping on the boundary, each time the largest ear with no other boundary point on or in
148/// it; then each inside point inserted into the triangle holding it, splitting an edge it lies
149/// on; then Lawson flips of every edge off the boundary until each is locally Delaunay.
150/// Triangles are counterclockwise.
151private func triangulate(boundary: [Int], inside: [Int], _ p: [SIMD2<Double>]) -> [(Int, Int, Int)] {
152 func area(_ a: Int, _ b: Int, _ c: Int) -> Double { cross(p[b] - p[a], p[c] - p[a]) / 2 }
153 let scale = boundary.map { simd_length_squared(p[$0] - p[boundary[0]]) }.max() ?? 1
154 var triangles: [SIMD3<Int>] = []
155
156 var ring = boundary
157 while ring.count > 3 {
158 var best = -1, bestArea = 0.0
159 for k in ring.indices {
160 let i = ring[(k + ring.count - 1) % ring.count], j = ring[k], l = ring[(k + 1) % ring.count]
161 let a = area(i, j, l)
162 guard a > bestArea else { continue }
163 let blocked = ring.contains { m in
164 m != i && m != j && m != l && area(i, j, m) >= -1e-12 * scale && area(j, l, m) >= -1e-12 * scale
165 && area(l, i, m) >= -1e-12 * scale
166 }
167 if !blocked { (best, bestArea) = (k, a) }
136168 }
169 if best < 0 || bestArea < 1e-14 * scale { break }
170 triangles.append(SIMD3(ring[(best + ring.count - 1) % ring.count], ring[best], ring[(best + 1) % ring.count]))
171 ring.remove(at: best)
137172 }
138 return [below, above]
139}
173 if ring.count == 3, area(ring[0], ring[1], ring[2]) > 0 { triangles.append(SIMD3(ring[0], ring[1], ring[2])) }
140174
141/// A convex cell, its corners counterclockwise, fanned from the first corner whose fan has no
142/// triangle of `minimumArea` or less; nil when every corner's fan does. A corner on a straight
143/// side would otherwise be left out of every triangle.
144private func fan(_ ids: [Int], _ points: [SIMD2<Double>], minimumArea: Double) -> [(Int, Int, Int)]? {
145 for apex in ids.indices {
146 let ring = (0..<ids.count).map { ids[(apex + $0) % ids.count] }
147 let triangles = (1..<(ring.count - 1)).map { (ring[0], ring[$0], ring[$0 + 1]) }
148 let flat = triangles.contains { a, b, c in
149 let (p, q, r) = (points[a], points[b], points[c])
150 return ((q - p).x * (r - p).y - (q - p).y * (r - p).x) / 2 <= minimumArea
175 for v in inside {
176 // the newest triangles first: consecutive points of a lattice row lie close together
177 for k in triangles.indices.reversed() {
178 let t = triangles[k]
179 let total = area(t.x, t.y, t.z)
180 let w = [area(v, t.y, t.z), area(t.x, v, t.z), area(t.x, t.y, v)]
181 guard w.allSatisfy({ $0 >= -1e-12 * total }) else { continue }
182 if let zero = w.firstIndex(where: { abs($0) <= 1e-9 * total }) {
183 // on the edge opposite corner `zero`: split both triangles beside it
184 let c = [t.x, t.y, t.z]
185 let a = c[(zero + 1) % 3], b = c[(zero + 2) % 3]
186 triangles[k] = SIMD3(c[zero], a, v)
187 triangles.append(SIMD3(c[zero], v, b))
188 if let n = triangles.indices.first(where: { n in
189 let u = triangles[n]
190 return n != k && [u.x, u.y, u.z].contains(a) && [u.x, u.y, u.z].contains(b)
191 }) {
192 let u = triangles[n]
193 let other = [u.x, u.y, u.z].first { $0 != a && $0 != b }!
194 triangles[n] = SIMD3(other, b, v)
195 triangles.append(SIMD3(other, v, a))
196 }
197 } else {
198 triangles[k] = SIMD3(t.x, t.y, v)
199 triangles.append(SIMD3(t.y, t.z, v))
200 triangles.append(SIMD3(t.z, t.x, v))
201 }
202 break
151203 }
152 if !flat { return triangles }
153204 }
154 return nil
155}
156205
157/// A convex cell fanned around an added point `centre` inside it.
158private func fan(_ ids: [Int], around centre: Int) -> [(Int, Int, Int)] {
159 ids.indices.map { (centre, ids[$0], ids[($0 + 1) % ids.count]) }
206 let kept = Set(boundary.indices.map { k in
207 SIMD2(min(boundary[k], boundary[(k + 1) % boundary.count]), max(boundary[k], boundary[(k + 1) % boundary.count]))
208 })
209 // whether d lies strictly inside the circle through the counterclockwise a, b, c
210 func inCircle(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool {
211 let pa = p[a] - p[d], pb = p[b] - p[d], pc = p[c] - p[d]
212 let det = simd_length_squared(pa) * cross(pb, pc) - simd_length_squared(pb) * cross(pa, pc)
213 + simd_length_squared(pc) * cross(pa, pb)
214 return det > 1e-15 * scale * scale
215 }
216 func key(_ a: Int, _ b: Int) -> SIMD2<Int> { SIMD2(min(a, b), max(a, b)) }
217 func corners(_ k: Int) -> [Int] { [triangles[k].x, triangles[k].y, triangles[k].z] }
218 var sides: [SIMD2<Int>: [Int]] = [:]
219 for k in triangles.indices {
220 let c = corners(k)
221 for i in 0..<3 { sides[key(c[i], c[(i + 1) % 3]), default: []].append(k) }
222 }
223 var pending = sides.keys.filter { !kept.contains($0) }.sorted { ($0.x, $0.y) > ($1.x, $1.y) }
224 while let edge = pending.popLast() {
225 guard let pair = sides[edge], pair.count == 2 else { continue }
226 let (k1, k2) = (pair[0], pair[1])
227 let first = corners(k1)
228 let i = first.firstIndex { $0 != edge.x && $0 != edge.y }!
229 let (c1, a, b) = (first[i], first[(i + 1) % 3], first[(i + 2) % 3])
230 let c2 = corners(k2).first { $0 != edge.x && $0 != edge.y }!
231 guard inCircle(c1, a, b, c2), area(c1, a, c2) > 0, area(c2, b, c1) > 0 else { continue }
232 triangles[k1] = SIMD3(c1, a, c2)
233 triangles[k2] = SIMD3(c2, b, c1)
234 sides[edge] = nil
235 sides[key(c1, c2)] = [k1, k2]
236 sides[key(a, c2)] = sides[key(a, c2)]!.map { $0 == k2 ? k1 : $0 }
237 sides[key(b, c1)] = sides[key(b, c1)]!.map { $0 == k1 ? k2 : $0 }
238 pending += [key(c1, a), key(a, c2), key(c2, b), key(b, c1)].filter { !kept.contains($0) }
239 }
240 return triangles.map { ($0.x, $0.y, $0.z) }
160241}
161242
162243/// The indices of the three corners spanning the largest triangle, the first such in index order.
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift −12
@@ -81,18 +81,6 @@ import FoldKitTestSupport
8181 #expect(elapsed / 100 < .milliseconds(4))
8282}
8383
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}
95
9684@Test func theReverseFoldMovesThroughNoStillFace() throws {
9785 // the open phase departs from frame 1 and the close phase arrives at frame 2
9886 #expect(layerMotionDefects(try compiled("reverse")).isEmpty)
Packages/FoldKit/Tests/FoldingTests/RenderMeshTests.swift +89
@@ -3,6 +3,7 @@ import Testing
33import simd
44import FoldFormat
55import Folding
6import FoldKitTestSupport
67
78/// A flat 2 × 1 sheet with `points` as its vertices and `faces` as its faces; edges are not read
89/// by the mesh and are left empty.
@@ -65,3 +66,91 @@ func aStraightCornerIsInItsFacesTriangles(_ spacing: Double) {
6566 #expect(everyFaceUsesItsVertices(file, i.mesh))
6667 #expect(zip(i.positions(at: 0.5), start).allSatisfy { simd_distance($0, $1) < 1e-9 })
6768}
69
70/// A unit square cut by one crease between irrational heights on its left and right sides; no two
71/// creases or sides meet at less than 80°.
72private func offGrid() -> FoldFile {
73 let a = 1 / 7.0.squareRoot(), b = 1 - 1 / 5.0.squareRoot()
74 return sheet([SIMD2(0, 0), SIMD2(1, 0), SIMD2(1, b), SIMD2(1, 1), SIMD2(0, 1), SIMD2(0, a)],
75 [[0, 1, 2, 5], [5, 2, 3, 4]])
76}
77
78/// The mesh's edges, each once, as pairs of mesh vertices.
79private func edges(_ mesh: RenderMesh) -> [SIMD2<Int>] {
80 var set = Set<SIMD2<Int>>()
81 for (a, b, c) in mesh.triangles {
82 for (i, j) in [(a, b), (b, c), (c, a)] { set.insert(SIMD2(min(i, j), max(i, j))) }
83 }
84 return set.sorted { ($0.x, $0.y) < ($1.x, $1.y) }
85}
86
87private func meshTestFiles() throws -> [FoldFile] {
88 [try FoldFile(contentsOf: fixture("reverse-cp.fold")), try FoldFile(contentsOf: fixture("preliminary-cp.fold")),
89 offGrid()]
90}
91
92@Test func noMeshEdgeIsMuchShorterThanTheSpacing() throws {
93 // decision 0003: 0.15 of the spacing, except where a crease is shorter or creases meet sharply,
94 // which none of these sheets has
95 for file in try meshTestFiles() {
96 let spacing = RenderMesh.spacing(for: file)
97 let mesh = RenderMesh(file: file, spacing: spacing)
98 let shortest = edges(mesh).map { simd_distance(mesh.vertices[$0.x], mesh.vertices[$0.y]) }.min()!
99 #expect(shortest >= 0.15 * spacing, "\(file.fileTitle ?? "off grid"): \(shortest / spacing) of the spacing")
100 }
101}
102
103@Test func eachSideOfAFaceIsDividedEvenly() throws {
104 // round(length / spacing) equal parts, the same points in both faces that share the side
105 for file in try meshTestFiles() {
106 let spacing = RenderMesh.spacing(for: file)
107 let mesh = RenderMesh(file: file, spacing: spacing)
108 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
109 for face in file.facesVertices {
110 for k in face.indices {
111 let a = flat[face[k]], b = flat[face[(k + 1) % face.count]]
112 let parts = max(1, Int((simd_distance(a, b) / spacing).rounded()))
113 let on = mesh.vertices.filter { p in
114 abs((b - a).x * (p - a).y - (b - a).y * (p - a).x) <= 1e-9 * simd_distance(a, b)
115 && simd_dot(p - a, b - a) >= -1e-12 && simd_dot(p - b, a - b) >= -1e-12
116 }
117 #expect(on.count == parts + 1)
118 for p in on {
119 let u = simd_dot(p - a, b - a) / simd_length_squared(b - a) * Double(parts)
120 #expect(abs(u - u.rounded()) < 1e-9)
121 }
122 }
123 }
124 }
125}
126
127@Test func theMeshIsDelaunayWithinEachFace() throws {
128 // no edge between two triangles of one face has the opposite corner of one inside the other's circumcircle
129 for file in try meshTestFiles() {
130 let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
131 var opposite: [SIMD2<Int>: [Int]] = [:]
132 for (a, b, c) in mesh.triangles {
133 for (i, j, k) in [(a, b, c), (b, c, a), (c, a, b)] { opposite[SIMD2(min(i, j), max(i, j)), default: []].append(k) }
134 }
135 var violations = 0
136 for (edge, corners) in opposite where corners.count == 2 {
137 let (p, q) = (mesh.vertices[edge.x], mesh.vertices[edge.y])
138 let (r, s) = (mesh.vertices[corners[0]], mesh.vertices[corners[1]])
139 // the angles opposite the edge sum to at most 180° when the edge is locally Delaunay
140 func angle(_ o: SIMD2<Double>) -> Double {
141 acos(max(-1, min(1, simd_dot(simd_normalize(p - o), simd_normalize(q - o)))))
142 }
143 if angle(r) + angle(s) > .pi + 1e-9 { violations += 1 }
144 }
145 #expect(violations == 0, "\(file.fileTitle ?? "off grid")")
146 }
147}
148
149@Test func eachFoldVertexIsAMeshVertex() throws {
150 for file in try meshTestFiles() {
151 let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
152 #expect(mesh.meshVertexOf.enumerated().allSatisfy { v, m in
153 mesh.vertices[m] == SIMD2(file.frames[0].verticesCoords[v].x, file.frames[0].verticesCoords[v].y)
154 })
155 }
156}