From 4eb1cbdd618c8961e26c71a3d2b4ac7824905b7e Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 12:37:34 -0700 Subject: [PATCH 01/18] feat(rigs): ship built-in factory starter rigs Add a factory rig library: 8 curated starter pedalboard rigs seeded into an empty rig library on first launch. Rigs are compile-checked builders (construct concrete pedals, set typed @UIParam values, board.add) rather than hand-written JSON, so a renamed pedal control is a build error, not a silently corrupted preset. Seeding builds each rig in a throwaway offline (never-started) engine, captures a RigEntry with a stable per-rig UUID (idempotent re-seed), and saves to the store. Bootstrap rolls back this run's saves if any store.save fails, so a partial library can't freeze future seeding (gated on isEmpty). Rigs are named/described by sound, not trademarked products or artists; a test guards against brand names leaking into names/blurbs. Full ship-path test loads and renders every rig to non-silent output. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRig.swift | 70 +++ .../Presets/Factory/FactoryRigCategory.swift | 33 ++ .../Presets/Factory/FactoryRigLibrary.swift | 438 ++++++++++++++++++ .../RigLibraryBootstrap.swift | 58 ++- .../FactoryRigLibraryTests.swift | 105 +++++ 5 files changed, 700 insertions(+), 4 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift create mode 100644 Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift new file mode 100644 index 0000000..97f63cc --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift @@ -0,0 +1,70 @@ +// FactoryRig.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// A single built-in starter rig: a named, described pedal chain shipped with the app and seeded +/// into a fresh rig library on first launch. +/// +/// A `FactoryRig` is a *builder*, not a stored snapshot. Its ``build`` closure constructs the chain +/// against a live ``ShoeGaze`` session using the concrete pedal editing API, so the recipe is +/// type-checked against the real pedal parameters at compile time — a renamed pedal control breaks +/// the build (a compile error) rather than silently corrupting a hand-written JSON preset. The +/// builder is run once at seed time (see ``FactoryRigLibrary/makeEntries(makeSession:)``), captured +/// to a ``RigEntry`` via ``ShoeGaze/captureEntry(name:id:)``, and thereafter behaves exactly like a +/// user-saved rig. +/// +/// The rig names and blurbs are deliberately descriptive of the *sound*, not any trademarked pedal, +/// amplifier, or artist; a blurb may nod at the era or style a tone evokes, but a factory rig is +/// never presented as a named product or a specific performer's endorsed setup. +public struct FactoryRig: Identifiable, Sendable { + + /// Stable identifier for this rig. + /// + /// Fixed per rig (a literal, not freshly generated) so re-seeding an already-populated library + /// overwrites the same entry in place rather than creating a duplicate — `RigLibraryStore.save` + /// keys on the entry `id`. + public let id: UUID + + /// Human-readable rig name shown in the picker and used as the saved ``RigEntry`` name. + public let name: String + + /// One- or two-sentence, user-facing description of the sound and how to play it. Shown as the + /// picker subtitle / info blurb. Descriptive of the tone only — never a trademarked product or + /// an artist endorsement. + public let blurb: String + + /// Sonic family this rig belongs to, for grouping in a picker. Presentational only. + public let category: FactoryRigCategory + + /// Builds the rig's pedal chain into `board`, an empty board freshly returned by + /// `session.addBoard()`. Set pedal parameters via the typed `configure` closures of + /// ``FactoryRigLibrary``'s helpers. Do **not** call `finalizeBoard` / `captureEntry` here — the + /// seeding driver owns that lifecycle. + public let build: @MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void + + /// Creates a factory rig descriptor. + /// + /// - Parameters: + /// - id: Stable identifier (a fixed literal per rig — see ``id``). + /// - name: Rig name (picker title + saved entry name). + /// - blurb: User-facing description of the sound. + /// - category: Sonic family for picker grouping. + /// - build: Chain-building closure run against a fresh, empty board at seed time. + public init( + id: UUID, + name: String, + blurb: String, + category: FactoryRigCategory, + build: @escaping @MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void + ) { + self.id = id + self.name = name + self.blurb = blurb + self.category = category + self.build = build + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift new file mode 100644 index 0000000..4e5dd81 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift @@ -0,0 +1,33 @@ +// FactoryRigCategory.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Broad sonic grouping for a built-in ``FactoryRig``. +/// +/// Purely presentational: the category lets a rig picker cluster the shipped starter rigs into +/// recognisable families ("Shoegaze Walls", "Dreampop", …). It is **not** persisted in the saved +/// ``RigEntry`` — a recalled rig is just a board, indistinguishable from a user rig once loaded. +public enum FactoryRigCategory: String, CaseIterable, Sendable { + + /// Dense fuzz-and-reverb "wall of sound" textures. + case shoegazeWalls = "Shoegaze Walls" + + /// Lush, clean, chorused and delayed dream-pop voices. + case dreamPop = "Dreampop" + + /// Classic overdrive / fuzz / wah lead and rhythm tones. + case classic = "Classic" + + /// Slow, evolving, reverb-heavy ambient beds. + case ambient = "Ambient" + + /// Lo-fi, bit-crushed, and otherwise experimental noise textures. + case experimental = "Experimental" + + /// Human-readable name shown as a section header in a rig picker. + public var displayName: String { rawValue } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift new file mode 100644 index 0000000..3cb1942 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -0,0 +1,438 @@ +// FactoryRigLibrary.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +// MARK: - Typed board-building helper + +extension PedalBoard { + + /// Constructs a concrete pedal, applies `configure` to its typed parameters, and appends it to + /// the end of the chain. + /// + /// This is the building block for ``FactoryRig`` recipes: because `configure` receives the + /// concrete pedal type, every parameter it touches (`$0.fuzz`, `$0.time`, …) is checked by the + /// compiler against the real pedal API — a renamed control is a build error, not a silently + /// broken preset. Bus wiring is handled by ``add(_:after:)``. + /// + /// - Parameters: + /// - pedal: A freshly-constructed pedal (its default buses are overwritten by the board). + /// - configure: Sets the pedal's parameters before it is inserted. + /// - Returns: The same pedal, now wired into the chain. + /// - Throws: `BusAllocatorError.noFreeBus`, `EngineAddError`, or `ShoeGazeError.stereoWidthExceeded`. + @discardableResult + func append( + _ pedal: P, + configure: (P) -> Void + ) throws -> P { + configure(pedal) + try add(pedal) + return pedal + } +} + +// MARK: - Factory rig catalog + +/// The built-in starter rigs shipped with the app and seeded into an empty rig library on first +/// launch. +/// +/// Each entry is a ``FactoryRig`` — a compile-checked builder, not a stored JSON blob. Call +/// ``makeEntries(makeSession:)`` at seed time to materialise them into ``RigEntry`` snapshots. +/// +/// Rig names and blurbs describe the *sound*; a blurb may reference an era or style but never a +/// trademarked product or a specific artist's endorsed setup. +@MainActor +public enum FactoryRigLibrary { + + /// Every built-in rig, in the order a picker should present them. + public static let all: [FactoryRig] = [ + glideWall, + chorusCathedral, + fuzzWahClassic, + dottedEighthAnthem, + ambientShimmerBed, + springReverbSurf, + octaveFuzzLead, + bitcrushNoiseTexture, + ] + + // MARK: Shoegaze walls + + /// Dense detuned fuzz + reverse swells + plate bloom. + static let glideWall: FactoryRig = FactoryRig( + id: stableID("Glide Wall"), + name: "90s Glide Wall", + blurb: "A dense, saturated fuzz wall with reverse swells blooming around it. Hold big open " + + "chords and let the reverse delay and plate wash carry them — early-'90s British " + + "shoegaze territory.", + category: .shoegazeWalls + ) { _, board in + try board.append(FuzzPedal()) { p in + p.fuzz = 42.0 + p.tone = 2600.0 + } + try board.append(ChimeTopBoostAmpPedal()) { p in + p.gain = 6.5 + p.bass = 0.6 + p.mid = 0.4 + p.treble = 0.7 + p.cut = 0.3 + p.brilliant = 1.0 + } + try board.append(ReverseDelayPedal()) { p in + p.time = 0.45 + p.feedback = 0.4 + } + try board.append(PlateReverbPedal()) { p in + p.decay = 0.8 + p.tone = 0.7 + p.damp = 0.25 + p.mod = 0.7 + } + } + + // MARK: Dreampop + + /// Glassy clean chorus into cascading delay and octave-up shimmer. + static let chorusCathedral: FactoryRig = FactoryRig( + id: stableID("Chorus Cathedral"), + name: "Dreampop Chorus Cathedral", + blurb: "Glassy clean chorus into cascading delay and octave-up shimmer — lush and " + + "weightless. Play slow arpeggios and let every note ring into the next.", + category: .dreamPop + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 3.0 + p.threshold = -18.0 + p.ratio = 3.0 + } + try board.append(FullertonReverbAmpPedal()) { p in + p.gain = 3.5 + p.bass = 0.5 + p.mid = 0.5 + p.treble = 0.6 + // Lean on the shimmer reverb downstream rather than the amp's own tank. + p.reverbEnabled = 0.0 + p.vibratoEnabled = 0.0 + } + // Chorus is a mono→stereo widener; keep it the only width change in the chain. + try board.append(ChorusPedal()) { p in + p.rate = 0.5 + p.depth = 0.005 + } + try board.append(DelayPedal()) { p in + p.time = 0.4 + p.feedback = 2.2 + } + try board.append(ShimmerReverbPedal()) { p in + p.size = 0.09 + p.decay = 0.85 + p.shimmer = 0.55 + p.damp = 0.35 + } + } + + // MARK: Classic + + /// Envelope-wah into thick fuzz and a cranked British stack. + static let fuzzWahClassic: FactoryRig = FactoryRig( + id: stableID("Fuzz Wah Classic"), + name: "Fuzz + Wah Classic", + blurb: "Envelope-wah into thick fuzz and a cranked British stack — an expressive, vocal " + + "lead voice with a touch of spring. Dig in and the wah opens up under your picking.", + category: .classic + ) { _, board in + try board.append(AutoWahPedal()) { p in + p.sensitivity = 2.5 + p.resonance = 4.0 + p.range = 2600.0 + } + try board.append(FuzzPedal()) { p in + p.fuzz = 38.0 + p.tone = 3200.0 + } + try board.append(BritishPlexiAmpPedal()) { p in + p.gain = 8.0 + p.bass = 0.6 + p.mid = 0.6 + p.treble = 0.6 + p.presence = 0.5 + p.bright = 1.0 + } + try board.append(SpringReverbPedal()) { p in + p.decay = 1.8 + p.tension = 0.5 + p.damp = 0.3 + } + } + + /// Chiming overdrive with a rhythmic dotted-eighth delay. + static let dottedEighthAnthem: FactoryRig = FactoryRig( + id: stableID("Dotted Eighth Anthem"), + name: "Dotted-Eighth Anthem", + blurb: "Chiming overdrive with a dotted-eighth delay that turns single notes into " + + "cascading patterns — bright, anthemic, arena-sized. Tuned to a dotted eighth at 120 " + + "BPM; play on the beat and let the echoes fill the gaps.", + category: .classic + ) { _, board in + try board.append(OverdrivePedal()) { p in + p.drive = 5.0 + p.tone = 4200.0 + } + try board.append(ChimeTopBoostAmpPedal()) { p in + p.gain = 5.0 + p.bass = 0.5 + p.mid = 0.5 + p.treble = 0.65 + p.cut = 0.25 + } + try board.append(DelayPedal()) { p in + // Dotted eighth at 120 BPM = 0.375 s. + p.time = 0.375 + p.feedback = 1.6 + } + try board.append(PlateReverbPedal()) { p in + p.decay = 0.6 + p.tone = 0.8 + p.damp = 0.3 + p.mod = 0.4 + } + } + + /// Wet spring reverb and throbbing tremolo through a clean combo. + static let springReverbSurf: FactoryRig = FactoryRig( + id: stableID("Spring Reverb Surf"), + name: "Spring-Reverb Surf", + blurb: "Drippy spring reverb and throbbing tremolo through a clean Fullerton-style combo — " + + "classic surf voicing. Stab chords and ride the tremolo.", + category: .classic + ) { _, board in + try board.append(TremoloPedal()) { p in + p.rate = 5.5 + p.depth = 0.6 + } + try board.append(FullertonReverbAmpPedal()) { p in + p.gain = 3.5 + p.bass = 0.55 + p.mid = 0.5 + p.treble = 0.6 + p.reverb = 0.5 + p.reverbEnabled = 1.0 + p.vibratoEnabled = 0.0 + } + try board.append(SpringReverbPedal()) { p in + p.decay = 2.2 + p.tension = 0.6 + p.damp = 0.25 + } + } + + // MARK: Ambient + + /// Long feedback echoes into octave-up shimmer and a cavernous room. + static let ambientShimmerBed: FactoryRig = FactoryRig( + id: stableID("Ambient Shimmer Bed"), + name: "Ambient Shimmer Bed", + blurb: "Long feedback echoes wash into octave-up shimmer and a cavernous room — a slow, " + + "evolving bed for swells and volume-knob fades. Play sparse and let it bloom.", + category: .ambient + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 4.0 + p.threshold = -20.0 + p.ratio = 4.0 + } + try board.append(FeedbackDelayPedal()) { p in + p.time = 0.6 + p.feedback = 5.0 + p.tone = 3500.0 + } + try board.append(ShimmerReverbPedal()) { p in + p.size = 0.11 + p.decay = 0.9 + p.shimmer = 0.7 + p.damp = 0.3 + } + try board.append(RoomReverbPedal()) { p in + p.size = 60.0 + p.decay = 8.0 + p.damp = 0.5 + p.tail = 0.7 + } + } + + // MARK: Experimental + + /// A sub-octave layered under saturated fuzz for a thick, synth-like lead. + static let octaveFuzzLead: FactoryRig = FactoryRig( + id: stableID("Octave Fuzz Lead"), + name: "Octave-Fuzz Lead", + blurb: "A sub-octave layered under saturated fuzz for a thick, synth-like lead, pushed " + + "through a British master-volume voice. Single-note lines turn huge.", + category: .experimental + ) { _, board in + try board.append(BassOctaverPedal()) { p in + p.oct1 = 0.8 + p.oct2 = 0.2 + p.direct = 0.9 + // Track mode: follow the played pitch rather than octave-flip. + p.mode = 1.0 + } + try board.append(FuzzPedal()) { p in + p.fuzz = 45.0 + p.tone = 2800.0 + } + try board.append(BritishMasterAmpPedal()) { p in + p.gain = 7.0 + p.master = 0.5 + p.bass = 0.55 + p.mid = 0.6 + p.treble = 0.55 + p.presence = 0.4 + } + try board.append(DelayPedal()) { p in + p.time = 0.28 + p.feedback = 1.4 + } + } + + /// Gritty sample-rate crushing into runaway feedback delay and a wide room. + static let bitcrushNoiseTexture: FactoryRig = FactoryRig( + id: stableID("Bitcrush Noise Texture"), + name: "Bitcrush Noise Texture", + blurb: "Gritty sample-rate crushing into runaway feedback delay and a wide room — harsh, " + + "lo-fi and unstable in the best way. Made for drones and glitch textures.", + category: .experimental + ) { _, board in + try board.append(BitcrusherPedal()) { p in + p.crush = 6.0 + p.bits = 5.0 + p.tone = 3200.0 + } + try board.append(FeedbackDelayPedal()) { p in + p.time = 0.33 + p.feedback = 4.0 + p.tone = 2800.0 + } + try board.append(ReverbPedal()) { p in + p.roomSize = 0.8 + p.damping = 0.4 + } + } + + // MARK: - Seeding + + /// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library. + /// + /// Each rig is constructed in a fresh, **never-started** ``ShoeGaze`` session (capturing a rig + /// only reads `@UIParam` values — no audio is rendered), captured with the rig's stable `id`, and + /// the session is torn down before the next. Because ids are stable, re-running this against an + /// already-seeded library overwrites entries in place rather than duplicating them. + /// + /// - Parameter makeSession: Returns a fresh, empty session (typically backed by an offline + /// engine). Called once per rig. + /// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order. + /// - Throws: Any error from session creation, board building, or finalisation. + public static func makeEntries( + makeSession: @MainActor () throws -> ShoeGaze + ) throws -> [RigEntry] { + var entries: [RigEntry] = [] + entries.reserveCapacity(all.count) + for rig: FactoryRig in all { + let session: ShoeGaze = try makeSession() + // Tear down on every exit from this iteration, including a throw from `build` / + // `finalizeBoard`, so a failing rig never leaks its throwaway engine's buses/nodes. + defer { session.teardown() } + let board: PedalBoard = try session.addBoard() + try rig.build(session, board) + try session.finalizeBoard(board) + entries.append(session.captureEntry(name: rig.name, id: rig.id)) + } + return entries + } + + /// Builds every factory rig using a self-contained offline engine per rig. + /// + /// Convenience over ``makeEntries(makeSession:)`` for callers with no session of their own (the + /// first-launch seeding path). Each rig gets a fresh ``NRTDriver``-backed engine that is never + /// started — no audio is rendered and no output file is written (the driver only touches disk in + /// `start()`), so the temporary URL handed to the driver never comes into existence. + /// + /// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order. + /// - Throws: Any error from board building or finalisation. + public static func makeEntries() throws -> [RigEntry] { + try makeEntries(makeSession: makeOfflineSeedSession) + } + + /// Block size for the throwaway seeding engine. Matches the framework default; never renders. + private static let seedBlockSize: Int = 512 + + /// Sample rate for the throwaway seeding engine. Only affects `@UIParam` capture indirectly; no + /// audio is produced. + private static let seedSampleRate: Double = 44_100.0 + + /// Audio bus count for the throwaway seeding engine — generous headroom for the longest chain. + private static let seedAudioBusCount: Int = 128 + + /// Control bus count for the throwaway seeding engine. + private static let seedControlBusCount: Int = 512 + + /// Nominal render duration handed to the offline driver. Unused — the engine is never started. + private static let seedRenderDuration: Double = 0.05 + + /// Creates a fresh, never-started offline ``ShoeGaze`` session for building one factory rig. + private static func makeOfflineSeedSession() -> ShoeGaze { + let outputURL: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".caf") + let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: seedRenderDuration) + let engine: SynthesisEngine = SynthesisEngine( + blockSize: seedBlockSize, + sampleRate: seedSampleRate, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: seedAudioBusCount, + numControlBuses: seedControlBusCount, + driver: driver + ) + return ShoeGaze(engine: engine, inputSource: .testLoop) + } + + // MARK: - Stable identifiers + + /// Deterministic UUID derived from a rig's identity string via two FNV-1a hashes. + /// + /// Gives each rig a stable library id across launches without a hand-written UUID literal, and + /// keeps seeding idempotent (same id ⇒ overwrite in place). Not a cryptographic identifier — + /// only stability and per-rig uniqueness matter here. + static func stableID(_ seed: String) -> UUID { + let fnvOffset: UInt64 = 0xcbf2_9ce4_8422_2325 + let fnvPrime: UInt64 = 0x0000_0100_0000_01b3 + + func hash(_ string: String) -> UInt64 { + var value: UInt64 = fnvOffset + for byte: UInt8 in string.utf8 { + value = (value ^ UInt64(byte)) &* fnvPrime + } + return value + } + + let high: UInt64 = hash(seed) + let low: UInt64 = hash(seed + "\u{1}salt") + + func byte(_ source: UInt64, _ shift: UInt64) -> UInt8 { + UInt8((source >> shift) & 0xFF) + } + + let bytes: uuid_t = ( + byte(high, 56), byte(high, 48), byte(high, 40), byte(high, 32), + byte(high, 24), byte(high, 16), byte(high, 8), byte(high, 0), + byte(low, 56), byte(low, 48), byte(low, 40), byte(low, 32), + byte(low, 24), byte(low, 16), byte(low, 8), byte(low, 0) + ) + return UUID(uuid: bytes) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift index 8c3f876..902e2a1 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -39,15 +39,65 @@ public enum RigLibraryBootstrap { // Seed only after the (possibly iCloud) library has loaded: an empty library here means a // genuine first run, not a not-yet-synced one. - guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return } + guard store.entries.isEmpty else { return } + + // First run: populate the library with the shipped starter rigs. These are built in + // throwaway offline sessions, so they are independent of the current working graph. The + // working session is intentionally left as-is (no `currentRigID`) — the user picks a starter + // rig from the sidebar to load it, rather than the highlight pointing at a rig the working + // graph has not actually loaded. + let entries: [RigEntry] + do { + entries = try FactoryRigLibrary.makeEntries() + } catch { + // Building the shipped rigs is deterministic and should never fail at runtime; if it + // somehow does, fall back to seeding the working rig so the library is not left empty. + print("[RigLibraryBootstrap] building factory rigs failed: \(error)") + seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName) + return + } + + // Save sequentially, rolling back on failure. Seeding is gated on `store.entries.isEmpty`, + // so a partially-saved library would be frozen forever (never retried, never completed). If + // any save fails, delete the entries saved this run so the library returns to empty and a + // later launch retries the full seed. (This is best-effort, not truly atomic: if a rollback + // `delete` itself fails, a partial set can still be left behind and frozen — the residual + // hole a non-transactional store cannot fully close.) + var savedThisRun: [RigEntry] = [] + do { + for entry: RigEntry in entries { + try store.save(entry) + savedThisRun.append(entry) + } + } catch { + print("[RigLibraryBootstrap] seeding factory rigs failed after " + + "\(savedThisRun.count)/\(entries.count); rolling back: \(error)") + for entry: RigEntry in savedThisRun { + do { + try store.delete(entry) + } catch { + print("[RigLibraryBootstrap] rollback of '\(entry.name)' failed: \(error)") + } + } + } + } + + /// Seeds the working session's current rig as a single named library entry. + /// + /// Last-resort fallback used only when the factory rigs could not be built; keeps the library + /// from being left empty on first run. + private static func seedWorkingRig( + _ store: RigLibraryStore, + seedFrom shoeGaze: ShoeGaze, + seedName: String + ) { + guard !shoeGaze.boards.isEmpty else { return } let entry: RigEntry = shoeGaze.captureEntry(name: seedName) do { try store.save(entry) - // The seeded entry was captured from the working graph, so it is the session's source - // rig — record it so the sidebar highlights it and the autosave envelope carries it. shoeGaze.currentRigID = entry.id } catch { - print("[RigLibraryBootstrap] seeding library failed: \(error)") + print("[RigLibraryBootstrap] fallback seeding failed: \(error)") } } } diff --git a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift new file mode 100644 index 0000000..650a1e6 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift @@ -0,0 +1,105 @@ +// FactoryRigLibraryTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("FactoryRigLibrary") +struct FactoryRigLibraryTests { + + // MARK: - Catalog integrity + + @Test func catalogIsWellFormed() { + let rigs: [FactoryRig] = FactoryRigLibrary.all + #expect(rigs.count >= 6, "expected a full starter slate") + + let ids: Set = Set(rigs.map { $0.id }) + #expect(ids.count == rigs.count, "rig ids must be unique") + + let names: Set = Set(rigs.map { $0.name }) + #expect(names.count == rigs.count, "rig names must be unique") + + let minBlurbLength: Int = 20 + for rig: FactoryRig in rigs { + #expect(!rig.name.isEmpty, "\(rig.name) has empty name") + #expect(rig.blurb.count >= minBlurbLength, "\(rig.name) blurb too short") + } + + // The slate should span more than one sonic family. + let categories: Set = Set(rigs.map { $0.category }) + #expect(categories.count >= 3, "starter slate should cover several categories") + } + + @Test func blurbsAvoidTrademarkedProductNames() { + // Guard against a blurb accidentally naming a real amp/pedal brand: factory rigs describe + // the sound, never a trademarked product. + let forbidden: [String] = [ + "marshall", "fender", "vox", "mesa", "boss", "orange", "dumble", "roland", "ibanez", + ] + for rig: FactoryRig in FactoryRigLibrary.all { + let haystack: String = (rig.name + " " + rig.blurb).lowercased() + for brand: String in forbidden { + #expect(!haystack.contains(brand), "\(rig.name) mentions '\(brand)'") + } + } + } + + // MARK: - Seeding entries + + @Test func makeEntriesMatchesCatalogAndIsStable() throws { + let entries: [RigEntry] = try FactoryRigLibrary.makeEntries() + let rigs: [FactoryRig] = FactoryRigLibrary.all + + #expect(entries.count == rigs.count, "one entry per rig") + for (entry, rig): (RigEntry, FactoryRig) in zip(entries, rigs) { + #expect(entry.id == rig.id, "entry id must be the rig's stable id") + #expect(entry.name == rig.name) + #expect(entry.state.boards.count == 1, "\(rig.name) should build exactly one board") + let pedalCount: Int = entry.state.boards.first?.pedals.count ?? 0 + #expect(pedalCount >= 3, "\(rig.name) should build a non-trivial chain") + } + + // Stable ids: re-seeding yields identical ids (so a re-seed overwrites in place). + let again: [RigEntry] = try FactoryRigLibrary.makeEntries() + #expect(entries.map { $0.id } == again.map { $0.id }) + } + + @Test func entriesRoundTripThroughJSON() throws { + let encoder: JSONEncoder = JSONEncoder() + let decoder: JSONDecoder = JSONDecoder() + for entry: RigEntry in try FactoryRigLibrary.makeEntries() { + let data: Data = try encoder.encode(entry) + let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data) + #expect(decoded == entry, "\(entry.name) did not survive a JSON round-trip") + } + } + + // MARK: - Load + render (full ship path) + + @Test func everyFactoryEntryLoadsAndRenders() throws { + let renderDuration: Double = 0.2 + let numAudioBuses: Int = 128 + + for entry: RigEntry in try FactoryRigLibrary.makeEntries() { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: renderDuration, + numAudioBuses: numAudioBuses + ) + defer { try? FileManager.default.removeItem(at: url) } + + let session: ShoeGaze = ShoeGaze(engine: engine) + try session.loadRig(from: entry.state) + + try engine.start() + let samples: [Float] = readStereoCAF(url: url) + #expect(hasNonSilentOutput(samples), "\(entry.name) rendered silence") + } + } +} From bb418ca2e8198a35c477bd4e270e8daafff9625c Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 12:42:03 -0700 Subject: [PATCH 02/18] feat(rigs): confirm before overwriting a built-in factory rig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Saving over a currently-loaded factory rig now shows a confirmation dialog instead of silently replacing the shipped original: Overwrite (destructive), Save as New Rig… (new id, keeps the original), or Cancel. The pending follow-up (e.g. the Save & Clear clear step) is threaded through all three paths. Adds FactoryRigLibrary.factoryIDs / isFactory(_:) so the UI can tell a shipped rig from a user rig by id, with a test. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRigLibrary.swift | 15 ++++++ .../ShoeGazeBuilderView.swift | 51 ++++++++++++++++++- .../FactoryRigLibraryTests.swift | 10 ++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index 3cb1942..97b3233 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -48,6 +48,21 @@ extension PedalBoard { @MainActor public enum FactoryRigLibrary { + /// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig. + /// + /// Because factory rigs are seeded with their fixed ``FactoryRig/id``, an entry recalled from the + /// library can be identified as shipped-vs-user by id membership here. Callers use this to guard + /// destructive actions (e.g. warn before overwriting a starter rig). + public static let factoryIDs: Set = Set(all.map { $0.id }) + + /// Whether `id` belongs to a shipped factory rig. + /// + /// - Parameter id: A ``RigEntry/id`` from the rig library. + /// - Returns: `true` if the entry is one of the built-in starter rigs. + public static func isFactory(_ id: UUID) -> Bool { + factoryIDs.contains(id) + } + /// Every built-in rig, in the order a picker should present them. public static let all: [FactoryRig] = [ glideWall, diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 52fb870..f272d4c 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -149,6 +149,18 @@ public struct ShoeGazeBuilderView: View { let message: String } + /// A pending confirmation to overwrite a built-in factory rig. Non-`nil` shows the dialog; + /// carries the target entry and the follow-up to run once the user resolves the choice (so the + /// "Save & Clear" flow still clears after a confirmed overwrite). + private struct FactoryOverwriteRequest: Identifiable { + let id: UUID = UUID() + let entry: RigEntry + let completion: () -> Void + } + + /// Drives the "overwrite a starter rig?" confirmation dialog. `nil` = not shown. + @State private var factoryOverwrite: FactoryOverwriteRequest? + /// Archive export state. Cross-platform: backs the sidebar's Export Archive and the /// "Save & Clear" flow is separate (it saves to the library, not a file). @State private var showExporter: Bool = false @@ -304,6 +316,32 @@ public struct ShoeGazeBuilderView: View { .background(rigImportAnchor) .background(actionErrorAnchor) .rigNamePrompt($namePrompt) + .confirmationDialog( + "Overwrite starter rig?", + isPresented: Binding( + get: { factoryOverwrite != nil }, + set: { presented in if !presented { factoryOverwrite = nil } } + ), + titleVisibility: .visible, + presenting: factoryOverwrite + ) { request in + Button("Overwrite", role: .destructive) { + persist( + shoeGaze.captureEntry(name: request.entry.name, id: request.entry.id), + then: request.completion + ) + } + Button("Save as New Rig…") { + // Defer one runloop hop: presenting the name-entry alert while the confirmation + // dialog is still dismissing can drop the new presentation on some SwiftUI versions. + let completion: () -> Void = request.completion + DispatchQueue.main.async { promptSaveAs(then: completion) } + } + Button("Cancel", role: .cancel) { } + } message: { request in + Text("“\(request.entry.name)” is a built-in starter rig. Overwriting replaces it in " + + "your library. Save as a new rig to keep the original.") + } .confirmationDialog( "Erase all rigs?", isPresented: $showEraseAllDialog, @@ -1649,6 +1687,12 @@ public struct ShoeGazeBuilderView: View { } return } + // Overwriting a built-in starter rig replaces it in the library. Confirm first, offering a + // non-destructive "Save as New Rig" so the shipped original can be kept. + if FactoryRigLibrary.isFactory(existing.id) { + factoryOverwrite = FactoryOverwriteRequest(entry: existing, completion: completion) + return + } persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion) } @@ -1664,13 +1708,16 @@ public struct ShoeGazeBuilderView: View { } /// Prompts for a name and saves the current session as a new library entry (new id). - private func promptSaveAs() { + /// + /// - Parameter completion: Follow-up run once the new entry is persisted (e.g. the "Save & Clear" + /// clear step, or the pending action from a factory-rig overwrite prompt). + private func promptSaveAs(then completion: @escaping () -> Void = { }) { namePrompt = RigNamePrompt( title: "Save Rig As", initialText: currentRigName() ?? defaultNewRigName(), confirmLabel: "Save" ) { name in - persist(shoeGaze.captureEntry(name: name)) + persist(shoeGaze.captureEntry(name: name), then: completion) } } diff --git a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift index 650a1e6..9faa750 100644 --- a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift +++ b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift @@ -51,6 +51,16 @@ struct FactoryRigLibraryTests { } } + @Test func factoryDetectionRecognisesEveryRigAndRejectsOthers() { + let rigs: [FactoryRig] = FactoryRigLibrary.all + #expect(FactoryRigLibrary.factoryIDs.count == rigs.count) + for rig: FactoryRig in rigs { + #expect(FactoryRigLibrary.isFactory(rig.id), "\(rig.name) not recognised as factory") + } + // A freshly generated id is not a factory rig. + #expect(!FactoryRigLibrary.isFactory(UUID())) + } + // MARK: - Seeding entries @Test func makeEntriesMatchesCatalogAndIsStable() throws { From 779c55493d20ae8b9cff404424f5b4f496230b87 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 12:58:23 -0700 Subject: [PATCH 03/18] feat(rigs): add six more single-board starter rigs Extend the factory catalog from 8 to 14 using existing pedals: Funk Envelope Clav, Nashville Clean Comp, Rockabilly Slapback (classic), Post-Rock Crescendo, Dub Delay Throw (ambient), and Ring-Mod Texture (experimental). All build/load/render green via the existing tests. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRigLibrary.swift | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index 97b3233..fa3729d 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -73,6 +73,12 @@ public enum FactoryRigLibrary { springReverbSurf, octaveFuzzLead, bitcrushNoiseTexture, + funkEnvelopeClav, + postRockCrescendo, + nashvilleCleanComp, + dubDelayThrow, + ringModTexture, + rockabillySlapback, ] // MARK: Shoegaze walls @@ -339,6 +345,169 @@ public enum FactoryRigLibrary { } } + // MARK: More classic voices + + /// Envelope filter into light overdrive and a clean amp — funky, vocal, touch-sensitive. + static let funkEnvelopeClav: FactoryRig = FactoryRig( + id: stableID("Funk Envelope Clav"), + name: "Funk Envelope Clav", + blurb: "An envelope filter that opens with your picking, into light grit and a clean amp — " + + "funky and vocal, the classic auto-wah clav voice. Play staccato and let your " + + "dynamics work the filter.", + category: .classic + ) { _, board in + try board.append(MutantPedal()) { p in + p.sensitivity = 3.0 + p.resonance = 6.0 + } + try board.append(OverdrivePedal()) { p in + p.drive = 3.0 + p.tone = 4500.0 + } + try board.append(JazzCleanAmpPedal()) { p in + p.gain = 4.0 + p.bass = 0.5 + p.mid = 0.6 + p.treble = 0.6 + p.reverb = 0.15 + p.chorusEnabled = 0.0 + } + } + + /// Compressed clean into slapback echo and spring — bright, springy country/rockabilly. + static let nashvilleCleanComp: FactoryRig = FactoryRig( + id: stableID("Nashville Clean Comp"), + name: "Nashville Clean Comp", + blurb: "Squashed clean tone into a short slapback and spring reverb — bright, snappy and " + + "articulate, the Nashville country voice. Hybrid-pick and let the compressor even it " + + "out.", + category: .classic + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 3.0 + p.threshold = -16.0 + p.ratio = 4.0 + } + try board.append(FullertonReverbAmpPedal()) { p in + p.gain = 3.0 + p.bass = 0.5 + p.mid = 0.55 + p.treble = 0.65 + p.reverb = 0.3 + p.reverbEnabled = 1.0 + p.vibratoEnabled = 0.0 + } + try board.append(DelayPedal()) { p in + // Short slapback. + p.time = 0.11 + p.feedback = 0.3 + } + } + + /// Compressed chime into tight slapback and spring — classic rockabilly. + static let rockabillySlapback: FactoryRig = FactoryRig( + id: stableID("Rockabilly Slapback"), + name: "Rockabilly Slapback", + blurb: "Compressed chime with a tight tape-style slapback and spring — the rockabilly " + + "bounce. Palm-mute and dig in for the classic '50s snap.", + category: .classic + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 2.0 + p.threshold = -14.0 + p.ratio = 3.0 + } + try board.append(ChimeTopBoostAmpPedal()) { p in + p.gain = 4.0 + p.bass = 0.5 + p.mid = 0.5 + p.treble = 0.65 + p.cut = 0.2 + } + try board.append(DelayPedal()) { p in + // Very short slapback echo. + p.time = 0.09 + p.feedback = 0.25 + } + try board.append(SpringReverbPedal()) { p in + p.decay = 1.2 + p.tension = 0.6 + p.damp = 0.3 + } + } + + // MARK: More ambient / experimental voices + + /// Overdriven arpeggios into long delay and shimmer — a swelling post-rock build. + static let postRockCrescendo: FactoryRig = FactoryRig( + id: stableID("Post-Rock Crescendo"), + name: "Post-Rock Crescendo", + blurb: "Warm overdrive into a long delay and octave-up shimmer — a swelling, cinematic " + + "post-rock build. Layer arpeggios and let the wash grow into a crescendo.", + category: .ambient + ) { _, board in + try board.append(OverdrivePedal()) { p in + p.drive = 6.0 + p.tone = 4000.0 + } + try board.append(DelayPedal()) { p in + p.time = 0.5 + p.feedback = 2.5 + } + try board.append(ShimmerReverbPedal()) { p in + p.size = 0.1 + p.decay = 0.88 + p.shimmer = 0.6 + p.damp = 0.3 + } + } + + /// A dub-style feedback echo washing into deep spring — sparse, spacious, delay-forward. + static let dubDelayThrow: FactoryRig = FactoryRig( + id: stableID("Dub Delay Throw"), + name: "Dub Delay Throw", + blurb: "A long, dark feedback echo washing into deep spring reverb — the dub delay-throw. " + + "Play sparse skanks and ride the feedback for runaway repeats.", + category: .ambient + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 2.0 + p.threshold = -16.0 + p.ratio = 3.0 + } + try board.append(FeedbackDelayPedal()) { p in + p.time = 0.45 + p.feedback = 6.0 + p.tone = 2500.0 + } + try board.append(SpringReverbPedal()) { p in + p.decay = 2.5 + p.tension = 0.5 + p.damp = 0.35 + } + } + + /// Ring modulation into delay and reverb — clangorous, inharmonic, otherworldly. + static let ringModTexture: FactoryRig = FactoryRig( + id: stableID("Ring-Mod Texture"), + name: "Ring-Mod Texture", + blurb: "Ring modulation into delay and a wide room — clangorous, inharmonic and " + + "otherworldly. Try single notes and let the metallic overtones ring out.", + category: .experimental + ) { _, board in + try board.append(RingModulatorPedal()) { p in + p.frequency = 180.0 + } + try board.append(DelayPedal()) { p in + p.time = 0.3 + p.feedback = 1.8 + } + try board.append(ReverbPedal()) { p in + p.roomSize = 0.75 + p.damping = 0.4 + } + } + // MARK: - Seeding /// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library. From 965633de3467da1e3d28866313d2ad8a4279ea1d Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 13:06:17 -0700 Subject: [PATCH 04/18] feat(pedals): add Vibe pedal + Psychedelic Vibe Lead rig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New "Vibe" pedal: a photocell-style vibe built as four staggered all-pass stages swept by one shared sine LFO (unequal centre frequencies give the uneven, vocal throb that distinguishes a vibe from a phaser). Speed and Intensity knobs, Chorus/Vibrato mode switch (chorus blends dry+swept, vibrato passes swept only). Composed from RBJAllPass in effect(), mirroring PhaserPedal — no new RT generator. Registered in PedalType/PedalRegistry, enclosure colour, and palette order. Tests cover build+non-silent, each control measurably changing output, the knob/switch listing, and preset round-trip. Adds the Psychedelic Vibe Lead factory rig (Fuzz -> Vibe -> Delay -> Plate). Co-Authored-By: Claude Opus 4.8 --- Sources/LyrebirdShoeGaze/PedalType.swift | 1 + .../LyrebirdShoeGaze/Pedals/VibePedal.swift | 154 ++++++++++++++++++ .../Presets/Factory/FactoryRigLibrary.swift | 31 ++++ .../Presets/PedalRegistry.swift | 1 + .../LyrebirdShoeGazeUI/PedalPaletteView.swift | 2 +- Sources/LyrebirdShoeGazeUI/PedalView.swift | 1 + .../VibePedalTests.swift | 104 ++++++++++++ 7 files changed, 293 insertions(+), 1 deletion(-) create mode 100644 Sources/LyrebirdShoeGaze/Pedals/VibePedal.swift create mode 100644 Tests/LyrebirdShoeGazeTests/VibePedalTests.swift diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index 97f560c..cb62d15 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -92,6 +92,7 @@ public extension PedalType { static let chorus = PedalType("Chorus") static let flanger = PedalType("Flanger") static let vibrato = PedalType("Vibrato") + static let vibe = PedalType("Vibe") static let rotary = PedalType("Rotary") static let ringModulator = PedalType("Ring Modulator") static let diffuser = PedalType("Diffuser") diff --git a/Sources/LyrebirdShoeGaze/Pedals/VibePedal.swift b/Sources/LyrebirdShoeGaze/Pedals/VibePedal.swift new file mode 100644 index 0000000..73fa5df --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/VibePedal.swift @@ -0,0 +1,154 @@ +// VibePedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Photocell "vibe" pedal: four staggered all-pass stages swept by one shared LFO. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → RBJAllPass(freq₀(t)) → RBJAllPass(freq₁(t)) → RBJAllPass(freq₂(t)) → RBJAllPass(freq₃(t)) → wet +/// out = wet·wetAmount + dry·dryAmount (mode: chorus blends dry+wet, vibrato is wet only) +/// ``` +/// +/// Unlike a phaser (evenly-spaced stages producing symmetric notches), the vibe cascades all-pass +/// stages at **staggered** centre frequencies, so the phase relationships between stages produce the +/// characteristic uneven, vocal throb. A single low-frequency sine modulates every stage's centre +/// frequency together; the `intensity` knob scales the sweep depth and the `speed` knob sets the LFO +/// rate. In *chorus* mode the swept signal is blended 50/50 with the dry signal (comb-filter throb); +/// in *vibrato* mode only the swept (phase-modulated) signal passes, for a pitch-vibrato-like warble. +/// +/// The bypass switching is handled by the `Pedal` base class. The base `mix` is fixed fully wet — the +/// chorus/vibrato dry blend is handled internally so the two modes behave correctly. +/// +/// ## Parameters +/// +/// Inherits `bypass` and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - speed: LFO sweep rate in Hz. Range `[0.1, 12.0]`. Defaults to `3.0`. +/// - intensity: Sweep depth as a fraction of each stage's centre frequency. Range `[0, 0.7]`. +/// Defaults to `0.5`. +/// - mode: `0` = chorus (dry + swept), `1` = vibrato (swept only). Defaults to chorus. +public final class VibePedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Throbbing photocell vibe — swirling chorus and warbling pitch-vibrato motion." + } + + // MARK: - Parameters + + /// LFO sweep rate in Hz. Range [0.1, 12.0]. + @UIParam public var speed: Double = 3.0 + + /// Sweep depth as a fraction of each stage's centre frequency. Range [0, 0.7]. + @UIParam public var intensity: Double = 0.5 + + /// Mode select: `0` = chorus (dry + swept), `1` = vibrato (swept only). + @UIParam public var mode: Double = 0.0 + + // MARK: - Constants + + /// Default wet/dry blend — fully wet; the chorus/vibrato dry mix is handled inside `effect`. + private static let defaultMix: Double = 1.0 + + /// Q for each all-pass stage. Gentle phase transition for a smooth, vocal vibe (not sharp notches). + private let vibeQ: Double = 0.6 + + /// Staggered all-pass stage centre frequencies in Hz. Unequal spacing is what distinguishes the + /// vibe's uneven throb from an evenly-spaced phaser. + private let stageCenterFreqs: [Double] = [300.0, 620.0, 1300.0, 2200.0] + + /// `mode` value selecting chorus (dry + swept). + private let modeChorusValue: Double = 0.0 + + /// `mode` value selecting vibrato (swept only). + private let modeVibratoValue: Double = 1.0 + + /// Wet gain at chorus mode (`mode == 0`); the swept signal sits 50/50 with dry. + private let chorusWetGain: Double = 0.5 + + // MARK: - UI knobs + + /// Speed knob range in Hz (LFO sweep rate). + private let speedRange: ClosedRange = 0.1 ... 12.0 + + /// Intensity knob range (sweep depth fraction). Capped below `1.0` so a stage's swept frequency + /// never collapses toward `0 Hz` at the bottom of the sweep. + private let intensityRange: ClosedRange = 0.0 ... 0.7 + + public override var tempoSyncableParams: [TempoSyncableParam] { + [ + TempoSyncableParam(key: "speed", label: "Speed", node: $speed, kind: .rate, range: speedRange), + ] + } + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Speed", node: $speed, range: speedRange), + PedalKnob(label: "Intensity", node: $intensity, range: intensityRange), + ] + } + + public override var effectSwitches: [PedalSwitch] { + [ + PedalSwitch( + label: "Mode", + node: $mode, + options: [ + PedalSwitch.Option(title: "Chorus", value: modeChorusValue), + PedalSwitch.Option(title: "Vibrato", value: modeVibratoValue), + ] + ), + ] + } + + // MARK: - Init + + /// Creates a vibe pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Vibe", + inputBus: inputBus, + outputBus: outputBus, + initialMix: VibePedal.defaultMix + ) + } + + // MARK: - Effect + + /// Cascades four staggered all-pass stages swept by a shared sine LFO, then blends per mode. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Wet mono vibe output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // One shared low-frequency sine drives every stage: ±1 scaled by intensity gives the sweep. + let lfo: any ValidGeneratorInput = OscSin.Audio(freq: $speed) + let sweep: any ValidGeneratorInput = lfo * $intensity // ±intensity + + // Cascade the stages. Each stage's centre frequency is centre·(1 + sweep) = centre + centre·sweep. + var signal: any ValidGeneratorInput = dry + for center: Double in stageCenterFreqs { + let stageFreq: any ValidGeneratorInput = sweep * center + center + signal = RBJAllPass.Audio(input: signal, freq: stageFreq, q: vibeQ) + } + let wet: any ValidGeneratorInput = signal + + // Blend by mode. Chorus (mode 0): 0.5·dry + 0.5·wet. Vibrato (mode 1): wet only. + let wetAmount: any ValidGeneratorInput = $mode * chorusWetGain + chorusWetGain // 0.5 → 1.0 + let dryAmount: any ValidGeneratorInput = (modeVibratoValue - $mode) * chorusWetGain // 0.5 → 0.0 + return wet * wetAmount + dry * dryAmount + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index fa3729d..a774154 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -79,6 +79,7 @@ public enum FactoryRigLibrary { dubDelayThrow, ringModTexture, rockabillySlapback, + psychVibeLead, ] // MARK: Shoegaze walls @@ -508,6 +509,36 @@ public enum FactoryRigLibrary { } } + /// Fuzz swirled by a throbbing vibe into delay and plate — vintage psychedelic lead. + static let psychVibeLead: FactoryRig = FactoryRig( + id: stableID("Psych Vibe Lead"), + name: "Psychedelic Vibe Lead", + blurb: "Thick fuzz swirled by a throbbing photocell vibe, into delay and plate — the " + + "late-'60s psychedelic lead voice. Hold notes and let the vibe pulse underneath.", + category: .classic + ) { _, board in + try board.append(FuzzPedal()) { p in + p.fuzz = 30.0 + p.tone = 3000.0 + } + try board.append(VibePedal()) { p in + p.speed = 2.5 + p.intensity = 0.6 + // Chorus mode: dry + swept, the classic vibe throb. + p.mode = 0.0 + } + try board.append(DelayPedal()) { p in + p.time = 0.4 + p.feedback = 2.0 + } + try board.append(PlateReverbPedal()) { p in + p.decay = 0.6 + p.tone = 0.75 + p.damp = 0.3 + p.mod = 0.5 + } + } + // MARK: - Seeding /// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library. diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 3edd427..92a452c 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -91,6 +91,7 @@ public enum PedalRegistry { "Chorus": { ChorusPedal() }, "Flanger": { FlangerPedal() }, "Vibrato": { VibratoPedal() }, + "Vibe": { VibePedal() }, "Rotary": { RotaryPedal() }, "Sustainer": { SustainerPedal() }, "Ring Modulator": { RingModulatorPedal() }, diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index 2cb16db..a682933 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -56,7 +56,7 @@ public struct PedalPaletteView: View { private static let preferredOrder: [String] = [ "California", "British", "British Plexi", "British JTM", "British Bluesbreaker", "British Master", "British Dual", "Boutique Lead", "Boutique OD", "Cali Hi-Gain", "Command", "Citrus", "Sixties Combo", "Magna Vibrato", "Anaheim", "Modern High-Gain", "Chime", "Chime 15", "Chime Normal", "Chime Baby", "Fullerton Reverb", "Fullerton Deluxe", "Fullerton Ivy League", "Fullerton Drive", "Jazz Clean", "Chime Top Boost", "Cabinet", "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "Volume", - "Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", + "Graphic EQ", "Tremolo", "Phaser", "Vibe", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", "Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator", "Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer", "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb", diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index 161aa99..0d93e66 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -56,6 +56,7 @@ private func enclosureColor(for displayName: String) -> Color { case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet + case "Vibe": return Color(red: 0.28, green: 0.20, blue: 0.62) // deep indigo case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold diff --git a/Tests/LyrebirdShoeGazeTests/VibePedalTests.swift b/Tests/LyrebirdShoeGazeTests/VibePedalTests.swift new file mode 100644 index 0000000..899f1be --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/VibePedalTests.swift @@ -0,0 +1,104 @@ +// VibePedalTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("VibePedal") +struct VibePedalTests { + + /// Renders the test loop through a vibe pedal configured by `configure`, returning stereo samples. + private func render(configure: (VibePedal) -> Void) throws -> [Float] { + let renderDuration: Double = 0.2 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: VibePedal = VibePedal(inputBus: srcBus.index, outputBus: dstBus.index) + configure(pedal) + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + return readStereoCAF(url: url) + } + + /// Sum of squared differences over a mid-render window, guarding on length. + private func windowSSD(_ a: [Float], _ b: [Float]) -> Double { + let skip: Int = 1024 + let window: Int = 2048 + guard a.count >= skip + window, b.count >= skip + window else { return 0 } + let aw: ArraySlice = a[skip..<(skip + window)] + let bw: ArraySlice = b[skip..<(skip + window)] + return zip(aw, bw).reduce(0.0) { acc, pair in + let d: Double = Double(pair.0 - pair.1) + return acc + d * d + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "VibePedal produced silence") + } + + @Test func speedChangesOutput() throws { + let slow: [Float] = try render { $0.speed = 1.0 } + let fast: [Float] = try render { $0.speed = 8.0 } + #expect(hasNonSilentOutput(slow)) + #expect(hasNonSilentOutput(fast)) + #expect(windowSSD(slow, fast) > 0, "vibe speed did not change output") + } + + @Test func intensityChangesOutput() throws { + let shallow: [Float] = try render { $0.intensity = 0.1 } + let deep: [Float] = try render { $0.intensity = 0.7 } + #expect(windowSSD(shallow, deep) > 0, "vibe intensity did not change output") + } + + @Test func modeChangesOutput() throws { + let chorus: [Float] = try render { $0.mode = 0.0 } + let vibrato: [Float] = try render { $0.mode = 1.0 } + #expect(hasNonSilentOutput(chorus)) + #expect(hasNonSilentOutput(vibrato)) + #expect(windowSSD(chorus, vibrato) > 0, "chorus and vibrato modes produced identical output") + } + + @Test func exposesSpeedIntensityKnobsAndModeSwitch() { + let pedal: VibePedal = VibePedal() + #expect(pedal.effectKnobs.map { $0.label } == ["Speed", "Intensity"]) + #expect(pedal.effectSwitches.map { $0.label } == ["Mode"]) + #expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Chorus", "Vibrato"]) + } + + @Test func stateRoundTripsThroughPreset() { + let pedal: VibePedal = VibePedal() + pedal.speed = 6.5 + pedal.intensity = 0.42 + pedal.mode = 1.0 + + let state: PedalState = pedal.captureState() + let restored: VibePedal = VibePedal() + restored.applyState(state) + + #expect(restored.speed == 6.5) + #expect(restored.intensity == 0.42) + #expect(restored.mode == 1.0) + } +} From 75b99a547b509a4270de9ecacb4832bda1af7678 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 13:10:16 -0700 Subject: [PATCH 05/18] feat(pedals): add Sustain Fuzz pedal + Gilmour/doom rigs New "Sustain Fuzz": a mid-scooped, high-sustain fuzz distinct from the single-stage Fuzz. Two cascaded soft-clip (softClipNormalized) stages compress and stack harmonics for smooth violin-like sustain; a fixed midrange scoop (RBJPeakingEQ cut at 750 Hz) hollows the mids; a tone low-pass sets the top end. Sustain/Tone/Scoop knobs. Composed in effect(), no new RT generator. Registered in PedalType/PedalRegistry, enclosure colour, palette order. Tests cover build+non-silent, each knob changing output, knob listing, preset round-trip. Adds two factory rigs: Comfortably Numb Lead and Doom Riff Wall. Co-Authored-By: Claude Opus 4.8 --- Sources/LyrebirdShoeGaze/PedalType.swift | 1 + .../Pedals/SustainFuzzPedal.swift | 150 ++++++++++++++++++ .../Presets/Factory/FactoryRigLibrary.swift | 61 +++++++ .../Presets/PedalRegistry.swift | 1 + .../LyrebirdShoeGazeUI/PedalPaletteView.swift | 2 +- Sources/LyrebirdShoeGazeUI/PedalView.swift | 1 + .../SustainFuzzPedalTests.swift | 100 ++++++++++++ 7 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 Sources/LyrebirdShoeGaze/Pedals/SustainFuzzPedal.swift create mode 100644 Tests/LyrebirdShoeGazeTests/SustainFuzzPedalTests.swift diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index cb62d15..353f863 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -74,6 +74,7 @@ public extension PedalType { static let overdrive = PedalType("Overdrive") static let distortion = PedalType("Distortion") static let fuzz = PedalType("Fuzz") + static let sustainFuzz = PedalType("Sustain Fuzz") static let compressor = PedalType("Compressor") static let limiter = PedalType("Limiter") static let noiseGate = PedalType("Noise Gate") diff --git a/Sources/LyrebirdShoeGaze/Pedals/SustainFuzzPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/SustainFuzzPedal.swift new file mode 100644 index 0000000..22627af --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/SustainFuzzPedal.swift @@ -0,0 +1,150 @@ +// SustainFuzzPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Sustaining, mid-scooped fuzz: two cascaded soft-clipping stages into a scoop-and-tone filter. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → Saturator(soft, sustain) → Saturator(soft, sustain) → RBJPeakingEQ(−scoop @ 750 Hz) → RBJLowPass(tone) → out +/// ``` +/// +/// This is the "wall of sustain" fuzz voice — distinct from the single-stage ``FuzzPedal``. Two +/// cascaded *soft*-clipping stages compress and stack harmonics for long, smooth, violin-like +/// sustain rather than the aggressive bite of a single hard `tanh` stage. A fixed mid **scoop** +/// (a bell cut around 750 Hz) hollows the midrange — the defining character of this fuzz family — +/// and the **tone** low-pass sets how dark or bright the top end sits. +/// +/// The wet/dry mix and bypass switching are handled by the `Pedal` base class; base `mix` is fully +/// wet so the fuzz replaces the dry signal. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - sustain: Drive into both soft-clip stages. Higher = more sustain and compression. +/// Range `[1, 30]`. Defaults to `6.0`. +/// - tone: Low-pass tone cutoff in Hz. Range `[800, 6000]`. Defaults to `2500.0`. +/// - scoop: Midrange cut depth in dB at 750 Hz (applied as a cut). Range `[0, 18]`. Defaults to `8.0`. +public final class SustainFuzzPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Sustaining, mid-scooped fuzz for smooth, violin-like leads and thick walls of sound." + } + + // MARK: - Parameters + + /// Drive into both cascaded soft-clip stages. Range [1, 30]; higher = more sustain. + @UIParam public var sustain: Double = 6.0 + + /// Tone low-pass cutoff in Hz. Range [800, 6000]. + @UIParam public var tone: Double = 2500.0 + + /// Midrange cut depth in dB at 750 Hz. Range [0, 18]. + @UIParam public var scoop: Double = 8.0 + + // MARK: - Constants + + /// Default wet/dry blend — fully wet so the fuzz completely replaces the dry signal. + private static let defaultMix: Double = 1.0 + + /// Oversampling factor for the soft-clip stages — 2× keeps generated harmonics from folding back. + private let oversampleFactor: Int = 2 + + /// Centre frequency of the midrange scoop in Hz. + private let scoopFreq: Double = 750.0 + + /// Q of the midrange scoop bell. Moderately wide for a broad, hollow midrange. + private let scoopQ: Double = 0.9 + + /// Q of the tone low-pass. Butterworth (no resonant peak). + private let toneQ: Double = 0.707 + + /// Output trim after two soft-clip stages (each ≈ ±1) plus the mid cut, to sit at a sane level. + private let outputTrim: Double = 0.6 + + // MARK: - UI knobs + + /// Sustain knob range (drive into the soft-clip stages). + private let sustainRange: ClosedRange = 1.0 ... 30.0 + + /// Tone knob range in Hz (low-pass cutoff). + private let toneRange: ClosedRange = 800.0 ... 6000.0 + + /// Scoop knob range in dB (midrange cut depth). + private let scoopRange: ClosedRange = 0.0 ... 18.0 + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Sustain", node: $sustain, range: sustainRange), + PedalKnob(label: "Tone", node: $tone, range: toneRange), + PedalKnob(label: "Scoop", node: $scoop, range: scoopRange), + ] + } + + // MARK: - Init + + /// Creates a sustain-fuzz pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Sustain Fuzz", + inputBus: inputBus, + outputBus: outputBus, + initialMix: SustainFuzzPedal.defaultMix + ) + } + + // MARK: - Effect + + /// Cascades two soft-clip stages, scoops the mids, then rolls off the top with the tone control. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Sustained, mid-scooped, tone-shaped mono output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // Two cascaded soft-clip stages. `softClipNormalized` keeps the level bounded as sustain + // rises, so stacking two stages compresses and sustains rather than runs away. + let stage1: OversampledSaturator = OversampledSaturator( + dry, + drive: $sustain, + curve: .softClipNormalized, + oversample: oversampleFactor + ) + let stage2: OversampledSaturator = OversampledSaturator( + stage1, + drive: $sustain, + curve: .softClipNormalized, + oversample: oversampleFactor + ) + + // Fixed midrange scoop (cut) — the hollow midrange that defines this fuzz family. + let scoopCutDB: any ValidGeneratorInput = 0.0 - $scoop + let scooped: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio( + input: stage2, + freq: scoopFreq, + gain: scoopCutDB, + q: scoopQ + ) + + // Tone low-pass rolls off the top end. + let toned: RBJLowPass.Audio = RBJLowPass.Audio( + input: scooped, + freq: $tone, + q: toneQ + ) + return toned * outputTrim + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index a774154..a1282fe 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -80,6 +80,8 @@ public enum FactoryRigLibrary { ringModTexture, rockabillySlapback, psychVibeLead, + comfortablyNumbLead, + doomRiffWall, ] // MARK: Shoegaze walls @@ -539,6 +541,65 @@ public enum FactoryRigLibrary { } } + /// Compressed sustaining fuzz into a dotted delay and shimmer — a soaring, singing lead. + static let comfortablyNumbLead: FactoryRig = FactoryRig( + id: stableID("Comfortably Numb Lead"), + name: "Comfortably Numb Lead", + blurb: "Compressed, mid-scooped sustain fuzz into a dotted delay and octave-up shimmer — a " + + "soaring, singing lead that holds forever. Bend into long notes and let them bloom.", + category: .classic + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 4.0 + p.threshold = -18.0 + p.ratio = 4.0 + } + try board.append(SustainFuzzPedal()) { p in + p.sustain = 14.0 + p.tone = 3000.0 + p.scoop = 10.0 + } + try board.append(DelayPedal()) { p in + // Dotted eighth at ~100 BPM. + p.time = 0.45 + p.feedback = 2.2 + } + try board.append(ShimmerReverbPedal()) { p in + p.size = 0.09 + p.decay = 0.85 + p.shimmer = 0.5 + p.damp = 0.35 + } + } + + /// Sub-octave under a huge scooped fuzz into a cavernous room — heavy, slow doom. + static let doomRiffWall: FactoryRig = FactoryRig( + id: stableID("Doom Riff Wall"), + name: "Doom Riff Wall", + blurb: "A sub-octave stacked under a huge mid-scooped fuzz, into a cavernous room — crushing, " + + "slow doom. Down-tune, play half-time and let the low end swallow the room.", + category: .experimental + ) { _, board in + try board.append(BassOctaverPedal()) { p in + p.oct1 = 0.8 + p.oct2 = 0.3 + p.direct = 0.9 + // Track mode: follow the played pitch. + p.mode = 1.0 + } + try board.append(SustainFuzzPedal()) { p in + p.sustain = 22.0 + p.tone = 2200.0 + p.scoop = 6.0 + } + try board.append(RoomReverbPedal()) { p in + p.size = 70.0 + p.decay = 6.0 + p.damp = 0.55 + p.tail = 0.7 + } + } + // MARK: - Seeding /// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library. diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 92a452c..4cc200d 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -66,6 +66,7 @@ public enum PedalRegistry { "Reverb": { ReverbPedal() }, "Modulation": { ModulationPedal() }, "Fuzz": { FuzzPedal() }, + "Sustain Fuzz": { SustainFuzzPedal() }, "Tremolo": { TremoloPedal() }, "Phaser": { PhaserPedal() }, "Compressor": { CompressorPedal() }, diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index a682933..5d58da9 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -54,7 +54,7 @@ public struct PedalPaletteView: View { /// Preferred display order for the built-in pedals. Any registered pedal not listed here is /// appended afterwards (sorted) so the palette never silently drops a newly added pedal. private static let preferredOrder: [String] = [ - "California", "British", "British Plexi", "British JTM", "British Bluesbreaker", "British Master", "British Dual", "Boutique Lead", "Boutique OD", "Cali Hi-Gain", "Command", "Citrus", "Sixties Combo", "Magna Vibrato", "Anaheim", "Modern High-Gain", "Chime", "Chime 15", "Chime Normal", "Chime Baby", "Fullerton Reverb", "Fullerton Deluxe", "Fullerton Ivy League", "Fullerton Drive", "Jazz Clean", "Chime Top Boost", "Cabinet", "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", + "California", "British", "British Plexi", "British JTM", "British Bluesbreaker", "British Master", "British Dual", "Boutique Lead", "Boutique OD", "Cali Hi-Gain", "Command", "Citrus", "Sixties Combo", "Magna Vibrato", "Anaheim", "Modern High-Gain", "Chime", "Chime 15", "Chime Normal", "Chime Baby", "Fullerton Reverb", "Fullerton Deluxe", "Fullerton Ivy League", "Fullerton Drive", "Jazz Clean", "Chime Top Boost", "Cabinet", "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "Sustain Fuzz", "Volume", "Graphic EQ", "Tremolo", "Phaser", "Vibe", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", "Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator", diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index 0d93e66..43940cd 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -54,6 +54,7 @@ private func enclosureColor(for displayName: String) -> Color { case "Spring Reverb": return Color(red: 0.20, green: 0.46, blue: 0.64) // steel cyan case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson + case "Sustain Fuzz": return Color(red: 0.72, green: 0.24, blue: 0.10) // rust / burnt orange case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet case "Vibe": return Color(red: 0.28, green: 0.20, blue: 0.62) // deep indigo diff --git a/Tests/LyrebirdShoeGazeTests/SustainFuzzPedalTests.swift b/Tests/LyrebirdShoeGazeTests/SustainFuzzPedalTests.swift new file mode 100644 index 0000000..3f9e6ea --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/SustainFuzzPedalTests.swift @@ -0,0 +1,100 @@ +// SustainFuzzPedalTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("SustainFuzzPedal") +struct SustainFuzzPedalTests { + + /// Renders the test loop through a sustain-fuzz configured by `configure`, returning stereo samples. + private func render(configure: (SustainFuzzPedal) -> Void) throws -> [Float] { + let renderDuration: Double = 0.2 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: SustainFuzzPedal = SustainFuzzPedal(inputBus: srcBus.index, outputBus: dstBus.index) + configure(pedal) + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + return readStereoCAF(url: url) + } + + /// Sum of squared differences over a mid-render window, guarding on length. + private func windowSSD(_ a: [Float], _ b: [Float]) -> Double { + let skip: Int = 1024 + let window: Int = 2048 + guard a.count >= skip + window, b.count >= skip + window else { return 0 } + let aw: ArraySlice = a[skip..<(skip + window)] + let bw: ArraySlice = b[skip..<(skip + window)] + return zip(aw, bw).reduce(0.0) { acc, pair in + let d: Double = Double(pair.0 - pair.1) + return acc + d * d + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "SustainFuzzPedal produced silence") + } + + @Test func sustainChangesOutput() throws { + let low: [Float] = try render { $0.sustain = 2.0 } + let high: [Float] = try render { $0.sustain = 25.0 } + #expect(hasNonSilentOutput(low)) + #expect(hasNonSilentOutput(high)) + #expect(windowSSD(low, high) > 0, "sustain did not change output") + } + + @Test func toneChangesOutput() throws { + let dark: [Float] = try render { $0.tone = 900.0 } + let bright: [Float] = try render { $0.tone = 5500.0 } + #expect(windowSSD(dark, bright) > 0, "tone did not change output") + } + + @Test func scoopChangesOutput() throws { + let flat: [Float] = try render { $0.scoop = 0.0 } + let scooped: [Float] = try render { $0.scoop = 16.0 } + #expect(windowSSD(flat, scooped) > 0, "scoop did not change output") + } + + @Test func exposesSustainToneScoopKnobs() { + let pedal: SustainFuzzPedal = SustainFuzzPedal() + #expect(pedal.effectKnobs.map { $0.label } == ["Sustain", "Tone", "Scoop"]) + } + + @Test func stateRoundTripsThroughPreset() { + let pedal: SustainFuzzPedal = SustainFuzzPedal() + pedal.sustain = 18.0 + pedal.tone = 3200.0 + pedal.scoop = 12.0 + + let state: PedalState = pedal.captureState() + let restored: SustainFuzzPedal = SustainFuzzPedal() + restored.applyState(state) + + #expect(restored.sustain == 18.0) + #expect(restored.tone == 3200.0) + #expect(restored.scoop == 12.0) + } +} From 7dccf596f4df478778090fb00564eaf7b1f53e7d Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 13:19:42 -0700 Subject: [PATCH 06/18] feat(rigs): persist chain routers + add Garcia two-board split rig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add ChainRouter persistence so routed multi-board rigs survive save/load — previously captureState/loadRig only handled plain boards, so any A/B router rig was silently lost on save (a latent gap this fixes for user rigs too). - New ChainRouterState (Codable): each router's two linear branches as [PedalState] plus splitter branch levels and merger output levels. - ShoeGazeState gains an additive `routers` field decoded with decodeIfPresent (nil for old rigs) — no format-version bump; routerless rigs stay byte-identical (nil, not []). - captureState snapshots routers; rebuildAllBoards reconstructs each via makeChainRouter/addTo{A,B}/finalize and restores the blend. FactoryRig gains a session-scoped builder variant (FactoryRigBuild enum) so a rig can create its own boards/routers; makeEntries branches on it. Ships the Garcia OBEL Clean/Effects Split: an effects/lead board (octave, envelope filter, overdrive, phaser, delay, amp) vs a clean direct board, selectable via the router — showcasing the multi-board capability. Tests: full router capture -> JSON -> load round-trip with structure and branch-level assertions plus a render check, backward-compat (no routers key when routerless), and the Garcia rig via the factory load+render suite. Co-Authored-By: Claude Opus 4.8 --- .../Presets/ChainRouterState.swift | 59 ++++++++++ .../Presets/Factory/FactoryRig.swift | 55 ++++++++-- .../Presets/Factory/FactoryRigLibrary.swift | 103 +++++++++++++++++- .../Presets/ShoeGaze+Preset.swift | 44 +++++++- .../Presets/ShoeGazeState.swift | 12 +- Sources/LyrebirdShoeGaze/ShoeGaze.swift | 5 +- .../ChainRouterPersistenceTests.swift | 79 ++++++++++++++ .../FactoryRigLibraryTests.swift | 9 +- 8 files changed, 348 insertions(+), 18 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift create mode 100644 Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift diff --git a/Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift b/Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift new file mode 100644 index 0000000..cb4693d --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift @@ -0,0 +1,59 @@ +// ChainRouterState.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Serialisable snapshot of one ``ChainRouter`` — its two linear board chains and its blend state. +/// +/// A router splits one input to two independent boards and blends their outputs. Its branches are +/// built linearly (via ``ChainRouter/addToA(_:)`` / ``ChainRouter/addToB(_:)``), so each is captured +/// as a flat list of ``PedalState``. The splitter's two branch-enable levels capture the A / B / both +/// selection (and any continuous blend between them); the merger's two levels capture the output mix. +/// +/// Persisted as part of ``ShoeGazeState/routers`` so a routed multi-board rig survives save / load. +public struct ChainRouterState: Codable, Equatable { + + /// Pedals on board A (the first branch), in chain order. + public let boardA: [PedalState] + + /// Pedals on board B (the second branch), in chain order. + public let boardB: [PedalState] + + /// Splitter branch-A enable level in `[0, 1]`. `1` = A audible, `0` = A muted. + public let branchA: Double + + /// Splitter branch-B enable level in `[0, 1]`. `1` = B audible, `0` = B muted. + public let branchB: Double + + /// Merger board-A output level in `[0, 1]`. + public let mergerLevelA: Double + + /// Merger board-B output level in `[0, 1]`. + public let mergerLevelB: Double + + /// Creates a router snapshot. + /// + /// - Parameters: + /// - boardA: Board A's pedals in chain order. + /// - boardB: Board B's pedals in chain order. + /// - branchA: Splitter branch-A enable level `[0, 1]`. + /// - branchB: Splitter branch-B enable level `[0, 1]`. + /// - mergerLevelA: Merger board-A output level `[0, 1]`. + /// - mergerLevelB: Merger board-B output level `[0, 1]`. + public init( + boardA: [PedalState], + boardB: [PedalState], + branchA: Double, + branchB: Double, + mergerLevelA: Double, + mergerLevelB: Double + ) { + self.boardA = boardA + self.boardB = boardB + self.branchA = branchA + self.branchB = branchB + self.mergerLevelA = mergerLevelA + self.mergerLevelB = mergerLevelB + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift index 97f63cc..2b2bce8 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift @@ -40,13 +40,14 @@ public struct FactoryRig: Identifiable, Sendable { /// Sonic family this rig belongs to, for grouping in a picker. Presentational only. public let category: FactoryRigCategory - /// Builds the rig's pedal chain into `board`, an empty board freshly returned by - /// `session.addBoard()`. Set pedal parameters via the typed `configure` closures of - /// ``FactoryRigLibrary``'s helpers. Do **not** call `finalizeBoard` / `captureEntry` here — the - /// seeding driver owns that lifecycle. - public let build: @MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void + /// How this rig builds its graph at seed time. + public let build: FactoryRigBuild - /// Creates a factory rig descriptor. + /// Creates a single-board factory rig. + /// + /// The `build` closure receives a fresh, empty ``PedalBoard`` (already returned by + /// `session.addBoard()`) and appends pedals to it. Do **not** call `finalizeBoard` / + /// `captureEntry` here — the seeding driver owns that lifecycle. /// /// - Parameters: /// - id: Stable identifier (a fixed literal per rig — see ``id``). @@ -65,6 +66,46 @@ public struct FactoryRig: Identifiable, Sendable { self.name = name self.blurb = blurb self.category = category - self.build = build + self.build = .singleBoard(build) + } + + /// Creates a session-scoped factory rig that builds its own boards and/or routers. + /// + /// Use this for rigs the single-board form can't express — e.g. a two-board signal split via + /// ``ShoeGaze/makeChainRouter()``. The `sessionBuild` closure gets the whole session and owns the + /// full lifecycle for what it creates: it must call `addBoard`/`finalizeBoard` (for plain boards) + /// and/or `makeChainRouter`/`addToA`/`addToB`/`finalize` (for routers) itself. Do **not** call + /// `captureEntry` here — the seeding driver owns that. + /// + /// - Parameters: + /// - id: Stable identifier (a fixed literal per rig — see ``id``). + /// - name: Rig name (picker title + saved entry name). + /// - blurb: User-facing description of the sound. + /// - category: Sonic family for picker grouping. + /// - sessionBuild: Graph-building closure run against the session at seed time. + public init( + id: UUID, + name: String, + blurb: String, + category: FactoryRigCategory, + sessionBuild: @escaping @MainActor (_ session: ShoeGaze) throws -> Void + ) { + self.id = id + self.name = name + self.blurb = blurb + self.category = category + self.build = .session(sessionBuild) } } + +/// How a ``FactoryRig`` builds its graph at seed time. +public enum FactoryRigBuild: Sendable { + + /// Appends pedals to a single pre-made, empty board; the seeding driver calls `addBoard` before + /// and `finalizeBoard` after. + case singleBoard(@MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void) + + /// Builds the whole graph against the session (boards and/or routers), owning its own + /// `addBoard`/`finalizeBoard` and `makeChainRouter`/`finalize` lifecycle. + case session(@MainActor (_ session: ShoeGaze) throws -> Void) +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index a1282fe..1d1bfed 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -35,6 +35,28 @@ extension PedalBoard { } } +extension ChainRouter { + + /// Constructs a concrete pedal, applies `configure`, and appends it to board A of the router. + /// + /// The concrete-type `configure` closure keeps every parameter compile-checked, exactly like + /// ``PedalBoard/append(_:configure:)``. Uses ``addToA(_:)`` so ``finalize()`` ordering stays correct. + @discardableResult + func appendToA(_ pedal: P, configure: (P) -> Void) throws -> P { + configure(pedal) + try addToA(pedal) + return pedal + } + + /// Constructs a concrete pedal, applies `configure`, and appends it to board B of the router. + @discardableResult + func appendToB(_ pedal: P, configure: (P) -> Void) throws -> P { + configure(pedal) + try addToB(pedal) + return pedal + } +} + // MARK: - Factory rig catalog /// The built-in starter rigs shipped with the app and seeded into an empty rig library on first @@ -82,6 +104,7 @@ public enum FactoryRigLibrary { psychVibeLead, comfortablyNumbLead, doomRiffWall, + garciaOBELSplit, ] // MARK: Shoegaze walls @@ -600,6 +623,69 @@ public enum FactoryRigLibrary { } } + // MARK: Two-board split + + /// A two-board split — a full effects chain vs a clean direct path — selectable like an on-board + /// effects loop. Showcases the multi-board router. + static let garciaOBELSplit: FactoryRig = FactoryRig( + id: stableID("Garcia OBEL Split"), + name: "Garcia OBEL Clean/Effects Split", + blurb: "Two boards, one footswitch: an effects/lead chain (octave, envelope filter, " + + "overdrive, phaser, delay) versus a clean direct path — switch between them like an " + + "on-board effects loop. In the spirit of a certain improvising guitarist's late-'80s " + + "rig. Flip the router to A for effects, B for clean.", + category: .classic, + sessionBuild: { session in + let router: ChainRouter = try session.makeChainRouter() + + // Board A — the effects / lead chain (effects loop engaged). + try router.appendToA(BassOctaverPedal()) { p in + p.oct1 = 0.5 + p.direct = 1.0 + p.mode = 1.0 + } + try router.appendToA(MutantPedal()) { p in + p.sensitivity = 2.5 + p.resonance = 5.0 + } + try router.appendToA(OverdrivePedal()) { p in + p.drive = 5.0 + p.tone = 4200.0 + } + try router.appendToA(PhaserPedal()) { p in + p.rate = 0.4 + p.feedback = 0.4 + } + try router.appendToA(DelayPedal()) { p in + p.time = 0.35 + p.feedback = 1.8 + } + try router.appendToA(CaliforniaAmpPedal()) { p in + p.gain = 5.0 + p.bass = 0.55 + p.mid = 0.6 + p.treble = 0.6 + } + + // Board B — the clean / direct path (effects loop bypassed). + try router.appendToB(CompressorPedal()) { p in + p.inputGain = 2.0 + p.threshold = -16.0 + p.ratio = 3.0 + } + try router.appendToB(CaliforniaAmpPedal()) { p in + p.gain = 3.5 + p.bass = 0.5 + p.mid = 0.55 + p.treble = 0.6 + } + + // Default to the effects board; the router's A/B control switches paths. + router.mode = .a + try router.finalize() + } + ) + // MARK: - Seeding /// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library. @@ -620,12 +706,19 @@ public enum FactoryRigLibrary { entries.reserveCapacity(all.count) for rig: FactoryRig in all { let session: ShoeGaze = try makeSession() - // Tear down on every exit from this iteration, including a throw from `build` / - // `finalizeBoard`, so a failing rig never leaks its throwaway engine's buses/nodes. + // Tear down on every exit from this iteration, including a throw from a builder, so a + // failing rig never leaks its throwaway engine's buses/nodes. defer { session.teardown() } - let board: PedalBoard = try session.addBoard() - try rig.build(session, board) - try session.finalizeBoard(board) + switch rig.build { + case .singleBoard(let build): + let board: PedalBoard = try session.addBoard() + try build(session, board) + try session.finalizeBoard(board) + case .session(let build): + // The builder owns its own board/router lifecycle (addBoard/finalizeBoard, + // makeChainRouter/finalize). + try build(session) + } entries.append(session.captureEntry(name: rig.name, id: rig.id)) } return entries diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index 0a9f292..5a45135 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -18,6 +18,16 @@ extension ShoeGaze { /// - Returns: A `ShoeGazeState` reflecting the current rig. public func captureState() -> ShoeGazeState { let boardStates: [BoardState] = boards.map { $0.captureState() } + let routerStates: [ChainRouterState] = routers.map { router in + ChainRouterState( + boardA: router.boardA.pedals.map { $0.captureState() }, + boardB: router.boardB.pedals.map { $0.captureState() }, + branchA: router.splitter.branchAEnabled, + branchB: router.splitter.branchBEnabled, + mergerLevelA: router.merger?.levelA ?? 1.0, + mergerLevelB: router.merger?.levelB ?? 1.0 + ) + } return ShoeGazeState( boards: boardStates, midiMap: midiMap, @@ -25,7 +35,10 @@ extension ShoeGaze { tempoEnabled: tempoEnabled, inputSource: inputSource, numInputChannels: engine.numInputChannels, - numOutputChannels: engine.numOutputChannels + numOutputChannels: engine.numOutputChannels, + // `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is + // unchanged and byte-identical to one saved before router persistence existed. + routers: routerStates.isEmpty ? nil : routerStates ) } @@ -162,6 +175,9 @@ extension ShoeGaze { try rebuildSegments(boardState.segments, into: board) try finalizeBoard(board) } + for routerState: ChainRouterState in snapshot.routers ?? [] { + try rebuildRouter(routerState) + } } catch { // Leave no partial rig behind: tear down whatever was built, then rethrow. teardown() @@ -169,6 +185,32 @@ extension ShoeGaze { } } + /// Reconstructs one ``ChainRouter`` from a saved snapshot: creates the router, replays both linear + /// branches (skipping unknown pedal types), finalizes, then restores the splitter branch levels + /// and merger output levels so the saved A / B / blend selection is preserved. + /// + /// - Parameter state: The router snapshot to reconstruct. + /// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from router construction. + private func rebuildRouter(_ state: ChainRouterState) throws { + let router: ChainRouter = try makeChainRouter() + for pedalState: PedalState in state.boardA { + if let pedal: Pedal = makeAndApply(pedalState) { + try router.addToA(pedal) + } + } + for pedalState: PedalState in state.boardB { + if let pedal: Pedal = makeAndApply(pedalState) { + try router.addToB(pedal) + } + } + try router.finalize() + // Restore the blend after finalize: the splitter exists from init, the merger only after. + router.splitter.branchAEnabled = state.branchA + router.splitter.branchBEnabled = state.branchB + router.merger?.levelA = state.mergerLevelA + router.merger?.levelB = state.mergerLevelB + } + /// Loads a rig from a JSON preset file and rebuilds the engine graph. /// /// This method: diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift index 0143480..60df45d 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift @@ -57,6 +57,11 @@ public struct ShoeGazeState: Codable, Equatable { /// persistence. Reapplied on load under the same conditions as ``numInputChannels``. public let numOutputChannels: Int? + /// The rig's chain routers (two-board split/blend units), or `nil` for a rig saved before router + /// persistence existed. Additive: decoded with `decodeIfPresent`, so older rigs — which never had + /// routers — decode cleanly to `nil` without a format-version bump. + public let routers: [ChainRouterState]? + /// Creates a rig state snapshot. /// /// - Parameters: @@ -68,6 +73,7 @@ public struct ShoeGazeState: Codable, Equatable { /// - inputSource: The rig's input selection, or `nil` to not persist one. Defaults to `nil`. /// - numInputChannels: The engine input-channel count, or `nil`. Defaults to `nil`. /// - numOutputChannels: The engine output-channel count, or `nil`. Defaults to `nil`. + /// - routers: The rig's chain routers, or `nil` when there are none. Defaults to `nil`. public init( version: Int = presetFormatVersion, boards: [BoardState], @@ -76,7 +82,8 @@ public struct ShoeGazeState: Codable, Equatable { tempoEnabled: Bool? = nil, inputSource: InputSource? = nil, numInputChannels: Int? = nil, - numOutputChannels: Int? = nil + numOutputChannels: Int? = nil, + routers: [ChainRouterState]? = nil ) { self.version = version self.boards = boards @@ -86,6 +93,7 @@ public struct ShoeGazeState: Codable, Equatable { self.inputSource = inputSource self.numInputChannels = numInputChannels self.numOutputChannels = numOutputChannels + self.routers = routers } private enum CodingKeys: String, CodingKey { @@ -97,6 +105,7 @@ public struct ShoeGazeState: Codable, Equatable { case inputSource case numInputChannels case numOutputChannels + case routers } /// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`. @@ -129,5 +138,6 @@ public struct ShoeGazeState: Codable, Equatable { self.inputSource = try container.decodeIfPresent(InputSource.self, forKey: .inputSource) self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels) self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels) + self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers) } } diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 4063e1f..6ecd5f1 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -199,7 +199,10 @@ public final class ShoeGaze { /// All chain routers created via ``makeChainRouter()``. /// Routers are torn down (in reverse-creation order) by ``teardown()``. - private var routers: [ChainRouter] = [] + /// + /// `internal` (not `private`) so the preset capture/rebuild path in `ShoeGaze+Preset.swift` can + /// snapshot and reconstruct routers. + var routers: [ChainRouter] = [] // MARK: - Init diff --git a/Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift b/Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift new file mode 100644 index 0000000..4cbd8c3 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift @@ -0,0 +1,79 @@ +// ChainRouterPersistenceTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("ChainRouter persistence") +struct ChainRouterPersistenceTests { + + @Test func routerRigRoundTripsThroughJSONAndRenders() throws { + // Build a routed session: two-pedal board A, one-pedal board B, selecting board B. + let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: urlA) } + let sessionA: ShoeGaze = ShoeGaze(engine: engineA) + let router: ChainRouter = try sessionA.makeChainRouter() + try router.addToA(FuzzPedal()) + try router.addToA(OverdrivePedal()) + try router.addToB(ReverbPedal()) + router.mode = .b + try router.finalize() + + let state: ShoeGazeState = sessionA.captureState() + #expect(state.routers?.count == 1, "router was not captured") + #expect(state.boards.isEmpty, "router rig should have no plain boards") + + // JSON round-trip. + let data: Data = try JSONEncoder().encode(state) + let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) + #expect(decoded == state, "router state did not survive a JSON round-trip") + + // Load into a fresh session and verify the router was rebuilt structurally. + let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: urlB) } + let sessionB: ShoeGaze = ShoeGaze(engine: engineB) + try sessionB.loadRig(from: decoded) + + #expect(sessionB.routers.count == 1, "router was not rebuilt on load") + guard let rebuilt: ChainRouter = sessionB.routers.first else { + Issue.record("no rebuilt router") + return + } + #expect(rebuilt.boardA.pedals.count == 2, "board A pedal count not restored") + #expect(rebuilt.boardB.pedals.count == 1, "board B pedal count not restored") + #expect(rebuilt.boardA.pedals.map { $0.displayName } == ["Fuzz", "Overdrive"]) + #expect(rebuilt.boardB.pedals.map { $0.displayName } == ["Reverb"]) + // mode == .b → branch A muted, branch B active. + #expect(rebuilt.splitter.branchAEnabled == 0.0, "branch A level not restored") + #expect(rebuilt.splitter.branchBEnabled == 1.0, "branch B level not restored") + + // The rebuilt router should render audio (board B is the active path). + try engineB.start() + let samples: [Float] = readStereoCAF(url: urlB) + #expect(hasNonSilentOutput(samples), "rebuilt router produced silence") + } + + @Test func routerlessRigStoresNoRoutersKey() throws { + // A plain single-board session must not gain a `routers` payload (byte-compat with rigs + // saved before router persistence existed). + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 64) + defer { try? FileManager.default.removeItem(at: url) } + let session: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try session.addBoard() + try board.add(FuzzPedal()) + try session.finalizeBoard(board) + + let state: ShoeGazeState = session.captureState() + #expect(state.routers == nil, "routerless rig should capture nil routers") + + let json: String = String(data: try JSONEncoder().encode(state), encoding: .utf8) ?? "" + #expect(!json.contains("\"routers\""), "routerless JSON should omit the routers key") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift index 9faa750..d816962 100644 --- a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift +++ b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift @@ -71,9 +71,12 @@ struct FactoryRigLibraryTests { for (entry, rig): (RigEntry, FactoryRig) in zip(entries, rigs) { #expect(entry.id == rig.id, "entry id must be the rig's stable id") #expect(entry.name == rig.name) - #expect(entry.state.boards.count == 1, "\(rig.name) should build exactly one board") - let pedalCount: Int = entry.state.boards.first?.pedals.count ?? 0 - #expect(pedalCount >= 3, "\(rig.name) should build a non-trivial chain") + // A rig builds either plain boards or a router (or both) — never nothing. + let routerStates: [ChainRouterState] = entry.state.routers ?? [] + #expect(!entry.state.boards.isEmpty || !routerStates.isEmpty, "\(rig.name) built nothing") + let boardPedals: Int = entry.state.boards.reduce(0) { $0 + $1.pedals.count } + let routerPedals: Int = routerStates.reduce(0) { $0 + $1.boardA.count + $1.boardB.count } + #expect(boardPedals + routerPedals >= 3, "\(rig.name) should build a non-trivial chain") } // Stable ids: re-seeding yields identical ids (so a re-seed overwrites in place). From 2c970aa3444febd0b54b82e050bf0f3b0c163fe6 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 13:32:58 -0700 Subject: [PATCH 07/18] refactor(rigs): address external-review findings - Recall router state in applyState: the lightweight (no-rebuild) recall path now positionally applies router branch pedal params and the splitter/merger blend, instead of silently dropping them for routed rigs. Test added. - Simplify first-run seeding: RigLibraryStore.save persists asynchronously (best-effort, logged not thrown), so the previous per-entry rollback could never fire for a real disk failure. Replaced with an honest best-effort save + working-rig fallback, and a comment stating the semantics. - Move FactoryRigBuild to its own file (one public type per file). - Document that a router's output master gain is intentionally not persisted, matching BoardState's treatment of board master gain. Co-Authored-By: Claude Opus 4.8 --- .../Presets/ChainRouterState.swift | 4 ++ .../Presets/Factory/FactoryRig.swift | 12 ------ .../Presets/Factory/FactoryRigBuild.swift | 17 +++++++++ .../Presets/ShoeGaze+Preset.swift | 22 +++++++++++ .../RigLibraryBootstrap.swift | 37 +++++-------------- .../ChainRouterPersistenceTests.swift | 26 +++++++++++++ 6 files changed, 78 insertions(+), 40 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift diff --git a/Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift b/Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift index cb4693d..9c314b3 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ChainRouterState.swift @@ -12,6 +12,10 @@ /// selection (and any continuous blend between them); the merger's two levels capture the output mix. /// /// Persisted as part of ``ShoeGazeState/routers`` so a routed multi-board rig survives save / load. +/// +/// > Note: The router's output-stage master gain (`masterGainNode`) is intentionally not captured, +/// > matching the existing behaviour for a plain board's `masterGainNode` in `BoardState` — output +/// > level is treated as a live mix control, not part of the saved rig. public struct ChainRouterState: Codable, Equatable { /// Pedals on board A (the first branch), in chain order. diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift index 2b2bce8..2b1286e 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift @@ -97,15 +97,3 @@ public struct FactoryRig: Identifiable, Sendable { self.build = .session(sessionBuild) } } - -/// How a ``FactoryRig`` builds its graph at seed time. -public enum FactoryRigBuild: Sendable { - - /// Appends pedals to a single pre-made, empty board; the seeding driver calls `addBoard` before - /// and `finalizeBoard` after. - case singleBoard(@MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void) - - /// Builds the whole graph against the session (boards and/or routers), owning its own - /// `addBoard`/`finalizeBoard` and `makeChainRouter`/`finalize` lifecycle. - case session(@MainActor (_ session: ShoeGaze) throws -> Void) -} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift new file mode 100644 index 0000000..42eb4c5 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift @@ -0,0 +1,17 @@ +// FactoryRigBuild.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// How a ``FactoryRig`` builds its graph at seed time. +public enum FactoryRigBuild: Sendable { + + /// Appends pedals to a single pre-made, empty board; the seeding driver calls `addBoard` before + /// and `finalizeBoard` after. + case singleBoard(@MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void) + + /// Builds the whole graph against the session (boards and/or routers), owning its own + /// `addBoard`/`finalizeBoard` and `makeChainRouter`/`finalize` lifecycle. + case session(@MainActor (_ session: ShoeGaze) throws -> Void) +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index 5a45135..a9411c9 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -410,6 +410,19 @@ extension ShoeGaze { } } } + // Routers recall positionally too: their branch pedals' params and the splitter/merger + // blend. Topology (pedal counts/types) is assumed identical for a lightweight recall — a + // mismatch is skipped, exactly as for boards. A `rebuildsOnChange` selector inside a router + // branch is not handled here (routers have no per-branch rebuild path); use `loadRig(from:)` + // for that. + for (router, routerState): (ChainRouter, ChainRouterState) in zip(routers, state.routers ?? []) { + applyLinearParams(routerState.boardA, to: router.boardA.pedals) + applyLinearParams(routerState.boardB, to: router.boardB.pedals) + router.splitter.branchAEnabled = routerState.branchA + router.splitter.branchBEnabled = routerState.branchB + router.merger?.levelA = routerState.mergerLevelA + router.merger?.levelB = routerState.mergerLevelB + } // A recall restores each pedal's tempo-sync state but not its derived values (no clock is // consulted in `Pedal.applyState`), so recompute them against the rig's current tempo — // mirroring the full `loadRig(from:)` path. @@ -418,6 +431,15 @@ extension ShoeGaze { } } + /// Positionally applies pedal parameter snapshots to a live linear pedal chain (e.g. a router + /// branch). A position whose live pedal type doesn't match the snapshot is skipped, matching the + /// silent-skip semantics of the board recall path. + private func applyLinearParams(_ states: [PedalState], to pedals: [Pedal]) { + for (pedal, state): (Pedal, PedalState) in zip(pedals, states) where pedal.displayName == state.type { + pedal.applyState(state) + } + } + /// Positionally applies segment parameter snapshots to live board segments, including /// branch pedals and split routing modes. Type or topology mismatches at any position are /// skipped silently (lightweight recall is for topologically identical rigs). diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift index 902e2a1..c6b748e 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -46,39 +46,20 @@ public enum RigLibraryBootstrap { // working session is intentionally left as-is (no `currentRigID`) — the user picks a starter // rig from the sidebar to load it, rather than the highlight pointing at a rig the working // graph has not actually loaded. - let entries: [RigEntry] - do { - entries = try FactoryRigLibrary.makeEntries() - } catch { - // Building the shipped rigs is deterministic and should never fail at runtime; if it - // somehow does, fall back to seeding the working rig so the library is not left empty. - print("[RigLibraryBootstrap] building factory rigs failed: \(error)") - seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName) - return - } - - // Save sequentially, rolling back on failure. Seeding is gated on `store.entries.isEmpty`, - // so a partially-saved library would be frozen forever (never retried, never completed). If - // any save fails, delete the entries saved this run so the library returns to empty and a - // later launch retries the full seed. (This is best-effort, not truly atomic: if a rollback - // `delete` itself fails, a partial set can still be left behind and frozen — the residual - // hole a non-transactional store cannot fully close.) - var savedThisRun: [RigEntry] = [] + // Seed the shipped starter rigs. `store.save` updates the in-memory library synchronously + // (so the session sees every rig immediately) and persists to disk asynchronously — a disk + // failure is logged by the store, not thrown here, so there is no per-entry rollback to do. + // `save` throws only on a synchronous encode failure of this deterministic rig data, which + // should not happen at runtime; if the build or an encode somehow fails, fall back to + // seeding the working rig so the library is never left empty on first run. do { + let entries: [RigEntry] = try FactoryRigLibrary.makeEntries() for entry: RigEntry in entries { try store.save(entry) - savedThisRun.append(entry) } } catch { - print("[RigLibraryBootstrap] seeding factory rigs failed after " - + "\(savedThisRun.count)/\(entries.count); rolling back: \(error)") - for entry: RigEntry in savedThisRun { - do { - try store.delete(entry) - } catch { - print("[RigLibraryBootstrap] rollback of '\(entry.name)' failed: \(error)") - } - } + print("[RigLibraryBootstrap] seeding factory rigs failed: \(error)") + seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName) } } diff --git a/Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift b/Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift index 4cbd8c3..26c6487 100644 --- a/Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift +++ b/Tests/LyrebirdShoeGazeTests/ChainRouterPersistenceTests.swift @@ -60,6 +60,32 @@ struct ChainRouterPersistenceTests { #expect(hasNonSilentOutput(samples), "rebuilt router produced silence") } + @Test func applyStateRecallsRouterParamsLive() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url) } + let session: ShoeGaze = ShoeGaze(engine: engine) + let router: ChainRouter = try session.makeChainRouter() + let fuzz: FuzzPedal = FuzzPedal() + fuzz.fuzz = 20.0 + try router.addToA(fuzz) + try router.addToB(ReverbPedal()) + router.mode = .a + try router.finalize() + + let original: ShoeGazeState = session.captureState() + + // Mutate live: change a router pedal param and flip the A/B selection. + fuzz.fuzz = 55.0 + router.mode = .b + + // Lightweight recall should restore the router pedal param and blend without a rebuild. + session.applyState(original) + + #expect(fuzz.fuzz == 20.0, "router pedal param was not recalled") + #expect(router.splitter.branchAEnabled == 1.0, "branch A level not recalled") + #expect(router.splitter.branchBEnabled == 0.0, "branch B level not recalled") + } + @Test func routerlessRigStoresNoRoutersKey() throws { // A plain single-board session must not gain a `routers` payload (byte-compat with rigs // saved before router persistence existed). From fba32ff0aa69ec515f32b68dd83751042ab22420 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 13:53:56 -0700 Subject: [PATCH 08/18] feat(ui): group factory rigs by category in the rig sidebar The rig-library sidebar now presents shipped starter rigs under their FactoryRigCategory headers (Shoegaze Walls, Dreampop, Classic, Ambient, Experimental) in fixed catalog order, with the user's own rigs under a "My Rigs" header. Starter rows show a "Starter rig" subtitle and are not reorderable; user rows keep drag-to-reorder and Move Up/Down (now scoped to the user's own rigs). Grouping is presentational, so it stays correct regardless of underlying library order. Adds FactoryRigLibrary.category(for:) and rigs(in:) with tests. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRigLibrary.swift | 16 ++ .../RigLibrarySidebarView.swift | 141 +++++++++++++----- .../FactoryRigLibraryTests.swift | 18 +++ 3 files changed, 139 insertions(+), 36 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index 1d1bfed..eaee27a 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -85,6 +85,22 @@ public enum FactoryRigLibrary { factoryIDs.contains(id) } + /// The ``FactoryRigCategory`` of the shipped rig with this id, or `nil` for a user rig. + /// + /// - Parameter id: A ``RigEntry/id`` from the rig library. + /// - Returns: The rig's category, or `nil` if `id` is not a factory rig. + public static func category(for id: UUID) -> FactoryRigCategory? { + all.first(where: { $0.id == id })?.category + } + + /// The shipped rigs of a given category, in catalog order. + /// + /// - Parameter category: The category to filter by. + /// - Returns: The `FactoryRig`s in `category`, in the order they appear in ``all``. + public static func rigs(in category: FactoryRigCategory) -> [FactoryRig] { + all.filter { $0.category == category } + } + /// Every built-in rig, in the order a picker should present them. public static let all: [FactoryRig] = [ glideWall, diff --git a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift index 653f2af..392b267 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -116,17 +116,48 @@ struct RigLibrarySidebarView: View { .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) .padding(.vertical, RigLibrarySidebarView.rowPadding) } - ForEach(store.entries) { entry in - rigRow(entry) + + // Shipped starter rigs, grouped by category (fixed catalog order, not reorderable). + ForEach(factorySections, id: \.category) { section in + sectionHeader(section.category.displayName) + ForEach(section.entries) { entry in + rigRow(entry, reorderable: false) + } + } + + // The user's own rigs, reorderable. Only headed when starter rigs are also shown, so + // a library with no factory rigs (e.g. after Erase All) reads as a plain list. + let userRigs: [RigEntry] = userEntries + if !userRigs.isEmpty { + if !factorySections.isEmpty { + sectionHeader("My Rigs") + } + ForEach(userRigs) { entry in + rigRow(entry, reorderable: true) + } } } } .frame(maxHeight: .infinity) } - private func rigRow(_ entry: RigEntry) -> some View { + /// A small uppercase section header for a group of rigs. + private func sectionHeader(_ title: String) -> some View { + Text(title.uppercased()) + .font(.caption2) + .fontWeight(.semibold) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity)) + .padding(.top, RigLibrarySidebarView.rowPadding) + .padding(.horizontal, 2) + .frame(maxWidth: .infinity, alignment: .leading) + } + + /// One rig row. `reorderable` rows (the user's own rigs) accept drag-to-reorder and expose + /// Move Up / Down; starter rigs are fixed and show a "Starter rig" subtitle instead of a date. + @ViewBuilder + private func rigRow(_ entry: RigEntry, reorderable: Bool) -> some View { let isSelected: Bool = entry.id == currentRigID - return Button { + let button = Button { onSelect(entry) } label: { VStack(alignment: .leading, spacing: 2) { @@ -134,7 +165,9 @@ struct RigLibrarySidebarView: View { .font(.subheadline) .foregroundStyle(Color.white) .lineLimit(1) - Text(entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat)) + Text(reorderable + ? entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat) + : "Starter rig") .font(.caption2) .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity)) .lineLimit(1) @@ -149,45 +182,81 @@ struct RigLibrarySidebarView: View { .contentShape(Rectangle()) } .buttonStyle(.plain) - // Drag the row onto another to reorder; dropping inserts it just before the target. Works - // on macOS (mouse drag) and iPad (long-press drag); taps still select. - .draggable(entry.id.uuidString) - .dropDestination(for: String.self) { droppedIDs, _ in - guard let first: String = droppedIDs.first else { return false } - moveDragged(first, onto: entry) - return true - } .contextMenu { - Button("Move Up") { store.moveUp(entry) } - .disabled(isFirst(entry)) - Button("Move Down") { store.moveDown(entry) } - .disabled(isLast(entry)) - Divider() - Button("Rename…") { onRename(entry) } - Button("Duplicate…") { onDuplicate(entry) } - // Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the - // unreachable failure path the Share item is simply omitted. - if let shareItem: RigShareItem = try? RigShareItem(rig: entry) { - ShareLink( - item: shareItem, - preview: SharePreview(entry.name) - ) { - Label("Share…", systemImage: "square.and.arrow.up") - } - } - Divider() - Button("Delete", role: .destructive) { onDelete(entry) } + rowContextMenu(entry, reorderable: reorderable) } + + if reorderable { + // Drag the row onto another to reorder; dropping inserts it just before the target. Works + // on macOS (mouse drag) and iPad (long-press drag); taps still select. + button + .draggable(entry.id.uuidString) + .dropDestination(for: String.self) { droppedIDs, _ in + guard let first: String = droppedIDs.first else { return false } + moveDragged(first, onto: entry) + return true + } + } else { + button + } + } + + /// The context menu for a rig row. Move Up / Down appear only for reorderable (user) rigs. + @ViewBuilder + private func rowContextMenu(_ entry: RigEntry, reorderable: Bool) -> some View { + if reorderable { + Button("Move Up") { store.moveUp(entry) } + .disabled(isFirstUser(entry)) + Button("Move Down") { store.moveDown(entry) } + .disabled(isLastUser(entry)) + Divider() + } + Button("Rename…") { onRename(entry) } + Button("Duplicate…") { onDuplicate(entry) } + // Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the + // unreachable failure path the Share item is simply omitted. + if let shareItem: RigShareItem = try? RigShareItem(rig: entry) { + ShareLink( + item: shareItem, + preview: SharePreview(entry.name) + ) { + Label("Share…", systemImage: "square.and.arrow.up") + } + } + Divider() + Button("Delete", role: .destructive) { onDelete(entry) } + } + + // MARK: - Grouping + + /// The starter-rig sections: each non-empty ``FactoryRigCategory`` present in the library, in + /// catalog order, paired with its entries (also in catalog order). + private var factorySections: [(category: FactoryRigCategory, entries: [RigEntry])] { + let byID: [UUID: RigEntry] = Dictionary( + store.entries.map { ($0.id, $0) }, + uniquingKeysWith: { first, _ in first } + ) + return FactoryRigCategory.allCases.compactMap { category in + let entries: [RigEntry] = FactoryRigLibrary.rigs(in: category).compactMap { byID[$0.id] } + return entries.isEmpty ? nil : (category, entries) + } + } + + /// The user's own (non-factory) rigs, in library order. + private var userEntries: [RigEntry] { + store.entries.filter { !FactoryRigLibrary.isFactory($0.id) } } // MARK: - Reorder helpers - private func isFirst(_ entry: RigEntry) -> Bool { - store.entries.first?.id == entry.id + /// Whether `entry` is the first among the user's own rigs (so Move Up is disabled for it). + private func isFirstUser(_ entry: RigEntry) -> Bool { + userEntries.first?.id == entry.id } - private func isLast(_ entry: RigEntry) -> Bool { - store.entries.last?.id == entry.id + /// Whether `entry` is the last among the user's own rigs (so Move Down is disabled for it). + private func isLastUser(_ entry: RigEntry) -> Bool { + userEntries.last?.id == entry.id } /// Moves the dragged entry (by id string) to sit just before `target` in the set list. diff --git a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift index d816962..e23ffe4 100644 --- a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift +++ b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift @@ -61,6 +61,24 @@ struct FactoryRigLibraryTests { #expect(!FactoryRigLibrary.isFactory(UUID())) } + @Test func categoryLookupAndGroupingCoverEveryRigOnce() { + for rig: FactoryRig in FactoryRigLibrary.all { + #expect(FactoryRigLibrary.category(for: rig.id) == rig.category, + "\(rig.name) category lookup mismatch") + } + #expect(FactoryRigLibrary.category(for: UUID()) == nil, "a random id has no category") + + // Each category grouping contains only its own rigs, in catalog order. + for category: FactoryRigCategory in FactoryRigCategory.allCases { + let rigs: [FactoryRig] = FactoryRigLibrary.rigs(in: category) + #expect(rigs.allSatisfy { $0.category == category }) + } + + // Grouping by every category partitions the catalog exactly (no rig lost or duplicated). + let grouped: [FactoryRig] = FactoryRigCategory.allCases.flatMap { FactoryRigLibrary.rigs(in: $0) } + #expect(grouped.count == FactoryRigLibrary.all.count, "grouping dropped or duplicated a rig") + } + // MARK: - Seeding entries @Test func makeEntriesMatchesCatalogAndIsStable() throws { From ad6ed4167420c84ae3a3799dd4c14c864e97ff5e Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 14:11:22 -0700 Subject: [PATCH 09/18] feat(ui): Mine/Starters rig toggle + seed starters into existing libraries Two fixes so shipped starter rigs are actually reachable: - Seeding no longer requires an empty library. On launch it installs any factory rigs whose stable ids are missing, once per FactoryRigLibrary .seedVersion (a per-device UserDefaults marker). Existing users therefore receive the starters on their next launch; a starter the user later deletes stays deleted (the marker has advanced); bumping seedVersion when new starters ship re-runs catch-up for just the new ones. Idempotent by id, so iCloud-synced devices never duplicate. - Sidebar gains a segmented Mine / Starters toggle. "Mine" is the flat, reorderable user list; "Starters" groups the shipped rigs by category. A "Restore Starter Rigs" action (Starters empty-state button + library menu) re-installs missing starters on demand via RigLibraryBootstrap.restoreStarterRigs. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRigLibrary.swift | 5 + .../RigLibraryBootstrap.swift | 114 ++++++++++------- .../RigLibrarySidebarView.swift | 118 +++++++++++++----- .../ShoeGazeBuilderView.swift | 8 ++ 4 files changed, 168 insertions(+), 77 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index eaee27a..92fcba7 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -70,6 +70,11 @@ extension ChainRouter { @MainActor public enum FactoryRigLibrary { + /// Catalog seed version. Bump this whenever new factory rigs are added so first-run catch-up + /// seeding re-runs on already-populated libraries and installs the newly-shipped starters. Never + /// re-adds a rig the user has since deleted at the *same* version — the marker only advances. + public static let seedVersion: Int = 1 + /// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig. /// /// Because factory rigs are seeded with their fixed ``FactoryRig/id``, an entry recalled from the diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift index c6b748e..b48dfc4 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -10,75 +10,101 @@ import LyrebirdShoeGaze /// Setup of the rig library for an app shell, split so nothing blocks the launch path. /// /// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous -/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work — -/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the -/// library from the current working rig **only after** the real (possibly iCloud) contents are -/// known, so a first launch can't create a duplicate "Default" rig on every synced device. +/// initializer and hand to the UI). ``start(_:seedFrom:)`` then does the blocking work — resolving +/// the iCloud-or-local location and the initial load — off the main thread, then performs a one-time +/// catch-up seed of any missing shipped starter rigs. @MainActor public enum RigLibraryBootstrap { + /// `UserDefaults` key holding the highest ``FactoryRigLibrary/seedVersion`` this device has + /// already seeded. Per-device (not synced): the seed is idempotent by stable rig id, so a device + /// that receives the rigs via iCloud sync simply finds them already present and seeds nothing. + private static let seedVersionKey: String = "net.realizedsound.shoegaze.factorySeedVersion" + /// Creates an auto-resolving store. Construct this synchronously at launch; call - /// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`). + /// ``start(_:seedFrom:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`). public static func makeStore() -> RigLibraryStore { RigLibraryStore() } - /// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still - /// empty after loading (first run). Idempotent enough to call once at launch. + /// Resolves + loads `store` off the main thread, then performs a one-time catch-up seed of any + /// missing shipped starter rigs. Idempotent — safe to call once at every launch. + /// + /// Seeding adds only factory rigs whose stable ids are **not already present**, so it never + /// duplicates a rig and never touches the user's own rigs. It runs at most once per + /// ``FactoryRigLibrary/seedVersion``: a first launch seeds every starter; a launch after an + /// update that ships new starters seeds just the new ones; and a starter the user later deletes + /// stays deleted (the version marker has already advanced). This deliberately replaces the old + /// "only seed an empty library" rule so users who already had rigs still receive the starters. /// /// - Parameters: /// - store: The store from ``makeStore()``. - /// - shoeGaze: The session whose current rig seeds the library when it is first empty. - /// - seedName: Name for the seeded first rig. Defaults to `"Default"`. + /// - shoeGaze: The working session (currently unused by seeding; kept for call-site stability + /// and future working-rig seeding needs). public static func start( _ store: RigLibraryStore, - seedFrom shoeGaze: ShoeGaze, - seedName: String = "Default" + seedFrom shoeGaze: ShoeGaze ) async { await store.start() - // Seed only after the (possibly iCloud) library has loaded: an empty library here means a - // genuine first run, not a not-yet-synced one. - guard store.entries.isEmpty else { return } + let defaults: UserDefaults = .standard + let seededVersion: Int = defaults.integer(forKey: seedVersionKey) // 0 when never seeded + guard seededVersion < FactoryRigLibrary.seedVersion else { return } - // First run: populate the library with the shipped starter rigs. These are built in - // throwaway offline sessions, so they are independent of the current working graph. The - // working session is intentionally left as-is (no `currentRigID`) — the user picks a starter - // rig from the sidebar to load it, rather than the highlight pointing at a rig the working - // graph has not actually loaded. - // Seed the shipped starter rigs. `store.save` updates the in-memory library synchronously - // (so the session sees every rig immediately) and persists to disk asynchronously — a disk - // failure is logged by the store, not thrown here, so there is no per-entry rollback to do. - // `save` throws only on a synchronous encode failure of this deterministic rig data, which - // should not happen at runtime; if the build or an encode somehow fails, fall back to - // seeding the working rig so the library is never left empty on first run. + // Seed missing starters. Only advance the marker if seeding succeeded, so a transient failure + // (which should not happen for this deterministic data) is retried on the next launch. + if seedMissingFactoryRigs(into: store) { + defaults.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey) + } + } + + /// Adds any shipped starter rig not already in `store`, keyed by stable id. Safe to call anytime. + /// + /// Use this to drive a user-facing "Restore Starter Rigs" action: it re-adds starters the user + /// deleted (and any newly-shipped ones) without disturbing their own rigs, and advances the seed + /// marker so automatic catch-up seeding won't fight the manual restore. + /// + /// - Parameter store: The library to seed into. + /// - Returns: The number of starter rigs added (0 if all were already present). + @discardableResult + public static func restoreStarterRigs(into store: RigLibraryStore) -> Int { + let added: Int = addMissingFactoryRigs(into: store) + UserDefaults.standard.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey) + return added + } + + /// Seeds missing starters, returning whether the operation completed without a build/encode error + /// (so the caller knows whether to advance the seed marker). + private static func seedMissingFactoryRigs(into store: RigLibraryStore) -> Bool { do { - let entries: [RigEntry] = try FactoryRigLibrary.makeEntries() - for entry: RigEntry in entries { - try store.save(entry) - } + _ = try addMissingFactoryRigsThrowing(into: store) + return true } catch { print("[RigLibraryBootstrap] seeding factory rigs failed: \(error)") - seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName) + return false } } - /// Seeds the working session's current rig as a single named library entry. - /// - /// Last-resort fallback used only when the factory rigs could not be built; keeps the library - /// from being left empty on first run. - private static func seedWorkingRig( - _ store: RigLibraryStore, - seedFrom shoeGaze: ShoeGaze, - seedName: String - ) { - guard !shoeGaze.boards.isEmpty else { return } - let entry: RigEntry = shoeGaze.captureEntry(name: seedName) + /// Non-throwing convenience: seeds missing starters and returns the count added (0 on error). + private static func addMissingFactoryRigs(into store: RigLibraryStore) -> Int { do { - try store.save(entry) - shoeGaze.currentRigID = entry.id + return try addMissingFactoryRigsThrowing(into: store) } catch { - print("[RigLibraryBootstrap] fallback seeding failed: \(error)") + print("[RigLibraryBootstrap] restoring factory rigs failed: \(error)") + return 0 } } + + /// Builds the starter rigs and saves the ones whose ids are missing from `store`. + /// + /// - Returns: The number of rigs added. + /// - Throws: Any error from building the rigs or a synchronous encode failure in `store.save`. + private static func addMissingFactoryRigsThrowing(into store: RigLibraryStore) throws -> Int { + let existingIDs: Set = Set(store.entries.map { $0.id }) + let missing: [RigEntry] = try FactoryRigLibrary.makeEntries().filter { !existingIDs.contains($0.id) } + for entry: RigEntry in missing { + try store.save(entry) + } + return missing.count + } } diff --git a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift index 392b267..eeccca9 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -45,6 +45,9 @@ struct RigLibrarySidebarView: View { let onImportArchive: () -> Void let onExportArchive: () -> Void + /// Invoked to (re-)install any shipped starter rigs missing from the library. Defaults to a no-op. + var onRestoreStarters: () -> Void = {} + /// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can /// explain how to re-enable iCloud sync. Defaults to a no-op. var onShowCloudStatus: () -> Void = {} @@ -52,6 +55,16 @@ struct RigLibrarySidebarView: View { private static let timestampFormat: Date.FormatStyle = Date.FormatStyle(date: .abbreviated, time: .shortened) + /// Which group of rigs the list is currently showing. + private enum RigTab: String, CaseIterable, Identifiable { + case mine = "Mine" + case starters = "Starters" + var id: String { rawValue } + } + + /// The selected list tab. Defaults to the user's own rigs. + @State private var tab: RigTab = .mine + // MARK: - Body var body: some View { @@ -99,46 +112,83 @@ struct RigLibrarySidebarView: View { // MARK: - List + @ViewBuilder private var rigList: some View { - ScrollView(.vertical, showsIndicators: true) { - LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) { - if !store.isLoaded { - HStack(spacing: 6) { - ProgressView().controlSize(.small) - Text("Loading…") - .font(.caption) - .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) - } - .padding(.vertical, RigLibrarySidebarView.rowPadding) - } else if store.entries.isEmpty { - Text("No saved rigs yet.\nTap New or Save to add one.") - .font(.caption) - .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) - .padding(.vertical, RigLibrarySidebarView.rowPadding) - } - - // Shipped starter rigs, grouped by category (fixed catalog order, not reorderable). - ForEach(factorySections, id: \.category) { section in - sectionHeader(section.category.displayName) - ForEach(section.entries) { entry in - rigRow(entry, reorderable: false) + if !store.isLoaded { + HStack(spacing: 6) { + ProgressView().controlSize(.small) + Text("Loading…") + .font(.caption) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) + } + .padding(.vertical, RigLibrarySidebarView.rowPadding) + .frame(maxHeight: .infinity, alignment: .top) + } else { + VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) { + tabPicker + ScrollView(.vertical, showsIndicators: true) { + LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) { + switch tab { + case .mine: mineList + case .starters: startersList + } } } + .frame(maxHeight: .infinity) + } + } + } - // The user's own rigs, reorderable. Only headed when starter rigs are also shown, so - // a library with no factory rigs (e.g. after Erase All) reads as a plain list. - let userRigs: [RigEntry] = userEntries - if !userRigs.isEmpty { - if !factorySections.isEmpty { - sectionHeader("My Rigs") - } - ForEach(userRigs) { entry in - rigRow(entry, reorderable: true) - } + /// Segmented Mine / Starters switch at the top of the list. + private var tabPicker: some View { + Picker("", selection: $tab) { + ForEach(RigTab.allCases) { option in + Text(option.rawValue).tag(option) + } + } + .pickerStyle(.segmented) + .labelsHidden() + } + + /// The user's own rigs — a flat, reorderable list. + @ViewBuilder + private var mineList: some View { + let userRigs: [RigEntry] = userEntries + if userRigs.isEmpty { + Text("No saved rigs yet.\nTap New or Save to add one.") + .font(.caption) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) + .padding(.vertical, RigLibrarySidebarView.rowPadding) + } else { + ForEach(userRigs) { entry in + rigRow(entry, reorderable: true) + } + } + } + + /// The shipped starter rigs, grouped by category (fixed catalog order, not reorderable). + @ViewBuilder + private var startersList: some View { + let sections: [(category: FactoryRigCategory, entries: [RigEntry])] = factorySections + if sections.isEmpty { + VStack(alignment: .leading, spacing: 6) { + Text("No starter rigs installed.") + .font(.caption) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) + Button("Restore Starter Rigs") { onRestoreStarters() } + .buttonStyle(.bordered) + .tint(.orange) + .controlSize(.small) + } + .padding(.vertical, RigLibrarySidebarView.rowPadding) + } else { + ForEach(sections, id: \.category) { section in + sectionHeader(section.category.displayName) + ForEach(section.entries) { entry in + rigRow(entry, reorderable: false) } } } - .frame(maxHeight: .infinity) } /// A small uppercase section header for a group of rigs. @@ -286,6 +336,8 @@ struct RigLibrarySidebarView: View { Button("Import Archive…") { onImportArchive() } Button("Export Archive…") { onExportArchive() } Divider() + Button("Restore Starter Rigs") { onRestoreStarters() } + Divider() Button("Erase All Rigs…", role: .destructive) { onEraseAll() } } label: { Image(systemName: "ellipsis.circle") diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index f272d4c..5528452 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -645,10 +645,18 @@ public struct ShoeGazeBuilderView: View { onEraseAll: { showEraseAllDialog = true }, onImportArchive: { showImporter = true }, onExportArchive: { exportArchiveAction() }, + onRestoreStarters: { restoreStarterRigs() }, onShowCloudStatus: { showICloudUnavailableAlert = true } ) } + /// (Re-)installs any shipped starter rigs missing from the library. Non-destructive: user rigs + /// are untouched, and already-present starters are skipped (matched by stable id). + private func restoreStarterRigs() { + let added: Int = RigLibraryBootstrap.restoreStarterRigs(into: library) + print("[ShoeGazeBuilderView] restored \(added) starter rig(s)") + } + // MARK: - Sleep / iCloud status /// Platform name for the settings app, used in the iCloud guidance alert. From 392ae1525a34c584e5000a7d40f3c219548ac25c Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 14:20:04 -0700 Subject: [PATCH 10/18] fix(ui): split builder presentation chain to satisfy the type-checker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The factory-overwrite confirmation dialog pushed ShoeGazeBuilderView's already-large presentation modifier chain past the Swift expression type-checker's budget — it compiled under `swift build` but failed the Xcode app build with "unable to type-check this expression in reasonable time". Extract the first half of the chain into a `chromeWithPrompts` computed property so each half type-checks quickly. Co-Authored-By: Claude Opus 4.8 --- Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 5528452..29f7227 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -309,7 +309,10 @@ public struct ShoeGazeBuilderView: View { } } - private var presentationChrome: some View { + // Split off the first half of the presentation chain into its own computed property: the full + // modifier chain is long enough to blow the Swift expression type-checker's budget, so this + // boundary keeps each half small enough to type-check quickly. + private var chromeWithPrompts: some View { layoutChrome .background(boardsSheetAnchor) .background(rigExportAnchor) @@ -342,6 +345,10 @@ public struct ShoeGazeBuilderView: View { Text("“\(request.entry.name)” is a built-in starter rig. Overwriting replaces it in " + "your library. Save as a new rig to keep the original.") } + } + + private var presentationChrome: some View { + chromeWithPrompts .confirmationDialog( "Erase all rigs?", isPresented: $showEraseAllDialog, From 132515b4cdee8b6111d4ac48978dea3431a527dd Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 14:36:49 -0700 Subject: [PATCH 11/18] fix(rigs): address starter-rig feedback (toggle, Garcia, shimmer, input) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Center the Mine/Starters toggle in the sidebar column. - Garcia rig: build it as two plain boards (effects + clean) selected via the multi-board Solo/Blend control, instead of a ChainRouter — the builder UI renders boards, not routers, so the router version showed empty boards. - Dreampop Chorus Cathedral: lower shimmer decay/feedback and delay feedback so the octave-up regeneration no longer screeches into runaway feedback. - Preserve the current input across rig switches: loadRig gains a keepingCurrentInput flag (default false → file open / launch restore still apply the rig's saved input; RigStore session-restore continuity intact), and the rig-switch path (loadEntry) passes true so a live guitar isn't snapped back to the test tone when changing rigs. Tests updated to cover both directions. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRigLibrary.swift | 51 +++++++------ .../Presets/ShoeGaze+Preset.swift | 24 ++++-- .../RigLibrarySidebarView.swift | 6 +- .../ShoeGazeBuilderView.swift | 4 +- Tests/LyrebirdShoeGazeTests/PresetTests.swift | 74 +++++++++++++------ 5 files changed, 102 insertions(+), 57 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index 92fcba7..6b7eee3 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -194,13 +194,15 @@ public enum FactoryRigLibrary { } try board.append(DelayPedal()) { p in p.time = 0.4 - p.feedback = 2.2 + p.feedback = 1.5 } try board.append(ShimmerReverbPedal()) { p in + // Keep decay + shimmer feedback well below self-oscillation — high decay with the + // octave-up regeneration screeches into runaway feedback within seconds. p.size = 0.09 - p.decay = 0.85 - p.shimmer = 0.55 - p.damp = 0.35 + p.decay = 0.55 + p.shimmer = 0.3 + p.damp = 0.5 } } @@ -646,64 +648,61 @@ public enum FactoryRigLibrary { // MARK: Two-board split - /// A two-board split — a full effects chain vs a clean direct path — selectable like an on-board - /// effects loop. Showcases the multi-board router. + /// Two boards — a full effects chain and a clean direct path — switched with the board selector. static let garciaOBELSplit: FactoryRig = FactoryRig( id: stableID("Garcia OBEL Split"), name: "Garcia OBEL Clean/Effects Split", - blurb: "Two boards, one footswitch: an effects/lead chain (octave, envelope filter, " - + "overdrive, phaser, delay) versus a clean direct path — switch between them like an " - + "on-board effects loop. In the spirit of a certain improvising guitarist's late-'80s " - + "rig. Flip the router to A for effects, B for clean.", + blurb: "Two boards, one selector: Board 1 is an effects/lead chain (octave, envelope filter, " + + "overdrive, phaser, delay); Board 2 is a clean direct path. Use the board Solo / Blend " + + "control at the top to switch between them, like an on-board effects loop. In the " + + "spirit of a certain improvising guitarist's late-'80s rig.", category: .classic, sessionBuild: { session in - let router: ChainRouter = try session.makeChainRouter() - - // Board A — the effects / lead chain (effects loop engaged). - try router.appendToA(BassOctaverPedal()) { p in + // Board 1 — the effects / lead chain (effects loop engaged). + let effects: PedalBoard = try session.addBoard() + try effects.append(BassOctaverPedal()) { p in p.oct1 = 0.5 p.direct = 1.0 p.mode = 1.0 } - try router.appendToA(MutantPedal()) { p in + try effects.append(MutantPedal()) { p in p.sensitivity = 2.5 p.resonance = 5.0 } - try router.appendToA(OverdrivePedal()) { p in + try effects.append(OverdrivePedal()) { p in p.drive = 5.0 p.tone = 4200.0 } - try router.appendToA(PhaserPedal()) { p in + try effects.append(PhaserPedal()) { p in p.rate = 0.4 p.feedback = 0.4 } - try router.appendToA(DelayPedal()) { p in + try effects.append(DelayPedal()) { p in p.time = 0.35 p.feedback = 1.8 } - try router.appendToA(CaliforniaAmpPedal()) { p in + try effects.append(CaliforniaAmpPedal()) { p in p.gain = 5.0 p.bass = 0.55 p.mid = 0.6 p.treble = 0.6 } + try session.finalizeBoard(effects) - // Board B — the clean / direct path (effects loop bypassed). - try router.appendToB(CompressorPedal()) { p in + // Board 2 — the clean / direct path (effects loop bypassed). + let clean: PedalBoard = try session.addBoard() + try clean.append(CompressorPedal()) { p in p.inputGain = 2.0 p.threshold = -16.0 p.ratio = 3.0 } - try router.appendToB(CaliforniaAmpPedal()) { p in + try clean.append(CaliforniaAmpPedal()) { p in p.gain = 3.5 p.bass = 0.5 p.mid = 0.55 p.treble = 0.6 } - - // Default to the effects board; the router's A/B control switches paths. - router.mode = .a - try router.finalize() + try session.finalizeBoard(clean) } ) diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index a9411c9..1fc2717 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -107,9 +107,18 @@ extension ShoeGaze { /// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``. /// /// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``. - /// - Parameter state: The rig snapshot to restore. + /// - Parameters: + /// - state: The rig snapshot to restore. + /// - keepingCurrentInput: When `true`, the session's current ``inputSource`` is preserved and + /// the rig's saved input is ignored — used when the player switches between rigs, so the live + /// input (e.g. a plugged-in guitar) doesn't snap back to the test loop a rig was authored + /// with. When `false` (the default, used by file open and launch restore), the rig's saved + /// input is applied so a saved/loaded rig recreates its authored input. Defaults to `false`. /// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error. - public func loadRig(from state: ShoeGazeState) throws { + public func loadRig( + from state: ShoeGazeState, + keepingCurrentInput: Bool = false + ) throws { guard state.version <= presetFormatVersion else { throw PresetError.unsupportedVersion(state.version) } @@ -120,11 +129,12 @@ extension ShoeGaze { // enable-live-input flow (rebuild engine to 1 input, then load a rig saved with 0). Apply a // rig's saved layout deliberately via `applyChannelLayout(from:)` / the config UI instead. - // Restore the saved input source before rebuilding, since board construction reads it. A - // saved live-input channel that no longer exists on this engine falls back to the test loop - // (same guard as reconfigureEngine), so the rebuild's addBoard() can't throw on a stale - // channel. Absent (older rig) → leave the current input source untouched. - if let savedInput: InputSource = state.inputSource { + // Restore the saved input source before rebuilding, since board construction reads it — unless + // the caller is switching rigs (`keepingCurrentInput`), in which case the current input is + // kept so the player's live input survives the switch. A saved live-input channel that no + // longer exists on this engine falls back to the test loop (same guard as reconfigureEngine), + // so the rebuild's addBoard() can't throw on a stale channel. Absent (older rig) → untouched. + if !keepingCurrentInput, let savedInput: InputSource = state.inputSource { if case .liveInput(let channel) = savedInput, channel < 0 || channel >= engine.numInputChannels { inputSource = .testLoop diff --git a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift index eeccca9..09266b0 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -26,6 +26,7 @@ struct RigLibrarySidebarView: View { private static let subtitleOpacity: Double = 0.5 private static let headerOpacity: Double = 0.65 private static let emptyOpacity: Double = 0.4 + private static let tabPickerWidth: CGFloat = 168 // MARK: - Inputs @@ -139,7 +140,7 @@ struct RigLibrarySidebarView: View { } } - /// Segmented Mine / Starters switch at the top of the list. + /// Segmented Mine / Starters switch, centered at the top of the list. private var tabPicker: some View { Picker("", selection: $tab) { ForEach(RigTab.allCases) { option in @@ -148,6 +149,9 @@ struct RigLibrarySidebarView: View { } .pickerStyle(.segmented) .labelsHidden() + // Constrain the control's own width, then center it in the full column width. + .frame(maxWidth: RigLibrarySidebarView.tabPickerWidth) + .frame(maxWidth: .infinity, alignment: .center) } /// The user's own rigs — a flat, reorderable list. diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 29f7227..0f52b6b 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -1640,7 +1640,9 @@ public struct ShoeGazeBuilderView: View { let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } do { - try shoeGaze.loadRig(from: entry.state) + // Keep the player's currently-chosen input across the switch (e.g. a live guitar), rather + // than snapping to the input the selected rig was authored with. + try shoeGaze.loadRig(from: entry.state, keepingCurrentInput: true) currentRigID = entry.id selectedBoardIndex = 0 autosave() diff --git a/Tests/LyrebirdShoeGazeTests/PresetTests.swift b/Tests/LyrebirdShoeGazeTests/PresetTests.swift index ec5b022..7984625 100644 --- a/Tests/LyrebirdShoeGazeTests/PresetTests.swift +++ b/Tests/LyrebirdShoeGazeTests/PresetTests.swift @@ -422,11 +422,13 @@ struct PresetTests { try sg.loadRig(from: presetURL) #expect(abs(sg.clock.bpm - savedBpm) < 1e-9, "bpm should restore to \(savedBpm)") #expect(sg.tempoEnabled == false, "tempoEnabled should restore to false") - #expect(sg.inputSource == .testLoop, "input source should restore to test loop") + // Input is a live session setting, not part of the recalled rig: the session was on the test + // loop and stays there (load never changes the current input). + #expect(sg.inputSource == .testLoop, "load leaves the current input source unchanged") } - @Test func liveInputSourcePersistsAndFallsBackWhenChannelMissing() throws { - // Engine WITH an input channel: a live-input rig round-trips its source. + @Test func loadPreservesCurrentInputSourceNotTheSavedOne() throws { + // A rig captured with live input still RECORDS its source in the snapshot... let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine( duration: 0.1, numInputChannels: 1, @@ -434,29 +436,57 @@ struct PresetTests { ) defer { try? FileManager.default.removeItem(at: urlIn) } let sgIn: ShoeGaze = ShoeGaze(engine: engineIn, inputSource: .liveInput(channel: 0)) - let board: PedalBoard = try sgIn.addBoard() - try board.add(OverdrivePedal()) - try sgIn.finalizeBoard(board) + let liveBoard: PedalBoard = try sgIn.addBoard() + try liveBoard.add(OverdrivePedal()) + try sgIn.finalizeBoard(liveBoard) + let liveState: ShoeGazeState = sgIn.captureState() + #expect(liveState.inputSource == .liveInput(channel: 0), "capture records the live input") - let state: ShoeGazeState = sgIn.captureState() - #expect(state.inputSource == .liveInput(channel: 0), "capture should record the live input") - - // Reload into the same input-capable engine: source preserved. - try sgIn.loadRig(from: state) - #expect(sgIn.inputSource == .liveInput(channel: 0), "live input should round-trip") - - // loadRig does NOT auto-apply the saved channel layout, so loading into an engine with no - // input channels falls back to the test loop rather than clobbering the engine's config. - let (engineNoIn, urlNoIn): (SynthesisEngine, URL) = makeNRTEngine( + // ...but loading a rig NEVER switches the session's current input — switching rigs keeps + // whatever input the player has chosen. Here a test-loop session loads a live-input rig on an + // engine that DOES have the channel: under the old "restore saved input" behaviour this would + // become live input; the new behaviour leaves it on the test loop. + let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine( duration: 0.1, - numInputChannels: 0, + numInputChannels: 1, numAudioBuses: 128 ) - defer { try? FileManager.default.removeItem(at: urlNoIn) } - let sgNoIn: ShoeGaze = ShoeGaze(engine: engineNoIn) - try sgNoIn.loadRig(from: state) - #expect(engineNoIn.numInputChannels == 0, "loadRig must not reconfigure the engine's I/O") - #expect(sgNoIn.inputSource == .testLoop, "missing channel should fall back to test loop") + defer { try? FileManager.default.removeItem(at: urlA) } + let sgA: ShoeGaze = ShoeGaze(engine: engineA) // defaults to .testLoop + try sgA.loadRig(from: liveState, keepingCurrentInput: true) + #expect(sgA.inputSource == .testLoop, "switch must keep the current input, not adopt the rig's") + + // The reverse: a live-input session loading a test-loop rig stays on live input. + let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.1, + numInputChannels: 1, + numAudioBuses: 128 + ) + defer { try? FileManager.default.removeItem(at: urlB) } + let sgTestLoop: ShoeGaze = ShoeGaze(engine: engineB) // .testLoop + let plainBoard: PedalBoard = try sgTestLoop.addBoard() + try plainBoard.add(OverdrivePedal()) + try sgTestLoop.finalizeBoard(plainBoard) + let testLoopState: ShoeGazeState = sgTestLoop.captureState() + #expect(testLoopState.inputSource == .testLoop) + + sgIn.currentRigID = nil + try sgIn.loadRig(from: testLoopState, keepingCurrentInput: true) + #expect(sgIn.inputSource == .liveInput(channel: 0), + "switch must keep the current live input, not adopt the rig's test loop") + + // A default load (file open / launch restore) still applies the rig's saved input. + let (engineC, urlC): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.1, numInputChannels: 1, numAudioBuses: 128 + ) + defer { try? FileManager.default.removeItem(at: urlC) } + let sgDefault: ShoeGaze = ShoeGaze(engine: engineC) // .testLoop + try sgDefault.loadRig(from: liveState) // default: restore saved input + #expect(sgDefault.inputSource == .liveInput(channel: 0), + "a default load restores the rig's saved input") + + // loadRig still never reconfigures the engine's channel layout. + #expect(engineA.numInputChannels == 1, "loadRig must not reconfigure the engine's I/O") } @Test func channelCountsPersistButLoadDoesNotReconfigure() throws { From 5decdd8693679c828f22b04ac3f3b8f29bb6a1a8 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 17:57:57 -0700 Subject: [PATCH 12/18] fix(rigs): refresh stale starters on update; tab follows current rig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Seeding now (re)installs every starter by stable id, so a corrected rig definition replaces the stale copy already in a library (save upserts by id, keeping its position) — user rigs untouched. Bumped seedVersion to 2 so existing libraries pick up the two-board Garcia rig (the old router version showed "No board at index 0" because the builder UI renders boards, not routers, and the stale entry was never refreshed). "Restore Starter Rigs" likewise refreshes all starters, not just missing ones. - The Mine/Starters toggle now opens on the group containing the currently loaded rig (Starters when a factory rig like Garcia is active, else Mine), and follows the selection when the current rig changes. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRigLibrary.swift | 9 +- .../RigLibraryBootstrap.swift | 82 ++++++++----------- .../RigLibrarySidebarView.swift | 12 +++ 3 files changed, 50 insertions(+), 53 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index 6b7eee3..2eb352c 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -70,10 +70,11 @@ extension ChainRouter { @MainActor public enum FactoryRigLibrary { - /// Catalog seed version. Bump this whenever new factory rigs are added so first-run catch-up - /// seeding re-runs on already-populated libraries and installs the newly-shipped starters. Never - /// re-adds a rig the user has since deleted at the *same* version — the marker only advances. - public static let seedVersion: Int = 1 + /// Catalog seed version. Bump this whenever the shipped starter rigs change — new rigs added, or + /// an existing rig's definition corrected — so launch catch-up re-runs on already-populated + /// libraries and refreshes every starter to its current form. Within a single version the marker + /// only advances once, so a starter the user deletes stays deleted until the next bump. + public static let seedVersion: Int = 2 /// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig. /// diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift index b48dfc4..f64bf5a 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -27,15 +27,16 @@ public enum RigLibraryBootstrap { RigLibraryStore() } - /// Resolves + loads `store` off the main thread, then performs a one-time catch-up seed of any - /// missing shipped starter rigs. Idempotent — safe to call once at every launch. + /// Resolves + loads `store` off the main thread, then performs a one-time catch-up install of the + /// shipped starter rigs. Idempotent — safe to call once at every launch. /// - /// Seeding adds only factory rigs whose stable ids are **not already present**, so it never - /// duplicates a rig and never touches the user's own rigs. It runs at most once per - /// ``FactoryRigLibrary/seedVersion``: a first launch seeds every starter; a launch after an - /// update that ships new starters seeds just the new ones; and a starter the user later deletes - /// stays deleted (the version marker has already advanced). This deliberately replaces the old - /// "only seed an empty library" rule so users who already had rigs still receive the starters. + /// Installing (re)saves every factory rig by its stable id, so it **adds** missing starters and + /// **refreshes** existing ones to their current shipped definition (a corrected rig replaces the + /// stale copy in place, keeping its library position). User rigs are never touched — factory rigs + /// have their own fixed ids. It runs at most once per ``FactoryRigLibrary/seedVersion``: a first + /// launch installs every starter; a launch after a version bump refreshes/adds; and within a + /// version a starter the user deletes stays deleted (the marker has already advanced). This + /// deliberately replaces the old "only seed an empty library" rule so existing users get starters. /// /// - Parameters: /// - store: The store from ``makeStore()``. @@ -51,60 +52,43 @@ public enum RigLibraryBootstrap { let seededVersion: Int = defaults.integer(forKey: seedVersionKey) // 0 when never seeded guard seededVersion < FactoryRigLibrary.seedVersion else { return } - // Seed missing starters. Only advance the marker if seeding succeeded, so a transient failure + // Install the starters. Only advance the marker if it succeeded, so a transient failure // (which should not happen for this deterministic data) is retried on the next launch. - if seedMissingFactoryRigs(into: store) { + if installFactoryRigs(into: store) != nil { defaults.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey) } } - /// Adds any shipped starter rig not already in `store`, keyed by stable id. Safe to call anytime. + /// (Re)installs every shipped starter rig to its current definition. Safe to call anytime. /// - /// Use this to drive a user-facing "Restore Starter Rigs" action: it re-adds starters the user - /// deleted (and any newly-shipped ones) without disturbing their own rigs, and advances the seed - /// marker so automatic catch-up seeding won't fight the manual restore. + /// Drives the user-facing "Restore Starter Rigs" action: it re-adds starters the user deleted, + /// adds newly-shipped ones, and refreshes any stale copies — all without disturbing the user's own + /// rigs — and advances the seed marker so automatic catch-up won't fight the manual restore. /// - /// - Parameter store: The library to seed into. - /// - Returns: The number of starter rigs added (0 if all were already present). + /// - Parameter store: The library to install into. + /// - Returns: The number of starter rigs written (0 on a build/encode failure). @discardableResult public static func restoreStarterRigs(into store: RigLibraryStore) -> Int { - let added: Int = addMissingFactoryRigs(into: store) + let written: Int = installFactoryRigs(into: store) ?? 0 UserDefaults.standard.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey) - return added + return written } - /// Seeds missing starters, returning whether the operation completed without a build/encode error - /// (so the caller knows whether to advance the seed marker). - private static func seedMissingFactoryRigs(into store: RigLibraryStore) -> Bool { - do { - _ = try addMissingFactoryRigsThrowing(into: store) - return true - } catch { - print("[RigLibraryBootstrap] seeding factory rigs failed: \(error)") - return false - } - } - - /// Non-throwing convenience: seeds missing starters and returns the count added (0 on error). - private static func addMissingFactoryRigs(into store: RigLibraryStore) -> Int { - do { - return try addMissingFactoryRigsThrowing(into: store) - } catch { - print("[RigLibraryBootstrap] restoring factory rigs failed: \(error)") - return 0 - } - } - - /// Builds the starter rigs and saves the ones whose ids are missing from `store`. + /// Builds every starter rig and saves it, overwriting any existing entry with the same stable id + /// (`store.save` upserts by id, keeping an overwritten entry's library position). /// - /// - Returns: The number of rigs added. - /// - Throws: Any error from building the rigs or a synchronous encode failure in `store.save`. - private static func addMissingFactoryRigsThrowing(into store: RigLibraryStore) throws -> Int { - let existingIDs: Set = Set(store.entries.map { $0.id }) - let missing: [RigEntry] = try FactoryRigLibrary.makeEntries().filter { !existingIDs.contains($0.id) } - for entry: RigEntry in missing { - try store.save(entry) + /// - Parameter store: The library to install into. + /// - Returns: The number of rigs written, or `nil` if building/encoding failed. + private static func installFactoryRigs(into store: RigLibraryStore) -> Int? { + do { + let entries: [RigEntry] = try FactoryRigLibrary.makeEntries() + for entry: RigEntry in entries { + try store.save(entry) + } + return entries.count + } catch { + print("[RigLibraryBootstrap] installing factory rigs failed: \(error)") + return nil } - return missing.count } } diff --git a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift index 09266b0..220c3ca 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -77,6 +77,18 @@ struct RigLibrarySidebarView: View { actionBar } .frame(width: RigLibrarySidebarView.width) + // Open on the tab that contains the currently-loaded rig, so a session restored on a starter + // rig (e.g. Garcia) shows Starters, and one on a user rig shows Mine. + .onAppear { tab = tabForCurrentRig() } + .onChange(of: currentRigID) { tab = tabForCurrentRig() } + } + + /// The tab whose group contains the currently-loaded rig: Starters for a factory rig, else Mine. + private func tabForCurrentRig() -> RigTab { + if let id: UUID = currentRigID, FactoryRigLibrary.isFactory(id) { + return .starters + } + return .mine } // MARK: - Header From 44e6c35550fc6f30f92bc300aa35101ab3c2672e Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Mon, 10 Aug 2026 16:40:35 -0700 Subject: [PATCH 13/18] fix(rigs): don't flag a rig dirty over input/channel differences MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Switching between starter rigs prompted "save changes?" even when nothing was edited. The unsaved-changes check compared full ShoeGazeState snapshots (`captureState() != entry.state`), which include the live input source and engine channel counts — and those legitimately differ from a factory rig's saved values now that a rig switch preserves the player's current input instead of adopting the rig's saved one. Add ShoeGazeState.hasSameRigContent(as:) comparing only rig content (boards, routers, MIDI map, tempo) and use it for the dirty check, so session/engine settings no longer register as unsaved changes. Test added. Co-Authored-By: Claude Opus 4.8 --- .../Presets/ShoeGazeState.swift | 16 +++++++++++++ .../ShoeGazeBuilderView.swift | 6 ++++- Tests/LyrebirdShoeGazeTests/PresetTests.swift | 23 +++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift index 60df45d..3cbe95b 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift @@ -140,4 +140,20 @@ public struct ShoeGazeState: Codable, Equatable { self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels) self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers) } + + /// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo — + /// ignoring live session settings that are not part of the recalled rig: the input source and the + /// engine's channel counts. + /// + /// Use this for unsaved-changes detection. Those session fields are deliberately not applied when + /// switching rigs (see ``ShoeGaze/loadRig(from:keepingCurrentInput:)``), so a plain `==` would + /// report a freshly-loaded rig as "changed" merely because the player's current input differs from + /// the input the rig was saved with — producing a spurious "save changes?" prompt. + public func hasSameRigContent(as other: ShoeGazeState) -> Bool { + boards == other.boards + && routers == other.routers + && midiMap == other.midiMap + && bpm == other.bpm + && tempoEnabled == other.tempoEnabled + } } diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 0f52b6b..9900a3e 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -1677,12 +1677,16 @@ public struct ShoeGazeBuilderView: View { /// Whether the working rig differs from the library entry it was loaded from. A working rig with /// no backing entry counts as dirty when it has any boards. + /// + /// Compares rig content only (boards, routers, MIDI, tempo) — not the live input source or engine + /// channel counts, which are intentionally kept across a rig switch and so must not register as + /// unsaved changes (otherwise switching between rigs always prompts to save). private func isCurrentRigDirty() -> Bool { guard let id: UUID = currentRigID, let entry: RigEntry = library.entries.first(where: { $0.id == id }) else { return !shoeGaze.boards.isEmpty } - return shoeGaze.captureState() != entry.state + return !shoeGaze.captureState().hasSameRigContent(as: entry.state) } /// Saves the current session over the loaded library entry, or prompts for a name when no entry diff --git a/Tests/LyrebirdShoeGazeTests/PresetTests.swift b/Tests/LyrebirdShoeGazeTests/PresetTests.swift index 7984625..d8c191e 100644 --- a/Tests/LyrebirdShoeGazeTests/PresetTests.swift +++ b/Tests/LyrebirdShoeGazeTests/PresetTests.swift @@ -427,6 +427,29 @@ struct PresetTests { #expect(sg.inputSource == .testLoop, "load leaves the current input source unchanged") } + @Test func rigContentComparisonIgnoresInputAndChannels() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.05, numInputChannels: 1, numAudioBuses: 64 + ) + defer { try? FileManager.default.removeItem(at: url) } + let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop) + let board: PedalBoard = try sg.addBoard() + try board.add(FuzzPedal()) + try sg.finalizeBoard(board) + let saved: ShoeGazeState = sg.captureState() + + // Changing only the live input source must NOT read as a rig change (the source of the + // spurious "save changes?" prompt when switching starter rigs). + sg.inputSource = .liveInput(channel: 0) + let afterInputChange: ShoeGazeState = sg.captureState() + #expect(afterInputChange.hasSameRigContent(as: saved), "input change must not be a rig change") + #expect(afterInputChange != saved, "but the raw snapshots still differ on the input field") + + // A genuine graph difference IS a content change. + let emptyRig: ShoeGazeState = ShoeGazeState(boards: []) + #expect(!saved.hasSameRigContent(as: emptyRig), "different boards must count as a rig change") + } + @Test func loadPreservesCurrentInputSourceNotTheSavedOne() throws { // A rig captured with live input still RECORDS its source in the snapshot... let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine( From 2aea609f342831a7f217f721faa9fb5e29330b74 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Mon, 10 Aug 2026 17:04:58 -0700 Subject: [PATCH 14/18] feat(rigs): ship the tweaked Garcia rig as a captured state Replace the code-built Garcia with the user's hand-authored version, transcribed verbatim as a ShoeGazeState: Board 1 (Bass Octaver, Mutant, Overdrive, Graphic EQ, Phaser, Delay, Fullerton Reverb) and Board 2 (Overdrive, Graphic EQ, Compressor, Fullerton Reverb), preserving exact mix, graphic-EQ slider, cab-selector and amp sag/bias values. Input source and channel counts are omitted so the rig stays input-agnostic. Adds a FactoryRigBuild.state case (and matching FactoryRig init) for rigs shipped as a pre-captured state rather than a live builder, and bumps seedVersion to 3 so existing libraries refresh Garcia to the new version. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRig.swift | 26 ++++ .../Presets/Factory/FactoryRigBuild.swift | 7 ++ .../Presets/Factory/FactoryRigLibrary.swift | 112 ++++++++++-------- 3 files changed, 95 insertions(+), 50 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift index 2b1286e..4ceb8b5 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift @@ -96,4 +96,30 @@ public struct FactoryRig: Identifiable, Sendable { self.category = category self.build = .session(sessionBuild) } + + /// Creates a factory rig from a pre-captured ``ShoeGazeState``. + /// + /// The rig's content is the supplied state verbatim — used for a complex, hand-authored rig + /// captured from the app. Seeding builds the entry directly from `state` (no live session). + /// + /// - Parameters: + /// - id: Stable identifier (a fixed literal per rig — see ``id``). + /// - name: Rig name (picker title + saved entry name). + /// - blurb: User-facing description of the sound. + /// - category: Sonic family for picker grouping. + /// - state: The captured rig content to ship. + @MainActor + public init( + id: UUID, + name: String, + blurb: String, + category: FactoryRigCategory, + state: ShoeGazeState + ) { + self.id = id + self.name = name + self.blurb = blurb + self.category = category + self.build = .state({ state }) + } } diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift index 42eb4c5..46839b0 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigBuild.swift @@ -14,4 +14,11 @@ public enum FactoryRigBuild: Sendable { /// Builds the whole graph against the session (boards and/or routers), owning its own /// `addBoard`/`finalizeBoard` and `makeChainRouter`/`finalize` lifecycle. case session(@MainActor (_ session: ShoeGaze) throws -> Void) + + /// Ships a pre-captured ``ShoeGazeState`` directly — the entry is built from it with no live + /// session. Use for a complex, hand-authored rig captured from the app, where transcribing the + /// exact `PedalState` arrays (mix, sliders, selectors, advanced values) is more faithful than + /// re-deriving them through typed setters. The closure returns the state so the case stays + /// `Sendable` without requiring `ShoeGazeState` itself to be `Sendable`. + case state(@MainActor () -> ShoeGazeState) } diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index 2eb352c..febc9bf 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -74,7 +74,7 @@ public enum FactoryRigLibrary { /// an existing rig's definition corrected — so launch catch-up re-runs on already-populated /// libraries and refreshes every starter to its current form. Within a single version the marker /// only advances once, so a starter the user deletes stays deleted until the next bump. - public static let seedVersion: Int = 2 + public static let seedVersion: Int = 3 /// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig. /// @@ -654,57 +654,61 @@ public enum FactoryRigLibrary { id: stableID("Garcia OBEL Split"), name: "Garcia OBEL Clean/Effects Split", blurb: "Two boards, one selector: Board 1 is an effects/lead chain (octave, envelope filter, " - + "overdrive, phaser, delay); Board 2 is a clean direct path. Use the board Solo / Blend " - + "control at the top to switch between them, like an on-board effects loop. In the " - + "spirit of a certain improvising guitarist's late-'80s rig.", + + "overdrive, graphic EQ, phaser, delay, reverb); Board 2 is a fuller direct voice " + + "(overdrive, graphic EQ, compression, reverb). Use the board Solo / Blend control at the " + + "top to switch between them, like an on-board effects loop. In the spirit of a certain " + + "improvising guitarist's late-'80s rig.", category: .classic, - sessionBuild: { session in - // Board 1 — the effects / lead chain (effects loop engaged). - let effects: PedalBoard = try session.addBoard() - try effects.append(BassOctaverPedal()) { p in - p.oct1 = 0.5 - p.direct = 1.0 - p.mode = 1.0 - } - try effects.append(MutantPedal()) { p in - p.sensitivity = 2.5 - p.resonance = 5.0 - } - try effects.append(OverdrivePedal()) { p in - p.drive = 5.0 - p.tone = 4200.0 - } - try effects.append(PhaserPedal()) { p in - p.rate = 0.4 - p.feedback = 0.4 - } - try effects.append(DelayPedal()) { p in - p.time = 0.35 - p.feedback = 1.8 - } - try effects.append(CaliforniaAmpPedal()) { p in - p.gain = 5.0 - p.bass = 0.55 - p.mid = 0.6 - p.treble = 0.6 - } - try session.finalizeBoard(effects) + // Hand-authored in the app and shipped as a captured state — transcribing the exact pedal + // values (mix, graphic-EQ sliders, cab selector, amp sag/bias) is more faithful than + // re-deriving them through typed setters. Input source / channel counts are intentionally + // omitted so the rig is input-agnostic. + state: garciaState + ) - // Board 2 — the clean / direct path (effects loop bypassed). - let clean: PedalBoard = try session.addBoard() - try clean.append(CompressorPedal()) { p in - p.inputGain = 2.0 - p.threshold = -16.0 - p.ratio = 3.0 - } - try clean.append(CaliforniaAmpPedal()) { p in - p.gain = 3.5 - p.bass = 0.5 - p.mid = 0.55 - p.treble = 0.6 - } - try session.finalizeBoard(clean) - } + /// The shipped Garcia rig content. `static let` so its (default) pedal ids are stable per process, + /// keeping seeding deterministic. + private static let garciaState: ShoeGazeState = ShoeGazeState( + boards: [ + BoardState(label: "Board 1", pedals: [ + PedalState(type: "Bass Octaver", + knobValues: [0.5, 0, 1, 1, 1], switchValues: [1], bypass: 0), + PedalState(type: "Mutant", + knobValues: [2.5, 4.45515625, 1, 1], switchValues: [1, 0], bypass: 0), + PedalState(type: "Overdrive", + knobValues: [5, 4200, 1, 1], bypass: 0), + PedalState(type: "Graphic EQ", + knobValues: [1, 1], + sliderValues: [-4.7786931818181815, -2.214204545454546, 1.552840909090909, + 1.8536931818181799, -3.3426136363636374, -0.45852272727272947], + bypass: 0), + PedalState(type: "Phaser", + knobValues: [0.4, 0.4, 0.5, 1], bypass: 0), + PedalState(type: "Delay", + knobValues: [0.35, 1.8, 0.35, 1], bypass: 0), + PedalState(type: "Fullerton Reverb", + knobValues: [2.5505078125, 0.5, 0.5, 0.6, 0.25, 4, 0, 1, 1], + switchValues: [0, 1, 0], selectorValues: [4], + advancedValues: [0, 0.5, 0], bypass: 0), + ]), + BoardState(label: "Board 2", pedals: [ + PedalState(type: "Overdrive", + knobValues: [6.54533203125, 4000, 1, 1], bypass: 0), + PedalState(type: "Graphic EQ", + knobValues: [1, 1], + sliderValues: [2.957386363636365, 0, 2.7741477272727266, + 1.940624999999999, -0.6767045454545446, 0], + bypass: 0), + PedalState(type: "Compressor", + knobValues: [2, -16, 3, 1, 1], switchValues: [0], bypass: 0), + PedalState(type: "Fullerton Reverb", + knobValues: [5.08, 0.5, 0.5, 0.6, 0.13624999999999998, 4, 0, 1, 1], + switchValues: [0, 1, 0], selectorValues: [4], + advancedValues: [0, 0.5, 0], bypass: 0), + ]), + ], + bpm: 120, + tempoEnabled: true ) // MARK: - Seeding @@ -726,6 +730,12 @@ public enum FactoryRigLibrary { var entries: [RigEntry] = [] entries.reserveCapacity(all.count) for rig: FactoryRig in all { + // A state-backed rig needs no live session — build its entry directly from the state. + if case .state(let makeState) = rig.build { + entries.append(RigEntry(id: rig.id, name: rig.name, state: makeState())) + continue + } + let session: ShoeGaze = try makeSession() // Tear down on every exit from this iteration, including a throw from a builder, so a // failing rig never leaks its throwaway engine's buses/nodes. @@ -739,6 +749,8 @@ public enum FactoryRigLibrary { // The builder owns its own board/router lifecycle (addBoard/finalizeBoard, // makeChainRouter/finalize). try build(session) + case .state: + continue // handled above } entries.append(session.captureEntry(name: rig.name, id: rig.id)) } From 850b86209a7eedffbd243ffb4d6f4c0508f4f9a3 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Wed, 12 Aug 2026 14:59:58 -0700 Subject: [PATCH 15/18] fix(shimmer): lower default + starter decay/shimmer to avoid self-oscillation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shimmer reverb's regenerating loop gain is ~decay + shimmer, so hot values screech into sustained feedback with little or no input. The pedal defaults summed to 1.3 (0.8 + 0.5) — over unity on a fresh add — and several starter rigs ran 1.3–1.6. - Pedal defaults: decay 0.8 -> 0.5, shimmer 0.5 -> 0.25, damp 0.4 -> 0.5 (sum 0.75), with a doc note on keeping decay + shimmer < 1. - Starter rigs using it (Dreampop Chorus Cathedral, Ambient Shimmer Bed, Post-Rock Crescendo, Comfortably Numb Lead): decay/shimmer pulled down so each sums to ~0.8 or less; damping raised. Bumped seedVersion to 4 so existing libraries refresh. Co-Authored-By: Claude Opus 4.8 --- .../Pedals/ShimmerReverbPedal.swift | 11 ++++--- .../Presets/Factory/FactoryRigLibrary.swift | 30 ++++++++++--------- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Pedals/ShimmerReverbPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ShimmerReverbPedal.swift index 15f6efb..0702a39 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/ShimmerReverbPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/ShimmerReverbPedal.swift @@ -31,13 +31,16 @@ public final class ShimmerReverbPedal: Pedal { @UIParam public var size: Double = 0.06 /// Tail length (feedback). Range [0, 0.92]. - @UIParam public var decay: Double = 0.8 + /// + /// The regenerating loop gain is roughly `decay + shimmer`; keep their sum well under `1` to avoid + /// self-oscillation (a sustaining screech with little or no input). Defaults sum to `0.75`. + @UIParam public var decay: Double = 0.5 - /// Octave-up regeneration amount. Range [0, 0.85]. - @UIParam public var shimmer: Double = 0.5 + /// Octave-up regeneration amount. Range [0, 0.85]. See ``decay`` on keeping `decay + shimmer < 1`. + @UIParam public var shimmer: Double = 0.25 /// High-frequency damping. Range [0, 1]. - @UIParam public var damp: Double = 0.4 + @UIParam public var damp: Double = 0.5 // MARK: - Constants diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift index febc9bf..696716b 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -74,7 +74,7 @@ public enum FactoryRigLibrary { /// an existing rig's definition corrected — so launch catch-up re-runs on already-populated /// libraries and refreshes every starter to its current form. Within a single version the marker /// only advances once, so a starter the user deletes stays deleted until the next bump. - public static let seedVersion: Int = 3 + public static let seedVersion: Int = 4 /// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig. /// @@ -198,11 +198,11 @@ public enum FactoryRigLibrary { p.feedback = 1.5 } try board.append(ShimmerReverbPedal()) { p in - // Keep decay + shimmer feedback well below self-oscillation — high decay with the - // octave-up regeneration screeches into runaway feedback within seconds. + // Keep decay + shimmer well below self-oscillation — the loop gain is ~decay + shimmer, so + // high values screech into runaway feedback with little or no input. p.size = 0.09 - p.decay = 0.55 - p.shimmer = 0.3 + p.decay = 0.5 + p.shimmer = 0.25 p.damp = 0.5 } } @@ -323,10 +323,12 @@ public enum FactoryRigLibrary { p.tone = 3500.0 } try board.append(ShimmerReverbPedal()) { p in + // Long ambient tail, but decay + shimmer kept under ~0.8 so it never self-oscillates; the + // room reverb downstream supplies the extra length. p.size = 0.11 - p.decay = 0.9 - p.shimmer = 0.7 - p.damp = 0.3 + p.decay = 0.6 + p.shimmer = 0.2 + p.damp = 0.5 } try board.append(RoomReverbPedal()) { p in p.size = 60.0 @@ -506,9 +508,9 @@ public enum FactoryRigLibrary { } try board.append(ShimmerReverbPedal()) { p in p.size = 0.1 - p.decay = 0.88 - p.shimmer = 0.6 - p.damp = 0.3 + p.decay = 0.55 + p.shimmer = 0.25 + p.damp = 0.5 } } @@ -613,9 +615,9 @@ public enum FactoryRigLibrary { } try board.append(ShimmerReverbPedal()) { p in p.size = 0.09 - p.decay = 0.85 - p.shimmer = 0.5 - p.damp = 0.35 + p.decay = 0.55 + p.shimmer = 0.25 + p.damp = 0.5 } } From 4a9bf0fb308eee64204bf847e19944968ab8cff2 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Thu, 13 Aug 2026 09:42:52 -0700 Subject: [PATCH 16/18] feat(mutant): add Range switch, Sweep, and Attack/Release controls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The envelope filter's cutoff sweep was fixed (80 Hz -> 3200 Hz, 5 ms / 150 ms), so it read as either muted (resting too low) or extreme (40x span). The underlying MuTronIII generator already takes freqLo/freqHi/attack/release as live params, so expose them: - Range switch (Lo/Hi) on the face — shifts the whole sweep window low (rhythm/bass) or high (harmonics/solos), matching the original Mu-Tron III. - Sweep, Attack, Release in the advanced pop-over — Sweep sets how far input amplitude drives the cutoff (peak = resting x sweep); Attack/Release shape the envelope response. - Tamer defaults: resting 80 -> 120 Hz, span 40x -> 20x. Serialization-safe: new continuous params live in advancedValues and Range is a trailing switch, so a rig saved with the old 2-switch / no-advanced layout loads unchanged with the new controls at their defaults (test covers it). Co-Authored-By: Claude Opus 4.8 --- .../LyrebirdShoeGaze/Pedals/MutantPedal.swift | 89 +++++++++++++---- .../MutantPedalTests.swift | 98 +++++++++++++++++-- 2 files changed, 161 insertions(+), 26 deletions(-) diff --git a/Sources/LyrebirdShoeGaze/Pedals/MutantPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/MutantPedal.swift index 21487a7..485eb1b 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/MutantPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/MutantPedal.swift @@ -17,6 +17,13 @@ import LyrebirdUI /// keeps every filter state warmed so switch changes are click-free (SuperCollider /// `Select` semantics: every input advances each block). /// +/// The cutoff sweeps exponentially from a resting frequency (`freqLo`) up to a peak +/// (`freqHi`) as the envelope opens: `cutoff = freqLo·(freqHi/freqLo)^envelope`. The +/// **Range** switch shifts that whole window low (rhythm / bass) or high (harmonics / +/// solos), matching the original pedal; the **Sweep** knob sets how far above the resting +/// frequency the envelope drives the cutoff (its "openness"), and **Attack** / **Release** +/// shape how quickly the filter follows the input dynamics. +/// /// ## Knobs /// - `sensitivity`: Drive into the envelope follower; higher values open the filter on quieter notes. /// - `resonance`: Filter peak emphasis at the swept cutoff. @@ -24,6 +31,12 @@ import LyrebirdUI /// ## Switches /// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it). /// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass. +/// - `range` (two-state): `0` = Low band (rhythm / bass), `1` = High band (harmonics / solos). +/// +/// ## Advanced +/// - `sweep`: How far the envelope drives the cutoff above its resting frequency (peak = resting × sweep). +/// - `attack`: Envelope attack time in seconds — how fast the filter opens on a transient. +/// - `release`: Envelope release time in seconds — how fast it closes after a note. public final class MutantPedal: Pedal { /// One-line description shown in the picker and info panel. @@ -45,19 +58,29 @@ public final class MutantPedal: Pedal { /// Filter resonance (Chamberlin SVF peak emphasis). Clamped to `≥ 1.0` internally. @UIParam public var resonance: Double = 4.0 + /// Frequency-band selector. `0` = Low band, `1` = High band. Shifts the resting cutoff (and with + /// it the whole sweep window) up or down. Driven by a two-state switch. + @UIParam public var range: Double = 0.0 + + /// Sweep amount: the peak cutoff is `restingCutoff × sweep`, so higher values open the filter + /// further as the input drives it. Advanced knob. + @UIParam public var sweep: Double = 20.0 + + /// Envelope attack time in seconds — how fast the filter opens on a transient. Advanced knob. + @UIParam public var attack: Double = 0.008 + + /// Envelope release time in seconds — how fast the filter closes after a note. Advanced knob. + @UIParam public var release: Double = 0.14 + // MARK: - Constants private static let defaultMix: Double = 1.0 - /// Cutoff at zero envelope, in Hz. - private let freqLo: Double = 80.0 + /// Resting cutoff (in Hz) at `range == Low`. + private let rangeLowBaseFreq: Double = 120.0 - /// Cutoff at maximum envelope, in Hz (≈40× sweep over `freqLo`). - private let freqHi: Double = 3200.0 - - /// Envelope attack/release times, in seconds. - private let attackTime: Double = 0.005 - private let releaseTime: Double = 0.15 + /// Resting cutoff (in Hz) at `range == High`. + private let rangeHighBaseFreq: Double = 380.0 /// Half-step bias added before each `Select`'s truncate-toward-zero index, turning a /// switch parameter into a round-to-nearest position selector. @@ -69,11 +92,17 @@ public final class MutantPedal: Pedal { private let modeHighpassValue: Double = 2.0 private let directionDownValue: Double = 0.0 private let directionUpValue: Double = 1.0 + private let rangeLowValue: Double = 0.0 + private let rangeHighValue: Double = 1.0 // MARK: - Ranges private let sensitivityRange: ClosedRange = 0.0 ... 4.0 private let resonanceRange: ClosedRange = 1.0 ... 12.0 + /// Sweep multiplier: peak cutoff = resting × sweep. `1` = no sweep; `50` ≈ 5.6 octaves. + private let sweepRange: ClosedRange = 1.0 ... 50.0 + private let attackRange: ClosedRange = 0.001 ... 0.08 + private let releaseRange: ClosedRange = 0.02 ... 0.6 // MARK: - Knobs @@ -84,12 +113,20 @@ public final class MutantPedal: Pedal { ] } + public override var advancedKnobs: [PedalKnob] { + [ + PedalKnob(label: "Sweep", node: $sweep, range: sweepRange), + PedalKnob(label: "Attack", node: $attack, range: attackRange), + PedalKnob(label: "Release", node: $release, range: releaseRange), + ] + } + // MARK: - Switches public override var effectSwitches: [PedalSwitch] { [ PedalSwitch( - label: "Sweep", + label: "Direction", node: $direction, options: [ PedalSwitch.Option(title: "Down", value: directionDownValue), @@ -105,6 +142,14 @@ public final class MutantPedal: Pedal { PedalSwitch.Option(title: "HP", value: modeHighpassValue), ] ), + PedalSwitch( + label: "Range", + node: $range, + options: [ + PedalSwitch.Option(title: "Lo", value: rangeLowValue), + PedalSwitch.Option(title: "Hi", value: rangeHighValue), + ] + ), ] } @@ -122,23 +167,29 @@ public final class MutantPedal: Pedal { // MARK: - Effect public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // Resting cutoff shifts with the Range switch (Low band vs High band); the peak the envelope + // reaches is `restingCutoff × sweep`. Both feed all six warmed filters (fan-out). + let restingFreq: any ValidGeneratorInput = + $range * (rangeHighBaseFreq - rangeLowBaseFreq) + rangeLowBaseFreq + let peakFreq: any ValidGeneratorInput = restingFreq * $sweep + // Inner mode selectors per sweep direction. `Select` rounds the [0, 2] mode switch // to the nearest position and advances all three filters each block (warmed state). let modeWhich: any ValidGeneratorInput = $mode + selectRoundingBias let downModes: Select.Audio = Select.Audio( which: modeWhich, inputs: [ - makeFilter(dry, mode: .lowpass, direction: .down), - makeFilter(dry, mode: .bandpass, direction: .down), - makeFilter(dry, mode: .highpass, direction: .down), + makeFilter(dry, mode: .lowpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq), + makeFilter(dry, mode: .bandpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq), + makeFilter(dry, mode: .highpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq), ] ) let upModes: Select.Audio = Select.Audio( which: modeWhich, inputs: [ - makeFilter(dry, mode: .lowpass, direction: .up), - makeFilter(dry, mode: .bandpass, direction: .up), - makeFilter(dry, mode: .highpass, direction: .up), + makeFilter(dry, mode: .lowpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq), + makeFilter(dry, mode: .bandpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq), + makeFilter(dry, mode: .highpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq), ] ) @@ -153,7 +204,9 @@ public final class MutantPedal: Pedal { private func makeFilter( _ dry: any ValidGeneratorInput, mode: MuTronIIIMode, - direction: MuTronIIISweep + direction: MuTronIIISweep, + freqLo: any ValidGeneratorInput, + freqHi: any ValidGeneratorInput ) -> MuTronIII.Audio { MuTronIII.Audio( input: dry, @@ -163,8 +216,8 @@ public final class MutantPedal: Pedal { peak: $resonance, freqLo: freqLo, freqHi: freqHi, - attackTime: attackTime, - releaseTime: releaseTime + attackTime: $attack, + releaseTime: $release ) } } diff --git a/Tests/LyrebirdShoeGazeTests/MutantPedalTests.swift b/Tests/LyrebirdShoeGazeTests/MutantPedalTests.swift index d5d550c..495ca7d 100644 --- a/Tests/LyrebirdShoeGazeTests/MutantPedalTests.swift +++ b/Tests/LyrebirdShoeGazeTests/MutantPedalTests.swift @@ -100,28 +100,110 @@ struct MutantPedalTests { pedal.mode = 2.0 // highpass pedal.direction = 0.0 // down + pedal.range = 1.0 // high band + pedal.sweep = 12.0 + pedal.attack = 0.02 + pedal.release = 0.3 + let state: PedalState = pedal.captureState() - #expect(state.switchValues == [0.0, 2.0]) // [direction, mode] + #expect(state.switchValues == [0.0, 2.0, 1.0]) // [direction, mode, range] + #expect(state.advancedValues == [12.0, 0.02, 0.3]) // [sweep, attack, release] let restored: MutantPedal = MutantPedal() restored.applyState(state) #expect(restored.mode == 2.0) #expect(restored.direction == 0.0) + #expect(restored.range == 1.0) + #expect(restored.sweep == 12.0) + #expect(restored.attack == 0.02) + #expect(restored.release == 0.3) + } + + @Test func oldTwoSwitchStateStillLoads() throws { + // A rig saved before Range / the advanced knobs existed carries only [direction, mode] and + // an empty advancedValues; it must load without mis-mapping, leaving the new controls at + // their defaults. + let legacy: PedalState = PedalState( + type: "Mutant", + knobValues: [2.5, 4.0, 1, 1], // sensitivity, resonance, mix, level + switchValues: [1.0, 0.0], // direction=up, mode=lowpass + bypass: 0 + ) + let pedal: MutantPedal = MutantPedal() + pedal.applyState(legacy) + #expect(pedal.direction == 1.0) + #expect(pedal.mode == 0.0) + #expect(pedal.sensitivity == 2.5) + #expect(pedal.resonance == 4.0) + // New controls keep their defaults. + #expect(pedal.range == 0.0) + #expect(pedal.sweep == 20.0) } @Test func exposesSensitivityAndResonanceKnobs() throws { let pedal: MutantPedal = MutantPedal() - let labels: [String] = pedal.effectKnobs.map { $0.label } - #expect(labels == ["Sensitivity", "Resonance"]) + #expect(pedal.effectKnobs.map { $0.label } == ["Sensitivity", "Resonance"]) + #expect(pedal.advancedKnobs.map { $0.label } == ["Sweep", "Attack", "Release"]) } - @Test func exposesTwoStateSweepAndThreeStateModeSwitches() throws { + @Test func exposesDirectionModeAndRangeSwitches() throws { let pedal: MutantPedal = MutantPedal() let switches: [PedalSwitch] = pedal.effectSwitches - #expect(switches.map { $0.label } == ["Sweep", "Mode"]) - // Two-state sweep (Down/Up), three-state mode (LP/BP/HP). - #expect(switches.first?.options.map { $0.title } == ["Down", "Up"]) - #expect(switches.last?.options.map { $0.title } == ["LP", "BP", "HP"]) + #expect(switches.map { $0.label } == ["Direction", "Mode", "Range"]) + #expect(switches[0].options.map { $0.title } == ["Down", "Up"]) + #expect(switches[1].options.map { $0.title } == ["LP", "BP", "HP"]) + #expect(switches[2].options.map { $0.title } == ["Lo", "Hi"]) + } + + /// Renders the test loop through a Mutant configured by `configure`, returning a mid-render window. + private func renderWindow(configure: (MutantPedal) -> Void) throws -> [Float] { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 64) + defer { try? FileManager.default.removeItem(at: url) } + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: MutantPedal = MutantPedal(inputBus: srcBus.index, outputBus: dstBus.index) + configure(pedal) + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + return readStereoCAF(url: url) + } + + private func windowSSD(_ a: [Float], _ b: [Float]) -> Double { + let skip: Int = 1024 + let window: Int = 2048 + guard a.count >= skip + window, b.count >= skip + window else { return 0 } + return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in + let d: Double = Double(pair.0 - pair.1) + return acc + d * d + } + } + + @Test func sweepAmountChangesOutput() throws { + let narrow: [Float] = try renderWindow { $0.sweep = 3.0 } + let wide: [Float] = try renderWindow { $0.sweep = 45.0 } + #expect(hasNonSilentOutput(narrow)) + #expect(hasNonSilentOutput(wide)) + #expect(windowSSD(narrow, wide) > 0, "sweep amount did not change output") + } + + @Test func rangeSwitchChangesOutput() throws { + let low: [Float] = try renderWindow { $0.range = 0.0 } + let high: [Float] = try renderWindow { $0.range = 1.0 } + #expect(windowSSD(low, high) > 0, "range band did not change output") + } + + @Test func attackReleaseChangesOutput() throws { + let fast: [Float] = try renderWindow { $0.attack = 0.001; $0.release = 0.03 } + let slow: [Float] = try renderWindow { $0.attack = 0.06; $0.release = 0.5 } + #expect(windowSSD(fast, slow) > 0, "attack/release did not change output") } @Test func sweepDirectionChangesOutput() throws { From 93ca9076d2fc6ed4973b4202754b6c71ae0e018f Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Thu, 13 Aug 2026 09:58:34 -0700 Subject: [PATCH 17/18] docs: 3.1.0 release notes, README refresh, Help + version bump - CHANGELOG: add the 3.1.0 entry (starter rigs, Mine/Starters sidebar, Vibe and Sustain Fuzz pedals, Mutant Range/Sweep/Attack/Release, input-preserved rig switching, shimmer defaults, overwrite guard, router persistence). - README: correct the pedal count (36 -> 67, incl. 26 amp models), add the Amp Model and Cabinet catalog rows and the new pedals, add a Starter Rigs feature, and bump the Lyrebird requirement to 1.7.0+. - Help: add a "Starter Rigs" topic and note that switching rigs keeps the current input. - Bump the iOS app MARKETING_VERSION to 3.1.0 to match macOS. Co-Authored-By: Claude Opus 4.8 --- CHANGELOG.md | 52 +++++++++++++++++++ .../project.pbxproj | 4 +- README.md | 28 ++++++---- Sources/LyrebirdShoeGazeUI/HelpView.swift | 19 +++++++ 4 files changed, 91 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfceae2..599b643 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,58 @@ All notable changes to ShoeGaze are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [semantic versioning](https://semver.org/spec/v2.0.0.html). +## [3.1.0] — 2026-08-13 + +Starter rigs and a deeper envelope filter. ShoeGaze now ships a library of ready-to-play +rigs grouped by style, two new pedals, and a much more expressive Mutant envelope filter — +plus a batch of rig-switching and reverb fixes. + +### Added + +- **19 built-in starter rigs**, seeded into the library on first launch and grouped by + style — **Shoegaze Walls**, **Dreampop**, **Classic**, **Ambient**, and **Experimental**. + A **Mine / Starters** toggle at the top of the rig sidebar switches between your own rigs + and the shipped ones (grouped under category headers); the sidebar opens on whichever + group holds the current rig. A **Restore Starter Rigs** action (rig-library menu, or the + Starters empty state) reinstalls the shipped rigs at any time. +- **Two-board starter rig** — a Garcia-style clean/effects split across two boards, switched + with the board Solo / Blend control, showing off multi-board rigs. +- **Vibe pedal** — a photocell "vibe": four staggered all-pass stages swept by one LFO, with + **Chorus** and **Vibrato** modes and Speed / Intensity controls. +- **Sustain Fuzz pedal** — a mid-scooped, high-sustain fuzz (two cascaded soft-clip stages), + distinct from the brighter single-stage Fuzz. Sustain / Tone / Scoop controls. +- **Mutant (envelope filter) controls** — a **Range** switch (Lo / Hi) that shifts the whole + sweep band, matching the original Mu-Tron III, plus **Sweep**, **Attack**, and **Release** + in the advanced pop-over. Sweep sets how far your picking drives the cutoff; Attack / + Release shape how quickly the filter follows. + +### Changed + +- **Switching rigs keeps your current input.** Loading a rig from the library no longer snaps + the input back to the test loop (or the input a rig was saved with) — your live guitar (or + whatever input you have selected) carries across the switch. Opening or restoring a rig + file still applies its saved input. +- **Shimmer Reverb backed off.** The regenerating loop gain is roughly `decay + shimmer`, so + the old defaults (0.8 + 0.5) self-oscillated into a screech with little or no input. + Defaults are now decay 0.5 / shimmer 0.25 / damp 0.5, and the starter rigs that use it were + re-tuned to stay well below self-oscillation. +- **Mutant sweep defaults tamed** — resting cutoff 80 → 120 Hz and sweep span 40× → 20×, so + the filter is neither muted at rest nor extreme when it opens. +- **Starter rigs refresh on update.** Shipped rigs install (and refresh to their current + form) by catalog version, so a corrected starter reaches libraries that were seeded + earlier — without touching your own rigs. + +### Fixed + +- **No more spurious "Save changes?" prompt when switching rigs.** The unsaved-changes check + compared live session settings (input source, engine channel counts) that legitimately + differ from a rig's saved values; it now compares rig content only. +- **Overwrite guard for starter rigs.** Saving over a loaded starter rig now asks first, + offering **Overwrite**, **Save as New Rig**, or **Cancel**, so a shipped rig isn't replaced + by accident. +- **Multi-board signal-router rigs now save and load.** Routed A/B rigs were previously lost + on save; their branch chains and blend now persist. + ## [3.0.0] — 2026-08-04 The big one: ShoeGaze becomes an amp-modeling rig. This release adds a full lineup of diff --git a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj index c738950..6e5d9aa 100644 --- a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj @@ -175,7 +175,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 3.0.0; + MARKETING_VERSION = 3.1.0; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; @@ -203,7 +203,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 3.0.0; + MARKETING_VERSION = 3.1.0; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; diff --git a/README.md b/README.md index 5da6952..ca90807 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,13 @@ signal (no hardware needed) or on live guitar through an audio input. ## Features -- **36 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and - texture — see the catalog below. +- **67 modeled pedals** — effects across gain, dynamics, EQ/filter, modulation, pitch, delay, + reverb, and texture, plus **26 tube-amp models** with their own tone stacks and a deep + speaker-cabinet / microphone section. All original DSP built on the Lyrebird engine — no + third-party captures or IR packs. See the catalog below. +- **Starter rigs** — a library of ready-to-play rigs ships with the app, grouped by style + (Shoegaze Walls, Dreampop, Classic, Ambient, Experimental) and reachable from a **Mine / + Starters** toggle in the rig sidebar. - **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel style) or **Blend** any subset, each with its own level and a click-free crossfade, plus a rig-wide **output volume and mute** on top. @@ -21,8 +26,9 @@ signal (no hardware needed) or on live guitar through an audio input. volume, with per-binding invert for crossfades. MIDI Learn, one binding per rig. - **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or stereo lanes, and merge back to mono. -- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across - your devices and both apps via iCloud. +- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar (your own rigs + and the shipped starters on separate tabs); synced across your devices and both apps via iCloud. + Switching rigs keeps your current input, and saving over a starter rig asks first. - **Sharing** — send a rig or a saved board to anyone as a `.shoegaze` file via the system share sheet (AirDrop, Mail, Messages, Files); export/import the whole library the same way. - **Recording** — capture your output to timestamped files. @@ -37,14 +43,16 @@ signal (no hardware needed) or on live guitar through an audio input. | Category | Pedals | |---|---| -| Gain | Overdrive, Distortion, Fuzz | -| Dynamics | Compressor, Sustainer, Limiter, Noise Gate | -| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Cabinet | -| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Rotary, Ring Modulator | +| Gain | Overdrive, Distortion, Fuzz, Sustain Fuzz | +| Dynamics | Compressor, Sustainer, Limiter, Noise Gate, Volume | +| EQ & filter | Graphic EQ, Auto-Wah, Wah, Mutant | +| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator | | Pitch | Bass Octaver, Octave Splitter, Harmonizer | | Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay | | Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb | -| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator | +| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Looper | +| Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim | +| Cabinet | Cabinet (speaker-voice + microphone modeling) | Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format. @@ -52,7 +60,7 @@ Every pedal exposes its parameters as knobs/switches and round-trips through the - macOS 15+ / iPadOS 18+ (iPad, landscape) - Swift 6.0 toolchain / Xcode 16+ -- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.2.0+ +- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.7.0+ ## Packages diff --git a/Sources/LyrebirdShoeGazeUI/HelpView.swift b/Sources/LyrebirdShoeGazeUI/HelpView.swift index 6b5955e..d3243d7 100644 --- a/Sources/LyrebirdShoeGazeUI/HelpView.swift +++ b/Sources/LyrebirdShoeGazeUI/HelpView.swift @@ -93,6 +93,25 @@ public struct HelpView: View { "Reorder rigs into a set list by dragging a row, or via each rig's Move Up / " + "Move Down menu. The order is saved and travels with an exported archive; " + "the top ten map to ⌘⇧1–⌘⇧0.", + "Switching rigs keeps your current input — your live guitar stays selected " + + "instead of snapping back to the test loop.", + ] + ) + topicSection( + icon: "guitars", + title: "Starter Rigs", + intro: "ShoeGaze ships a library of ready-to-play rigs so you always have somewhere " + + "to start.", + steps: [ + "The Rigs sidebar has a Mine / Starters toggle at the top: Mine is your own " + + "saved rigs; Starters is the shipped set, grouped by style — Shoegaze " + + "Walls, Dreampop, Classic, Ambient, and Experimental.", + "Tap a starter to load it. To keep your tweaks, use Save As or Duplicate to make " + + "your own copy — saving directly over a starter asks first and offers Save " + + "as New Rig.", + "Restore Starter Rigs (the rig-library ⋯ menu, or the Starters empty state) " + + "reinstalls the shipped rigs — handy if you deleted some, or to refresh " + + "them after an update.", ] ) topicSection( From 812a240e55c3b068851080541875df01ea1a5721 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Thu, 13 Aug 2026 10:17:21 -0700 Subject: [PATCH 18/18] chore(release): prep 3.1.0 (RELEASES backfill, version + dep pin) - RELEASES.md: backfill the 3.0.0 (amp modeling) and 3.1.0 (starter rigs) narrative entries so the release doc is current again. - Bump the macOS app to MARKETING_VERSION 3.1.0 (build 19). - Pin the iOS app's resolved Lyrebird to 1.7.2 (was 1.2.3). Co-Authored-By: Claude Opus 4.8 --- .../ShoeGazeBuilder.xcodeproj/project.pbxproj | 8 ++-- .../xcshareddata/swiftpm/Package.resolved | 4 +- RELEASES.md | 45 +++++++++++++++++++ 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj index 3c34e4c..1bcb389 100644 --- a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj @@ -163,7 +163,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 15; + CURRENT_PROJECT_VERSION = 19; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_HARDENED_RUNTIME = YES; @@ -175,7 +175,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.0; - MARKETING_VERSION = 3.0.0; + MARKETING_VERSION = 3.1.0; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; @@ -193,7 +193,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 15; + CURRENT_PROJECT_VERSION = 19; DEAD_CODE_STRIPPING = YES; ENABLE_HARDENED_RUNTIME = YES; INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; @@ -204,7 +204,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.0; - MARKETING_VERSION = 3.0.0; + MARKETING_VERSION = 3.1.0; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; diff --git a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 0c7f3cc..7401a62 100644 --- a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://realizedsound.mooo.com/josh/Lyrebird", "state" : { - "revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0", - "version" : "1.2.3" + "revision" : "77580ee98e05cb4a94aac367097d27b91d3776c0", + "version" : "1.7.2" } }, { diff --git a/RELEASES.md b/RELEASES.md index 0c731d1..427d57f 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,4 +1,49 @@ # Releases +## ShoeGaze 3.1.0 + +Starter rigs, two new pedals, and a deeper envelope filter — plus smoother rig switching. + +### Highlights +- **Starter rigs** — a library of ready-to-play rigs ships with the app, grouped by style + (Shoegaze Walls, Dreampop, Classic, Ambient, Experimental) behind a **Mine / Starters** toggle + in the rig sidebar. Includes a two-board clean/effects split. **Restore Starter Rigs** reinstalls + them any time. +- **Vibe** — a photocell "vibe" (four staggered all-pass stages swept by one LFO) with Chorus and + Vibrato modes. +- **Sustain Fuzz** — a mid-scooped, high-sustain fuzz, distinct from the brighter single-stage Fuzz. +- **A deeper Mutant envelope filter** — a **Range** switch (Lo / Hi) that shifts the whole sweep + band like the original Mu-Tron III, plus **Sweep**, **Attack**, and **Release** in the advanced + pop-over. +- **Rig switching keeps your input** — your live guitar stays selected across a rig change instead + of snapping back to the test loop. + +### Fixed +- No more spurious "Save changes?" prompt when switching between rigs. +- Shimmer Reverb no longer self-oscillates into a screech at its defaults. +- Saving over a starter rig asks first (Overwrite / Save as New Rig / Cancel). +- Multi-board signal-router rigs now save and load. + +## ShoeGaze 3.0.0 + +The big one: ShoeGaze becomes an amp-modeling rig — a full lineup of tube-amp voices plus a deep +speaker-cabinet and microphone section, all original DSP built from the Lyrebird engine with no +third-party captures or IR packs. + +### Highlights +- **26 amp-model pedals** in their own **Amp Model** palette category — Fullerton blackface combos, + California and Jazz Clean cleans, British stack / combo voices, the Chime top-boost family, + Boutique and high-gain amps, and character amps (Command, Citrus, Sixties Combo, Magna Vibrato, + Anaheim). Each has its own tone stack, a selectable speaker cabinet, and a real master volume that + drives the power-amp stage. +- **Speaker-cabinet + microphone section** on the Cabinet pedal — eight speaker voicings, mic + modeling (Dynamic / Ribbon / Condenser), placement and proximity, and a dual-mic blend. +- **Power-amp feel controls** — Sag, Bias, and Bias X in an advanced pop-over — and analog-style + soft limiting, so a driven amp compresses toward its ceiling instead of clipping harshly. +- **Gain and Drive read 1–11** with a musical taper. + +### Fixed +- Noise Gate no longer pops as a note decays. + ## ShoeGaze 2.1.3 A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — even