SPB Git

Repository Public License

PulseMusic.swift 27.1 KB 553 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/PulseBeat/PulseMusic.swift10// Description      : Pulse Beat — the five original tracks as data (tempo, key,11//                    progression, structure) and the composer that turns a12//                    track into event lists on a sixteenth-note grid. Pure and13//                    deterministic.14// Module           : Games15// Repository       : https://git.spboucher.ai/orix-arcade16// Created          : 2026-11-2217// Last Modified    : 2026-11-2218//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : Proprietary, all rights reserved (see license file)84// License File     : LICENSE85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394nonisolated enum PulseSectionKind: String, Sendable, Equatable {95    case intro, verse, build, drop, breakdown, outro, tail9697    var title: String {98        switch self {99        case .intro: "Intro"100        case .verse: "Verse"101        case .build: "Build"102        case .drop: "Drop"103        case .breakdown: "Break"104        case .outro: "Outro"105        case .tail: "End"106        }107    }108}109110nonisolated struct PulseSection: Sendable, Equatable {111    var kind: PulseSectionKind112    var bars: Int113}114115nonisolated enum PulseDrumStyle: Sendable { case laidBack, backbeat, fourFloor, trance, breakbeat }116nonisolated enum PulseBassStyle: Sendable { case sustained, octaves, offbeat, rolling, syncopated }117nonisolated enum PulseTimbre: Sendable { case sine, triangle, saw, square }118119/// A rhythm for a two-bar phrase: (start, length) pairs in sixteenth notes, 0…31.120nonisolated struct PulseRhythm: Sendable, Equatable {121    var cells: [(start: Int, length: Int)]122    init(_ cells: [(Int, Int)]) { self.cells = cells.map { (start: $0.0, length: $0.1) } }123    static func == (a: PulseRhythm, b: PulseRhythm) -> Bool {124        a.cells.count == b.cells.count && zip(a.cells, b.cells).allSatisfy { $0.start == $1.start && $0.length == $1.length }125    }126}127128/// Everything that defines one track. The music itself is generated from this by `PulseComposer`.129nonisolated struct PulseTrackSpec: Sendable, Identifiable, Equatable {130    let id: String131    let title: String132    let mood: String133    let keyName: String134    let bpm: Double135    /// MIDI note of the tonic.136    let root: Int137    /// Semitone offsets of the seven scale degrees.138    let scale: [Int]139    /// Scale degree of the chord of each bar; cycles.140    let progression: [Int]141    let dropProgression: [Int]142    let sections: [PulseSection]143    let drums: PulseDrumStyle144    let bass: PulseBassStyle145    let lead: PulseTimbre146    /// Sixteenths between arpeggio notes.147    let arpStep: Int148    let verseRhythm: PulseRhythm149    let dropRhythm: PulseRhythm150    let breakRhythm: PulseRhythm151    let seed: UInt64152    let hexA: UInt32153    let hexB: UInt32154155    static func == (a: PulseTrackSpec, b: PulseTrackSpec) -> Bool { a.id == b.id }156}157158/// A pitched note. `step` and `length` are in sixteenths from the start of the track.159nonisolated struct PulseTone: Sendable, Equatable {160    var step: Int161    var length: Int162    var midi: Int163    var velocity: Double164    /// The first note of a hook phrase or the landing note of a fill: charts turn these into swipes and doubles.165    var accent = false166}167168nonisolated struct PulseHit: Sendable, Equatable {169    var step: Int170    var velocity: Double171}172173nonisolated struct PulseChord: Sendable, Equatable {174    var step: Int175    var length: Int176    var midis: [Int]177    var velocity: Double178}179180nonisolated struct PulseSpan: Sendable, Equatable {181    var kind: PulseSectionKind182    var start: Int183    var end: Int184}185186/// The composed track: every sound that will be synthesised, as events. Charts are derived from the same lists.187nonisolated struct PulseSong: Sendable, Equatable {188    let spec: PulseTrackSpec189    var kicks: [PulseHit] = []190    var snares: [PulseHit] = []191    var hats: [PulseHit] = []192    var openHats: [PulseHit] = []193    var crashes: [Int] = []194    var risers: [PulseSpan] = []195    var bass: [PulseTone] = []196    var lead: [PulseTone] = []197    var arp: [PulseTone] = []198    var pads: [PulseChord] = []199    var spans: [PulseSpan] = []200    var totalSteps = 0201202    var stepDuration: Double { 15 / spec.bpm }203    var beatDuration: Double { 60 / spec.bpm }204    var duration: Double { Double(totalSteps) * stepDuration }205    func time(_ step: Int) -> Double { Double(step) * stepDuration }206207    func section(atStep step: Int) -> PulseSectionKind {208        for span in spans where step >= span.start && step < span.end { return span.kind }209        return .tail210    }211212    func section(at time: Double) -> PulseSectionKind { section(atStep: Int((time / stepDuration).rounded(.down))) }213}214215nonisolated enum PulseLibrary {216    static let major = [0, 2, 4, 5, 7, 9, 11]217    static let minor = [0, 2, 3, 5, 7, 8, 10]218    static let dorian = [0, 2, 3, 5, 7, 9, 10]219    static let phrygian = [0, 1, 3, 5, 7, 8, 10]220221    static let tracks: [PulseTrackSpec] = [222        PulseTrackSpec(223            id: "firstLight", title: "First Light", mood: "Warm · Mellow", keyName: "C major", bpm: 100, root: 48, scale: major,224            progression: [0, 4, 5, 3], dropProgression: [5, 3, 0, 4],225            sections: [.init(kind: .intro, bars: 4), .init(kind: .verse, bars: 8), .init(kind: .build, bars: 2), .init(kind: .drop, bars: 8),226                       .init(kind: .breakdown, bars: 4), .init(kind: .build, bars: 2), .init(kind: .drop, bars: 8), .init(kind: .outro, bars: 2)],227            drums: .laidBack, bass: .sustained, lead: .triangle, arpStep: 2,228            verseRhythm: PulseRhythm([(0, 6), (6, 2), (8, 8), (16, 4), (20, 4), (24, 8)]),229            dropRhythm: PulseRhythm([(0, 4), (4, 2), (6, 2), (8, 6), (14, 2), (16, 4), (20, 2), (22, 2), (24, 8)]),230            breakRhythm: PulseRhythm([(0, 12), (12, 4), (16, 16)]),231            seed: 0xF1A57, hexA: 0xFFB86B, hexB: 0xFF4FA3),232        PulseTrackSpec(233            id: "neonPulse", title: "Neon Pulse", mood: "Synthwave · Driving", keyName: "A minor", bpm: 120, root: 45, scale: minor,234            progression: [0, 5, 2, 6], dropProgression: [0, 2, 6, 5],235            sections: [.init(kind: .intro, bars: 4), .init(kind: .verse, bars: 8), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 8),236                       .init(kind: .breakdown, bars: 4), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 8), .init(kind: .outro, bars: 4)],237            drums: .backbeat, bass: .octaves, lead: .saw, arpStep: 2,238            verseRhythm: PulseRhythm([(0, 3), (3, 3), (6, 2), (8, 4), (12, 4), (16, 3), (19, 3), (22, 2), (24, 8)]),239            dropRhythm: PulseRhythm([(0, 2), (2, 2), (4, 4), (8, 3), (11, 3), (14, 2), (16, 2), (18, 2), (20, 4), (24, 6), (30, 2)]),240            breakRhythm: PulseRhythm([(0, 8), (8, 8), (16, 12), (28, 4)]),241            seed: 0x2E0F, hexA: 0xF94CFF, hexB: 0x5B8CFF),242        PulseTrackSpec(243            id: "midnightCircuit", title: "Midnight Circuit", mood: "House · Hypnotic", keyName: "F♯ dorian", bpm: 128, root: 54, scale: dorian,244            progression: [0, 0, 5, 6], dropProgression: [0, 3, 5, 6],245            sections: [.init(kind: .intro, bars: 8), .init(kind: .verse, bars: 8), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 8),246                       .init(kind: .breakdown, bars: 4), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 8), .init(kind: .outro, bars: 4)],247            drums: .fourFloor, bass: .offbeat, lead: .square, arpStep: 1,248            verseRhythm: PulseRhythm([(0, 2), (3, 2), (6, 2), (8, 4), (14, 2), (16, 2), (19, 2), (22, 2), (24, 4), (28, 4)]),249            dropRhythm: PulseRhythm([(0, 2), (3, 1), (4, 2), (6, 2), (8, 2), (11, 3), (14, 2), (16, 2), (19, 1), (20, 2), (22, 2), (24, 4), (28, 2), (30, 2)]),250            breakRhythm: PulseRhythm([(0, 6), (6, 6), (12, 4), (16, 16)]),251            seed: 0x3C1C, hexA: 0x35E0D0, hexB: 0x7C5CFF),252        PulseTrackSpec(253            id: "voltageRun", title: "Voltage Run", mood: "Trance · Euphoric", keyName: "E minor", bpm: 140, root: 52, scale: minor,254            progression: [0, 5, 3, 4], dropProgression: [0, 6, 5, 4],255            sections: [.init(kind: .intro, bars: 8), .init(kind: .verse, bars: 8), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 16),256                       .init(kind: .breakdown, bars: 4), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 8), .init(kind: .outro, bars: 4)],257            drums: .trance, bass: .rolling, lead: .saw, arpStep: 1,258            verseRhythm: PulseRhythm([(0, 4), (4, 2), (6, 2), (8, 6), (14, 2), (16, 4), (20, 2), (22, 2), (24, 8)]),259            dropRhythm: PulseRhythm([(0, 2), (2, 2), (4, 2), (6, 2), (8, 6), (14, 2), (16, 2), (18, 2), (20, 2), (22, 2), (24, 6), (30, 2)]),260            breakRhythm: PulseRhythm([(0, 12), (12, 4), (16, 12), (28, 4)]),261            seed: 0x40A7, hexA: 0x4DF0FF, hexB: 0xB6F24A),262        PulseTrackSpec(263            id: "hyperdrive", title: "Hyperdrive", mood: "Breakbeat · Relentless", keyName: "D phrygian", bpm: 160, root: 50, scale: phrygian,264            progression: [0, 1, 0, 6], dropProgression: [0, 5, 1, 0],265            sections: [.init(kind: .intro, bars: 8), .init(kind: .verse, bars: 8), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 16),266                       .init(kind: .breakdown, bars: 8), .init(kind: .build, bars: 4), .init(kind: .drop, bars: 16), .init(kind: .outro, bars: 4)],267            drums: .breakbeat, bass: .syncopated, lead: .square, arpStep: 2,268            verseRhythm: PulseRhythm([(0, 2), (2, 2), (4, 4), (8, 2), (10, 2), (12, 4), (16, 2), (18, 2), (20, 2), (22, 2), (24, 8)]),269            dropRhythm: PulseRhythm([(0, 2), (2, 1), (3, 1), (4, 2), (6, 2), (8, 4), (12, 2), (14, 2), (16, 2), (18, 1), (19, 1), (20, 2), (22, 2), (24, 6), (30, 2)]),270            breakRhythm: PulseRhythm([(0, 16), (16, 8), (24, 8)]),271            seed: 0x5D21, hexA: 0xFF5470, hexB: 0xFFC94D),272    ]273274    static func track(_ id: String) -> PulseTrackSpec? { tracks.first { $0.id == id } }275    static func index(of id: String) -> Int { tracks.firstIndex { $0.id == id } ?? 0 }276277    /// Composed once per process: composition is cheap (events only) and deterministic.278    static let songs: [PulseSong] = tracks.map(PulseComposer.compose)279    static func song(_ id: String) -> PulseSong { songs[index(of: id)] }280281    private static let chartTable: [[PulseChart]] = songs.map { song in PulseDifficulty.allCases.map { PulseChartBuilder.build(song, difficulty: $0) } }282    static func chart(_ id: String, _ difficulty: PulseDifficulty) -> PulseChart { chartTable[index(of: id)][difficulty.rawValue] }283    static var chartCount: Int { tracks.count * PulseDifficulty.allCases.count }284}285286nonisolated enum PulseComposer {287    /// Silence after the last section so the final chord rings out and the chart can end well before the audio does.288    static func tailBars(bpm: Double) -> Int { Int((3.2 / (240 / bpm)).rounded(.up)) }289290    /// Pitch of a scale degree (may be negative or above 6: octaves wrap).291    static func pitch(_ spec: PulseTrackSpec, degree: Int) -> Int {292        let octave = Int((Double(degree) / 7).rounded(.down))293        let index = degree - octave * 7294        return spec.root + 12 * octave + spec.scale[index]295    }296297    private static func fold(_ midi: Int, into range: Range<Int>) -> Int {298        var value = midi299        while value >= range.upperBound { value -= 12 }300        while value < range.lowerBound { value += 12 }301        return value302    }303304    /// A two-bar melodic cell: scale degrees relative to the chord root, so it follows the harmony when the chord changes.305    private struct Motif {306        var notes: [(start: Int, length: Int, relative: Int)]307    }308309    private static func motif(_ rhythm: PulseRhythm, rng: inout SeededRNG, low: Int, high: Int) -> Motif {310        let chordTones = [-3, 0, 2, 4, 7, 9, 11, 14, 16].filter { $0 >= low && $0 <= high }311        var cursor = rng.pick(chordTones.filter { $0 >= low + 2 && $0 <= high - 2 })312        var notes: [(start: Int, length: Int, relative: Int)] = []313        for cell in rhythm.cells {314            if cell.start % 8 == 0 || cell.length >= 6 {315                // Strong position: land on a chord tone near the cursor.316                let ranked = chordTones.sorted { abs($0 - cursor) != abs($1 - cursor) ? abs($0 - cursor) < abs($1 - cursor) : $0 < $1 }317                let choice = ranked[min(ranked.count - 1, rng.pick([0, 0, 1, 1, 2]))]318                cursor = choice == cursor && ranked.count > 1 && rng.chance(0.6) ? ranked[1] : choice319            } else {320                cursor = min(max(cursor + rng.pick([-2, -1, -1, 1, 1, 2]), low), high)321            }322            notes.append((cell.start, cell.length, cursor))323        }324        return Motif(notes: notes)325    }326327    static func compose(_ spec: PulseTrackSpec) -> PulseSong {328        var song = PulseSong(spec: spec)329        var rng = SeededRNG(seed: spec.seed)330        let verse = motif(spec.verseRhythm, rng: &rng, low: 4, high: 13)331        let verseAlt = motif(spec.verseRhythm, rng: &rng, low: 4, high: 13)332        let hook = motif(spec.dropRhythm, rng: &rng, low: 6, high: 16)333        let hookAlt = motif(spec.dropRhythm, rng: &rng, low: 6, high: 16)334        let calm = motif(spec.breakRhythm, rng: &rng, low: 4, high: 11)335336        var bar = 0337        var dropsSeen = 0338        for (sectionIndex, section) in spec.sections.enumerated() {339            let start = bar * 16340            song.spans.append(PulseSpan(kind: section.kind, start: start, end: start + section.bars * 16))341            let progression = section.kind == .drop ? spec.dropProgression : spec.progression342            if section.kind == .drop {343                song.crashes.append(start)344                dropsSeen += 1345            }346            if section.kind == .build { song.risers.append(PulseSpan(kind: .build, start: start, end: start + section.bars * 16)) }347            let isLastSection = sectionIndex == spec.sections.count - 1348349            for local in 0..<section.bars {350                let s0 = (bar + local) * 16351                let degree = progression[local % progression.count]352                let finalBar = isLastSection && local == section.bars - 1353                let chord = finalBar ? 0 : degree354                let lastOfSection = local == section.bars - 1355356                // Pad: the triad plus the octave, voiced close.357                let padTones = [0, 2, 4, 7].map { fold(pitch(spec, degree: chord + $0), into: 50..<68) }358                let padLevel: Double = switch section.kind {359                case .intro, .breakdown: 1360                case .build: 0.85361                case .drop: 0.7362                default: 0.75363                }364                song.pads.append(PulseChord(step: s0, length: finalBar ? 16 + tailBars(bpm: spec.bpm) * 12 : 16, midis: padTones, velocity: padLevel))365366                if finalBar {367                    // The ending: one crash, one bass note and the tonic held on the lead.368                    song.crashes.append(s0)369                    song.kicks.append(PulseHit(step: s0, velocity: 1))370                    song.bass.append(PulseTone(step: s0, length: 12, midi: fold(pitch(spec, degree: 0), into: 31..<43), velocity: 1))371                    song.lead.append(PulseTone(step: s0, length: 12, midi: pitch(spec, degree: 7), velocity: 1, accent: true))372                    continue373                }374375                drums(&song, spec: spec, kind: section.kind, s0: s0, local: local, bars: section.bars, lastOfSection: lastOfSection)376                bass(&song, spec: spec, kind: section.kind, s0: s0, degree: chord, local: local, bars: section.bars)377                arp(&song, spec: spec, kind: section.kind, s0: s0, degree: chord, local: local, bars: section.bars)378379                // Lead: two-bar motifs, restated with a variation every other phrase.380                guard local % 2 == 0 else { continue }381                let phrase = local / 2382                let cell: Motif?383                let level: Double384                switch section.kind {385                case .intro:386                    cell = local >= section.bars / 2 ? calm : nil387                    level = 0.6388                case .verse:389                    cell = phrase % 2 == 0 ? verse : verseAlt390                    level = 0.8391                case .build:392                    cell = local < max(2, section.bars - 2) && section.bars > 2 ? verse : nil393                    level = 0.75394                case .drop:395                    cell = phrase % 2 == 0 ? hook : (dropsSeen > 1 ? hookAlt : hook)396                    level = 1397                case .breakdown:398                    cell = calm399                    level = 0.8400                case .outro:401                    cell = verse402                    level = 0.7403                case .tail:404                    cell = nil405                    level = 0406                }407                guard let cell else { continue }408                for (index, note) in cell.notes.enumerated() {409                    // The second bar of the phrase follows its own chord.410                    let barOffset = note.start / 16411                    guard local + barOffset < section.bars else { continue }412                    if isLastSection, local + barOffset == section.bars - 1 { continue }413                    let chordHere = progression[(local + barOffset) % progression.count]414                    let stepStart = s0 + note.start415                    let limit = (bar + section.bars) * 16416                    let length = min(note.length, limit - stepStart)417                    guard length > 0 else { continue }418                    song.lead.append(PulseTone(step: stepStart, length: length, midi: pitch(spec, degree: chordHere + note.relative),419                                               velocity: level * (note.start % 8 == 0 ? 1 : 0.86),420                                               accent: index == 0 && (section.kind == .drop || section.kind == .verse)))421                }422            }423            bar += section.bars424        }425        let tail = tailBars(bpm: spec.bpm)426        song.spans.append(PulseSpan(kind: .tail, start: bar * 16, end: (bar + tail) * 16))427        song.totalSteps = (bar + tail) * 16428        song.kicks.sort { $0.step < $1.step }429        song.snares.sort { $0.step < $1.step }430        song.hats.sort { $0.step < $1.step }431        song.openHats.sort { $0.step < $1.step }432        song.lead.sort { $0.step < $1.step }433        song.bass.sort { $0.step < $1.step }434        song.arp.sort { $0.step < $1.step }435        song.crashes.sort()436        return song437    }438439    private static func drums(_ song: inout PulseSong, spec: PulseTrackSpec, kind: PulseSectionKind, s0: Int, local: Int, bars: Int, lastOfSection: Bool) {440        func kick(_ steps: [Int], _ velocity: Double = 1) { for s in steps { song.kicks.append(PulseHit(step: s0 + s, velocity: velocity)) } }441        func snare(_ steps: [Int], _ velocity: Double = 1) { for s in steps { song.snares.append(PulseHit(step: s0 + s, velocity: velocity)) } }442        func hat(_ steps: [Int], _ velocity: Double = 0.7) { for s in steps { song.hats.append(PulseHit(step: s0 + s, velocity: velocity)) } }443        func open(_ steps: [Int], _ velocity: Double = 0.7) { for s in steps { song.openHats.append(PulseHit(step: s0 + s, velocity: velocity)) } }444        let offbeats = [2, 6, 10, 14]445446        switch kind {447        case .intro:448            if local >= bars / 2 {449                hat(offbeats, 0.5)450                if spec.drums == .fourFloor || spec.drums == .trance { kick([0, 4, 8, 12], 0.8) } else { kick([0, 8], 0.8) }451            }452        case .verse:453            switch spec.drums {454            case .laidBack: kick([0, 10]); snare([4, 12], 0.85); hat([0, 2, 4, 6, 8, 10, 12, 14], 0.45)455            case .backbeat: kick([0, 8]); snare([4, 12]); hat(offbeats, 0.6)456            case .fourFloor: kick([0, 4, 8, 12]); snare([4, 12], 0.8); open(offbeats, 0.5)457            case .trance: kick([0, 4, 8, 12]); snare([4, 12], 0.75); open(offbeats, 0.5)458            case .breakbeat: kick([0, 10]); snare([4, 12]); hat([0, 2, 4, 6, 8, 10, 12, 14], 0.5)459            }460            if lastOfSection { snare([14, 15], 0.7) }461        case .build:462            kick([0, 4, 8, 12])463            // The roll tightens towards the drop: quarters, then eighths, then sixteenths.464            let remaining = bars - 1 - local465            if remaining == 0 {466                for s in 0..<16 { snare([s], 0.45 + 0.55 * Double(s) / 15) }467            } else if remaining == 1 {468                for s in stride(from: 0, to: 16, by: 2) { snare([s], 0.4 + 0.2 * Double(s) / 14) }469            } else {470                snare([4, 12], 0.6)471            }472            hat(offbeats, 0.5)473        case .drop:474            switch spec.drums {475            case .laidBack:476                kick([0, 6, 10]); snare([4, 12]); hat([0, 2, 4, 6, 8, 10, 12, 14], 0.5); open([14], 0.5)477            case .backbeat:478                kick([0, 6, 8]); snare([4, 12]); hat([0, 2, 4, 6, 8, 10, 12, 14], 0.55); open([14], 0.55)479            case .fourFloor:480                kick([0, 4, 8, 12]); snare([4, 12]); open(offbeats, 0.65); hat([1, 3, 5, 7, 9, 11, 13, 15], 0.3)481            case .trance:482                kick([0, 4, 8, 12]); snare([4, 12], 0.9); open(offbeats, 0.7); hat([0, 1, 3, 4, 5, 7, 8, 9, 11, 12, 13, 15], 0.3)483            case .breakbeat:484                kick(local % 2 == 0 ? [0, 6, 10] : [0, 3, 10]); snare([4, 12]); snare([7], 0.45)485                hat([0, 2, 4, 6, 8, 10, 12, 14], 0.55); open([14], 0.5)486            }487            // A fill closes every fourth bar.488            if local % 4 == 3 { snare(lastOfSection ? [10, 12, 13, 14, 15] : [13, 14, 15], 0.75) }489        case .breakdown:490            if local >= bars / 2 { kick([0], 0.8); hat(offbeats, 0.4) }491        case .outro:492            kick(spec.drums == .fourFloor || spec.drums == .trance ? [0, 4, 8, 12] : [0, 8])493            snare([4, 12], 0.8)494            hat(offbeats, 0.5)495        case .tail:496            break497        }498    }499500    private static func bass(_ song: inout PulseSong, spec: PulseTrackSpec, kind: PulseSectionKind, s0: Int, degree: Int, local: Int, bars: Int) {501        let rootNote = fold(pitch(spec, degree: degree), into: 31..<43)502        func add(_ step: Int, _ length: Int, _ midi: Int, _ velocity: Double = 1) {503            song.bass.append(PulseTone(step: s0 + step, length: length, midi: midi, velocity: velocity))504        }505        switch kind {506        case .intro, .tail:507            return508        case .breakdown:509            add(0, 14, rootNote, 0.7)510        case .build:511            if local < bars - 1 { add(0, 8, rootNote, 0.8); add(8, 8, rootNote, 0.8) }512        case .verse, .drop, .outro:513            let full = kind == .drop514            switch spec.bass {515            case .sustained:516                add(0, 6, rootNote)517                add(10, full ? 2 : 4, rootNote, 0.85)518                if full { add(12, 3, rootNote + 7, 0.8) }519            case .octaves:520                for s in stride(from: 0, to: 16, by: 2) { add(s, 2, s % 4 == 2 && full ? rootNote + 12 : rootNote, s % 4 == 0 ? 1 : 0.8) }521            case .offbeat:522                for s in [2, 6, 10, 14] { add(s, 2, rootNote) }523                if full { add(15, 1, rootNote + 12, 0.7) }524            case .rolling:525                for s in 0..<16 where s % 4 != 0 { add(s, 1, rootNote, s % 4 == 2 ? 1 : 0.8) }526            case .syncopated:527                add(0, 2, rootNote); add(3, 2, rootNote, 0.85); add(6, 3, rootNote + (full ? 12 : 0), 0.9)528                add(10, 2, rootNote); add(12, 3, rootNote + 7, 0.85)529            }530        }531    }532533    private static func arp(_ song: inout PulseSong, spec: PulseTrackSpec, kind: PulseSectionKind, s0: Int, degree: Int, local: Int, bars: Int) {534        let pattern = [7, 9, 11, 14, 11, 9, 11, 9]535        let level: Double536        var every = spec.arpStep537        switch kind {538        case .intro: level = 0.9; every = max(2, spec.arpStep)539        case .drop: level = 0.7540        case .breakdown: level = 0.6; every = max(2, spec.arpStep)541        case .build: level = local < bars - 1 ? 0.6 : 0542        default: level = 0543        }544        guard level > 0 else { return }545        var index = 0546        for s in stride(from: 0, to: 16, by: every) {547            song.arp.append(PulseTone(step: s0 + s, length: every, midi: pitch(spec, degree: degree + pattern[index % pattern.count]) + 12,548                                      velocity: level * (s % 4 == 0 ? 1 : 0.75)))549            index += 1550        }551    }552}553
Files main
Menu

Theme