summaryrefslogtreecommitdiff
path: root/src/sketch
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 00:09:10 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit896855648c3371ede3c672bbfa75175fa3a1e42e (patch)
tree62dbf603661c970efc0b2547e23fe9c0c2b37e32 /src/sketch
parentcddefdd6e5c7fb632088d504d2ed96368fa44e0f (diff)
downloadsketchbook-896855648c3371ede3c672bbfa75175fa3a1e42e.tar.gz
sketchbook-896855648c3371ede3c672bbfa75175fa3a1e42e.zip
sk.sfxr: the sfxr sound-effect generator, from 02-dont-rat-me-out
02-dont-rat-me-out's synth.zig, a pure and deterministic port of DrPetter's sfxr, moves into the library as src/sketch/sfxr.zig, exposed as sk.sfxr: render(params, rate, out) gives a coin, blip, laser or explosion as samples for host.newSound. Its knobs count in samples at 44.1 kHz, so the one change is the rate: every length (envelope, arpeggio, repeat, phaser offset, period) grows by rate/44.1 kHz and every per-sample step (slides, duty sweep, vibrato, filter coefficients and their ramps) shrinks by it, to first order for the slides and filters; at 44.1 kHz each factor is 1 and the samples are the original's to the bit. Two spellings change without changing a sample: the phaser buffer is @splat (Zig 0.17 has no ** on arrays) and the phaser delay is clamped before it is converted, so a long sweep cannot overflow it. Test: four parameter sets that between them turn every knob render the lengths and Wyhash of the samples the original rendered at 44.1 kHz (run once, outside the repo), and at 48 kHz a sound as long within 1 %. test/voices.zig makes its blip with sfxr in draw, at in.sample_rate, and is the README's example: a blip in six lines. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/sketch')
-rw-r--r--src/sketch/root.zig3
-rw-r--r--src/sketch/sfxr.zig267
2 files changed, 270 insertions, 0 deletions
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index c70b326..1270b5d 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -41,6 +41,8 @@ pub const List = @import("list.zig").List;
/// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload).
pub const Derived = @import("derived.zig").Derived;
pub const web = @import("web.zig");
+/// sfxr's sound effects, rendered to samples for `host.newSound`.
+pub const sfxr = @import("sfxr.zig");
const request = @import("request.zig");
pub const Request = request.Request;
pub const Handled = request.Handled;
@@ -456,6 +458,7 @@ test {
_ = @import("clock.zig");
_ = @import("list.zig");
_ = @import("derived.zig");
+ _ = sfxr;
}
test "setup receives session resources without a Frame and reports errors" {
diff --git a/src/sketch/sfxr.zig b/src/sketch/sfxr.zig
new file mode 100644
index 0000000..01657b5
--- /dev/null
+++ b/src/sketch/sfxr.zig
@@ -0,0 +1,267 @@
+//! sfxr, DrPetter's sound-effect generator (blips, coins, lasers,
+//! explosions): one waveform through an envelope, pitch slides, vibrato,
+//! arpeggio, duty sweep, a phaser and two filters, 8× oversampled. Pure and
+//! deterministic: the same `Params` and rate give the same samples, so a
+//! sketch renders its sounds whenever it likes and plays them as voices:
+//!
+//! const n = sk.sfxr.render(.{ .freq = 0.5, .decay = 0.2 }, f.in.sample_rate, &buf);
+//! ss.blip = f.host.newSound(buf[0..n]);
+//!
+//! Ported from 02-dont-rat-me-out's synth.zig. sfxr's knobs count in
+//! samples at 44.1 kHz; at another rate every length, step and filter
+//! coefficient is scaled to keep the same durations, pitches and cutoffs
+//! (to first order for the slides and filters), and at 44.1 kHz the
+//! samples are the original's to the bit.
+const std = @import("std");
+
+/// The rate sfxr's knobs were tuned at.
+pub const reference_rate = 44_100;
+
+pub const Wave = enum(u8) { square, sawtooth, sine, noise };
+
+/// All sfxr knobs. Most are 0..1, a few -1..1.
+pub const Params = struct {
+ wave: Wave = .square,
+ // envelope
+ attack: f32 = 0.0,
+ sustain: f32 = 0.3,
+ punch: f32 = 0.0,
+ decay: f32 = 0.4,
+ // frequency
+ freq: f32 = 0.3,
+ freq_limit: f32 = 0.0,
+ freq_ramp: f32 = 0.0,
+ freq_dramp: f32 = 0.0,
+ // vibrato
+ vibrato_depth: f32 = 0.0,
+ vibrato_speed: f32 = 0.0,
+ // arpeggio
+ arp_mod: f32 = 0.0,
+ arp_speed: f32 = 0.0,
+ // square duty
+ duty: f32 = 0.0,
+ duty_ramp: f32 = 0.0,
+ // phaser
+ phaser_offset: f32 = 0.0,
+ phaser_ramp: f32 = 0.0,
+ // filters
+ lpf_freq: f32 = 1.0,
+ lpf_ramp: f32 = 0.0,
+ lpf_resonance: f32 = 0.0,
+ hpf_freq: f32 = 0.0,
+ hpf_ramp: f32 = 0.0,
+ // repeat
+ repeat_speed: f32 = 0.0,
+ // output
+ volume: f32 = 0.5,
+};
+
+inline fn sq(x: f32) f32 {
+ return x * x;
+}
+inline fn cube(x: f32) f32 {
+ return x * x * x;
+}
+inline fn xs(s: *u32) u32 {
+ s.* ^= s.* << 13;
+ s.* ^= s.* >> 17;
+ s.* ^= s.* << 5;
+ return s.*;
+}
+fn frnd(s: *u32, range: f32) f32 {
+ return @as(f32, @floatFromInt(xs(s))) / 4294967295.0 * range;
+}
+
+/// Synthesizes `p` at `rate` samples a second into `out` (mono, -1..1).
+/// Returns the number of samples written: the envelope's length, or less
+/// when `out` is shorter or the pitch falls to `freq_limit`.
+pub fn render(p: Params, rate: u32, out: []f32) usize {
+ // Samples at `rate` per sample at 44.1 kHz: lengths grow by it, steps
+ // per sample shrink by it.
+ const k: f64 = @as(f64, @floatFromInt(rate)) / reference_rate;
+ const kf: f32 = @floatCast(k);
+ var rng: u32 = 0x52ad4326;
+
+ var fperiod: f64 = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k;
+ var period: i32 = @intFromFloat(fperiod);
+ const fmaxperiod: f64 = 100.0 / (@as(f64, p.freq_limit) * p.freq_limit + 0.001) * k;
+ var fslide: f64 = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k;
+ const fdslide: f64 = -@as(f64, cube(p.freq_dramp)) * 0.000001 / (k * k);
+
+ var square_duty: f32 = 0.5 - p.duty * 0.5;
+ const square_slide: f32 = -p.duty_ramp * 0.00005 / kf;
+
+ const arp_mod: f64 = if (p.arp_mod >= 0) 1.0 - @as(f64, sq(p.arp_mod)) * 0.9 else 1.0 + @as(f64, sq(p.arp_mod)) * 10.0;
+ var arp_time: i32 = 0;
+ var arp_limit: i32 = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf);
+ if (p.arp_speed == 1.0) arp_limit = 0;
+
+ var env_vol: f32 = 0;
+ var env_stage: usize = 0;
+ var env_time: i32 = 0;
+ const env_length = [3]i32{
+ @intFromFloat(p.attack * p.attack * 100000 * kf),
+ @intFromFloat(p.sustain * p.sustain * 100000 * kf),
+ @intFromFloat(p.decay * p.decay * 100000 * kf),
+ };
+
+ var fphase: f32 = sq(p.phaser_offset) * 1020 * kf;
+ if (p.phaser_offset < 0) fphase = -fphase;
+ var fdphase: f32 = sq(p.phaser_ramp) * 1.0;
+ if (p.phaser_ramp < 0) fdphase = -fdphase;
+ var iphase: i32 = @intFromFloat(@min(@abs(fphase), 1023));
+ var ipp: i32 = 0;
+ var phaser_buffer: [1024]f32 = @splat(0);
+
+ var noise_buffer: [32]f32 = undefined;
+ for (&noise_buffer) |*nb| nb.* = frnd(&rng, 2) - 1;
+
+ var fltp: f32 = 0;
+ var fltdp: f32 = 0;
+ var fltw: f32 = cube(p.lpf_freq) * 0.1 / kf;
+ const fltw_d: f32 = 1.0 + p.lpf_ramp * 0.0001 / kf;
+ var fltdmp: f32 = 5.0 / (1.0 + sq(p.lpf_resonance) * 20) * (0.01 + fltw);
+ if (fltdmp > 0.8) fltdmp = 0.8;
+ var fltphp: f32 = 0;
+ var flthp: f32 = sq(p.hpf_freq) * 0.1 / kf;
+ const flthp_d: f32 = 1.0 + p.hpf_ramp * 0.0003 / kf;
+
+ var vib_phase: f32 = 0;
+ const vib_speed: f32 = sq(p.vibrato_speed) * 0.01 / kf;
+ const vib_amp: f32 = p.vibrato_depth * 0.5;
+
+ var rep_time: i32 = 0;
+ var rep_limit: i32 = @intFromFloat((sq(1 - p.repeat_speed) * 20000 + 32) * kf);
+ if (p.repeat_speed == 0) rep_limit = 0;
+
+ var phase: i32 = 0;
+ var n: usize = 0;
+ var finished = false;
+ while (!finished and n < out.len) : (n += 1) {
+ rep_time += 1;
+ if (rep_limit != 0 and rep_time >= rep_limit) {
+ rep_time = 0;
+ fperiod = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k;
+ period = @intFromFloat(fperiod);
+ fslide = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k;
+ arp_time = 0;
+ arp_limit = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf);
+ if (p.arp_speed == 1.0) arp_limit = 0;
+ }
+
+ arp_time += 1;
+ if (arp_limit != 0 and arp_time >= arp_limit) {
+ arp_limit = 0;
+ fperiod *= arp_mod;
+ }
+
+ fslide += fdslide;
+ fperiod *= fslide;
+ if (fperiod > fmaxperiod) {
+ fperiod = fmaxperiod;
+ if (p.freq_limit > 0) finished = true;
+ }
+
+ var rfperiod: f32 = @floatCast(fperiod);
+ if (vib_amp > 0) {
+ vib_phase += vib_speed;
+ rfperiod = @floatCast(fperiod * (1.0 + @as(f64, @sin(vib_phase) * vib_amp)));
+ }
+ period = @intFromFloat(rfperiod);
+ if (period < 8) period = 8;
+
+ square_duty += square_slide;
+ square_duty = std.math.clamp(square_duty, 0, 0.5);
+
+ env_time += 1;
+ if (env_time > env_length[env_stage]) {
+ env_time = 0;
+ env_stage += 1;
+ if (env_stage == 3) finished = true;
+ }
+ env_vol = switch (env_stage) {
+ 0 => @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[0]))),
+ 1 => 1.0 + (1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[1])))) * 2.0 * p.punch,
+ else => 1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[2]))),
+ };
+
+ fphase += fdphase;
+ iphase = @intFromFloat(@min(@abs(fphase), 1023));
+
+ flthp *= flthp_d;
+ flthp = std.math.clamp(flthp, 0.00001, 0.1);
+
+ var ssample: f32 = 0;
+ var oi: u32 = 0;
+ while (oi < 8) : (oi += 1) {
+ var sample: f32 = 0;
+ phase += 1;
+ if (phase >= period) {
+ phase = @mod(phase, period);
+ if (p.wave == .noise) for (&noise_buffer) |*nb| {
+ nb.* = frnd(&rng, 2) - 1;
+ };
+ }
+ const fp: f32 = @as(f32, @floatFromInt(phase)) / @as(f32, @floatFromInt(period));
+ sample = switch (p.wave) {
+ .square => if (fp < square_duty) 0.5 else -0.5,
+ .sawtooth => 1.0 - fp * 2,
+ .sine => @sin(fp * 2.0 * std.math.pi),
+ .noise => noise_buffer[@intCast(@as(i32, @intFromFloat(fp * 32)) & 31)],
+ };
+
+ const pp = fltp;
+ fltw *= fltw_d;
+ fltw = std.math.clamp(fltw, 0, 0.1);
+ if (p.lpf_freq != 1.0) {
+ fltdp += (sample - fltp) * fltw;
+ fltdp -= fltdp * fltdmp;
+ } else {
+ fltp = sample;
+ fltdp = 0;
+ }
+ fltp += fltdp;
+ fltphp += fltp - pp;
+ fltphp -= fltphp * flthp;
+ sample = fltphp;
+ phaser_buffer[@intCast(ipp & 1023)] = sample;
+ sample += phaser_buffer[@intCast((ipp - iphase + 1024) & 1023)];
+ ipp = (ipp + 1) & 1023;
+
+ ssample += sample * env_vol;
+ }
+ ssample = ssample / 8.0 * p.volume * 2.0;
+ out[n] = std.math.clamp(ssample, -1, 1);
+ }
+ return n;
+}
+
+/// One parameter set per wave, between them every knob: a coin with punch,
+/// arpeggio and a duty sweep; an explosion through both filters; a laser
+/// with vibrato, phaser, repeat and a pitch limit; a rising sine.
+const sets = [_]Params{
+ .{ .wave = .square, .sustain = 0.1, .punch = 0.5, .decay = 0.3, .freq = 0.45, .freq_ramp = -0.2, .arp_mod = 0.4, .arp_speed = 0.6, .duty = 0.3, .duty_ramp = 0.2 },
+ .{ .wave = .noise, .sustain = 0.2, .decay = 0.4, .freq = 0.2, .freq_ramp = -0.1, .lpf_freq = 0.6, .lpf_ramp = -0.1, .lpf_resonance = 0.4, .hpf_freq = 0.1, .hpf_ramp = 0.05 },
+ .{ .wave = .sawtooth, .sustain = 0.25, .decay = 0.2, .freq = 0.5, .freq_limit = 0.1, .freq_dramp = 0.1, .vibrato_depth = 0.3, .vibrato_speed = 0.5, .phaser_offset = 0.3, .phaser_ramp = -0.1, .repeat_speed = 0.5 },
+ .{ .wave = .sine, .attack = 0.2, .sustain = 0.2, .decay = 0.2, .freq = 0.3, .freq_ramp = 0.1, .freq_limit = 0.2, .volume = 0.8 },
+};
+
+test "sfxr renders the original's samples at 44.1 kHz, and as long a sound at 48 kHz" {
+ // Length and Wyhash of the samples the original (02-dont-rat-me-out
+ // synth.zig) rendered for each set at 44.1 kHz.
+ const original = [_]struct { usize, u64 }{
+ .{ 10003, 0xb969b441e8bd800 },
+ .{ 20003, 0x5fc62aaf3122de5a },
+ .{ 10253, 0x8d81ee15b98f33ac },
+ .{ 12003, 0xe656fadd21b7dedb },
+ };
+ const out = try std.testing.allocator.alloc(f32, 2 * 48_000);
+ defer std.testing.allocator.free(out);
+ for (sets, original) |p, want| {
+ const n = render(p, reference_rate, out);
+ try std.testing.expectEqual(want[0], n);
+ try std.testing.expectEqual(want[1], std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(out[0..n])));
+ const at48 = render(p, 48_000, out);
+ try std.testing.expectApproxEqRel(@as(f64, @floatFromInt(n)) * 48_000 / reference_rate, @as(f64, @floatFromInt(at48)), 0.01);
+ }
+}