Files
Lyrebird/Sources/LyrebirdUI/LyrebirdEnvelopeView.swift
T
2026-06-01 18:27:40 -07:00

260 lines
9.2 KiB
Swift

// 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..<segCount {
let region: _EnvelopeRegion = _regionForSegment(
index: seg,
loopNode: envelope.loopNode,
releaseNode: envelope.releaseNode,
segmentCount: segCount
)
let tStart: Double = boundaryTimes[seg]
let tEnd: Double = boundaryTimes[seg + 1]
let segDur: Double = tEnd - tStart
let frac: Double = segDur / envelope.totalDuration
// nSamples is a step count; the loop runs 0...nSamples (nSamples+1 points),
// so the final point lands exactly at tEnd, closing each segment cleanly.
let nSamples: Int = max(2, Int(ceil(CGFloat(totalSamples) * CGFloat(frac))))
var path: Path = Path()
for i: Int in 0...nSamples {
let t: Double = tStart + segDur * Double(i) / Double(nSamples)
let v: Double = envelope.valueAtTime(t)
let x: CGFloat = _xFor(t, width: size.width)
let y: CGFloat = _yFor(v, yMin: yMin, yMax: yMax, height: size.height)
let pt: CGPoint = CGPoint(x: x, y: y)
if i == 0 { path.move(to: pt) } else { path.addLine(to: pt) }
}
ctx.stroke(path, with: .color(region.color),
lineWidth: LyrebirdEnvelopeView.signalLineWidth)
}
// Vertical dashed markers — loopNode and releaseNode are pre-validated by Envelope.init
// to be in [0, segmentCount), so boundaryTimes[ln/rn] is always in bounds.
if let ln: Int = envelope.loopNode {
_drawMarker(ctx: ctx, time: boundaryTimes[ln], label: "L",
color: .green, size: size)
}
if let rn: Int = envelope.releaseNode {
_drawMarker(ctx: ctx, time: boundaryTimes[rn], label: "R",
color: .orange, size: size)
}
}
private func _drawMarker(
ctx: GraphicsContext,
time: Double,
label: String,
color: Color,
size: CGSize
) {
let x: CGFloat = _xFor(time, width: size.width)
var line: Path = Path()
line.move(to: CGPoint(x: x, y: 0))
line.addLine(to: CGPoint(x: x, y: size.height))
ctx.stroke(line,
with: .color(color.opacity(LyrebirdEnvelopeView.markerOpacity)),
style: StrokeStyle(lineWidth: LyrebirdEnvelopeView.markerLineWidth,
dash: LyrebirdEnvelopeView.markerDash))
ctx.draw(
Text(label)
.font(LyrebirdEnvelopeView.labelFont)
.foregroundStyle(color),
at: CGPoint(x: x + LyrebirdEnvelopeView.markerLabelOffsetX,
y: LyrebirdEnvelopeView.markerLabelOffsetY),
anchor: .leading
)
}
// MARK: - Coordinate helpers
private func _xFor(
_ t: Double,
width: CGFloat
) -> 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))
}
}