SPB Git

Repository Public

VisualBuilderModel.swift 30.5 KB 660 lines swift

1// ORIX DJ2// File: App/Sources/Features/AutomationStudio/VisualBuilderModel.swift3// Description: Pure model of the Visual Builder: the block tree, block → ORIX Script source generation, and the4//              syntax tree → blocks import. No interface code; everything here is deterministic and testable.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXDJCore1011/// A literal value held by a block. Mirrors the ORIX Script literal kinds the builder can write.12enum VBValue: Codable, Equatable, Sendable {13    case number(Double)14    case gain(Double)15    case frequency(Double)16    case beats(Double)17    case seconds(Double)18    case bool(Bool)19    case string(String)2021    init?(_ value: Value) {22        switch value {23        case let .number(n): self = .number(n)24        case let .gain(d): self = .gain(d)25        case let .frequency(f): self = .frequency(f)26        case let .duration(.beats(b)): self = .beats(b)27        case let .duration(.seconds(s)): self = .seconds(s)28        case let .bool(b): self = .bool(b)29        case let .string(s): self = .string(s)30        default: return nil31        }32    }3334    var value: Value {35        switch self {36        case let .number(n): .number(n)37        case let .gain(d): .gain(d)38        case let .frequency(f): .frequency(f)39        case let .beats(b): .duration(.beats(b))40        case let .seconds(s): .duration(.seconds(s))41        case let .bool(b): .bool(b)42        case let .string(s): .string(s)43        }44    }4546    /// Canonical ORIX Script text. Whole bars are written in bars, everything else as the language prints it.47    var source: String {48        if case let .beats(b) = self, b != 0, b.truncatingRemainder(dividingBy: ORIXScriptLanguage.beatsPerBar) == 0 {49            let bars = b / ORIXScriptLanguage.beatsPerBar50            return Value.number(bars).description + (abs(bars) == 1 ? "bar" : "bars")51        }52        return value.description53    }5455    /// The scalar shown in a number field, in the unit of `unitLabel`.56    var magnitude: Double {57        switch self {58        case let .number(n), let .gain(n), let .frequency(n): n59        case let .beats(b): b != 0 && b.truncatingRemainder(dividingBy: 4) == 0 ? b / 4 : b60        case let .seconds(s): abs(s) < 1 && s != 0 ? s * 1000 : s61        case let .bool(b): b ? 1 : 062        case .string: 063        }64    }6566    var unitLabel: String {67        switch self {68        case .number, .bool, .string: ""69        case .gain: "dB"70        case .frequency: "Hz"71        case let .beats(b): b != 0 && b.truncatingRemainder(dividingBy: 4) == 0 ? "bars" : "beats"72        case let .seconds(s): abs(s) < 1 && s != 0 ? "ms" : "s"73        }74    }7576    /// The same kind of value with a new magnitude typed in the unit currently shown.77    func with(magnitude m: Double) -> VBValue {78        switch self {79        case .number: .number(m)80        case .gain: .gain(m)81        case .frequency: .frequency(m)82        case .beats: unitLabel == "bars" ? .beats(m * 4) : .beats(m)83        case .seconds: unitLabel == "ms" ? .seconds(m / 1000) : .seconds(m)84        case .bool: .bool(m != 0)85        case .string: self86        }87    }8889    static let durationUnits = ["beats", "bars", "s", "ms"]9091    /// Reinterprets the shown magnitude in another duration unit.92    func with(durationUnit unit: String) -> VBValue {93        let m = magnitude94        switch unit {95        case "beats": return .beats(m)96        case "bars": return .beats(m * 4)97        case "s": return .seconds(m)98        case "ms": return .seconds(m / 1000)99        default: return self100        }101    }102103    static func defaultValue(for def: ParamDef) -> VBValue { VBValue(def.defaultValue) ?? .number(0) }104}105106enum VBEvent: Codable, Equatable, Sendable {107    case deck(Int, String)108    case beat109    case bar110    case trigger(Int)111112    var source: String {113        switch self {114        case let .deck(d, name): "deck.\(deckLetters[min(max(d, 0), deckLetters.count - 1)]).\(name)"115        case .beat: "beat"116        case .bar: "bar"117        case let .trigger(n): "trigger(\(n))"118        }119    }120}121122enum VBWait: Codable, Equatable, Sendable {123    case duration(VBValue)124    case nextBeat125    case nextBar126}127128enum VBEffectOp: Codable, Equatable, Sendable {129    case enable, disable, toggle130    case set(key: String, value: VBValue)131}132133struct VBRamp: Codable, Equatable, Sendable, Identifiable {134    var id = UUID()135    var target: ParamAddress136    var value: VBValue137}138139struct VBCondition: Codable, Equatable, Sendable {140    var left: ParamAddress141    var op: String142    var right: VBValue143144    static let operators = ["==", "!=", "<", "<=", ">", ">="]145}146147indirect enum VBKind: Codable, Equatable, Sendable {148    /// `on <event> [once] { … }` — an event trigger. Top level only.149    case event(VBEvent, once: Bool, body: [VBBlock])150    case wait(VBWait)151    case deckAction(deck: Int, action: String, args: [VBValue])152    /// Sets a deck, mixer or master parameter.153    case setParam(ParamAddress, VBValue)154    /// `rack` nil is the master rack.155    case effect(rack: Int?, effect: EffectKind, op: VBEffectOp)156    case over(duration: VBValue, curve: String?, ramps: [VBRamp])157    case condition(VBCondition, then: [VBBlock], otherwise: [VBBlock]?)158    case loop(count: Int, body: [VBBlock])159    case stop160}161162struct VBBlock: Codable, Equatable, Sendable, Identifiable {163    var id = UUID()164    var kind: VBKind165166    init(_ kind: VBKind) { self.kind = kind }167}168169/// Which child list of a container block.170enum VBSlot: Sendable { case body, otherwise }171172struct VBGraph: Codable, Equatable, Sendable {173    var name = "Untitled"174    /// The start trigger: now, on the next beat or on the next bar.175    var quantize = StartQuantize.bar176    var blocks: [VBBlock] = []177178    var blockCount: Int { VBTree.count(blocks) }179}180181// MARK: - Tree editing182183enum VBTree {184    static func count(_ blocks: [VBBlock]) -> Int {185        blocks.reduce(0) { n, b in186            switch b.kind {187            case let .event(_, _, body), let .loop(_, body): n + 1 + count(body)188            case let .condition(_, a, b): n + 1 + count(a) + count(b ?? [])189            default: n + 1190            }191        }192    }193194    static func find(_ id: UUID, in blocks: [VBBlock]) -> VBBlock? {195        for b in blocks {196            if b.id == id { return b }197            switch b.kind {198            case let .event(_, _, body), let .loop(_, body): if let f = find(id, in: body) { return f }199            case let .condition(_, a, o): if let f = find(id, in: a) ?? find(id, in: o ?? []) { return f }200            default: break201            }202        }203        return nil204    }205206    /// Applies `change` to every child list, depth first, until one reports it handled the edit.207    @discardableResult208    static func editLists(_ blocks: inout [VBBlock], _ change: (inout [VBBlock]) -> Bool) -> Bool {209        if change(&blocks) { return true }210        for i in blocks.indices {211            switch blocks[i].kind {212            case .event(let e, let once, var body):213                if editLists(&body, change) { blocks[i].kind = .event(e, once: once, body: body); return true }214            case .loop(let n, var body):215                if editLists(&body, change) { blocks[i].kind = .loop(count: n, body: body); return true }216            case .condition(let c, var a, var o):217                if editLists(&a, change) { blocks[i].kind = .condition(c, then: a, otherwise: o); return true }218                if o != nil, editLists(&o!, change) { blocks[i].kind = .condition(c, then: a, otherwise: o); return true }219            default: break220            }221        }222        return false223    }224225    static func update(_ id: UUID, in blocks: inout [VBBlock], _ change: (inout VBKind) -> Void) {226        editLists(&blocks) { list in227            guard let i = list.firstIndex(where: { $0.id == id }) else { return false }228            change(&list[i].kind); return true229        }230    }231232    static func remove(_ id: UUID, from blocks: inout [VBBlock]) {233        editLists(&blocks) { list in234            guard let i = list.firstIndex(where: { $0.id == id }) else { return false }235            list.remove(at: i); return true236        }237    }238239    /// Moves a block up (-1) or down (+1) inside its own list.240    static func move(_ id: UUID, by delta: Int, in blocks: inout [VBBlock]) {241        editLists(&blocks) { list in242            guard let i = list.firstIndex(where: { $0.id == id }) else { return false }243            let j = i + delta244            if list.indices.contains(j) { list.swapAt(i, j) }245            return true246        }247    }248249    /// Appends to the top level (`parent` nil) or to a child list of a container block.250    static func append(_ block: VBBlock, to parent: UUID?, slot: VBSlot, in blocks: inout [VBBlock]) {251        guard let parent else { blocks.append(block); return }252        update(parent, in: &blocks) { kind in253            switch kind {254            case .event(let e, let once, var body): body.append(block); kind = .event(e, once: once, body: body)255            case .loop(let n, var body): body.append(block); kind = .loop(count: n, body: body)256            case .condition(let c, var a, var o):257                if slot == .otherwise { o = (o ?? []) + [block] } else { a.append(block) }258                kind = .condition(c, then: a, otherwise: o)259            default: break260            }261        }262    }263264    static func position(of id: UUID, in blocks: [VBBlock]) -> (index: Int, count: Int)? {265        if let i = blocks.firstIndex(where: { $0.id == id }) { return (i, blocks.count) }266        for b in blocks {267            switch b.kind {268            case let .event(_, _, body), let .loop(_, body): if let p = position(of: id, in: body) { return p }269            case let .condition(_, a, o): if let p = position(of: id, in: a) ?? position(of: id, in: o ?? []) { return p }270            default: break271            }272        }273        return nil274    }275}276277// MARK: - Schema choices offered by the block editors278279enum VBSchema {280    /// Deck, mixer and master parameters a "Set parameter" block can write (deck parameters for deck `deck`).281    static func writableTargets(deck: Int) -> [ParamAddress] {282        ScriptSchema.deckParams.filter(\.writable).map { .deck(deck, $0.key) }283            + ScriptSchema.mixerParams.filter(\.writable).map { .mixer($0.key) }284            + ScriptSchema.masterParams.filter(\.writable).map { .master($0.key) }285    }286287    static func rampableTargets(deck: Int) -> [ParamAddress] {288        ScriptSchema.deckParams.filter(\.rampable).map { .deck(deck, $0.key) }289            + ScriptSchema.mixerParams.filter(\.rampable).map { .mixer($0.key) }290    }291292    static func rampableEffectTargets(_ kind: EffectKind, rack: Int?) -> [ParamAddress] {293        ScriptSchema.fxParams(kind).filter(\.rampable).map { .fx(kind, deck: rack, $0.key) }294    }295296    /// Properties a condition can read.297    static func readableTargets(deck: Int) -> [ParamAddress] {298        ScriptSchema.deckParams.map { .deck(deck, $0.key) } + ScriptSchema.masterParams.map { .master($0.key) }299            + ScriptSchema.mixerParams.map { .mixer($0.key) }300    }301302    static func defaultArguments(for action: ActionDef) -> [VBValue] {303        action.params.filter { !$0.optional }.map { p in304            switch p.type {305            case .duration: .beats(4)306            case .number: .number(1)307            case .bool: .bool(true)308            case .string: .string("")309            case .gain: .gain(0)310            case .frequency: .frequency(1000)311            default: .number(0)312            }313        }314    }315316    /// Script address for path segments, with `mixer.channel.X.<alias>` resolved to the deck parameter.317    static func address(_ segments: [String]) -> ParamAddress? {318        guard let first = segments.first else { return nil }319        func key(_ from: Int) -> String { segments.dropFirst(from).joined(separator: ".") }320        switch first {321        case "deck":322            guard segments.count >= 3, let d = deckLetters.firstIndex(of: segments[1]) else { return nil }323            if segments[2] == "fx" {324                guard segments.count >= 5, let kind = EffectKind(rawValue: segments[3]), ScriptSchema.fxParam(kind, key(4)) != nil else { return nil }325                return .fx(kind, deck: d, key(4))326            }327            return ScriptSchema.deckParam(key(2)) != nil ? .deck(d, key(2)) : nil328        case "mixer":329            if segments.count >= 4, segments[1] == "channel" {330                guard let d = deckLetters.firstIndex(of: segments[2]), let k = ScriptSchema.mixerChannelAliases[key(3)] else { return nil }331                return .deck(d, k)332            }333            return ScriptSchema.mixerParam(key(1)) != nil ? .mixer(key(1)) : nil334        case "master":335            return ScriptSchema.masterParam(key(1)) != nil ? .master(key(1)) : nil336        case "fx":337            guard segments.count >= 3, let kind = EffectKind(rawValue: segments[1]), ScriptSchema.fxParam(kind, key(2)) != nil else { return nil }338            return .fx(kind, deck: nil, key(2))339        default:340            return nil341        }342    }343}344345// MARK: - Blocks → source346347enum VBCodegen {348    static let header = "// Built with the ORIX DJ Visual Builder."349350    static func source(for graph: VBGraph) -> String {351        let name = graph.name.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespaces)352        var lines = [header]353        lines.append("automation \(Value.string(name.isEmpty ? "Untitled" : name).description)" + (graph.quantize == .none ? "" : " quantize \(graph.quantize.rawValue)") + " {")354        emit(graph.blocks, depth: 1, into: &lines)355        lines.append("}")356        return lines.joined(separator: "\n") + "\n"357    }358359    private static func rackPrefix(_ rack: Int?) -> String { rack.map { "deck.\(deckLetters[min(max($0, 0), deckLetters.count - 1)])." } ?? "" }360361    private static func emit(_ blocks: [VBBlock], depth: Int, into lines: inout [String]) {362        let pad = String(repeating: "    ", count: depth)363        for block in blocks {364            switch block.kind {365            case let .event(event, once, body):366                lines.append("\(pad)on \(event.source)\(once ? " once" : "") {")367                emit(body, depth: depth + 1, into: &lines)368                lines.append("\(pad)}")369            case let .wait(wait):370                switch wait {371                case let .duration(v): lines.append("\(pad)wait \(v.source)")372                case .nextBeat: lines.append("\(pad)wait nextBeat")373                case .nextBar: lines.append("\(pad)wait nextBar")374                }375            case let .deckAction(deck, action, args):376                lines.append("\(pad)deck.\(deckLetters[min(max(deck, 0), deckLetters.count - 1)]).\(action)(\(args.map(\.source).joined(separator: ", ")))")377            case let .setParam(target, value):378                lines.append("\(pad)\(target.description) = \(value.source)")379            case let .effect(rack, effect, op):380                let base = "\(pad)\(rackPrefix(rack))fx.\(effect.rawValue)"381                switch op {382                case .enable: lines.append(base + ".enable()")383                case .disable: lines.append(base + ".disable()")384                case .toggle: lines.append(base + ".toggle()")385                case let .set(key, value): lines.append(base + ".\(key) = \(value.source)")386                }387            case let .over(duration, curve, ramps):388                lines.append("\(pad)over \(duration.source)\(curve.map { " curve \($0)" } ?? "") {")389                for r in ramps { lines.append("\(pad)    \(r.target.description) -> \(r.value.source)") }390                lines.append("\(pad)}")391            case let .condition(c, thenBody, otherwise):392                lines.append("\(pad)if \(c.left.description) \(c.op) \(c.right.source) {")393                emit(thenBody, depth: depth + 1, into: &lines)394                if let otherwise {395                    lines.append("\(pad)} else {")396                    emit(otherwise, depth: depth + 1, into: &lines)397                }398                lines.append("\(pad)}")399            case let .loop(count, body):400                lines.append("\(pad)repeat \(max(0, count)) {")401                emit(body, depth: depth + 1, into: &lines)402                lines.append("\(pad)}")403            case .stop:404                lines.append("\(pad)stop")405            }406        }407    }408}409410// MARK: - Source → blocks411412/// Why a script cannot be shown as blocks.413struct VBImportFailure: Error, Equatable, Sendable {414    var construct: String415    var line: Int416417    var message: String { line > 0 ? "Line \(line): \(construct) is not supported by the Visual Builder." : "\(construct) is not supported by the Visual Builder." }418}419420enum VBImporter {421    /// Converts a script to blocks, or names the first construct the builder cannot represent. Never imports partially.422    static func graph(from source: String) -> Result<VBGraph, VBImportFailure> {423        let (file, diagnostics) = Parser.parse(source)424        if let e = diagnostics.first(where: { $0.severity == .error }) {425            return .failure(VBImportFailure(construct: "A script with syntax errors (\(e.message))", line: e.location.line))426        }427        do {428            if let c = file.constants.first { throw VBImportFailure(construct: "A top-level constant", line: c.location.line) }429            if let f = file.functions.first { throw VBImportFailure(construct: "A function ('\(f.name)')", line: f.location.line) }430            guard let automation = file.automations.first else { throw VBImportFailure(construct: "A script without an automation", line: 0) }431            if file.automations.count > 1 { throw VBImportFailure(construct: "A second automation in the same script", line: file.automations[1].location.line) }432            return .success(VBGraph(name: automation.name, quantize: automation.quantize, blocks: try blocks(automation.body, topLevel: true)))433        } catch let failure as VBImportFailure {434            return .failure(failure)435        } catch {436            return .failure(VBImportFailure(construct: "This script", line: 0))437        }438    }439440    private static func literal(_ e: Expr, _ what: String) throws -> VBValue {441        switch e {442        case let .literal(v, loc):443            guard let b = VBValue(v) else { throw VBImportFailure(construct: what, line: loc.line) }444            return b445        case let .unary(op, .literal(v, _), loc) where op == "-" || op == "+":446            guard let b = VBValue(v) else { throw VBImportFailure(construct: what, line: loc.line) }447            if op == "+" { return b }448            switch b {449            case .number, .gain, .frequency: return b.with(magnitude: -b.magnitude)450            case let .beats(x): return .beats(-x)451            case let .seconds(x): return .seconds(-x)452            default: throw VBImportFailure(construct: what, line: loc.line)453            }454        default:455            throw VBImportFailure(construct: what, line: e.location.line)456        }457    }458459    private static func condition(_ e: Expr) throws -> VBCondition {460        let what = "A condition other than '<property> <comparison> <value>'"461        func left(_ p: PathExpr) throws -> ParamAddress {462            guard let a = VBSchema.address(p.segments), a.area != .fx else { throw VBImportFailure(construct: "A condition on '\(p.text)'", line: p.location.line) }463            return a464        }465        switch e {466        case let .binary(op, .path(p), rhs, _) where VBCondition.operators.contains(op):467            return VBCondition(left: try left(p), op: op, right: try literal(rhs, what))468        case let .path(p):469            return VBCondition(left: try left(p), op: "==", right: .bool(true))470        case let .unary("!", .path(p), _):471            return VBCondition(left: try left(p), op: "==", right: .bool(false))472        case let .binary(op, _, _, loc) where op == "&&" || op == "||":473            throw VBImportFailure(construct: "A compound condition ('\(op == "&&" ? "and" : "or")')", line: loc.line)474        default:475            throw VBImportFailure(construct: what, line: e.location.line)476        }477    }478479    private static func blocks(_ stmts: [Stmt], topLevel: Bool) throws -> [VBBlock] {480        try stmts.map { VBBlock(try kind($0, topLevel: topLevel)) }481    }482483    private static func kind(_ s: Stmt, topLevel: Bool) throws -> VBKind {484        let line = s.location.line485        func unsupported(_ what: String) -> VBImportFailure { VBImportFailure(construct: what, line: line) }486        switch s.kind {487        case let .declare(name, _, _, mutable):488            throw unsupported("A variable declaration ('\(mutable ? "var" : "let") \(name)')")489        case let .assign(path, value):490            guard let target = VBSchema.address(path.segments) else { throw unsupported("An assignment to '\(path.text)'") }491            let v = try literal(value, "A computed value assigned to '\(path.text)'")492            if target.area == .fx, let effect = target.effect { return .effect(rack: target.deck, effect: effect, op: .set(key: target.key, value: v)) }493            return .setParam(target, v)494        case let .ramp(path, _):495            throw unsupported("A ramp of '\(path.text)' outside an 'over' block")496        case let .call(path, args):497            let segs = path.segments498            if segs.count == 3, segs[0] == "deck", let d = deckLetters.firstIndex(of: segs[1]), ScriptSchema.deckAction(segs[2]) != nil {499                return .deckAction(deck: d, action: segs[2], args: try args.map { try literal($0, "A computed argument of '\(path.text)'") })500            }501            var rack: Int?502            var rest = segs[...]503            if rest.count == 5, rest.first == "deck", let d = deckLetters.firstIndex(of: segs[1]) { rack = d; rest = rest.dropFirst(2) }504            if rest.count == 3, rest.first == "fx", let effect = EffectKind(rawValue: rest[rest.startIndex + 1]), args.isEmpty {505                switch rest[rest.startIndex + 2] {506                case "enable": return .effect(rack: rack, effect: effect, op: .enable)507                case "disable": return .effect(rack: rack, effect: effect, op: .disable)508                case "toggle": return .effect(rack: rack, effect: effect, op: .toggle)509                default: break510                }511            }512            throw unsupported("A call to '\(path.text)'")513        case let .wait(spec):514            switch spec {515            case .nextBeat: return .wait(.nextBeat)516            case .nextBar: return .wait(.nextBar)517            case .until: throw unsupported("'wait until'")518            case let .duration(e):519                let v = try literal(e, "A computed wait")520                switch v { case .beats, .seconds: return .wait(.duration(v)); default: throw unsupported("A wait that is not a duration") }521            }522        case .at:523            throw unsupported("An 'at' block")524        case let .over(duration, curve, body):525            let d = try literal(duration, "A computed 'over' duration")526            switch d { case .beats, .seconds: break; default: throw unsupported("An 'over' length that is not a duration") }527            var ramps: [VBRamp] = []528            for inner in body {529                guard case let .ramp(path, value) = inner.kind else {530                    throw VBImportFailure(construct: "A statement other than a ramp inside an 'over' block", line: inner.location.line)531                }532                guard let target = VBSchema.address(path.segments) else { throw VBImportFailure(construct: "A ramp of '\(path.text)'", line: inner.location.line) }533                ramps.append(VBRamp(target: target, value: try literal(value, "A computed ramp target for '\(path.text)'")))534            }535            return .over(duration: d, curve: curve, ramps: ramps)536        case .every:537            throw unsupported("An 'every' loop")538        case let .repeatLoop(count, body):539            guard case let .literal(.number(n), _) = count, n >= 0, n == n.rounded(), n <= Double(CompileLimits.maxLoopIterations) else {540                throw unsupported("A 'repeat' with a computed count")541            }542            return .loop(count: Int(n), body: try blocks(body, topLevel: false))543        case .forRange, .forIn:544            throw unsupported("A 'for' loop")545        case .whileLoop:546            throw unsupported("A 'while' loop")547        case let .ifElse(cond, thenBody, elseBody):548            return .condition(try condition(cond), then: try blocks(thenBody, topLevel: false), otherwise: try elseBody.map { try blocks($0, topLevel: false) })549        case let .on(spec, once, body):550            guard topLevel else { throw unsupported("An event handler nested inside another block") }551            let segs = spec.path.segments552            let event: VBEvent553            if segs == ["beat"], spec.argument == nil { event = .beat }554            else if segs == ["bar"], spec.argument == nil { event = .bar }555            else if segs == ["trigger"], case let .literal(.number(n), _)? = spec.argument, n == n.rounded(), n >= 1, n <= Double(ScriptSchema.triggerCount) { event = .trigger(Int(n)) }556            else if segs.count == 3, segs[0] == "deck", let d = deckLetters.firstIndex(of: segs[1]), ScriptSchema.deckEvents.contains(where: { $0.name == segs[2] }), spec.argument == nil {557                event = .deck(d, segs[2])558            } else { throw unsupported("The event '\(spec.path.text)'") }559            return .event(event, once: once, body: try blocks(body, topLevel: false))560        case .returnValue:561            throw unsupported("'return'")562        case .stop:563            return .stop564        case .breakLoop:565            throw unsupported("'break'")566        case .continueLoop:567            throw unsupported("'continue'")568        }569    }570}571572// MARK: - Round-trip check573574/// Outcome of one round-trip case: blocks → source → blocks → source must be stable and the source must compile.575struct VBRoundTripResult: Sendable, Equatable {576    var name: String577    var passed: Bool578    var detail: String579}580581enum VBRoundTrip {582    /// A graph that uses every block kind the builder has.583    static var everyBlockGraph: VBGraph {584        VBGraph(name: "Every \"Block\"", quantize: .beat, blocks: [585            VBBlock(.deckAction(deck: 1, action: "sync", args: [.bool(true)])),586            VBBlock(.setParam(.deck(1, "volume"), .gain(-12))),587            VBBlock(.setParam(.mixer("curve"), .string("smooth"))),588            VBBlock(.setParam(.deck(0, "keylock"), .bool(true))),589            VBBlock(.effect(rack: nil, effect: .echo, op: .enable)),590            VBBlock(.effect(rack: 0, effect: .reverb, op: .set(key: "mix", value: .number(0.35)))),591            VBBlock(.deckAction(deck: 1, action: "play", args: [])),592            VBBlock(.over(duration: .beats(32), curve: "smooth", ramps: [593                VBRamp(target: .deck(0, "filter.highpass"), value: .frequency(12000)),594                VBRamp(target: .deck(0, "volume"), value: .gain(-60)),595                VBRamp(target: .mixer("crossfader"), value: .number(1)),596            ])),597            VBBlock(.wait(.duration(.beats(2)))),598            VBBlock(.wait(.duration(.seconds(0.25)))),599            VBBlock(.wait(.nextBar)),600            VBBlock(.condition(VBCondition(left: .deck(0, "bpm"), op: ">", right: .number(124.5)), then: [601                VBBlock(.loop(count: 4, body: [602                    VBBlock(.deckAction(deck: 0, action: "jump", args: [.beats(-1)])),603                    VBBlock(.wait(.nextBeat)),604                ])),605            ], otherwise: [606                VBBlock(.condition(VBCondition(left: .master("deck"), op: "==", right: .string("A")), then: [VBBlock(.effect(rack: nil, effect: .echo, op: .toggle))], otherwise: nil)),607            ])),608            VBBlock(.event(.deck(0, "trackEnd"), once: true, body: [VBBlock(.deckAction(deck: 1, action: "play", args: [])), VBBlock(.stop)])),609            VBBlock(.event(.trigger(3), once: false, body: [VBBlock(.effect(rack: nil, effect: .echo, op: .disable))])),610            VBBlock(.event(.bar, once: false, body: [])),611        ])612    }613614    static func check(name: String, graph: VBGraph) -> VBRoundTripResult {615        let first = VBCodegen.source(for: graph)616        let compiled = ScriptCompiler.compile(first)617        guard compiled.succeeded else {618            return VBRoundTripResult(name: name, passed: false, detail: "generated source does not compile: " + (compiled.errors.first?.description ?? "unknown error"))619        }620        switch VBImporter.graph(from: first) {621        case let .failure(f): return VBRoundTripResult(name: name, passed: false, detail: "generated source does not import: " + f.message)622        case let .success(back):623            let second = VBCodegen.source(for: back)624            guard second == first else { return VBRoundTripResult(name: name, passed: false, detail: "second generation differs from the first") }625            guard case let .success(again) = VBImporter.graph(from: second), VBCodegen.source(for: again) == second else {626                return VBRoundTripResult(name: name, passed: false, detail: "third generation differs")627            }628            return VBRoundTripResult(name: name, passed: true, detail: "\(graph.blockCount) blocks, stable, compiles")629        }630    }631632    /// True when both scripts produce the same simulated trace (beats, kinds and texts) in the default rig.633    static func sameBehaviour(_ a: String, _ b: String) -> Bool {634        func trace(_ source: String) -> [String]? {635            guard let program = ScriptCompiler.compile(source).program, let result = Simulator.run(program) else { return nil }636            return result.trace.map { "\(String(format: "%.4f", $0.beat)) \($0.kind.rawValue) \($0.text)" } + ["\(result.state)", "\(result.beats)"]637        }638        guard let x = trace(a), let y = trace(b) else { return false }639        return x == y640    }641642    /// The builder's own graph plus every bundled preset that the importer accepts. Presets that use constructs the643    /// builder does not have are reported as skipped with the reason.644    static func runAll() -> [VBRoundTripResult] {645        var out = [check(name: "every block kind", graph: everyBlockGraph), check(name: "empty graph", graph: VBGraph())]646        for preset in PresetLibrary.all {647            switch VBImporter.graph(from: preset.source) {648            case let .success(g):649                var r = check(name: "preset \(preset.name)", graph: g)650                // The imported graph must also behave like the preset: same simulated trace, event for event.651                if r.passed, !sameBehaviour(preset.source, VBCodegen.source(for: g)) { r.passed = false; r.detail = "the generated script simulates differently from the preset" }652                else if r.passed { r.detail += ", simulates like the preset" }653                out.append(r)654            case let .failure(f): out.append(VBRoundTripResult(name: "preset \(preset.name)", passed: true, detail: "not importable (expected): " + f.message))655            }656        }657        return out658    }659}660
Files main
Menu

Theme