summaryrefslogtreecommitdiff
path: root/examples/spheres/src/chords.zig
blob: 54a4413741266fd7b391aab22f96c7c70ebe3e2e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//! spheres as an instrument: the CPU's side of the look-ahead. The GPU
//! (lookahead.comp) integrates `alternatives` futures of system 0 from the
//! preset's start, a few samples a frame, keeping a snapshot every
//! `sample_dt` and the chord sung there: the pitch classes of the three
//! voices (the silent modulator's counts: it sets the carrier's sidebands).
//! The chords come back here, a frame or two later; the ones that fit the
//! grid of buttons (a sanfona's bass side, see `Grid`) light up as found,
//! and choosing one finds the nearest time it plays, in whichever future
//! plays it soonest.
const std = @import("std");
const layouts = @import("layouts");

/// The mapping from motion to voices (voices.glsl), which the shaders get
/// as uniforms; and leapfrog's base step, as physics.glsl's callers use it.
pub const base: f32 = 220;
pub const speed_ref: f32 = 0.6;
pub const depth_scale: f32 = 1.2;
pub const couple_scale: f32 = 0.9;
pub const base_step = 0.004;

/// Futures integrated side by side: 0 is system 0's own, the rest nudged.
pub const alternatives = layouts.alternatives;
pub const horizon = layouts.horizon;
pub const sample_dt = 0.05;
/// Samples the look-ahead advances each frame: 0.4 s of simulated time,
/// against the live system's 0.7 s a second, so it pulls well ahead.
pub const per_frame = 8;
/// What a pick costs besides its travel time, in seconds of travel: being
/// in another future than the system's own; not having the root in the
/// bass; and per unit of voicing badness (voices.glsl's 0 to 255: a
/// sprawling, high or hard-modulated voicing costs up to 3 s more).
const elsewhere = 0.5;
const inverted = 0.6;
const per_bad = 3.0 / 255.0;

/// A snapshot's chord and voicing, as voices.glsl's `voicing` packs them.
pub const Sung = packed struct(u32) {
    chord: u12,
    playable: bool,
    _: u3,
    lowest: u4,
    _2: u4,
    bad: u8,
};

/// The pitch classes three voices sing, as bits (C is bit 0): as
/// voices.glsl's chordOf, for what is sounding.
pub fn chordOf(voices: [3]layouts.Voice) u16 {
    var mask: u16 = 0;
    for (voices) |v| {
        if (v.carrier <= 0) continue;
        const midi: i32 = @intFromFloat(@round(69 + 12 * std.math.log2(v.carrier / 440)));
        mask |= @as(u16, 1) << @intCast(@mod(midi, 12));
    }
    return mask;
}

const names = [12][]const u8{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };

fn bits(intervals: []const u4) u16 {
    var m: u16 = 0;
    for (intervals) |i| m |= @as(u16, 1) << i;
    return m;
}

/// Chord shapes, most wanted first, as intervals over the root.
const shapes = [_]struct { u16, []const u8 }{
    .{ bits(&.{ 0, 4, 7 }), "" },
    .{ bits(&.{ 0, 3, 7 }), "m" },
    .{ bits(&.{ 0, 2, 7 }), "sus2" },
    .{ bits(&.{ 0, 5, 7 }), "sus4" },
    .{ bits(&.{ 0, 4, 10 }), "7" },
    .{ bits(&.{ 0, 3, 10 }), "m7" },
    .{ bits(&.{ 0, 4, 9 }), "6" },
    .{ bits(&.{ 0, 3, 9 }), "m6" },
    .{ bits(&.{ 0, 3, 6 }), "dim" },
    .{ bits(&.{ 0, 4, 8 }), "aug" },
    .{ bits(&.{ 0, 2, 4 }), "add9" },
    .{ bits(&.{ 0, 5, 10 }), "7sus4" },
    .{ bits(&.{ 0, 7, 10 }), "7no3" },
    .{ bits(&.{ 0, 7 }), "5" },
};

/// A name for a set of pitch classes: a chord where one fits ("Am",
/// "Csus2"), else the notes ("A+C+D").
pub fn name(buf: []u8, mask: u16) []const u8 {
    if (mask == 0) return "";
    if (@popCount(mask) == 1) return names[@ctz(mask)];
    for (shapes) |shape| for (0..12) |root| {
        if (mask & (@as(u16, 1) << @intCast(root)) == 0) continue;
        const r: u4 = @intCast(root);
        const rotated = ((mask >> r) | (mask << @intCast(12 - @as(u5, r)))) & 0xfff;
        if (rotated == shape[0]) return std.fmt.bufPrint(buf, "{s}{s}", .{ names[root], shape[1] }) catch "?";
    };
    var w: std.Io.Writer = .fixed(buf);
    var first = true;
    for (0..12) |pc| if (mask & (@as(u16, 1) << @intCast(pc)) != 0) {
        w.print("{s}{s}", .{ if (first) "" else "+", names[pc] }) catch break;
        first = false;
    };
    return w.buffered();
}

/// A snapshot: sample `sample` of future `alternative`, at `index` in the
/// GPU's snapshot buffer.
pub const Pick = struct {
    sample: u32,
    alternative: u32,

    pub fn index(p: Pick) u32 {
        return p.sample * alternatives + p.alternative;
    }
    pub fn time(p: Pick) f64 {
        return @as(f64, @floatFromInt(p.sample)) * sample_dt;
    }
};

/// The buttons, laid out as a sanfona's (Stradella) bass side: columns
/// round the circle of fifths, so neighbours are related chords, and rows
/// by quality, each half a button over from the one above, so a progression
/// is the same shape of hand in any key.
pub const Grid = struct {
    pub const Quality = enum { major, minor, seventh, sus, power };
    pub const rows = @typeInfo(Quality).@"enum".field_names.len;
    pub const columns = 12;
    /// Roots by column, by fifths from G flat to B, as pitch classes.
    pub const roots = [columns]u4{ 6, 1, 8, 3, 10, 5, 0, 7, 2, 9, 4, 11 };
    pub const root_names = [columns][]const u8{ "Gb", "Db", "Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B" };

    /// Three voices make triads at most: the seventh without its fifth.
    pub fn shape(q: Quality) u16 {
        return switch (q) {
            .major => bits(&.{ 0, 4, 7 }),
            .minor => bits(&.{ 0, 3, 7 }),
            .seventh => bits(&.{ 0, 4, 10 }),
            .sus => bits(&.{ 0, 5, 7 }),
            .power => bits(&.{ 0, 7 }),
        };
    }

    pub fn suffix(q: Quality) []const u8 {
        return switch (q) {
            .major => "",
            .minor => "m",
            .seventh => "7",
            .sus => "sus",
            .power => "5",
        };
    }

    /// The chord of the button at `row`, `column`.
    pub fn chord(row: usize, column: usize) u16 {
        const s = shape(@enumFromInt(row));
        const r: u4 = roots[column];
        return ((s << r) | (s >> @intCast(12 - @as(u5, r)))) & 0xfff;
    }

    /// The button playing `mask`, if one does.
    pub fn find(mask: u16) ?struct { row: usize, column: usize } {
        for (0..rows) |row| for (0..columns) |column| {
            if (chord(row, column) == mask) return .{ .row = row, .column = column };
        };
        return null;
    }
};

pub const Ahead = struct {
    /// The chords back from the GPU, with their voicings, sample-major as
    /// it keeps them.
    sung: [horizon][alternatives]Sung = undefined,
    /// Samples asked of the GPU, and how many have come back.
    asked: u32 = 0,
    known: u32 = 0,
    /// Every chord found in a playable voicing, by mask, and how many.
    found: [1 << 12]bool = @splat(false),
    distinct: u32 = 0,

    pub fn reset(a: *Ahead) void {
        a.asked = 0;
        a.known = 0;
        a.forget();
    }

    /// The chords again from nothing (another scale).
    pub fn forget(a: *Ahead) void {
        a.known = 0;
        a.found = @splat(false);
        a.distinct = 0;
    }

    /// Chords back from the GPU: samples from `first`, all alternatives.
    pub fn arrived(a: *Ahead, first: u32, words: []const u32) void {
        const samples: u32 = @intCast(words.len / alternatives);
        for (0..samples) |s| {
            const t = first + @as(u32, @intCast(s));
            if (t >= horizon) break;
            for (0..alternatives) |alt| {
                const sung: Sung = @bitCast(words[s * alternatives + alt]);
                a.sung[t][alt] = sung;
                if (sung.playable) a.pad(sung.chord);
            }
            a.known = @max(a.known, t + 1);
        }
    }

    fn pad(a: *Ahead, chord: u16) void {
        if (chord == 0 or a.found[chord]) return;
        a.found[chord] = true;
        a.distinct += 1;
    }

    /// The best snapshot where `chord` plays in a playable voicing: near
    /// `time`, in the system's own future, with `root` in the bass, and
    /// sounding well, weighed against each other (see the costs above).
    pub fn nearest(a: *const Ahead, chord: u16, root: u4, time: f64) ?Pick {
        var best: ?Pick = null;
        var cost: f64 = std.math.inf(f64);
        for (a.sung[0..a.known], 0..) |row, t| for (row, 0..) |sung, alt| {
            if (sung.chord != chord or !sung.playable) continue;
            const pick: Pick = .{ .sample = @intCast(t), .alternative = @intCast(alt) };
            const c = @abs(pick.time() - time) +
                @as(f64, if (alt == 0) 0 else elsewhere) +
                @as(f64, if (sung.lowest == root) 0 else inverted) +
                per_bad * @as(f64, @floatFromInt(sung.bad));
            if (c < cost) {
                cost = c;
                best = pick;
            }
        };
        return best;
    }
};

test "chords by name" {
    var buf: [32]u8 = undefined;
    const set = struct {
        fn of(pcs: []const u5) u16 {
            var m: u16 = 0;
            for (pcs) |p| m |= @as(u16, 1) << @intCast(p);
            return m;
        }
    }.of;
    try std.testing.expectEqualStrings("Am", name(&buf, set(&.{ 9, 0, 4 })));
    try std.testing.expectEqualStrings("C", name(&buf, set(&.{ 0, 4, 7 })));
    try std.testing.expectEqualStrings("Csus2", name(&buf, set(&.{ 0, 2, 7 })));
    try std.testing.expectEqualStrings("A5", name(&buf, set(&.{ 9, 4 })));
    try std.testing.expectEqualStrings("E", name(&buf, set(&.{4})));
    try std.testing.expectEqualStrings("C#+D", name(&buf, set(&.{ 1, 2 })));
}

fn word(chord: u12, playable: bool, lowest: u4, bad: u8) u32 {
    return @bitCast(Sung{ .chord = chord, .playable = playable, ._ = 0, .lowest = lowest, ._2 = 0, .bad = bad });
}

test "a pick prefers the system's own future, unless another plays the chord much sooner" {
    var a: Ahead = .{};
    var words: [3 * alternatives]u32 = @splat(word(1, true, 0, 0));
    // Chord 2 at sample 2 of future 0, and at sample 0 of future 5.
    words[2 * alternatives + 0] = word(2, true, 1, 0);
    words[0 * alternatives + 5] = word(2, true, 1, 0);
    a.arrived(0, &words);
    try std.testing.expectEqual(@as(u32, 3), a.known);
    try std.testing.expect(a.found[1] and a.found[2]);
    try std.testing.expectEqual(@as(u32, 2), a.distinct);
    // From time 0.1: future 0 at 0.1 away beats future 5 at 0.1 + 0.5.
    try std.testing.expectEqual(Pick{ .sample = 2, .alternative = 0 }, a.nearest(2, 1, 0.1).?);
    // Ask for a chord no future plays: nothing.
    try std.testing.expectEqual(@as(?Pick, null), a.nearest(4, 2, 0));
}

test "voicings: unplayable ones do not count, good ones win over near ones" {
    var a: Ahead = .{};
    var words: [3 * alternatives]u32 = @splat(word(1, true, 0, 0));
    // Chord 2 now, but shrill and sprawling (unplayable); later, playable
    // but inverted and harsh; later still, in root position and clean.
    words[0] = word(2, false, 1, 0);
    words[1 * alternatives] = word(2, true, 3, 200);
    words[2 * alternatives] = word(2, true, 1, 0);
    a.arrived(0, &words);
    try std.testing.expectEqual(Pick{ .sample = 2, .alternative = 0 }, a.nearest(2, 1, 0).?);
    // A chord heard only unplayably is not found.
    var b: Ahead = .{};
    var only: [alternatives]u32 = @splat(word(4, false, 2, 0));
    b.arrived(0, &only);
    try std.testing.expect(!b.found[4]);
}

test "the grid: fifths across, qualities down" {
    var buf: [16]u8 = undefined;
    // Column 6 is C, column 9 is A.
    try std.testing.expectEqualStrings("C", name(&buf, Grid.chord(0, 6)));
    try std.testing.expectEqualStrings("Am", name(&buf, Grid.chord(1, 9)));
    try std.testing.expectEqualStrings("G5", name(&buf, Grid.chord(4, 7)));
    const at = Grid.find(Grid.chord(2, 3)).?;
    try std.testing.expectEqual(@as(usize, 2), at.row);
    try std.testing.expectEqual(@as(usize, 3), at.column);
    // Every button its own chord.
    for (0..Grid.rows) |r| for (0..Grid.columns) |c| {
        try std.testing.expectEqual(r, Grid.find(Grid.chord(r, c)).?.row);
    };
}

test "voices to chords" {
    const v = [3]layouts.Voice{
        .{ .carrier = 220, .ratio = 1, .depth = 0, .amp = 1 },
        .{ .carrier = 261.63, .ratio = 1, .depth = 0, .amp = 1 },
        .{ .carrier = 329.63, .ratio = 1, .depth = 0, .amp = 1 },
    };
    var buf: [16]u8 = undefined;
    try std.testing.expectEqualStrings("Am", name(&buf, chordOf(v)));
}