// LyrebirdEnvelopeView.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import SwiftUI import LyrebirdSynth // MARK: - Region /// Render region for one envelope segment. enum _EnvelopeRegion { case preLoop case loop case release var color: Color { switch self { case .preLoop: return .cyan case .loop: return .green case .release: return .orange } } } // MARK: - Pure helpers (internal for testability via @testable import LyrebirdUI) /// Returns the render region for a single segment index given loopNode/releaseNode. /// /// Loop-only semantics (loopNode set, releaseNode nil): only the segment *at* loopNode /// is colored `.loop`. Segments after it are the gate-off release path — they play once /// after gate drops and are correctly classified as `.preLoop`. func _regionForSegment( index: Int, loopNode: Int?, releaseNode: Int?, segmentCount: Int ) -> _EnvelopeRegion { switch (loopNode, releaseNode) { case (let ln?, let rn?): if index < ln { return .preLoop } if index < rn { return .loop } return .release case (let ln?, nil): return index == ln ? .loop : .preLoop case (nil, let rn?): return index < rn ? .preLoop : .release case (nil, nil): return .preLoop } } /// Returns cumulative boundary times: `[0, d0, d0+d1, …, totalDuration]`. /// Length is `durations.count + 1`. func _segmentBoundaryTimes(durations: [Double]) -> [Double] { var times: [Double] = [0] var elapsed: Double = 0 for d: Double in durations { elapsed += d times.append(elapsed) } return times } /// Returns Y display bounds for `levels` with 10 % headroom on each side. /// Returns `(0, 1)` when `levels` is empty. func _envelopeYBounds(levels: [Double]) -> (yMin: Double, yMax: Double) { let minimumLevelRange: Double = 1e-6 let headroomFactor: Double = 0.1 guard let lo: Double = levels.min(), let hi: Double = levels.max() else { return (0, 1) } let range: Double = max(hi - lo, minimumLevelRange) let headroom: Double = range * headroomFactor return (lo - headroom, hi + headroom) } // MARK: - LyrebirdEnvelopeView /// A SwiftUI view that plots an `Envelope` as a color-coded shape. /// /// Segments are drawn in distinct colors based on their role: /// - **Cyan** — normal segments before any loop or release point /// - **Green** — loop region `[loopNode, releaseNode)` /// - **Orange** — release region from `releaseNode` to the end /// /// Vertical dashed markers indicate `loopNode` ("L") and `releaseNode` ("R") boundaries. /// Horizontal hairlines show the target level for each segment endpoint. /// /// ```swift /// let env = Envelope( /// levels: [0, 1, 0.6, 0], /// durations: [0.01, 0.3, 0.2], /// curves: [.sine, .lin, .exponential], /// loopNode: 1, /// releaseNode: 2 /// ) /// LyrebirdEnvelopeView(env) /// .padding() /// ``` public struct LyrebirdEnvelopeView: View { private let envelope: Envelope private let width: CGFloat private let height: CGFloat private static let backgroundBrightness: CGFloat = 0.08 private static let backgroundColor: Color = Color(white: backgroundBrightness) /// 2 path points per canvas pixel — smooth enough for all curve shapes. private static let oversample: CGFloat = 2 private static let markerOpacity: Double = 0.7 private static let levelTickOpacity: Double = 0.2 private static let markerDash: [CGFloat] = [4, 3] private static let labelFontSize: CGFloat = 9 private static let labelFont: Font = .system(size: labelFontSize, weight: .semibold, design: .monospaced) private static let signalLineWidth: CGFloat = 1.5 private static let guideLineWidth: CGFloat = 0.5 private static let markerLineWidth: CGFloat = 1 private static let markerLabelOffsetX: CGFloat = 4 private static let markerLabelOffsetY: CGFloat = 6 private static let cornerRadius: CGFloat = 4 public init( _ envelope: Envelope, width: CGFloat = 300, height: CGFloat = 120 ) { self.envelope = envelope self.width = width self.height = height } public var body: some View { Canvas { ctx, size in _draw(ctx: ctx, size: size) } .frame(width: width, height: height) .background(LyrebirdEnvelopeView.backgroundColor) .clipShape(RoundedRectangle(cornerRadius: LyrebirdEnvelopeView.cornerRadius)) } // MARK: - Drawing private func _draw( ctx: GraphicsContext, size: CGSize ) { let (yMin, yMax) = _envelopeYBounds(levels: envelope.levels) let segCount: Int = envelope.segmentCount // Zero-segment or zero-duration: draw flat line at constant level. guard segCount > 0 && envelope.totalDuration > 0 else { let v: Double = envelope.levels.first ?? 0 let y: CGFloat = _yFor(v, yMin: yMin, yMax: yMax, height: size.height) var path: Path = Path() path.move(to: CGPoint(x: 0, y: y)) path.addLine(to: CGPoint(x: size.width, y: y)) ctx.stroke(path, with: .color(.cyan), lineWidth: LyrebirdEnvelopeView.signalLineWidth) return } let boundaryTimes: [Double] = _segmentBoundaryTimes(durations: envelope.durations) let totalSamples: Int = Int(ceil(size.width * LyrebirdEnvelopeView.oversample)) // Horizontal level hairlines for level: Double in envelope.levels { let y: CGFloat = _yFor(level, yMin: yMin, yMax: yMax, height: size.height) var tick: Path = Path() tick.move(to: CGPoint(x: 0, y: y)) tick.addLine(to: CGPoint(x: size.width, y: y)) ctx.stroke(tick, with: .color(.white.opacity(LyrebirdEnvelopeView.levelTickOpacity)), lineWidth: LyrebirdEnvelopeView.guideLineWidth) } // One colored path per segment for seg: Int in 0.. CGFloat { CGFloat(t / envelope.totalDuration) * width } private func _yFor( _ v: Double, yMin: Double, yMax: Double, height: CGFloat ) -> CGFloat { let t: Double = (v - yMin) / (yMax - yMin) return height * (1.0 - CGFloat(t)) } }