Commit 41f7bf531e
Verified · cmc
Layout: unified · split
Packages/FoldKit/Package.swift +6 −1
| @@ -9,6 +9,7 @@ let package = Package( | |||
| 9 | .library(name: "Folding", targets: ["Folding"]), | 9 | .library(name: "Folding", targets: ["Folding"]), |
| 10 | .library(name: "FoldCompiler", targets: ["FoldCompiler"]), | 10 | .library(name: "FoldCompiler", targets: ["FoldCompiler"]), |
| 11 | .library(name: "Models", targets: ["Models"]), | 11 | .library(name: "Models", targets: ["Models"]), |
| 12 | .library(name: "Notation", targets: ["Notation"]), | ||
| 12 | .executable(name: "foldc", targets: ["foldc"]), | 13 | .executable(name: "foldc", targets: ["foldc"]), |
| 13 | .executable(name: "foldlint", targets: ["foldlint"]), | 14 | .executable(name: "foldlint", targets: ["foldlint"]), |
| 14 | ], | 15 | ], |
| @@ -17,11 +18,12 @@ let package = Package( | |||
| 17 | .target(name: "Folding", dependencies: ["FoldFormat"]), | 18 | .target(name: "Folding", dependencies: ["FoldFormat"]), |
| 18 | .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]), | 19 | .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]), |
| 19 | .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]), | 20 | .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]), |
| 21 | .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]), | ||
| 20 | .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]), | 22 | .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]), |
| 21 | .executableTarget(name: "foldlint", dependencies: ["FoldFormat", "Folding"]), | 23 | .executableTarget(name: "foldlint", dependencies: ["FoldFormat", "Folding"]), |
| 22 | .target( | 24 | .target( |
| 23 | name: "FoldKitTestSupport", | 25 | name: "FoldKitTestSupport", |
| 24 | dependencies: ["FoldFormat", "Folding", "FoldCompiler"], | 26 | dependencies: ["FoldFormat", "Folding", "FoldCompiler", "Notation"], |
| 25 | resources: [.copy("Fixtures")] | 27 | resources: [.copy("Fixtures")] |
| 26 | ), | 28 | ), |
| 27 | .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]), | 29 | .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]), |
| @@ -30,6 +32,9 @@ let package = Package( | |||
| 30 | dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]), | 32 | dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]), |
| 31 | .testTarget(name: "ModelsTests", | 33 | .testTarget(name: "ModelsTests", |
| 32 | dependencies: ["Models", "FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport", "foldlint"]), | 34 | dependencies: ["Models", "FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport", "foldlint"]), |
| 35 | .testTarget(name: "NotationTests", | ||
| 36 | dependencies: ["Notation", "Models", "Folding", "FoldFormat", "FoldKitTestSupport"], | ||
| 37 | resources: [.copy("Snapshots")]), | ||
| 33 | ], | 38 | ], |
| 34 | swiftLanguageModes: [.v6] | 39 | swiftLanguageModes: [.v6] |
| 35 | ) | 40 | ) |
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +289
| @@ -1,8 +1,13 @@ | |||
| 1 | import CoreGraphics | ||
| 2 | import CoreText | ||
| 1 | import Foundation | 3 | import Foundation |
| 2 | import FoldCompiler | 4 | import FoldCompiler |
| 3 | import FoldFormat | 5 | import FoldFormat |
| 4 | import Folding | 6 | import Folding |
| 7 | import ImageIO | ||
| 8 | import Notation | ||
| 5 | import simd | 9 | import simd |
| 10 | import Testing | ||
| 6 | 11 | ||
| 7 | /// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases | 12 | /// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases |
| 8 | /// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step. | 13 | /// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step. |
| @@ -507,3 +512,287 @@ public func runFoldlint(on url: URL) throws -> (exitCode: Int32, output: String) | |||
| 507 | return (process.terminationStatus, String(decoding: output, as: UTF8.self)) | 512 | return (process.terminationStatus, String(decoding: output, as: UTF8.self)) |
| 508 | } | 513 | } |
| 509 | #endif | 514 | #endif |
| 515 | |||
| 516 | /// The diagram for step `step` (counted from 1) of a fixture. | ||
| 517 | public func diagram(_ fixtureName: String, step: Int) throws -> Diagram { | ||
| 518 | let file = try FoldFile(contentsOf: fixture(fixtureName)) | ||
| 519 | return buildDiagram(file: file, step: try readStep(step, in: file)) | ||
| 520 | } | ||
| 521 | |||
| 522 | /// `visibleSegments` of a fixture's edge in frame `n`, with frame n's order and step n + 1's | ||
| 523 | /// viewpoint (the default one after the last step). | ||
| 524 | public func visibleSegmentsOf(_ fixtureName: String, edge: Int, inFrame n: Int) throws -> [(SIMD2<Double>, SIMD2<Double>)] { | ||
| 525 | let file = try FoldFile(contentsOf: fixture(fixtureName)) | ||
| 526 | let frame = file.frames[n] | ||
| 527 | let order = try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, file)) | ||
| 528 | let viewpoint = n + 1 < file.frames.count | ||
| 529 | ? try readStep(n + 1, in: file).viewpoint | ||
| 530 | : Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) | ||
| 531 | return visibleSegments(of: edge, frame: frame, file: file, order: order, viewpoint: viewpoint) | ||
| 532 | } | ||
| 533 | |||
| 534 | public func segmentLength(_ segment: (SIMD2<Double>, SIMD2<Double>)) -> Double { | ||
| 535 | simd_distance(segment.0, segment.1) | ||
| 536 | } | ||
| 537 | |||
| 538 | /// The canvas is square, this many pixels a side, white. | ||
| 539 | private let canvasSide = 480 | ||
| 540 | /// The model and its arrows fill the canvas inside these margins; the turn-over and rotate | ||
| 541 | /// symbols sit in the bottom one. | ||
| 542 | private let sideMargin = 48.0, bottomMargin = 96.0 | ||
| 543 | |||
| 544 | /// `diagram` drawn with `DiagramStyle.standard`, the model and its arrows fitted to the canvas. | ||
| 545 | public func render(_ diagram: Diagram) -> CGImage { | ||
| 546 | let style = DiagramStyle.standard | ||
| 547 | let side = Double(canvasSide) | ||
| 548 | let context = CGContext(data: nil, width: canvasSide, height: canvasSide, bitsPerComponent: 8, bytesPerRow: 0, | ||
| 549 | space: CGColorSpace(name: CGColorSpace.sRGB)!, | ||
| 550 | bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! | ||
| 551 | context.setFillColor(gray: 1, alpha: 1) | ||
| 552 | context.fill(CGRect(x: 0, y: 0, width: side, height: side)) | ||
| 553 | |||
| 554 | var points = diagram.edges.flatMap { [$0.from, $0.to] } | ||
| 555 | for arrow in diagram.arrows { | ||
| 556 | switch arrow { | ||
| 557 | case let .valleyFold(from, over, to), let .mountainFold(from, over, to), let .foldAndUnfold(from, over, to, _): | ||
| 558 | points += [from, over, to] | ||
| 559 | case let .technique(_, at, toward): | ||
| 560 | points += [at, toward] | ||
| 561 | case .turnOver, .rotate, .repeatMark: | ||
| 562 | break | ||
| 563 | } | ||
| 564 | } | ||
| 565 | let low = points.reduce(points.first ?? .zero, simd_min) | ||
| 566 | let high = points.reduce(points.first ?? .zero, simd_max) | ||
| 567 | let area = CGRect(x: sideMargin, y: bottomMargin, width: side - 2 * sideMargin, height: side - bottomMargin - sideMargin) | ||
| 568 | let extent = simd_max(high - low, SIMD2(repeating: 1e-9)) | ||
| 569 | let scale = min(area.width / extent.x, area.height / extent.y) | ||
| 570 | let offset = SIMD2(area.midX, area.midY) - scale * (low + high) / 2 | ||
| 571 | func pixel(_ p: SIMD2<Double>) -> CGPoint { | ||
| 572 | let q = offset + scale * p | ||
| 573 | return CGPoint(x: q.x, y: q.y) | ||
| 574 | } | ||
| 575 | |||
| 576 | context.setLineJoin(.round) | ||
| 577 | let layers: [(DiagramLine, Double, Double, [Double])] = [ | ||
| 578 | (.light, style.lightWidth, style.lightGrey, []), | ||
| 579 | (.solid, style.outlineWidth, 0, []), | ||
| 580 | (.dashed, style.creaseWidth, 0, style.valleyDash), | ||
| 581 | (.dashDot, style.creaseWidth, 0, style.mountainDash), | ||
| 582 | ] | ||
| 583 | for (line, width, grey, dash) in layers { | ||
| 584 | context.setStrokeColor(gray: grey, alpha: 1) | ||
| 585 | context.setLineWidth(width) | ||
| 586 | context.setLineCap(dash.isEmpty ? .round : .butt) | ||
| 587 | context.setLineDash(phase: 0, lengths: dash.map { CGFloat($0) }) | ||
| 588 | for edge in diagram.edges where edge.style == line { | ||
| 589 | context.move(to: pixel(edge.from)) | ||
| 590 | context.addLine(to: pixel(edge.to)) | ||
| 591 | } | ||
| 592 | context.strokePath() | ||
| 593 | } | ||
| 594 | context.setLineDash(phase: 0, lengths: []) | ||
| 595 | context.setLineCap(.round) | ||
| 596 | context.setStrokeColor(gray: 0, alpha: 1) | ||
| 597 | context.setLineWidth(style.arrowWidth) | ||
| 598 | |||
| 599 | let repeated = diagram.arrows.contains { if case .repeatMark = $0 { true } else { false } } | ||
| 600 | let symbolCentre = SIMD2(side / 2, bottomMargin / 2) | ||
| 601 | for arrow in diagram.arrows { | ||
| 602 | switch arrow { | ||
| 603 | case let .valleyFold(from, over, to): | ||
| 604 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .filled, returnHead: false, tick: repeated) | ||
| 605 | case let .mountainFold(from, over, to): | ||
| 606 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowHalf, returnHead: false, tick: repeated) | ||
| 607 | case let .foldAndUnfold(from, over, to, mountain): | ||
| 608 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: mountain ? .hollowHalf : .filled, | ||
| 609 | returnHead: true, tick: repeated) | ||
| 610 | case let .technique(technique, at, toward): | ||
| 611 | let tip = vector(pixel(at)), direction = normalize(vector(pixel(toward)) - tip) | ||
| 612 | if technique == .petal { | ||
| 613 | let tail = tip - style.symbolSize * 1.5 * direction | ||
| 614 | let over = (tip + tail) / 2 + 0.3 * SIMD2(direction.y, -direction.x) * style.symbolSize * 1.5 | ||
| 615 | drawFoldArrow(context, style, point(tail), point(over), point(tip), head: .filled, returnHead: false, | ||
| 616 | tick: repeated) | ||
| 617 | } else { | ||
| 618 | drawPushArrow(context, style, tip: tip, direction: direction) | ||
| 619 | } | ||
| 620 | case let .turnOver(axis): | ||
| 621 | drawTurnOver(context, style, centre: symbolCentre, vertical: axis == .vertical) | ||
| 622 | case let .rotate(degrees): | ||
| 623 | drawRotate(context, style, centre: symbolCentre, degrees: degrees) | ||
| 624 | case .repeatMark: | ||
| 625 | break | ||
| 626 | } | ||
| 627 | } | ||
| 628 | return context.makeImage()! | ||
| 629 | } | ||
| 630 | |||
| 631 | private enum Head { case filled, hollowHalf, hollowFull } | ||
| 632 | |||
| 633 | private func vector(_ p: CGPoint) -> SIMD2<Double> { SIMD2(p.x, p.y) } | ||
| 634 | private func point(_ v: SIMD2<Double>) -> CGPoint { CGPoint(x: v.x, y: v.y) } | ||
| 635 | |||
| 636 | /// A quadratic arc from `from` through `over` to `to`, its head at `to`; with `returnHead` a | ||
| 637 | /// hollow head at `from` pointing back; with `tick` a stroke across the shaft near its tail. | ||
| 638 | private func drawFoldArrow(_ context: CGContext, _ style: DiagramStyle, _ from: CGPoint, _ over: CGPoint, _ to: CGPoint, | ||
| 639 | head: Head, returnHead: Bool, tick: Bool) { | ||
| 640 | let a = vector(from), m = vector(over), b = vector(to) | ||
| 641 | let control = 2 * m - (a + b) / 2 | ||
| 642 | context.move(to: from) | ||
| 643 | context.addQuadCurve(to: to, control: point(control)) | ||
| 644 | context.strokePath() | ||
| 645 | // the barb of a half head goes on the outside of the arc | ||
| 646 | let outside = m - (a + b) / 2 | ||
| 647 | drawHead(context, style, head, tip: b, direction: normalize(b - control), outside: outside) | ||
| 648 | if returnHead { | ||
| 649 | drawHead(context, style, .hollowFull, tip: a, direction: normalize(a - control), outside: outside) | ||
| 650 | } | ||
| 651 | if tick { | ||
| 652 | let t = 0.25 | ||
| 653 | let p = (1 - t) * (1 - t) * a + 2 * t * (1 - t) * control + t * t * b | ||
| 654 | let tangent = normalize(2 * (1 - t) * (control - a) + 2 * t * (b - control)) | ||
| 655 | let across = SIMD2(-tangent.y, tangent.x) * style.headLength / 2 | ||
| 656 | context.move(to: point(p - across)) | ||
| 657 | context.addLine(to: point(p + across)) | ||
| 658 | context.strokePath() | ||
| 659 | } | ||
| 660 | } | ||
| 661 | |||
| 662 | private func drawHead(_ context: CGContext, _ style: DiagramStyle, _ head: Head, tip: SIMD2<Double>, | ||
| 663 | direction: SIMD2<Double>, outside: SIMD2<Double>) { | ||
| 664 | let back = tip - style.headLength * direction | ||
| 665 | var across = SIMD2(-direction.y, direction.x) * style.headWidth / 2 | ||
| 666 | if dot(across, outside) < 0 { across = -across } | ||
| 667 | let corners: [SIMD2<Double>] | ||
| 668 | switch head { | ||
| 669 | case .filled, .hollowFull: corners = [tip, back + across, back - across] | ||
| 670 | case .hollowHalf: corners = [tip, back + 2 * across, back] | ||
| 671 | } | ||
| 672 | context.addLines(between: corners.map(point)) | ||
| 673 | context.closePath() | ||
| 674 | context.setFillColor(gray: head == .filled ? 0 : 1, alpha: 1) | ||
| 675 | context.drawPath(using: .fillStroke) | ||
| 676 | } | ||
| 677 | |||
| 678 | /// The hollow push arrow, its tip at `tip`, with a notched tail. | ||
| 679 | private func drawPushArrow(_ context: CGContext, _ style: DiagramStyle, tip: SIMD2<Double>, direction: SIMD2<Double>) { | ||
| 680 | let s = style.symbolSize | ||
| 681 | let outline: [SIMD2<Double>] = [ | ||
| 682 | SIMD2(0, 0), SIMD2(-0.36, 0.3), SIMD2(-0.36, 0.12), SIMD2(-1, 0.12), | ||
| 683 | SIMD2(-0.86, 0), SIMD2(-1, -0.12), SIMD2(-0.36, -0.12), SIMD2(-0.36, -0.3), | ||
| 684 | ] | ||
| 685 | let across = SIMD2(-direction.y, direction.x) | ||
| 686 | context.addLines(between: outline.map { point(tip + s * ($0.x * direction + $0.y * across)) }) | ||
| 687 | context.closePath() | ||
| 688 | context.setFillColor(gray: 1, alpha: 1) | ||
| 689 | context.drawPath(using: .fillStroke) | ||
| 690 | } | ||
| 691 | |||
| 692 | /// The loop-the-loop arrow: left to right for a turn about the vertical axis, bottom to top about | ||
| 693 | /// the horizontal. | ||
| 694 | private func drawTurnOver(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, vertical: Bool) { | ||
| 695 | // a prolate cycloid over one period, its loop above the line of travel, between straight tails | ||
| 696 | let a = style.symbolSize / (3 * .pi), b = 2 * a | ||
| 697 | let loop = (0...64).map { i -> SIMD2<Double> in | ||
| 698 | let u = -Double.pi + 2 * .pi * Double(i) / 64 | ||
| 699 | return SIMD2(a * u - b * sin(u), b * cos(u)) | ||
| 700 | } | ||
| 701 | let tail = SIMD2(style.symbolSize / 4, 0) | ||
| 702 | let path = [loop[0] - tail] + loop + [loop[64] + tail] | ||
| 703 | let place = { (p: SIMD2<Double>) in centre + (vertical ? p : SIMD2(-p.y, p.x)) } | ||
| 704 | context.addLines(between: path.map { point(place($0)) }) | ||
| 705 | context.strokePath() | ||
| 706 | let tip = place(path[path.count - 1]) | ||
| 707 | drawHead(context, style, .filled, tip: tip, direction: normalize(tip - place(loop[64])), outside: SIMD2(0, 1)) | ||
| 708 | } | ||
| 709 | |||
| 710 | /// Two arcs around a circle, counterclockwise for positive `degrees`, with the amount at the centre. | ||
| 711 | private func drawRotate(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, degrees: Double) { | ||
| 712 | let r = style.symbolSize / 2 | ||
| 713 | let turn = degrees >= 0 ? 1.0 : -1.0 | ||
| 714 | let headAngle = style.headLength / r | ||
| 715 | for start in [Double.pi * 0.6, Double.pi * 1.6] { | ||
| 716 | let end = start + turn * Double.pi * 0.75, back = end - turn * headAngle | ||
| 717 | context.addArc(center: point(centre), radius: r, startAngle: start, endAngle: back, clockwise: turn < 0) | ||
| 718 | context.strokePath() | ||
| 719 | let tip = centre + r * SIMD2(cos(end), sin(end)), base = centre + r * SIMD2(cos(back), sin(back)) | ||
| 720 | drawHead(context, style, .filled, tip: tip, direction: normalize(tip - base), outside: tip - centre) | ||
| 721 | } | ||
| 722 | let label = String(format: "%g°", abs(degrees)) | ||
| 723 | let font = CTFontCreateWithName("Helvetica" as CFString, 14, nil) | ||
| 724 | let text = NSAttributedString(string: label, attributes: [ | ||
| 725 | NSAttributedString.Key(kCTFontAttributeName as String): font, | ||
| 726 | NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true, | ||
| 727 | ]) | ||
| 728 | let line = CTLineCreateWithAttributedString(text) | ||
| 729 | let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds) | ||
| 730 | context.setFillColor(gray: 0, alpha: 1) | ||
| 731 | context.textPosition = CGPoint(x: centre.x - bounds.midX, y: centre.y - bounds.midY) | ||
| 732 | CTLineDraw(line, context) | ||
| 733 | } | ||
| 734 | |||
| 735 | /// Golden images differ from a render when any channel of any pixel differs by more than this, | ||
| 736 | /// out of 255. | ||
| 737 | private let snapshotTolerance = 24 | ||
| 738 | |||
| 739 | public enum SnapshotError: Error { | ||
| 740 | case unreadable(String) | ||
| 741 | } | ||
| 742 | |||
| 743 | /// Compares `image` with `Snapshots/<name>.png` beside the calling test file. Records the image | ||
| 744 | /// there, and fails saying so, when the golden is missing or `FOLD_RECORD_SNAPSHOTS=1`. | ||
| 745 | public func expectSnapshot(_ image: CGImage, named name: String, filePath: String = #filePath, | ||
| 746 | sourceLocation: SourceLocation = #_sourceLocation) throws { | ||
| 747 | let url = URL(fileURLWithPath: filePath).deletingLastPathComponent() | ||
| 748 | .appendingPathComponent("Snapshots").appendingPathComponent("\(name).png") | ||
| 749 | let recording = ProcessInfo.processInfo.environment["FOLD_RECORD_SNAPSHOTS"] == "1" | ||
| 750 | if recording || !FileManager.default.fileExists(atPath: url.path) { | ||
| 751 | try writePNG(image, to: url) | ||
| 752 | Issue.record("recorded \(url.path); inspect it and run again", sourceLocation: sourceLocation) | ||
| 753 | return | ||
| 754 | } | ||
| 755 | guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), | ||
| 756 | let golden = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw SnapshotError.unreadable(url.path) } | ||
| 757 | guard golden.width == image.width, golden.height == image.height else { | ||
| 758 | Issue.record("\(name): \(image.width)×\(image.height), golden \(golden.width)×\(golden.height)", | ||
| 759 | sourceLocation: sourceLocation) | ||
| 760 | return | ||
| 761 | } | ||
| 762 | let (rendered, expected) = (rgba(image), rgba(golden)) | ||
| 763 | var pixels = 0, first: Int? | ||
| 764 | for p in 0..<(image.width * image.height) { | ||
| 765 | let differs = (0..<4).contains { abs(Int(rendered[4 * p + $0]) - Int(expected[4 * p + $0])) > snapshotTolerance } | ||
| 766 | if differs { | ||
| 767 | pixels += 1 | ||
| 768 | first = first ?? p | ||
| 769 | } | ||
| 770 | } | ||
| 771 | if let first { | ||
| 772 | let actual = FileManager.default.temporaryDirectory.appendingPathComponent("\(name).png") | ||
| 773 | try writePNG(image, to: actual) | ||
| 774 | let x = first % image.width, y = first / image.width | ||
| 775 | Issue.record("\(name): \(pixels) pixels differ from the golden image, first at (\(x), \(y)); this render is at \(actual.path)", | ||
| 776 | sourceLocation: sourceLocation) | ||
| 777 | } | ||
| 778 | } | ||
| 779 | |||
| 780 | private func writePNG(_ image: CGImage, to url: URL) throws { | ||
| 781 | guard let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else { | ||
| 782 | throw SnapshotError.unreadable(url.path) | ||
| 783 | } | ||
| 784 | CGImageDestinationAddImage(destination, image, nil) | ||
| 785 | guard CGImageDestinationFinalize(destination) else { throw SnapshotError.unreadable(url.path) } | ||
| 786 | } | ||
| 787 | |||
| 788 | /// The image's pixels as 8-bit premultiplied RGBA in sRGB, row by row from the top. | ||
| 789 | private func rgba(_ image: CGImage) -> [UInt8] { | ||
| 790 | var bytes = [UInt8](repeating: 0, count: image.width * image.height * 4) | ||
| 791 | bytes.withUnsafeMutableBytes { buffer in | ||
| 792 | let context = CGContext(data: buffer.baseAddress, width: image.width, height: image.height, bitsPerComponent: 8, | ||
| 793 | bytesPerRow: image.width * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!, | ||
| 794 | bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! | ||
| 795 | context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) | ||
| 796 | } | ||
| 797 | return bytes | ||
| 798 | } | ||
Packages/FoldKit/Sources/Notation/DiagramBuilder.swift added +249
| @@ -0,0 +1,249 @@ | |||
| 1 | import FoldFormat | ||
| 2 | import Folding | ||
| 3 | import simd | ||
| 4 | |||
| 5 | public enum DiagramLine: Equatable, Sendable { | ||
| 6 | /// `B` edges and creases folded in the drawn frame. | ||
| 7 | case solid | ||
| 8 | /// Creases made in an earlier step and flat again. | ||
| 9 | case light | ||
| 10 | /// The step's valley, as seen. | ||
| 11 | case dashed | ||
| 12 | /// The step's mountain, as seen. | ||
| 13 | case dashDot | ||
| 14 | } | ||
| 15 | |||
| 16 | /// A diagram symbol in screen coordinates, the drawn frame projected along the step's viewpoint | ||
| 17 | /// in the sheet's units. A fold arrow curves from `from`, a point of the moving set before the | ||
| 18 | /// step, through `over`, the apex of its arc, to `to`, the same point after the fold (at the peak | ||
| 19 | /// for a fold-and-unfold). | ||
| 20 | public enum DiagramArrow: Equatable, Sendable { | ||
| 21 | case valleyFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>) | ||
| 22 | case mountainFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>) | ||
| 23 | case foldAndUnfold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>, mountain: Bool) | ||
| 24 | /// The technique's symbol at the midpoint of the step's first crease, pointing toward where | ||
| 25 | /// that axis's moving set ends. | ||
| 26 | case technique(StepTechnique, at: SIMD2<Double>, toward: SIMD2<Double>) | ||
| 27 | case turnOver(TurnOverAxis) | ||
| 28 | /// Counterclockwise as seen when positive. | ||
| 29 | case rotate(degrees: Double) | ||
| 30 | /// The step repeats step `of`. | ||
| 31 | case repeatMark(of: Int) | ||
| 32 | } | ||
| 33 | |||
| 34 | /// A visible piece of FOLD edge `edge`, in the arrows' screen coordinates. | ||
| 35 | public struct DiagramEdge: Equatable, Sendable { | ||
| 36 | public let edge: Int | ||
| 37 | public let from: SIMD2<Double> | ||
| 38 | public let to: SIMD2<Double> | ||
| 39 | public let style: DiagramLine | ||
| 40 | |||
| 41 | public init(edge: Int, from: SIMD2<Double>, to: SIMD2<Double>, style: DiagramLine) { | ||
| 42 | self.edge = edge | ||
| 43 | self.from = from | ||
| 44 | self.to = to | ||
| 45 | self.style = style | ||
| 46 | } | ||
| 47 | } | ||
| 48 | |||
| 49 | /// Edges in FOLD edge order. | ||
| 50 | public struct Diagram: Equatable, Sendable { | ||
| 51 | public let edges: [DiagramEdge] | ||
| 52 | public let arrows: [DiagramArrow] | ||
| 53 | |||
| 54 | public init(edges: [DiagramEdge], arrows: [DiagramArrow]) { | ||
| 55 | self.edges = edges | ||
| 56 | self.arrows = arrows | ||
| 57 | } | ||
| 58 | } | ||
| 59 | |||
| 60 | /// The arc's apex lies this fraction of the chord from the chord's midpoint. | ||
| 61 | private let arcBulge = 0.3 | ||
| 62 | |||
| 63 | /// The diagram for step `step.index`: frame `step.index − 1` seen orthographically from the | ||
| 64 | /// step's viewpoint, with the step's creases and symbols. | ||
| 65 | /// | ||
| 66 | /// Edges whose `edges_krz:firstCreasedAtStep` is later than the step, and subdivision edges, are | ||
| 67 | /// not drawn. An edge the step creases (its two faces move differently) is dashed for a valley as | ||
| 68 | /// seen and dash-dot for a mountain, whatever its assignment; other `B` edges and folded creases | ||
| 69 | /// are solid; earlier creases flat again are light. Each edge is clipped by `visibleSegments`, and | ||
| 70 | /// a piece coincident with one already drawn is drawn once, step creases before solid before light. | ||
| 71 | /// | ||
| 72 | /// - Precondition: `validate(file)` is empty. | ||
| 73 | public func buildDiagram(file: FoldFile, step: FoldStep) -> Diagram { | ||
| 74 | let n = step.index | ||
| 75 | let frame = file.frames[n - 1] | ||
| 76 | let normals = faceNormals(frame, file) | ||
| 77 | // a validated frame's orders have no cycle | ||
| 78 | let order = try! LayerOrder(faceOrders: frame.faceOrders, normals: normals) | ||
| 79 | let occlusion = Occlusion(frame: frame, file: file, order: order, viewpoint: step.viewpoint) | ||
| 80 | let eye = step.viewpoint.eye | ||
| 81 | |||
| 82 | let valley = step.axes.map { axis -> Bool in | ||
| 83 | let face = occlusion.edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }! | ||
| 84 | let turn = (step.kind == .foldAndUnfold ? axis.peakAngle ?? axis.endAngle : axis.endAngle) - axis.startAngle | ||
| 85 | return turn * dot(normals[face], eye) > 0 | ||
| 86 | } | ||
| 87 | let creasing = creasingAxes(step, faceCount: file.facesVertices.count, edgeFaces: occlusion.edgeFaces) | ||
| 88 | |||
| 89 | var candidates: [(edge: Int, style: DiagramLine, rank: Int)] = [] | ||
| 90 | for e in file.edgesVertices.indices { | ||
| 91 | let created = file.edgesFirstCreasedAtStep[e] | ||
| 92 | if let created, created > n { continue } | ||
| 93 | if frame.edgesAssignment[e] == .boundary { | ||
| 94 | candidates.append((e, .solid, 1)) | ||
| 95 | } else if created == nil { | ||
| 96 | continue | ||
| 97 | } else if let axis = creasing[e] { | ||
| 98 | candidates.append((e, valley[axis] ? .dashed : .dashDot, 0)) | ||
| 99 | } else if abs(frame.edgesFoldAngle[e]) > 1e-9 { | ||
| 100 | candidates.append((e, .solid, 1)) | ||
| 101 | } else if created! < n { | ||
| 102 | candidates.append((e, .light, 2)) | ||
| 103 | } | ||
| 104 | } | ||
| 105 | candidates.sort { ($0.rank, $0.edge) < ($1.rank, $1.edge) } | ||
| 106 | |||
| 107 | var drawn: [DiagramEdge] = [] | ||
| 108 | for c in candidates { | ||
| 109 | for (a, b) in occlusion.visibleSegments(of: c.edge) { | ||
| 110 | for (p, q) in uncovered(a, b, by: drawn, tolerance: occlusion.tolerance) { | ||
| 111 | drawn.append(DiagramEdge(edge: c.edge, from: p, to: q, style: c.style)) | ||
| 112 | } | ||
| 113 | } | ||
| 114 | } | ||
| 115 | let edges = drawn.enumerated().sorted { ($0.element.edge, $0.offset) < ($1.element.edge, $1.offset) }.map(\.element) | ||
| 116 | let symbols = arrows(file, step, valley: valley, project: ViewProjection(step.viewpoint), | ||
| 117 | edgeFaces: occlusion.edgeFaces) | ||
| 118 | return Diagram(edges: edges, arrows: symbols) | ||
| 119 | } | ||
| 120 | |||
| 121 | /// For each edge, the index in `step.axes` of the axis whose motion creases it, or nil. Each face | ||
| 122 | /// belongs to the axis whose moving set holds it, or to the fixed group; an edge is creased when | ||
| 123 | /// its faces' groups differ, by the deeper group's axis. | ||
| 124 | private func creasingAxes(_ step: FoldStep, faceCount: Int, edgeFaces: [[Int]]) -> [Int?] { | ||
| 125 | var group = Array<Int?>(repeating: nil, count: faceCount) | ||
| 126 | for (i, axis) in step.axes.enumerated() { | ||
| 127 | for f in axis.movingFaces { group[f] = i } | ||
| 128 | } | ||
| 129 | func depth(_ axis: Int?) -> Int { | ||
| 130 | guard let axis else { return -1 } | ||
| 131 | return 1 + depth(step.axes[axis].parent) | ||
| 132 | } | ||
| 133 | return edgeFaces.map { faces in | ||
| 134 | guard faces.count == 2, group[faces[0]] != group[faces[1]] else { return nil } | ||
| 135 | let (a, b) = (group[faces[0]], group[faces[1]]) | ||
| 136 | return depth(a) >= depth(b) ? a : b | ||
| 137 | } | ||
| 138 | } | ||
| 139 | |||
| 140 | /// The parts of `a`–`b` not lying along an edge already drawn. | ||
| 141 | private func uncovered(_ a: SIMD2<Double>, _ b: SIMD2<Double>, by drawn: [DiagramEdge], | ||
| 142 | tolerance: Double) -> [(SIMD2<Double>, SIMD2<Double>)] { | ||
| 143 | let d = b - a, length2 = length_squared(d) | ||
| 144 | let normal = normalize(SIMD2(-d.y, d.x)) | ||
| 145 | var covered: [ClosedRange<Double>] = [] | ||
| 146 | for e in drawn where abs(dot(e.from - a, normal)) <= tolerance && abs(dot(e.to - a, normal)) <= tolerance { | ||
| 147 | let s = dot(e.from - a, d) / length2, t = dot(e.to - a, d) / length2 | ||
| 148 | let low = max(min(s, t), 0), high = min(max(s, t), 1) | ||
| 149 | if high > low { covered.append(low...high) } | ||
| 150 | } | ||
| 151 | var pieces: [ClosedRange<Double>] = [] | ||
| 152 | var start = 0.0 | ||
| 153 | for range in covered.sorted(by: { $0.lowerBound < $1.lowerBound }) { | ||
| 154 | if range.lowerBound > start { pieces.append(start...range.lowerBound) } | ||
| 155 | start = max(start, range.upperBound) | ||
| 156 | } | ||
| 157 | if start < 1 { pieces.append(start...1) } | ||
| 158 | let minimum = tolerance / length2.squareRoot() | ||
| 159 | return pieces.filter { $0.upperBound - $0.lowerBound > minimum } | ||
| 160 | .map { (a + $0.lowerBound * d, a + $0.upperBound * d) } | ||
| 161 | } | ||
| 162 | |||
| 163 | private func arrows(_ file: FoldFile, _ step: FoldStep, valley: [Bool], project: ViewProjection, | ||
| 164 | edgeFaces: [[Int]]) -> [DiagramArrow] { | ||
| 165 | var arrows: [DiagramArrow] = [] | ||
| 166 | let start = file.frames[step.index - 1].verticesCoords | ||
| 167 | switch step.kind { | ||
| 168 | case .turnOver: | ||
| 169 | if let axis = step.turnOverAxis { arrows.append(.turnOver(axis)) } | ||
| 170 | case .rotate: | ||
| 171 | if let degrees = step.rotateDegrees { arrows.append(.rotate(degrees: degrees)) } | ||
| 172 | case .fold, .foldAndUnfold: | ||
| 173 | let interpolator = step.kind == .foldAndUnfold ? FoldInterpolator(file: file, step: step) : nil | ||
| 174 | // a point of the axis's moving set and where it is at the end of the step, or at the peak | ||
| 175 | func track(_ axis: FoldAxis, _ point: SIMD3<Double>) -> (SIMD2<Double>, SIMD2<Double>) { | ||
| 176 | let end = interpolator?.positions(at: (axis.window.lowerBound + axis.window.upperBound) / 2) | ||
| 177 | ?? file.frames[step.index].verticesCoords | ||
| 178 | let face = edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }! | ||
| 179 | return (project(point), project(carried(point, with: file.facesVertices[face], from: start, to: end))) | ||
| 180 | } | ||
| 181 | if step.technique != .plain { | ||
| 182 | guard let axis = step.axes.first else { break } | ||
| 183 | let ends = file.edgesVertices[axis.edge].map { project(start[$0]) } | ||
| 184 | let toward = track(axis, centroid(of: axis.movingFaces, file, positions: start)).1 | ||
| 185 | arrows.append(.technique(step.technique, at: (ends[0] + ends[1]) / 2, toward: toward)) | ||
| 186 | break | ||
| 187 | } | ||
| 188 | // simultaneous arrows are spread along their creases, in one screen direction, so that | ||
| 189 | // they do not meet | ||
| 190 | let count = Double(step.axes.count) | ||
| 191 | for (i, axis) in step.axes.enumerated() { | ||
| 192 | let ends = file.edgesVertices[axis.edge].map { start[$0] } | ||
| 193 | let shift = (Double(i) - (count - 1) / 2) / (count + 1) * distance(ends[0], ends[1]) | ||
| 194 | let along = project(axis.direction) | ||
| 195 | let sign = along.y < -1e-9 || (abs(along.y) <= 1e-9 && along.x < 0) ? -1.0 : 1.0 | ||
| 196 | let point = centroid(of: axis.movingFaces, file, positions: start) + sign * shift * axis.direction | ||
| 197 | let (from, to) = track(axis, point) | ||
| 198 | let over = apex(from, to) | ||
| 199 | if step.kind == .foldAndUnfold { | ||
| 200 | arrows.append(.foldAndUnfold(from: from, over: over, to: to, mountain: !valley[i])) | ||
| 201 | } else if valley[i] { | ||
| 202 | arrows.append(.valleyFold(from: from, over: over, to: to)) | ||
| 203 | } else { | ||
| 204 | arrows.append(.mountainFold(from: from, over: over, to: to)) | ||
| 205 | } | ||
| 206 | } | ||
| 207 | } | ||
| 208 | if let repeated = step.repeatOf { arrows.append(.repeatMark(of: repeated)) } | ||
| 209 | return arrows | ||
| 210 | } | ||
| 211 | |||
| 212 | /// The area-weighted mean of the faces' vertex means. | ||
| 213 | private func centroid(of faces: Set<Int>, _ file: FoldFile, positions: [SIMD3<Double>]) -> SIMD3<Double> { | ||
| 214 | var sum = SIMD3<Double>.zero, total = 0.0 | ||
| 215 | for f in faces.sorted() { | ||
| 216 | let corners = file.facesVertices[f].map { positions[$0] } | ||
| 217 | let area = length(corners.indices.reduce(SIMD3<Double>.zero) { s, i in | ||
| 218 | s + simd.cross(corners[i], corners[(i + 1) % corners.count]) | ||
| 219 | }) / 2 | ||
| 220 | sum += area * corners.reduce(.zero, +) / Double(corners.count) | ||
| 221 | total += area | ||
| 222 | } | ||
| 223 | return sum / total | ||
| 224 | } | ||
| 225 | |||
| 226 | /// `point` moved rigidly with the face whose corners are `corners`, from `start` to `end`. | ||
| 227 | private func carried(_ point: SIMD3<Double>, with corners: [Int], from start: [SIMD3<Double>], | ||
| 228 | to end: [SIMD3<Double>]) -> SIMD3<Double> { | ||
| 229 | let o = start[corners[0]], u = start[corners[1]] - o | ||
| 230 | // the corner farthest from the line of the first two spans the face's plane best | ||
| 231 | let spread = { (i: Int) in length(cross(u, start[corners[i]] - o)) } | ||
| 232 | let k = corners.indices.dropFirst(2).max { spread($0) < spread($1) }! | ||
| 233 | func basis(_ x: [SIMD3<Double>]) -> simd_double3x3 { | ||
| 234 | let e1 = x[corners[1]] - x[corners[0]], e2 = x[corners[k]] - x[corners[0]] | ||
| 235 | return simd_double3x3(columns: (e1, e2, normalize(cross(e1, e2)))) | ||
| 236 | } | ||
| 237 | return end[corners[0]] + basis(end) * (basis(start).inverse * (point - o)) | ||
| 238 | } | ||
| 239 | |||
| 240 | /// The apex of an arc from `from` to `to`, to the side of the chord toward screen-up, or toward | ||
| 241 | /// screen-right for a vertical chord. | ||
| 242 | private func apex(_ from: SIMD2<Double>, _ to: SIMD2<Double>) -> SIMD2<Double> { | ||
| 243 | let chord = to - from | ||
| 244 | var side = SIMD2(-chord.y, chord.x) | ||
| 245 | if side.y < -1e-12 * length(chord) || (abs(side.y) <= 1e-12 * length(chord) && side.x < 0) { | ||
| 246 | side = -side | ||
| 247 | } | ||
| 248 | return (from + to) / 2 + arcBulge * side | ||
| 249 | } | ||
Packages/FoldKit/Sources/Notation/DiagramStyle.swift added +43
| @@ -0,0 +1,43 @@ | |||
| 1 | /// How a `Diagram` is drawn. Lengths are in points; `lightGrey` is a grey level, 0 black to 1 white. | ||
| 2 | /// | ||
| 3 | /// `NOTATION.md` beside the golden images records the source of each choice. | ||
| 4 | public struct DiagramStyle: Sendable { | ||
| 5 | /// `B` edges and creases folded in the drawn frame. | ||
| 6 | public var outlineWidth: Double | ||
| 7 | /// Creases made earlier and flat again. | ||
| 8 | public var lightWidth: Double | ||
| 9 | public var lightGrey: Double | ||
| 10 | /// The step's own creases. | ||
| 11 | public var creaseWidth: Double | ||
| 12 | /// Dash, gap: a valley. | ||
| 13 | public var valleyDash: [Double] | ||
| 14 | /// Dash, gap, dot, gap, dot, gap: a mountain, drawn with butt caps. | ||
| 15 | public var mountainDash: [Double] | ||
| 16 | public var arrowWidth: Double | ||
| 17 | public var headLength: Double | ||
| 18 | /// The full head's width; a half head has one barb of half this. | ||
| 19 | public var headWidth: Double | ||
| 20 | /// The longer side of the push arrow and of the turn-over and rotate symbols. | ||
| 21 | public var symbolSize: Double | ||
| 22 | |||
| 23 | public init(outlineWidth: Double, lightWidth: Double, lightGrey: Double, creaseWidth: Double, | ||
| 24 | valleyDash: [Double], mountainDash: [Double], arrowWidth: Double, headLength: Double, | ||
| 25 | headWidth: Double, symbolSize: Double) { | ||
| 26 | self.outlineWidth = outlineWidth | ||
| 27 | self.lightWidth = lightWidth | ||
| 28 | self.lightGrey = lightGrey | ||
| 29 | self.creaseWidth = creaseWidth | ||
| 30 | self.valleyDash = valleyDash | ||
| 31 | self.mountainDash = mountainDash | ||
| 32 | self.arrowWidth = arrowWidth | ||
| 33 | self.headLength = headLength | ||
| 34 | self.headWidth = headWidth | ||
| 35 | self.symbolSize = symbolSize | ||
| 36 | } | ||
| 37 | |||
| 38 | public static let standard = DiagramStyle( | ||
| 39 | outlineWidth: 2, lightWidth: 1, lightGrey: 0.6, creaseWidth: 1.5, | ||
| 40 | valleyDash: [7, 4], mountainDash: [9, 3, 2, 3, 2, 3], | ||
| 41 | arrowWidth: 1.5, headLength: 14, headWidth: 10, symbolSize: 60 | ||
| 42 | ) | ||
| 43 | } | ||
Packages/FoldKit/Sources/Notation/EdgeOcclusion.swift added +133
| @@ -0,0 +1,133 @@ | |||
| 1 | import FoldFormat | ||
| 2 | import Folding | ||
| 3 | import simd | ||
| 4 | |||
| 5 | /// The parts of `edge`, projected orthographically along `viewpoint`, that are not inside the | ||
| 6 | /// union of the faces above either of its faces in `frame`. | ||
| 7 | /// | ||
| 8 | /// A face is above an edge's face when it follows that face in their cluster's back-to-front list, | ||
| 9 | /// `order.clusters` read looking along −`eye`; faces in other clusters do not occlude. An edge on | ||
| 10 | /// the outer boundary of the union stays visible; one under the seam between two upper faces, | ||
| 11 | /// covered on both sides, does not. | ||
| 12 | public func visibleSegments(of edge: Int, frame: FoldFrame, file: FoldFile, order: LayerOrder, | ||
| 13 | viewpoint: Viewpoint) -> [(SIMD2<Double>, SIMD2<Double>)] { | ||
| 14 | Occlusion(frame: frame, file: file, order: order, viewpoint: viewpoint).visibleSegments(of: edge) | ||
| 15 | } | ||
| 16 | |||
| 17 | /// Orthographic projection onto the screen plane of a viewpoint: x along `right`, y along `up`. | ||
| 18 | struct ViewProjection { | ||
| 19 | let right: SIMD3<Double> | ||
| 20 | let up: SIMD3<Double> | ||
| 21 | |||
| 22 | init(_ viewpoint: Viewpoint) { | ||
| 23 | let eye = normalize(viewpoint.eye) | ||
| 24 | right = normalize(cross(viewpoint.up, eye)) | ||
| 25 | up = cross(eye, right) | ||
| 26 | } | ||
| 27 | |||
| 28 | func callAsFunction(_ p: SIMD3<Double>) -> SIMD2<Double> { | ||
| 29 | SIMD2(dot(p, right), dot(p, up)) | ||
| 30 | } | ||
| 31 | } | ||
| 32 | |||
| 33 | /// One frame projected for a viewpoint, with each face's occluders. | ||
| 34 | struct Occlusion { | ||
| 35 | let points: [SIMD2<Double>] | ||
| 36 | let edgesVertices: [[Int]] | ||
| 37 | let edgeFaces: [[Int]] | ||
| 38 | /// Each face's projected outline, counterclockwise. | ||
| 39 | let outlines: [[SIMD2<Double>]] | ||
| 40 | /// Each face's followers in its cluster. | ||
| 41 | let above: [[Int]] | ||
| 42 | let tolerance: Double | ||
| 43 | |||
| 44 | init(frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) { | ||
| 45 | let project = ViewProjection(viewpoint) | ||
| 46 | let points = frame.verticesCoords.map(project.callAsFunction) | ||
| 47 | self.points = points | ||
| 48 | edgesVertices = file.edgesVertices | ||
| 49 | edgeFaces = edgesFaces(file) | ||
| 50 | outlines = file.facesVertices.map { corners in | ||
| 51 | let outline = corners.map { points[$0] } | ||
| 52 | return signedArea(outline) < 0 ? outline.reversed() : outline | ||
| 53 | } | ||
| 54 | var above = Array(repeating: [Int](), count: file.facesVertices.count) | ||
| 55 | let clusters = order.clusters(positions: frame.verticesCoords, faces: file.facesVertices, | ||
| 56 | viewDirection: -viewpoint.eye) | ||
| 57 | for cluster in clusters { | ||
| 58 | for (i, face) in cluster.faces.enumerated() { | ||
| 59 | above[face] = Array(cluster.faces[(i + 1)...]) | ||
| 60 | } | ||
| 61 | } | ||
| 62 | self.above = above | ||
| 63 | let low = points.reduce(points.first ?? .zero, simd_min) | ||
| 64 | let high = points.reduce(points.first ?? .zero, simd_max) | ||
| 65 | tolerance = max(length(high - low), 1) * 1e-9 | ||
| 66 | } | ||
| 67 | |||
| 68 | func endpoints(of edge: Int) -> (SIMD2<Double>, SIMD2<Double>) { | ||
| 69 | (points[edgesVertices[edge][0]], points[edgesVertices[edge][1]]) | ||
| 70 | } | ||
| 71 | |||
| 72 | func visibleSegments(of edge: Int) -> [(SIMD2<Double>, SIMD2<Double>)] { | ||
| 73 | let (a, b) = endpoints(of: edge) | ||
| 74 | guard length(b - a) > tolerance else { return [] } | ||
| 75 | let occluders = Set(edgeFaces[edge].flatMap { above[$0] }) | ||
| 76 | let covers = occluders.sorted().compactMap { cover(a, b, by: outlines[$0]) } | ||
| 77 | |||
| 78 | // between consecutive cut points coverage is constant; test each piece's midpoint | ||
| 79 | let cuts = Set([0.0, 1.0] + covers.flatMap { [$0.range.lowerBound, $0.range.upperBound] }).sorted() | ||
| 80 | var visible: [ClosedRange<Double>] = [] | ||
| 81 | for (t0, t1) in zip(cuts, cuts.dropFirst()) where t1 > t0 { | ||
| 82 | let t = (t0 + t1) / 2 | ||
| 83 | let sides = covers.filter { $0.range.contains(t) }.map(\.side) | ||
| 84 | let hidden = sides.contains(.both) || (sides.contains(.left) && sides.contains(.right)) | ||
| 85 | if hidden { continue } | ||
| 86 | if let last = visible.last, last.upperBound == t0 { | ||
| 87 | visible[visible.count - 1] = last.lowerBound...t1 | ||
| 88 | } else { | ||
| 89 | visible.append(t0...t1) | ||
| 90 | } | ||
| 91 | } | ||
| 92 | let minimum = tolerance / length(b - a) | ||
| 93 | return visible.filter { $0.upperBound - $0.lowerBound > minimum } | ||
| 94 | .map { (a + $0.lowerBound * (b - a), a + $0.upperBound * (b - a)) } | ||
| 95 | } | ||
| 96 | |||
| 97 | enum Side { case left, right, both } | ||
| 98 | |||
| 99 | /// The parameters of the segment `a`–`b` the counterclockwise convex `polygon` covers, and on | ||
| 100 | /// which side: both sides where the segment crosses its open interior, one side where the | ||
| 101 | /// segment lies along one of its sides. | ||
| 102 | private func cover(_ a: SIMD2<Double>, _ b: SIMD2<Double>, | ||
| 103 | by polygon: [SIMD2<Double>]) -> (range: ClosedRange<Double>, side: Side)? { | ||
| 104 | let d = b - a | ||
| 105 | var low = 0.0, high = 1.0 | ||
| 106 | var side = Side.both | ||
| 107 | for i in polygon.indices { | ||
| 108 | let p = polygon[i], s = polygon[(i + 1) % polygon.count] - p | ||
| 109 | let sideLength = length(s) | ||
| 110 | guard sideLength > tolerance else { continue } | ||
| 111 | // distance inside this side's line at parameter t: c0 + c1 t | ||
| 112 | let c0 = perpDot(s, a - p) / sideLength, c1 = perpDot(s, d) / sideLength | ||
| 113 | if abs(c0) <= tolerance && abs(c0 + c1) <= tolerance { | ||
| 114 | side = dot(s, d) > 0 ? .left : .right | ||
| 115 | continue | ||
| 116 | } | ||
| 117 | if c1 == 0 { | ||
| 118 | if c0 <= 0 { return nil } | ||
| 119 | } else if c1 > 0 { | ||
| 120 | low = max(low, -c0 / c1) | ||
| 121 | } else { | ||
| 122 | high = min(high, -c0 / c1) | ||
| 123 | } | ||
| 124 | } | ||
| 125 | return high - low > tolerance / length(d) ? (low...high, side) : nil | ||
| 126 | } | ||
| 127 | } | ||
| 128 | |||
| 129 | func perpDot(_ u: SIMD2<Double>, _ v: SIMD2<Double>) -> Double { u.x * v.y - u.y * v.x } | ||
| 130 | |||
| 131 | func signedArea(_ p: [SIMD2<Double>]) -> Double { | ||
| 132 | p.indices.reduce(0) { sum, i in sum + perpDot(p[i], p[(i + 1) % p.count]) / 2 } | ||
| 133 | } | ||
Packages/FoldKit/Tests/NotationTests/DiagramTests.swift added +96
| @@ -0,0 +1,96 @@ | |||
| 1 | import Testing | ||
| 2 | import FoldFormat | ||
| 3 | import Folding | ||
| 4 | import Models | ||
| 5 | import Notation | ||
| 6 | import FoldKitTestSupport | ||
| 7 | |||
| 8 | @Test func valleyCreaseOfThisStepIsDashed() throws { | ||
| 9 | #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .dashed }.map(\.edge) == [6]) | ||
| 10 | } | ||
| 11 | |||
| 12 | @Test func mountainCreaseOfThisStepIsDashDot() throws { | ||
| 13 | #expect(try diagram("mountain.fold", step: 1).edges.filter { $0.style == .dashDot }.map(\.edge) == [6]) | ||
| 14 | } | ||
| 15 | |||
| 16 | @Test func valleyAndMountainAreAsSeenNotAsAssigned() throws { | ||
| 17 | // quarters step 3 folds both layers; the top layer is flipped, so its edge e9 is | ||
| 18 | // assigned M, but the fold is a valley as seen and nothing is dash-dot | ||
| 19 | let d = try diagram("quarters.fold", step: 3) | ||
| 20 | #expect(d.edges.contains { $0.style == .dashed }) | ||
| 21 | #expect(!d.edges.contains { $0.style == .dashDot }) | ||
| 22 | #expect(d.arrows.contains { if case .valleyFold = $0 { true } else { false } }) | ||
| 23 | } | ||
| 24 | |||
| 25 | @Test func anEdgeUnderASeamIsHidden() throws { | ||
| 26 | // quarters step 3 draws frame 2: e8 lies under the seam between f3 and f2 | ||
| 27 | #expect(try !diagram("quarters.fold", step: 3).edges.contains { $0.edge == 8 }) | ||
| 28 | } | ||
| 29 | |||
| 30 | @Test func boundaryEdgesAreSolid() throws { | ||
| 31 | #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .solid }.count == 6) | ||
| 32 | } | ||
| 33 | |||
| 34 | @Test func aCreaseMadeEarlierAndFlatAgainIsLight() throws { | ||
| 35 | // quarters step 2 draws frame 1, after the fold-and-unfold on x = 1 | ||
| 36 | #expect(Set(try diagram("quarters.fold", step: 2).edges.filter { $0.style == .light }.map(\.edge)) == [8, 9]) | ||
| 37 | } | ||
| 38 | |||
| 39 | @Test func creasesNotYetMetAreNotDrawnAtAll() throws { | ||
| 40 | // frame 0 carries the y = 1 creases too; step 1's diagram must not show them | ||
| 41 | #expect(try diagram("quarters.fold", step: 1).edges.allSatisfy { ![10, 11].contains($0.edge) }) | ||
| 42 | } | ||
| 43 | |||
| 44 | @Test func edgesOccludedByLayersAboveThemAreOmitted() throws { | ||
| 45 | // occlusion step 3 draws frame 2: f0's raw edge from (2,2) to (2,0) is under the strip | ||
| 46 | #expect(try !diagram("occlusion.fold", step: 3).edges.contains { $0.edge == 0 }) | ||
| 47 | } | ||
| 48 | |||
| 49 | @Test func anEdgePartlyOccludedIsClippedNotDropped() throws { | ||
| 50 | // f0's raw edge from (0,2) to (2,2) is covered for x in [1, 2] | ||
| 51 | let segments = try visibleSegmentsOf("occlusion.fold", edge: 7, inFrame: 2) | ||
| 52 | #expect(segments.count == 1) | ||
| 53 | #expect(abs(segmentLength(segments[0]) - 1) < 1e-9) | ||
| 54 | } | ||
| 55 | |||
| 56 | @Test func aPlainMultiAxisStepGetsOneArrowPerAxis() throws { | ||
| 57 | let arrows = try diagram("letter.fold", step: 1).arrows | ||
| 58 | #expect(arrows.filter { if case .valleyFold = $0 { true } else { false } }.count == 1) | ||
| 59 | #expect(arrows.filter { if case .mountainFold = $0 { true } else { false } }.count == 1) | ||
| 60 | } | ||
| 61 | |||
| 62 | @Test func aTechniqueStepGetsItsOwnArrowsNotOnePerAxis() throws { | ||
| 63 | let arrows = try diagram("letter-technique.fold", step: 1).arrows | ||
| 64 | #expect(arrows.filter { if case .technique(.insideReverse, _, _) = $0 { true } else { false } }.count == 1) | ||
| 65 | #expect(!arrows.contains { if case .valleyFold = $0 { true } else if case .mountainFold = $0 { true } else { false } }) | ||
| 66 | } | ||
| 67 | |||
| 68 | @Test func foldAndUnfoldStepGetsTheReturnHead() throws { | ||
| 69 | #expect(try diagram("quarters.fold", step: 1).arrows | ||
| 70 | .contains { if case .foldAndUnfold = $0 { true } else { false } }) | ||
| 71 | } | ||
| 72 | |||
| 73 | @Test func turnOverStepCarriesTheTurnOverSymbol() throws { | ||
| 74 | #expect(try diagram("half.fold", step: 2).arrows.contains(.turnOver(.vertical))) | ||
| 75 | } | ||
| 76 | |||
| 77 | @Test func rotateStepCarriesItsDegrees() throws { | ||
| 78 | #expect(try diagram("half.fold", step: 3).arrows.contains(.rotate(degrees: 90))) | ||
| 79 | } | ||
| 80 | |||
| 81 | @Test func aRepeatedStepCarriesTheRepeatMark() throws { | ||
| 82 | #expect(try diagram("letter-sequential.fold", step: 2).arrows.contains(.repeatMark(of: 1))) | ||
| 83 | } | ||
| 84 | |||
| 85 | @Test func everyStepMatchesItsGoldenImage() throws { | ||
| 86 | for name in ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"] { | ||
| 87 | let file = try FoldFile(contentsOf: fixture("\(name).fold")) | ||
| 88 | for step in try readSteps(file) { | ||
| 89 | try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)") | ||
| 90 | } | ||
| 91 | } | ||
| 92 | let cup = try ModelLibrary.model(named: "cup") | ||
| 93 | for step in try readSteps(cup) { | ||
| 94 | try expectSnapshot(render(buildDiagram(file: cup, step: step)), named: "cup-\(step.index)") | ||
| 95 | } | ||
| 96 | } | ||
Packages/FoldKit/Tests/NotationTests/Snapshots/NOTATION.md added +36
| @@ -0,0 +1,36 @@ | |||
| 1 | # Notation | ||
| 2 | |||
| 3 | Symbols drawn by `buildDiagram` and the test renderer, with their source. The reference is | ||
| 4 | Randlett's conventions in *The Art of Origami* (1961) and the symbol set as summarised by | ||
| 5 | OrigamiUSA; where they differ, OrigamiUSA's is used. Sizes are `DiagramStyle.standard`, in | ||
| 6 | points. | ||
| 7 | |||
| 8 | | Symbol | Drawn as | Source | | ||
| 9 | |---|---|---| | ||
| 10 | | Edge of the paper, folded edge | solid line, 2 | Randlett and OrigamiUSA agree | | ||
| 11 | | Crease made earlier, flat again | thin grey line, 1, grey 0.6 | OrigamiUSA (existing crease) | | ||
| 12 | | Valley fold | dashed line, 7 on 4 off | Randlett and OrigamiUSA agree | | ||
| 13 | | Mountain fold | dash-dot-dot line, 9 on, dots of 2, gaps of 3 | OrigamiUSA; Randlett uses dash-dot | | ||
| 14 | | Hidden edge or crease | not drawn; x-ray lines are not used | Randlett and OrigamiUSA agree | | ||
| 15 | | Valley-fold arrow | curved arrow, filled full head | OrigamiUSA (filled head) | | ||
| 16 | | Mountain-fold arrow | curved arrow, hollow half head, barb on the outside of the arc | Randlett and OrigamiUSA agree | | ||
| 17 | | Fold and unfold | curved arrow, fold head at the destination, hollow full head at the start pointing back | OrigamiUSA (double-headed form; the zig-zag form is not used) | | ||
| 18 | | Inside and outside reverse fold, sink, squash | hollow push arrow with a notched tail, tip on the crease | OrigamiUSA (push) | | ||
| 19 | | Petal fold | valley-fold arrow lifting the flap | OrigamiUSA | | ||
| 20 | | Turn over | loop-the-loop arrow: left to right for a vertical axis, bottom to top for a horizontal one | Randlett and OrigamiUSA agree | | ||
| 21 | | Rotate | two arcs around a circle with heads in the direction of turn, the amount in degrees at the centre | OrigamiUSA (amount written in the circle) | | ||
| 22 | | Repeat | one stroke across each fold arrow's shaft near its tail | OrigamiUSA (strokes count repetitions) | | ||
| 23 | |||
| 24 | Valley and mountain are as seen from the step's viewpoint, not FOLD's assignment. | ||
| 25 | |||
| 26 | Arrow geometry: a fold arrow runs from the area-weighted centroid of the axis's moving set before | ||
| 27 | the step to the same point after it (at the peak for a fold and unfold), its apex 0.3 of the chord | ||
| 28 | from the chord's midpoint, toward screen-up or, for a vertical chord, screen-right. Arrows of a | ||
| 29 | step with several axes start from points spread along their creases so that they do not meet. A | ||
| 30 | technique's symbol sits at the midpoint of the step's first crease, pointing toward where that | ||
| 31 | axis's moving set ends. | ||
| 32 | |||
| 33 | The canvas is 480 × 480, white; the model and its arrows fill it inside 48-point margins, 96 at | ||
| 34 | the bottom, where the turn-over and rotate symbols sit. A render matches its golden image when no | ||
| 35 | channel of any pixel differs by more than 24 of 255. Missing images are recorded by the test, | ||
| 36 | which then fails; `FOLD_RECORD_SNAPSHOTS=1` records them all. | ||
Packages/FoldKit/Tests/NotationTests/Snapshots/cup-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/cup-2.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/cup-3.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/cup-4.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/cup-5.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/cup-6.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/half-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/half-2.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/half-3.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/letter-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/letter-sequential-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/letter-sequential-2.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/letter-staggered-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/mountain-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/occlusion-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/occlusion-2.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/occlusion-3.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/quarters-1.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/quarters-2.png added
Binary file not shown.
Packages/FoldKit/Tests/NotationTests/Snapshots/quarters-3.png added
Binary file not shown.