Packages/FoldKit/Sources/Notation/DiagramDrawing.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/Packages/FoldKit/Sources/Notation/DiagramDrawing.swift history · blame · raw

213 lines · 10803 bytes

10 symbols in this file
  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             let .unfold(from, over, to):
 27            points += [from, over, to]
 28        case let .technique(_, at, toward):
 29            points += [at, toward]
 30        case .turnOver, .rotate, .repeatMark:
 31            break
 32        }
 33    }
 34    let low = points.reduce(points.first ?? .zero, simd_min)
 35    let high = points.reduce(points.first ?? .zero, simd_max)
 36    let area = CGRect(x: sideMargin, y: bottomMargin, width: size.width - 2 * sideMargin,
 37                      height: size.height - bottomMargin - sideMargin)
 38    let extent = simd_max(high - low, SIMD2(repeating: 1e-9))
 39    let scale = min(area.width / extent.x, area.height / extent.y)
 40    let offset = SIMD2(area.midX, area.midY) - scale * (low + high) / 2
 41    func pixel(_ p: SIMD2<Double>) -> CGPoint {
 42        let q = offset + scale * p
 43        return CGPoint(x: q.x, y: q.y)
 44    }
 45
 46    context.setLineJoin(.round)
 47    let layers: [(DiagramLine, Double, Double, [Double])] = [
 48        (.light, style.lightWidth, style.lightGrey, []),
 49        (.solid, style.outlineWidth, 0, []),
 50        (.dashed, style.creaseWidth, 0, style.valleyDash),
 51        (.dashDot, style.creaseWidth, 0, style.mountainDash),
 52    ]
 53    for (line, width, grey, dash) in layers {
 54        context.setStrokeColor(gray: grey, alpha: 1)
 55        context.setLineWidth(width)
 56        context.setLineCap(dash.isEmpty ? .round : .butt)
 57        context.setLineDash(phase: 0, lengths: dash.map { CGFloat($0) })
 58        for edge in diagram.edges where edge.style == line {
 59            context.move(to: pixel(edge.from))
 60            context.addLine(to: pixel(edge.to))
 61        }
 62        context.strokePath()
 63    }
 64    context.setLineDash(phase: 0, lengths: [])
 65    context.setLineCap(.round)
 66    context.setStrokeColor(gray: 0, alpha: 1)
 67    context.setLineWidth(style.arrowWidth)
 68
 69    let repeated = diagram.arrows.contains { if case .repeatMark = $0 { true } else { false } }
 70    let symbolCentre = SIMD2(size.width / 2, bottomMargin / 2)
 71    for arrow in diagram.arrows {
 72        switch arrow {
 73        case let .valleyFold(from, over, to):
 74            drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .filled, returnHead: false, tick: repeated)
 75        case let .mountainFold(from, over, to):
 76            drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowHalf, returnHead: false, tick: repeated)
 77        case let .foldAndUnfold(from, over, to, mountain):
 78            drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: mountain ? .hollowHalf : .filled,
 79                          returnHead: true, tick: repeated)
 80        case let .technique(technique, at, toward):
 81            let tip = vector(pixel(at)), direction = normalize(vector(pixel(toward)) - tip)
 82            if technique == .petal {
 83                let tail = tip - style.symbolSize * 1.5 * direction
 84                let over = (tip + tail) / 2 + 0.3 * SIMD2(direction.y, -direction.x) * style.symbolSize * 1.5
 85                drawFoldArrow(context, style, point(tail), point(over), point(tip), head: .filled, returnHead: false,
 86                              tick: repeated)
 87            } else {
 88                drawPushArrow(context, style, tip: tip, direction: direction, tick: repeated)
 89            }
 90        case let .turnOver(axis):
 91            drawTurnOver(context, style, centre: symbolCentre, vertical: axis == .vertical)
 92        case let .rotate(degrees):
 93            drawRotate(context, style, centre: symbolCentre, degrees: degrees)
 94        case let .unfold(from, over, to):
 95            drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowFull, returnHead: false,
 96                          tick: repeated)
 97        case .repeatMark:
 98            break
 99        }
100    }
101}
102
103private enum Head { case filled, hollowHalf, hollowFull }
104
105private func vector(_ p: CGPoint) -> SIMD2<Double> { SIMD2(p.x, p.y) }
106private func point(_ v: SIMD2<Double>) -> CGPoint { CGPoint(x: v.x, y: v.y) }
107
108/// A quadratic arc from `from` through `over` to `to`, its head at `to`; with `returnHead` a
109/// hollow head at `from` pointing back; with `tick` a stroke across the shaft near its tail.
110private func drawFoldArrow(_ context: CGContext, _ style: DiagramStyle, _ from: CGPoint, _ over: CGPoint, _ to: CGPoint,
111                           head: Head, returnHead: Bool, tick: Bool) {
112    let a = vector(from), m = vector(over), b = vector(to)
113    let control = 2 * m - (a + b) / 2
114    context.move(to: from)
115    context.addQuadCurve(to: to, control: point(control))
116    context.strokePath()
117    // the barb of a half head goes on the outside of the arc
118    let outside = m - (a + b) / 2
119    drawHead(context, style, head, tip: b, direction: normalize(b - control), outside: outside)
120    if returnHead {
121        drawHead(context, style, .hollowFull, tip: a, direction: normalize(a - control), outside: outside)
122    }
123    if tick {
124        let t = 0.25
125        let p = (1 - t) * (1 - t) * a + 2 * t * (1 - t) * control + t * t * b
126        let tangent = normalize(2 * (1 - t) * (control - a) + 2 * t * (b - control))
127        let across = SIMD2(-tangent.y, tangent.x) * style.headLength / 2
128        context.move(to: point(p - across))
129        context.addLine(to: point(p + across))
130        context.strokePath()
131    }
132}
133
134private func drawHead(_ context: CGContext, _ style: DiagramStyle, _ head: Head, tip: SIMD2<Double>,
135                      direction: SIMD2<Double>, outside: SIMD2<Double>) {
136    let back = tip - style.headLength * direction
137    var across = SIMD2(-direction.y, direction.x) * style.headWidth / 2
138    if dot(across, outside) < 0 { across = -across }
139    let corners: [SIMD2<Double>]
140    switch head {
141    case .filled, .hollowFull: corners = [tip, back + across, back - across]
142    case .hollowHalf: corners = [tip, back + 2 * across, back]
143    }
144    context.addLines(between: corners.map(point))
145    context.closePath()
146    context.setFillColor(gray: head == .filled ? 0 : 1, alpha: 1)
147    context.drawPath(using: .fillStroke)
148}
149
150/// The hollow push arrow, its tip at `tip`, with a notched tail; with `tick` a stroke across the
151/// shaft near its tail, standing out of the shaft by half a head length on each side.
152private func drawPushArrow(_ context: CGContext, _ style: DiagramStyle, tip: SIMD2<Double>, direction: SIMD2<Double>,
153                           tick: Bool) {
154    let s = style.symbolSize
155    let outline: [SIMD2<Double>] = [
156        SIMD2(0, 0), SIMD2(-0.36, 0.3), SIMD2(-0.36, 0.12), SIMD2(-1, 0.12),
157        SIMD2(-0.86, 0), SIMD2(-1, -0.12), SIMD2(-0.36, -0.12), SIMD2(-0.36, -0.3),
158    ]
159    let across = SIMD2(-direction.y, direction.x)
160    context.addLines(between: outline.map { point(tip + s * ($0.x * direction + $0.y * across)) })
161    context.closePath()
162    context.setFillColor(gray: 1, alpha: 1)
163    context.drawPath(using: .fillStroke)
164    if tick {
165        let p = tip - 0.7 * s * direction, half = 0.12 * s + style.headLength / 2
166        context.move(to: point(p - half * across))
167        context.addLine(to: point(p + half * across))
168        context.strokePath()
169    }
170}
171
172/// The loop-the-loop arrow: left to right for a turn about the vertical axis, bottom to top about
173/// the horizontal.
174private func drawTurnOver(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, vertical: Bool) {
175    // a prolate cycloid over one period, its loop above the line of travel, between straight tails
176    let a = style.symbolSize / (3 * .pi), b = 2 * a
177    let loop = (0...64).map { i -> SIMD2<Double> in
178        let u = -Double.pi + 2 * .pi * Double(i) / 64
179        return SIMD2(a * u - b * sin(u), b * cos(u))
180    }
181    let tail = SIMD2(style.symbolSize / 4, 0)
182    let path = [loop[0] - tail] + loop + [loop[64] + tail]
183    let place = { (p: SIMD2<Double>) in centre + (vertical ? p : SIMD2(-p.y, p.x)) }
184    context.addLines(between: path.map { point(place($0)) })
185    context.strokePath()
186    let tip = place(path[path.count - 1])
187    drawHead(context, style, .filled, tip: tip, direction: normalize(tip - place(loop[64])), outside: SIMD2(0, 1))
188}
189
190/// Two arcs around a circle, counterclockwise for positive `degrees`, with the amount at the centre.
191private func drawRotate(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, degrees: Double) {
192    let r = style.symbolSize / 2
193    let turn = degrees >= 0 ? 1.0 : -1.0
194    let headAngle = style.headLength / r
195    for start in [Double.pi * 0.6, Double.pi * 1.6] {
196        let end = start + turn * Double.pi * 0.75, back = end - turn * headAngle
197        context.addArc(center: point(centre), radius: r, startAngle: start, endAngle: back, clockwise: turn < 0)
198        context.strokePath()
199        let tip = centre + r * SIMD2(cos(end), sin(end)), base = centre + r * SIMD2(cos(back), sin(back))
200        drawHead(context, style, .filled, tip: tip, direction: normalize(tip - base), outside: tip - centre)
201    }
202    let label = String(format: "%g°", abs(degrees))
203    let font = CTFontCreateWithName("Helvetica" as CFString, 14, nil)
204    let text = NSAttributedString(string: label, attributes: [
205        NSAttributedString.Key(kCTFontAttributeName as String): font,
206        NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true,
207    ])
208    let line = CTLineCreateWithAttributedString(text)
209    let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds)
210    context.setFillColor(gray: 0, alpha: 1)
211    context.textPosition = CGPoint(x: centre.x - bounds.midX, y: centre.y - bounds.midY)
212    CTLineDraw(line, context)
213}