import CoreGraphics import CoreText import Foundation import simd /// The model and its arrows fill the canvas inside these margins, in points; the turn-over and /// rotate symbols sit in the bottom one. private let sideMargin = 48.0, bottomMargin = 96.0 /// Draws `diagram` into the rectangle from the origin to `size`, the model and its arrows fitted /// inside the margins. /// /// The context's user space must be y-up with its origin at the bottom-left of the canvas, as in a /// `CGBitmapContext`; a y-down context such as SwiftUI's `GraphicsContext.withCGContext` must be /// flipped first (`translateBy(x: 0, y: height)`, `scaleBy(x: 1, y: -1)`). Nothing is drawn /// behind the diagram: the caller fills the background, and hollow heads and the push arrow are /// filled white. The context's graphics state is restored on return. public func drawDiagram(_ diagram: Diagram, style: DiagramStyle, in context: CGContext, size: CGSize) { context.saveGState() defer { context.restoreGState() } var points = diagram.edges.flatMap { [$0.from, $0.to] } for arrow in diagram.arrows { switch arrow { case let .valleyFold(from, over, to), let .mountainFold(from, over, to), let .foldAndUnfold(from, over, to, _), let .unfold(from, over, to): points += [from, over, to] case let .technique(_, at, toward): points += [at, toward] case .turnOver, .rotate, .repeatMark: break } } let low = points.reduce(points.first ?? .zero, simd_min) let high = points.reduce(points.first ?? .zero, simd_max) let area = CGRect(x: sideMargin, y: bottomMargin, width: size.width - 2 * sideMargin, height: size.height - bottomMargin - sideMargin) let extent = simd_max(high - low, SIMD2(repeating: 1e-9)) let scale = min(area.width / extent.x, area.height / extent.y) let offset = SIMD2(area.midX, area.midY) - scale * (low + high) / 2 func pixel(_ p: SIMD2) -> CGPoint { let q = offset + scale * p return CGPoint(x: q.x, y: q.y) } context.setLineJoin(.round) let layers: [(DiagramLine, Double, Double, [Double])] = [ (.light, style.lightWidth, style.lightGrey, []), (.solid, style.outlineWidth, 0, []), (.dashed, style.creaseWidth, 0, style.valleyDash), (.dashDot, style.creaseWidth, 0, style.mountainDash), ] for (line, width, grey, dash) in layers { context.setStrokeColor(gray: grey, alpha: 1) context.setLineWidth(width) context.setLineCap(dash.isEmpty ? .round : .butt) context.setLineDash(phase: 0, lengths: dash.map { CGFloat($0) }) for edge in diagram.edges where edge.style == line { context.move(to: pixel(edge.from)) context.addLine(to: pixel(edge.to)) } context.strokePath() } context.setLineDash(phase: 0, lengths: []) context.setLineCap(.round) context.setStrokeColor(gray: 0, alpha: 1) context.setLineWidth(style.arrowWidth) let repeated = diagram.arrows.contains { if case .repeatMark = $0 { true } else { false } } let symbolCentre = SIMD2(size.width / 2, bottomMargin / 2) for arrow in diagram.arrows { switch arrow { case let .valleyFold(from, over, to): drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .filled, returnHead: false, tick: repeated) case let .mountainFold(from, over, to): drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowHalf, returnHead: false, tick: repeated) case let .foldAndUnfold(from, over, to, mountain): drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: mountain ? .hollowHalf : .filled, returnHead: true, tick: repeated) case let .technique(technique, at, toward): let tip = vector(pixel(at)), direction = normalize(vector(pixel(toward)) - tip) if technique == .petal { let tail = tip - style.symbolSize * 1.5 * direction let over = (tip + tail) / 2 + 0.3 * SIMD2(direction.y, -direction.x) * style.symbolSize * 1.5 drawFoldArrow(context, style, point(tail), point(over), point(tip), head: .filled, returnHead: false, tick: repeated) } else { drawPushArrow(context, style, tip: tip, direction: direction, tick: repeated) } case let .turnOver(axis): drawTurnOver(context, style, centre: symbolCentre, vertical: axis == .vertical) case let .rotate(degrees): drawRotate(context, style, centre: symbolCentre, degrees: degrees) case let .unfold(from, over, to): drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowFull, returnHead: false, tick: repeated) case .repeatMark: break } } } private enum Head { case filled, hollowHalf, hollowFull } private func vector(_ p: CGPoint) -> SIMD2 { SIMD2(p.x, p.y) } private func point(_ v: SIMD2) -> CGPoint { CGPoint(x: v.x, y: v.y) } /// A quadratic arc from `from` through `over` to `to`, its head at `to`; with `returnHead` a /// hollow head at `from` pointing back; with `tick` a stroke across the shaft near its tail. private func drawFoldArrow(_ context: CGContext, _ style: DiagramStyle, _ from: CGPoint, _ over: CGPoint, _ to: CGPoint, head: Head, returnHead: Bool, tick: Bool) { let a = vector(from), m = vector(over), b = vector(to) let control = 2 * m - (a + b) / 2 context.move(to: from) context.addQuadCurve(to: to, control: point(control)) context.strokePath() // the barb of a half head goes on the outside of the arc let outside = m - (a + b) / 2 drawHead(context, style, head, tip: b, direction: normalize(b - control), outside: outside) if returnHead { drawHead(context, style, .hollowFull, tip: a, direction: normalize(a - control), outside: outside) } if tick { let t = 0.25 let p = (1 - t) * (1 - t) * a + 2 * t * (1 - t) * control + t * t * b let tangent = normalize(2 * (1 - t) * (control - a) + 2 * t * (b - control)) let across = SIMD2(-tangent.y, tangent.x) * style.headLength / 2 context.move(to: point(p - across)) context.addLine(to: point(p + across)) context.strokePath() } } private func drawHead(_ context: CGContext, _ style: DiagramStyle, _ head: Head, tip: SIMD2, direction: SIMD2, outside: SIMD2) { let back = tip - style.headLength * direction var across = SIMD2(-direction.y, direction.x) * style.headWidth / 2 if dot(across, outside) < 0 { across = -across } let corners: [SIMD2] switch head { case .filled, .hollowFull: corners = [tip, back + across, back - across] case .hollowHalf: corners = [tip, back + 2 * across, back] } context.addLines(between: corners.map(point)) context.closePath() context.setFillColor(gray: head == .filled ? 0 : 1, alpha: 1) context.drawPath(using: .fillStroke) } /// The hollow push arrow, its tip at `tip`, with a notched tail; with `tick` a stroke across the /// shaft near its tail, standing out of the shaft by half a head length on each side. private func drawPushArrow(_ context: CGContext, _ style: DiagramStyle, tip: SIMD2, direction: SIMD2, tick: Bool) { let s = style.symbolSize let outline: [SIMD2] = [ SIMD2(0, 0), SIMD2(-0.36, 0.3), SIMD2(-0.36, 0.12), SIMD2(-1, 0.12), SIMD2(-0.86, 0), SIMD2(-1, -0.12), SIMD2(-0.36, -0.12), SIMD2(-0.36, -0.3), ] let across = SIMD2(-direction.y, direction.x) context.addLines(between: outline.map { point(tip + s * ($0.x * direction + $0.y * across)) }) context.closePath() context.setFillColor(gray: 1, alpha: 1) context.drawPath(using: .fillStroke) if tick { let p = tip - 0.7 * s * direction, half = 0.12 * s + style.headLength / 2 context.move(to: point(p - half * across)) context.addLine(to: point(p + half * across)) context.strokePath() } } /// The loop-the-loop arrow: left to right for a turn about the vertical axis, bottom to top about /// the horizontal. private func drawTurnOver(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2, vertical: Bool) { // a prolate cycloid over one period, its loop above the line of travel, between straight tails let a = style.symbolSize / (3 * .pi), b = 2 * a let loop = (0...64).map { i -> SIMD2 in let u = -Double.pi + 2 * .pi * Double(i) / 64 return SIMD2(a * u - b * sin(u), b * cos(u)) } let tail = SIMD2(style.symbolSize / 4, 0) let path = [loop[0] - tail] + loop + [loop[64] + tail] let place = { (p: SIMD2) in centre + (vertical ? p : SIMD2(-p.y, p.x)) } context.addLines(between: path.map { point(place($0)) }) context.strokePath() let tip = place(path[path.count - 1]) drawHead(context, style, .filled, tip: tip, direction: normalize(tip - place(loop[64])), outside: SIMD2(0, 1)) } /// Two arcs around a circle, counterclockwise for positive `degrees`, with the amount at the centre. private func drawRotate(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2, degrees: Double) { let r = style.symbolSize / 2 let turn = degrees >= 0 ? 1.0 : -1.0 let headAngle = style.headLength / r for start in [Double.pi * 0.6, Double.pi * 1.6] { let end = start + turn * Double.pi * 0.75, back = end - turn * headAngle context.addArc(center: point(centre), radius: r, startAngle: start, endAngle: back, clockwise: turn < 0) context.strokePath() let tip = centre + r * SIMD2(cos(end), sin(end)), base = centre + r * SIMD2(cos(back), sin(back)) drawHead(context, style, .filled, tip: tip, direction: normalize(tip - base), outside: tip - centre) } let label = String(format: "%g°", abs(degrees)) let font = CTFontCreateWithName("Helvetica" as CFString, 14, nil) let text = NSAttributedString(string: label, attributes: [ NSAttributedString.Key(kCTFontAttributeName as String): font, NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true, ]) let line = CTLineCreateWithAttributedString(text) let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds) context.setFillColor(gray: 0, alpha: 1) context.textPosition = CGPoint(x: centre.x - bounds.midX, y: centre.y - bounds.midY) CTLineDraw(line, context) }