summaryrefslogtreecommitdiff
path: root/examples/spheres/src/chords.zig
diff options
context:
space:
mode:
Diffstat (limited to 'examples/spheres/src/chords.zig')
-rw-r--r--examples/spheres/src/chords.zig311
1 files changed, 311 insertions, 0 deletions
diff --git a/examples/spheres/src/chords.zig b/examples/spheres/src/chords.zig
new file mode 100644
index 0000000..54a4413
--- /dev/null
+++ b/examples/spheres/src/chords.zig
@@ -0,0 +1,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)));
+}