spikes/bending/Sources/Bending/Refine.swift
138 lines · 6759 bytes
1import FoldFormat
2import simd
3
4/// The model with new creases: the preimage, in every face of `faces` that frame `k` places across
5/// the folded segment p–q, of that segment (the line of a fold through every layer of a flap).
6/// Each crossed face splits in two along it; the new edges are flat (F, 0°) in every frame and the
7/// new vertices sit where their old face places them. Face orders are dropped.
8func refine(_ model: Model, frame k: Int, from p: V3, to q: V3, faces candidates: Set<Int>) -> (model: Model, faceOld: [Int]) {
9 let x = model.positions(k)
10 var points = model.flat
11 var key: [SIMD2<Int64>: Int] = [:]
12 let unit = model.size * 1e-9
13 func keyOf(_ p: V2) -> SIMD2<Int64> { SIMD2(Int64((p.x / unit).rounded()), Int64((p.y / unit).rounded())) }
14 for (v, pt) in points.enumerated() { key[keyOf(pt)] = v }
15 func id(_ pt: V2) -> Int {
16 // snap to an existing point within 1e-9 of the size
17 for dx in -1...1 {
18 for dy in -1...1 {
19 let k = keyOf(pt) &+ SIMD2(Int64(dx), Int64(dy))
20 if let v = key[k], simd_distance(points[v], pt) < 2 * unit { return v }
21 }
22 }
23 points.append(pt)
24 key[keyOf(pt)] = points.count - 1
25 return points.count - 1
26 }
27 var owner: [Int: Int] = [:] // new point -> the old face it lies in
28
29 // the cut of each crossed face, in crease-pattern coordinates
30 var cuts: [Int: (Int, Int)] = [:]
31 for f in candidates.sorted() {
32 let face = model.faces[f]
33 let c = widest(face.map { model.flat[$0] }).map { face[$0] }
34 // folded → crease pattern for this face: solve x = o + a·u + b·v in the face's plane
35 let o = x[c[0]], u = x[c[1]] - o, v = x[c[2]] - o
36 let n = cross(u, v)
37 func back(_ pt: V3) -> V2 {
38 let w = pt - o
39 let a = dot(cross(w, v), n) / dot(n, n), b = dot(cross(u, w), n) / dot(n, n)
40 return model.flat[c[0]] + a * (model.flat[c[1]] - model.flat[c[0]]) + b * (model.flat[c[2]] - model.flat[c[0]])
41 }
42 // the segment must lie in the face's plane
43 guard abs(dot(p - o, normalize(n))) < 1e-9 * model.size, abs(dot(q - o, normalize(n))) < 1e-9 * model.size else { continue }
44 let a = back(p), b = back(q)
45 var poly = face.map { model.flat[$0] }
46 if polygonArea(poly) < 0 { poly.reverse() }
47 // clip the infinite line a–b to the polygon
48 var lo = -Double.infinity, hi = Double.infinity
49 for i in poly.indices {
50 let e0 = poly[i], e = poly[(i + 1) % poly.count] - e0
51 let num = cross2(e, a - e0), den = cross2(e, b - a)
52 if abs(den) < 1e-15 { if num < 0 { lo = .infinity }; continue }
53 let t = -num / den
54 if den > 0 { lo = max(lo, t) } else { hi = min(hi, t) }
55 }
56 // only where the folded segment itself crosses the face
57 lo = max(lo, 0)
58 hi = min(hi, 1)
59 guard hi - lo > 1e-9 else { continue }
60 let p0 = a + lo * (b - a), p1 = a + hi * (b - a)
61 // a cut must run from boundary to boundary
62 guard distanceInside(poly, p0) < 1e-9 * model.size, distanceInside(poly, p1) < 1e-9 * model.size else {
63 fatalError("the fold line ends inside face \(f)")
64 }
65 let i0 = id(p0), i1 = id(p1)
66 if i0 >= model.flat.count { owner[i0] = f }
67 if i1 >= model.flat.count { owner[i1] = f }
68 guard i0 != i1 else { continue }
69 // a cut along an existing edge is no cut
70 let isEdge = model.edges.contains { Set($0) == Set([i0, i1]) }
71 if !isEdge { cuts[f] = (i0, i1) }
72 }
73
74 // split the old edges at new points on them
75 let newPoints = Array(model.flat.count..<points.count)
76 var newEdges: [[Int]] = []
77 var edgeOld: [Int?] = [] // the old edge each new edge lies on
78 var pieces: [[Int]] = [] // per old edge, its points in order
79 for (e, ends) in model.edges.enumerated() {
80 let a = model.flat[ends[0]], b = model.flat[ends[1]]
81 var on = newPoints.compactMap { v -> (Double, Int)? in
82 let t = dot(points[v] - a, b - a) / dot(b - a, b - a)
83 guard t > 1e-12, t < 1 - 1e-12, simd_distance(a + t * (b - a), points[v]) < 2 * unit else { return nil }
84 return (t, v)
85 }
86 on.sort { $0.0 < $1.0 }
87 let chain = [ends[0]] + on.map(\.1) + [ends[1]]
88 pieces.append(chain)
89 for i in 0..<(chain.count - 1) {
90 newEdges.append([chain[i], chain[i + 1]])
91 edgeOld.append(e)
92 }
93 }
94 var newFaces: [[Int]] = []
95 var faceOld: [Int] = []
96 let edgeIndex = model.edgeIndex
97 for (f, face) in model.faces.enumerated() {
98 var ring: [Int] = []
99 for i in face.indices {
100 let a = face[i], b = face[(i + 1) % face.count]
101 let e = edgeIndex[SIMD2(min(a, b), max(a, b))]!
102 let chain = model.edges[e][0] == a ? pieces[e] : pieces[e].reversed()
103 ring += chain.dropLast()
104 }
105 if let (c0, c1) = cuts[f] {
106 let i0 = ring.firstIndex(of: c0)!, i1 = ring.firstIndex(of: c1)!
107 let (s, t) = (min(i0, i1), max(i0, i1))
108 newFaces.append(Array(ring[s...t]))
109 newFaces.append(Array(ring[t...] + ring[...s]))
110 faceOld += [f, f]
111 newEdges.append([c0, c1])
112 edgeOld.append(nil)
113 } else {
114 newFaces.append(ring)
115 faceOld.append(f)
116 }
117 }
118 for v in newPoints where owner[v] == nil {
119 owner[v] = model.faces.indices.first { contains(model.faces[$0].map { model.flat[$0] }, points[v], tolerance: 1e-12) }!
120 }
121
122 var frames: [FoldFrame] = []
123 for (k, frame) in model.file.frames.enumerated() {
124 let old = model.positions(k)
125 var coords = old
126 for v in newPoints { coords.append(model.place(points[v], face: owner[v]!, old)) }
127 if k == 0 { coords = points.map { V3($0.x, $0.y, 0) } }
128 frames.append(FoldFrame(verticesCoords: coords,
129 edgesAssignment: edgeOld.map { $0.map { frame.edgesAssignment[$0] } ?? .flat },
130 edgesFoldAngle: edgeOld.map { $0.map { frame.edgesFoldAngle[$0] } ?? 0 },
131 faceOrders: [], step: frame.step))
132 }
133 let file = FoldFile(fileSpec: model.file.fileSpec, fileCreator: model.file.fileCreator, fileTitle: model.file.fileTitle,
134 fileAuthor: model.file.fileAuthor, fileClasses: model.file.fileClasses,
135 edgesVertices: newEdges, facesVertices: newFaces,
136 edgesFirstCreasedAtStep: newEdges.map { _ in nil }, frames: frames)
137 return (Model(file), faceOld)
138}