| @@ -1,10 +1,12 @@ |
| 1 | import FoldFormat |
1 | import FoldFormat |
| 2 | import simd |
2 | import simd |
| 3 | |
3 | |
| 4 | /// The triangles the renderer draws, finer than the FOLD faces: frame 0's faces cut by lines |
4 | /// The triangles the renderer draws, finer than the FOLD faces (decision 0003). Each side of each |
| 5 | /// every `spacing` in x and in y, each resulting convex cell fanned into triangles. Cells on both |
5 | /// frame 0 face is divided into round(length / `spacing`) equal parts; inside each face, points of |
| 6 | /// sides of an edge share its vertices, so the mesh is one connected sheet. The FOLD topology is |
6 | /// a triangular lattice `spacing` apart are kept at least 0.6 `spacing` from its sides; each face |
| 7 | /// unchanged; a non-rigid step bends this mesh, not the FOLD faces. |
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. |
| 8 | public struct RenderMesh: Sendable { |
10 | public struct RenderMesh: Sendable { |
| 9 | /// Frame 0 positions in its plane. |
11 | /// Frame 0 positions in its plane. |
| 10 | public let vertices: [SIMD2<Double>] |
12 | public let vertices: [SIMD2<Double>] |
| @@ -27,51 +29,66 @@ public struct RenderMesh: Sendable { |
| 27 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } |
29 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } |
| 28 | let lower = flat.dropFirst().reduce(flat[0], simd_min) |
30 | let lower = flat.dropFirst().reduce(flat[0], simd_min) |
| 29 | let upper = flat.dropFirst().reduce(flat[0], simd_max) |
31 | let upper = flat.dropFirst().reduce(flat[0], simd_max) |
| 30 | let size = (upper - lower).max() |
32 | let tolerance = (upper - lower).max() * 1e-9 |
| 31 | let tolerance = size * 1e-9 |
33 | let rowSpacing = spacing * 3.0.squareRoot() / 2 |
| 32 | let xs = lines(from: lower.x, to: upper.x, spacing: spacing, tolerance: tolerance) |
| |
| 33 | let ys = lines(from: lower.y, to: upper.y, spacing: spacing, tolerance: tolerance) |
| |
| 34 | |
34 | |
| 35 | var points = PointSet(tolerance: tolerance) |
35 | 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 | |
| 36 | var triangles: [(Int, Int, Int)] = [] |
51 | var triangles: [(Int, Int, Int)] = [] |
| 37 | var faceOf: [Int] = [] |
52 | var faceOf: [Int] = [] |
| 38 | var anchors: [Int: Anchor] = [:] |
53 | var anchors: [Int: Anchor] = [:] |
| 39 | for (f, face) in file.facesVertices.enumerated() { |
54 | for (f, face) in file.facesVertices.enumerated() { |
| 40 | var cells = [face.map { flat[$0] }] |
55 | let outline = face.map { flat[$0] } |
| 41 | for x in xs { cells = cells.flatMap { split($0, at: x, axis: 0, tolerance: tolerance) } } |
56 | let corners = signedArea(outline) < 0 ? face.reversed() : face |
| 42 | for y in ys { cells = cells.flatMap { split($0, at: y, axis: 1, tolerance: tolerance) } } |
57 | let polygon = corners.map { flat[$0] } |
| 43 | let corners = widestCorners(face.map { flat[$0] }) |
58 | var boundary: [Int] = [] |
| 44 | let origin = flat[face[corners[0]]] |
59 | for k in corners.indices { boundary += side(corners[k], corners[(k + 1) % corners.count]).dropLast() } |
| 45 | let u = flat[face[corners[1]]] - origin, v = flat[face[corners[2]]] - origin |
60 | |
| 46 | let det = u.x * v.y - u.y * v.x |
61 | var inside: [Int] = [] |
| 47 | func point(_ p: SIMD2<Double>) -> Int { |
62 | let low = polygon.dropFirst().reduce(polygon[0], simd_min) |
| 48 | let id = points.index(of: p) |
63 | let high = polygon.dropFirst().reduce(polygon[0], simd_max) |
| 49 | if anchors[id] == nil { |
64 | var row = Int(((low.y - lower.y) / rowSpacing).rounded(.down)) |
| 50 | let w = points.points[id] - origin |
65 | while lower.y + Double(row) * rowSpacing <= high.y { |
| 51 | anchors[id] = Anchor(corners: SIMD3(face[corners[0]], face[corners[1]], face[corners[2]]), |
66 | let y = lower.y + Double(row) * rowSpacing |
| 52 | a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det) |
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 |
| 53 | } |
73 | } |
| 54 | return id |
74 | row += 1 |
| 55 | } |
75 | } |
| 56 | for cell in cells { |
76 | |
| 57 | var ids: [Int] = [] |
77 | for triangle in triangulate(boundary: boundary, inside: inside, points.points) { |
| 58 | for p in cell { |
78 | triangles.append(triangle) |
| 59 | let id = point(p) |
79 | faceOf.append(f) |
| 60 | if ids.last != id && ids.first != id { ids.append(id) } |
80 | } |
| 61 | } |
81 | let widest = widestCorners(outline) |
| 62 | guard ids.count >= 3 else { continue } |
82 | let origin = outline[widest[0]] |
| 63 | var fanned = fan(ids, points.points, minimumArea: tolerance * size) |
83 | let u = outline[widest[1]] - origin, v = outline[widest[2]] - origin |
| 64 | if fanned == nil { |
84 | let det = u.x * v.y - u.y * v.x |
| 65 | let centre = ids.reduce(SIMD2<Double>.zero) { $0 + points.points[$1] } / Double(ids.count) |
85 | for id in boundary + inside where anchors[id] == nil { |
| 66 | fanned = fan(ids, around: point(centre)) |
86 | let w = points.points[id] - origin |
| 67 | } |
87 | anchors[id] = Anchor(corners: SIMD3(face[widest[0]], face[widest[1]], face[widest[2]]), |
| 68 | for triangle in fanned! { |
88 | a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det) |
| 69 | triangles.append(triangle) |
| |
| 70 | faceOf.append(f) |
| |
| 71 | } |
| |
| 72 | } |
89 | } |
| 73 | } |
90 | } |
| 74 | meshVertexOf = flat.map { points.index(of: $0) } |
91 | self.meshVertexOf = meshVertexOf |
| 75 | vertices = points.points |
92 | vertices = points.points |
| 76 | self.triangles = triangles |
93 | self.triangles = triangles |
| 77 | self.faceOf = faceOf |
94 | self.faceOf = faceOf |
| @@ -107,56 +124,120 @@ public func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double { |
| 107 | return worst |
124 | return worst |
| 108 | } |
125 | } |
| 109 | |
126 | |
| 110 | /// The grid lines strictly inside `low...high`: `low + k·spacing` for k ≥ 1. |
127 | /// Twice the signed area of a polygon, positive when its corners run counterclockwise. |
| 111 | private func lines(from low: Double, to high: Double, spacing: Double, tolerance: Double) -> [Double] { |
128 | private func signedArea(_ polygon: [SIMD2<Double>]) -> Double { |
| 112 | var result: [Double] = [] |
129 | polygon.indices.reduce(0) { sum, k in |
| 113 | var k = 1.0 |
130 | let p = polygon[k], q = polygon[(k + 1) % polygon.count] |
| 114 | while low + k * spacing < high - tolerance { |
131 | return sum + p.x * q.y - p.y * q.x |
| 115 | result.append(low + k * spacing) |
| |
| 116 | k += 1 |
| |
| 117 | } |
132 | } |
| 118 | return result |
| |
| 119 | } |
133 | } |
| 120 | |
134 | |
| 121 | /// A convex polygon cut by the line where coordinate `axis` equals `value`, or the polygon itself |
135 | private func cross(_ u: SIMD2<Double>, _ v: SIMD2<Double>) -> Double { u.x * v.y - u.y * v.x } |
| 122 | /// when the line does not cross it. Crossing points lie exactly on the line. |
136 | |
| 123 | private func split(_ polygon: [SIMD2<Double>], at value: Double, axis: Int, tolerance: Double) -> [[SIMD2<Double>]] { |
137 | /// The distance from `p` to the nearest side of a convex counterclockwise polygon, negative outside. |
| 124 | let d = polygon.map { $0[axis] - value } |
138 | private func distanceInside(_ polygon: [SIMD2<Double>], _ p: SIMD2<Double>) -> Double { |
| 125 | guard d.contains(where: { $0 < -tolerance }), d.contains(where: { $0 > tolerance }) else { return [polygon] } |
139 | polygon.indices.map { k in |
| 126 | var below: [SIMD2<Double>] = [], above: [SIMD2<Double>] = [] |
140 | let a = polygon[k], b = polygon[(k + 1) % polygon.count] |
| 127 | for i in polygon.indices { |
141 | return cross(b - a, p - a) / simd_distance(a, b) |
| 128 | let j = (i + 1) % polygon.count |
142 | }.min() ?? 0 |
| 129 | if d[i] <= tolerance { below.append(polygon[i]) } |
143 | } |
| 130 | if d[i] >= -tolerance { above.append(polygon[i]) } |
144 | |
| 131 | if (d[i] < -tolerance && d[j] > tolerance) || (d[i] > tolerance && d[j] < -tolerance) { |
145 | /// A Delaunay triangulation of a convex polygon whose `boundary` points run counterclockwise |
| 132 | var crossing = polygon[i] + (polygon[j] - polygon[i]) * (d[i] / (d[i] - d[j])) |
146 | /// (straight runs allowed), with `inside` points strictly inside, keeping the boundary's edges. |
| 133 | crossing[axis] = value |
147 | /// Ear clipping on the boundary, each time the largest ear with no other boundary point on or in |
| 134 | below.append(crossing) |
148 | /// it; then each inside point inserted into the triangle holding it, splitting an edge it lies |
| 135 | above.append(crossing) |
149 | /// on; then Lawson flips of every edge off the boundary until each is locally Delaunay. |
| |
150 | /// Triangles are counterclockwise. |
| |
151 | private 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) } |
| 136 | } |
168 | } |
| |
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) |
| 137 | } |
172 | } |
| 138 | return [below, above] |
173 | if ring.count == 3, area(ring[0], ring[1], ring[2]) > 0 { triangles.append(SIMD3(ring[0], ring[1], ring[2])) } |
| 139 | } |
| |
| 140 | |
174 | |
| 141 | /// A convex cell, its corners counterclockwise, fanned from the first corner whose fan has no |
175 | for v in inside { |
| 142 | /// triangle of `minimumArea` or less; nil when every corner's fan does. A corner on a straight |
176 | // the newest triangles first: consecutive points of a lattice row lie close together |
| 143 | /// side would otherwise be left out of every triangle. |
177 | for k in triangles.indices.reversed() { |
| 144 | private func fan(_ ids: [Int], _ points: [SIMD2<Double>], minimumArea: Double) -> [(Int, Int, Int)]? { |
178 | let t = triangles[k] |
| 145 | for apex in ids.indices { |
179 | let total = area(t.x, t.y, t.z) |
| 146 | let ring = (0..<ids.count).map { ids[(apex + $0) % ids.count] } |
180 | let w = [area(v, t.y, t.z), area(t.x, v, t.z), area(t.x, t.y, v)] |
| 147 | let triangles = (1..<(ring.count - 1)).map { (ring[0], ring[$0], ring[$0 + 1]) } |
181 | guard w.allSatisfy({ $0 >= -1e-12 * total }) else { continue } |
| 148 | let flat = triangles.contains { a, b, c in |
182 | if let zero = w.firstIndex(where: { abs($0) <= 1e-9 * total }) { |
| 149 | let (p, q, r) = (points[a], points[b], points[c]) |
183 | // on the edge opposite corner `zero`: split both triangles beside it |
| 150 | return ((q - p).x * (r - p).y - (q - p).y * (r - p).x) / 2 <= minimumArea |
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 |
| 151 | } |
203 | } |
| 152 | if !flat { return triangles } |
| |
| 153 | } |
204 | } |
| 154 | return nil |
| |
| 155 | } |
| |
| 156 | |
205 | |
| 157 | /// A convex cell fanned around an added point `centre` inside it. |
206 | let kept = Set(boundary.indices.map { k in |
| 158 | private func fan(_ ids: [Int], around centre: Int) -> [(Int, Int, Int)] { |
207 | SIMD2(min(boundary[k], boundary[(k + 1) % boundary.count]), max(boundary[k], boundary[(k + 1) % boundary.count])) |
| 159 | ids.indices.map { (centre, ids[$0], ids[($0 + 1) % ids.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) } |
| 160 | } |
241 | } |
| 161 | |
242 | |
| 162 | /// The indices of the three corners spanning the largest triangle, the first such in index order. |
243 | /// The indices of the three corners spanning the largest triangle, the first such in index order. |