// Made by tools/listings.mjs from stages/world-08.html, region 8-sound. Do not edit.

// region: gullCall
// A gull's cry as notes: [start, length, pitch at start, pitch at end] in
// seconds and hertz. A few long falling calls, then a run of short ones.
function gullCall(r) {
  const notes = [];
  const base = 1500 + r() * 700;
  let t = 0;
  for (let k = 0, long = 1 + ((r() * 3) | 0); k < long; k++) {
    notes.push([t, 0.32, base * 1.25, base * 0.8]);
    t += 0.45 + r() * 0.15;
  }
  for (let k = 0, short = 3 + ((r() * 5) | 0); k < short; k++) {
    notes.push([t, 0.11, base * 1.1, base * 0.92]);
    t += 0.17;
  }
  return notes;
}
// endregion: gullCall

// region: callEnvelope
// How loud a note of the call is, as points [seconds from its start, level]:
// from silence up to half in 0.03 seconds, then down to silence at the end. A
// note that started or stopped at full level would click.
function callEnvelope(len) {
  return [
    [0, 0],
    [0.03, 0.5],
    [len, 0],
  ];
}
// endregion: callEnvelope

// region: cry
// One gull cry: a buzzy tone through a narrow filter, its pitch sliding down
// through each note.
function cry() {
  const C = audio.ctx;
  const t0 = C.currentTime + 0.05;
  const o = C.createOscillator();
  const g = C.createGain();
  const f = C.createBiquadFilter();
  o.type = 'sawtooth';
  f.type = 'bandpass';
  f.Q.value = 5;
  g.gain.value = 0;
  o.connect(f);
  f.connect(g);
  g.connect(audio.gulls);
  let end = t0;
  for (const [at, len, f0, f1] of gullCall(audio.rng)) {
    o.frequency.setValueAtTime(f0, t0 + at);
    o.frequency.exponentialRampToValueAtTime(f1, t0 + at + len);
    f.frequency.setValueAtTime(f0 * 1.6, t0 + at);
    const [[u0, first], ...rest] = callEnvelope(len);
    g.gain.setValueAtTime(first, t0 + at + u0);
    for (const [u, level] of rest)
      g.gain.linearRampToValueAtTime(level, t0 + at + u);
    end = t0 + at + len;
  }
  o.start(t0);
  o.stop(end + 0.1);
}
// endregion: cry

// region: soundMix
// How loud each voice is, from where the listener is: [surf, wind, crickets,
// gulls], each 0..1. ground = land height under the camera, alt = camera height
// above it (or above the sea), speed in m/s.
function soundMix(ground, alt, speed, night, flockDist) {
  const sea = ground <= 0.5 ? 1 : 1 - smooth(0, 90, ground);
  return [
    (0.25 + 0.75 * sea) / (1 + alt / 45),
    clamp(0.12 + alt / 400 + speed / 60, 0, 1),
    (night * (ground > 1 ? 1 : 0.3)) / (1 + alt / 30),
    1 / (1 + flockDist / 160),
  ];
}
// endregion: soundMix
