A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sound): a made sound is built as a real one is - noise in bands that each die at their own rate, a tail to a decay, an impulse for the front of a bang, strikes scattered in time and pitch, a bounce, a peak filter, and a place made by convolution with first echoes and a top that dies before its bottom
yhh02ace9378573
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 652106118..7dd8033b4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ published separately; it ships inside the editor.- **A flower turns to face the eye.** A flat flower faces the sky, so a field of them is seen edge on from a few metres up and has no colour a field away; tipping each far plant's head at random (`farTilt`) showed half of them from behind. `Foliage.faceEyeNear` and `Foliage.faceEye` turn the head of every mesh plant toward the eye, by the first close to and by the second from half the draw distance away, as a clump of flowers shows its colour from the side. It is done the way a pivot painted into a uv is elsewhere: the copies carry in a second uv where each vertex of a head sits from its plant's axis, and a material's vertex hook now reads a mesh's second uv as `es_vertexUv1` (zero on a mesh with none), beside `es_vertexColor`. At 0 and 0, the default, no channel is added and nothing turns.- **A far field of flowers shows its colour.** A mesh plant kept in a far version grows across the ground to stand for those left out. A flat flower grown that way is a disc facing the sky: from an eye a few metres up it is seen edge on, and a meadow that is all flowers at your feet was plain green a field away. `Foliage.farTilt` tips the top of each far plant over by so many degrees (the last tenth of its height: the flower, not its stem), each plant its own way round, so half the field shows its face. 0, the default, leaves a far plant as it was.- **A layer with a grain is read without repeat and without hexagons.** Near the eye a terrain layer is read in hexagonal cells, each shifted and turned at random, so no tile shows. A layer with a direction to it (sand in ripples, rock in beds) turned cell by cell has its normal map lit cell by cell, and the ground showed a mosaic of light and dark hexagons a metre wide. `u_antiTileTurn` on the Terrain and Terrain Layers materials is how far round a cell may be turned: 1, the default, is any way as before; 0 shifts the cell and does not turn it, which is the setting for a layer with a grain.-- **An AI can make a sound effect.** The engine played recordings and nothing here made one: a game built by an agent had pictures and models of its own and no sounds. A sound is now layers, as a picture is: `sound_write` takes a source of tones (sine, triangle, saw, square), noise (white, pink, brown) and `modes`, the tones a struck thing rings with, each placed in time and shaped by a level, a decay, filters whose corner can move, a second tone bending it, drive, pan and repeats, with an echo and a room over the whole, and writes an `.essound` and the `.wav` a scene plays. Whoever writes one cannot hear it, so the reply is a picture: the wave on top and pitch against time under it, a thump a blot low on the left, a hiss a haze across the top, a falling tone a falling line, with the level and the share of the energy that is low, middle and high. `sound_edit` changes a number and makes it again; `loop` runs the end into the start for an engine or a wind. A gunshot, footsteps, breaking glass, a pickup, an explosion, an engine loop and a laser are 150 to 500 bytes of source each and are made in under a tenth of a second. The same source is the same file on every machine. Nothing has been listened to: the recipes in the tool text were judged by their pictures.+- **An AI can make a sound effect.** The engine played recordings and nothing here made one: a game built by an agent had pictures and models of its own and no sounds. A sound is now layers, as a picture is: `sound_write` takes a source of tones (sine, triangle, saw, square), noise (white, pink, brown) and `modes`, the tones a struck thing rings with, each placed in time and shaped by a level, a decay, filters whose corner can move, a second tone bending it, drive, pan and repeats, with an echo and a room over the whole, and writes an `.essound` and the `.wav` a scene plays. Whoever writes one cannot hear it, so the reply is a picture: the wave on top and pitch against time under it, a thump a blot low on the left, a hiss a haze across the top, a falling tone a falling line, with the level and the share of the energy that is low, middle and high. `sound_edit` changes a number and makes it again; `loop` runs the end into the start for an engine or a wind. A gunshot, footsteps, breaking glass, a pickup, an explosion, an engine loop and a laser are 150 to 500 bytes of source each and are made in under a tenth of a second. The same source is the same file on every machine. The first sounds made this way were listened to and did not pass: one noise through one filter with one decay is heard at once as a machine. So a layer can now be what a real sound is made of: noise cut to a `band` and brought back to full level, several of which die at different rates behind an `impulse`; a `tail` that lets part of a decay linger; `scatter`, which strikes a layer hundreds of times at random in time, pitch, loudness and side, for glass, gravel and rain; `repeat` with `faster`, for a thing bouncing to rest; a `peak` filter for the note a body adds; and `reverb` as a place, `room` or `open`, made by laying the sound over what that place answers to a click, with distinct first echoes and a wash whose top dies before its bottom. The tool text gives the method and the numbers for a shot, glass, a step and an explosion.- **An AI can draw a surface: a picture that repeats, with what the light does on it.** `image_write` drew one picture, and a picture laid beside itself shows its edges; nor is a wall only its colour. `tile: true` on an image source makes it repeat: a shape, a line or a brush stroke that leaves one edge comes in at the opposite one, a shadow and a blur go round with it, and a noise fill meets itself. `material: { relief, height, roughness, metal }` makes it a surface: each of height, roughness and metal is layers drawn as a grey picture of their own (light is high, rough, metal), or the colour's own lightness stands in for the relief, and a normal map, a map of roughness and metal and an `.esmaterial` are written beside the picture. The reply shows the picture laid beside itself two by two, where a join would run through the middle, and the same under a low light, and gives the fields to put on a mesh. A brick wall, a plank floor and a riveted plate, 256 pixels each, drew in under a third of a second apiece and tiled three across in the engine with no join. A `filter` still stops at the edges, and a noise turned or stretched by `transform` does not come round.- **A model is written once for all its like parts, and a leaf can be a picture.** A model's source was a flat list of steps with plain numbers: a plant of ten fronds wrote out a frond ten times, and every leaf was a thin solid in one colour. Three things change that. `params` names numbers and points, and a value written `"=length * 0.4"` is a sum over them, with points that add and scale, angles in degrees, and makers for what shapes keep asking for: `polar` for a point round the upright axis, `arc` for a line that bends from one lean to another, `part` for a share of a line. `{ op: "repeat", over: [rows], steps: [...] }` runs its steps once for each row, the row's fields being names inside it, and `let` names a value for the steps after it; what is saved and edited is the source as written, so one edit to a name changes every part. The `strip` step carries a band with no thickness along a path, shaped by `widths`, folded by `cup`, with a picture laid along it from root to tip. `material.texture` names that picture, and with `alpha: "cutout"` its alpha is the outline: a leaf with veins and a torn edge, drawn once. `loft` takes an `up` for the way its section stands. The palm that was 386 steps is six steps written in two models of 2.9 and 2.4 KB, and 9,150 triangles where it was 26,814. Drawn in the engine it cost a little more GPU than the solid one all the same (about 1.1 ms against 0.8 for the frame at 1024 by 1024 on an RTX 3060): cut-out leaves draw both sides and test every pixel.- **An AI can lay leaflets along a stem in one step.** `scatter` along a `path` pointed every copy the way the path runs, turned at random, so the leaflets of a frond, the barbs of a feather or the legs of a centipede had to be written out one step each: a palm was 386 steps and a 749 KB model file. `rows` (1 or 2) stands the copies off the path instead, in a row or in pairs, `sweep` degrees from the way it runs and `lift` out of the plane, each as one number or as a start and an end. A copy's +z faces `up`, so a flat blade keeps its face to the sky whichever way it points. `sizes` shapes them along the path, widest in the middle if you say so. The same palm is 40 steps and 38 KB, and bakes to the same triangle count. A scatter without `rows` is as it was.diff --git a/desktop b/desktopindex abfd7414a..0fdd3ac6f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit abfd7414a992984703f7520009bf4c705a598096+Subproject commit 0fdd3ac6fb990dc35960662dda3e67dcbdc993a5diff --git a/pipeline/src/sound/soundPicture.ts b/pipeline/src/sound/soundPicture.tsindex 2679566f7..0ce9ab539 100644--- a/pipeline/src/sound/soundPicture.ts+++ b/pipeline/src/sound/soundPicture.ts@@ -14,7 +14,7 @@ import type { RenderedSound } from './soundRender';export interface SoundPicture { width: number; height: number; rgba: Uint8Array }/** In place: the transform of @p re + i @p im, their length a power of two. */-function fft(re: Float64Array, im: Float64Array): void {+export function fft(re: Float64Array, im: Float64Array): void {const n = re.length;for (let i = 1, j = 0; i < n; i++) {let bit = n >> 1;diff --git a/pipeline/src/sound/soundRender.ts b/pipeline/src/sound/soundRender.tsindex 1c61d6a14..692cbd3b6 100644--- a/pipeline/src/sound/soundRender.ts+++ b/pipeline/src/sound/soundRender.ts@@ -4,9 +4,16 @@* @file soundRender.ts — a sound source worked out into samples, and the samples as a `.wav`.** Every layer is rendered on its own, placed in time, and summed; then what the source says of the whole (a- * filter, an echo, a room, a level) is applied to the sum. Nothing depends on the machine: no random number is+ * filter, an echo, a place, a level) is applied to the sum. Nothing depends on the machine: no random number is* drawn that is not seeded, and the arithmetic is plain doubles.+ *+ * What makes a made sound pass for a real one is mostly here, and it is not more kinds of wave. A bang is several+ * bands of noise that die at different rates, the high ones first, behind a spike a fifth of a millisecond wide;+ * a breaking thing is hundreds of small rings scattered in time and pitch; a place is a wash whose top dies before+ * its bottom, after a handful of distinct first echoes. A layer of noise through one filter with one decay has+ * none of that and is heard at once as a machine.*/+import { fft } from './soundPicture';import type { SoundCurve, SoundFilter, SoundLayer, SoundSource } from './soundSource';export interface RenderedSound {@@ -19,11 +26,13 @@ export interface RenderedSound {/** The level over the whole, as the square root of the mean square. */rms: number;/** Where each layer sounds and how loud it is on its own, before the sum. */- layers: { id?: string; source: string; from: number; to: number; peak: number }[];+ layers: { id?: string; source: string; from: number; to: number; peak: number; strikes?: number }[];notes: string[];}const TAU = Math.PI * 2;+/** The level white noise has here, which a band of it is brought back to. */+const NOISE_LEVEL = 1 / Math.sqrt(3);/** A curve read at @p t seconds: straight between its points, or along the ratio between them for a pitch. */function curveAt(curve: SoundCurve | undefined, t: number, fallback: number, ratio: boolean): number {@@ -65,7 +74,7 @@ class Biquad {private x1 = 0; private x2 = 0; private y1 = 0; private y2 = 0;private b0 = 1; private b1 = 0; private b2 = 0; private a1 = 0; private a2 = 0;private last = -1;- constructor(private readonly type: SoundFilter['type'], private readonly q: number, private readonly rate: number) {}+ constructor(private readonly type: SoundFilter['type'], private readonly q: number, private readonly rate: number, private readonly gainDb = 0) {}tune(freq: number): void {const f = Math.max(20, Math.min(this.rate * 0.45, freq));@@ -73,15 +82,21 @@ class Biquad {this.last = f;const w = (TAU * f) / this.rate;const [cos, alpha] = [Math.cos(w), Math.sin(w) / (2 * this.q)];- const a0 = 1 + alpha;+ let a0 = 1 + alpha, a1 = -2 * cos, a2 = 1 - alpha;let b0: number, b1: number, b2: number;switch (this.type) {case 'lowpass': [b0, b1, b2] = [(1 - cos) / 2, 1 - cos, (1 - cos) / 2]; break;case 'highpass': [b0, b1, b2] = [(1 + cos) / 2, -(1 + cos), (1 + cos) / 2]; break;case 'bandpass': [b0, b1, b2] = [alpha, 0, -alpha]; break;+ case 'peak': {+ const lift = Math.pow(10, this.gainDb / 40);+ [b0, b1, b2] = [1 + alpha * lift, -2 * cos, 1 - alpha * lift];+ [a0, a1, a2] = [1 + alpha / lift, -2 * cos, 1 - alpha / lift];+ break;+ }default: [b0, b1, b2] = [1, -2 * cos, 1];}- [this.b0, this.b1, this.b2, this.a1, this.a2] = [b0 / a0, b1 / a0, b2 / a0, (-2 * cos) / a0, (1 - alpha) / a0];+ [this.b0, this.b1, this.b2, this.a1, this.a2] = [b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0];}run(x: number): number {@@ -91,34 +106,63 @@ class Biquad {}}+const rmsOf = (a: Float32Array): number => { let s = 0; for (const v of a) s += v * v; return Math.sqrt(s / Math.max(1, a.length)); };++/** @p count samples of a noise layer's own sound, before its loudness is shaped: its colour, and its band at the level of the whole. */+function noiseBody(layer: SoundLayer, count: number, rate: number, seed: number, pitch: number): Float32Array {+ const random = noiseOf(seed);+ const out = new Float32Array(count);+ // Pink and brown are white put through a few poles; these are their memories.+ let [p0, p1, p2, brown] = [0, 0, 0, 0];+ for (let n = 0; n < count; n++) {+ const white = random();+ if (layer.color === 'pink') {+ p0 = 0.99765 * p0 + white * 0.099046;+ p1 = 0.963 * p1 + white * 0.2965164;+ p2 = 0.57 * p2 + white * 1.0526913;+ out[n] = (p0 + p1 + p2 + white * 0.1848) * 0.25;+ } else if (layer.color === 'brown') {+ brown = (brown + white * 0.02) / 1.02;+ out[n] = brown * 3.5;+ } else out[n] = white;+ }+ if (layer.band) {+ // Cut to the band, then brought back up: what is left of noise after two filters is faint, and a band that+ // had to be turned up by guess would never balance against the others.+ const [high, low] = [new Biquad('highpass', 0.7, rate), new Biquad('lowpass', 0.7, rate)];+ high.tune(layer.band[0] * pitch);+ low.tune(layer.band[1] * pitch);+ // Run in a little first, so the filters are not still starting when the sound is.+ for (let n = 0; n < 64; n++) low.run(high.run(random()));+ for (let n = 0; n < count; n++) out[n] = low.run(high.run(out[n]!));+ const level = rmsOf(out);+ if (level > 1e-9) for (let n = 0; n < count; n++) out[n]! *= NOISE_LEVEL / level;+ }+ return out;+}+/** One striking of a layer: its samples from its own start, at @p pitch times its written pitch. */function strike(layer: SoundLayer, seconds: number, rate: number, pitch: number, seed: number): Float32Array {const count = Math.max(1, Math.round(seconds * rate));const out = new Float32Array(count);- const random = noiseOf(seed);- const filters = (layer.filters ?? []).map((f) => ({ run: new Biquad(f.type, f.q ?? 0.7, rate), freq: f.freq }));- const [attack, release] = [layer.attack ?? 0.002, layer.release ?? 0.01];+ const filters = (layer.filters ?? []).map((f) => ({ run: new Biquad(f.type, f.q ?? 0.7, rate, f.gain ?? 0), freq: f.freq }));+ // The fades that only stop a click are never most of a short layer: a strike two milliseconds long keeps its front.+ const [attack, release] = [layer.attack ?? (layer.source === 'impulse' ? 0 : Math.min(0.002, seconds * 0.1)), layer.release ?? Math.min(0.01, seconds * 0.25)];const drive = layer.drive ?? 0;const push = 1 + drive * 14;const pushed = Math.tanh(push);+ const noise = layer.source === 'noise' ? noiseBody(layer, count, rate, seed, pitch) : null;+ // A spike: up in one sample and down over its width, as the air does in front of a bang.+ const spike = layer.source === 'impulse' ? (layer.width ?? 0.0002) * rate : 0;let [phase, bend] = [0, 0];- // Pink and brown are white put through a few poles; these are their memories.- let [p0, p1, p2, brown] = [0, 0, 0, 0];for (let n = 0; n < count; n++) {const t = n / rate;let v: number;- if (layer.source === 'noise') {- const white = random();- if (layer.color === 'pink') {- p0 = 0.99765 * p0 + white * 0.099046;- p1 = 0.963 * p1 + white * 0.2965164;- p2 = 0.57 * p2 + white * 1.0526913;- v = (p0 + p1 + p2 + white * 0.1848) * 0.25;- } else if (layer.color === 'brown') {- brown = (brown + white * 0.02) / 1.02;- v = brown * 3.5;- } else v = white;+ if (noise) v = noise[n]!;+ else if (layer.source === 'impulse') {+ const b = n / spike;+ v = b < 10 ? (1 - b) * Math.exp(-b) : 0;} else if (layer.source === 'modes') {v = 0;for (const [hz, loud, dies] of layer.modes!) {@@ -150,13 +194,17 @@ function strike(layer: SoundLayer, seconds: number, rate: number, pitch: number,}}for (const f of filters) {- // The corner is read every 16 samples: often enough for a sweep, seldom enough to cost little.- if ((n & 15) === 0) f.run.tune(curveAt(f.freq, t, 1000, true));+ // The corner is read every 16 samples: often enough for a sweep, seldom enough to cost little. A noise struck+ // at another pitch has no pitch of its own to move, so its filters move instead.+ if ((n & 15) === 0) f.run.tune(curveAt(f.freq, t, 1000, true) * (noise ? pitch : 1));v = f.run.run(v);}if (drive > 0) v = Math.tanh(v * push) / pushed;let level = curveAt(layer.gain, t, 1, false);- if (layer.decay) level *= Math.exp(-t / layer.decay);+ if (layer.decay) {+ const fast = Math.exp(-t / layer.decay);+ level *= layer.tail ? fast * (1 - layer.tail.mix) + Math.exp(-t / layer.tail.decay) * layer.tail.mix : fast;+ }if (layer.tremolo) level *= 1 - layer.tremolo.depth * (0.5 + 0.5 * Math.sin(TAU * layer.tremolo.rate * t));if (attack > 0 && t < attack) level *= t / attack;const left = seconds - t;@@ -166,30 +214,131 @@ function strike(layer: SoundLayer, seconds: number, rate: number, pitch: number,return out;}-/** Eight delays and four all-pass loops, as rooms have been faked since the seventies: dense enough to pass for one, cheap enough to run on a sum. */-function room(input: Float32Array, rate: number, size: number, spread: number): Float32Array {- const scale = rate / 44100;- const combs = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617].map((d) => ({ buf: new Float32Array(Math.round((d + spread) * scale)), at: 0, damp: 0 }));- const passes = [556, 441, 341, 225].map((d) => ({ buf: new Float32Array(Math.round((d + spread) * scale)), at: 0 }));- const feedback = 0.7 + size * 0.28;- const out = new Float32Array(input.length);- for (let n = 0; n < input.length; n++) {- const x = input[n]! * 0.015;- let sum = 0;- for (const c of combs) {- const y = c.buf[c.at]!;- c.damp = y * 0.8 + c.damp * 0.2;- c.buf[c.at] = x + c.damp * feedback;- c.at = (c.at + 1) % c.buf.length;- sum += y;+/** @p a and @p b laid over one another at every offset: what a sound becomes in a place whose answer to a click is @p b. */+function convolve(a: Float32Array, b: Float32Array, keep: number): Float32Array {+ let size = 1;+ while (size < a.length + b.length) size <<= 1;+ const [ar, ai, br, bi] = [new Float64Array(size), new Float64Array(size), new Float64Array(size), new Float64Array(size)];+ ar.set(a); br.set(b);+ fft(ar, ai); fft(br, bi);+ for (let k = 0; k < size; k++) {+ const [re, im] = [ar[k]! * br[k]! - ai[k]! * bi[k]!, ar[k]! * bi[k]! + ai[k]! * br[k]!];+ // Back the same way: the transform of the conjugate, conjugated and shared out.+ ar[k] = re; ai[k] = -im;+ }+ fft(ar, ai);+ const out = new Float32Array(keep);+ for (let n = 0; n < keep; n++) out[n] = ar[n]! / size;+ return out;+}++/**+ * What a place answers to one click, for one ear. A room: noise in three bands that each die at their own rate, the+ * top in half the time of the bottom, coming up over a hundredth of a second, with thirty-odd distinct first echoes+ * ahead of it. Open ground: a few slaps off far walls, each duller than the last, and a long faint tail.+ */+function placeResponse(rate: number, size: number, kind: 'room' | 'open', side: number): Float32Array {+ const random = noiseOf(kind === 'room' ? 6923 + side * 977 : 32324 + side * 977);+ const unit = (): number => random() * 0.5 + 0.5;+ const seconds = kind === 'room' ? 0.35 + size * 2.4 : 0.6 + size * 2.6;+ const count = Math.floor(rate * seconds);+ const out = new Float32Array(count);+ const banded = (low: number | null, high: number | null): Float32Array => {+ const buf = new Float32Array(count);+ const [hp, lp] = [low ? new Biquad('highpass', 0.6, rate) : null, high ? new Biquad('lowpass', 0.6, rate) : null];+ hp?.tune(low!); lp?.tune(high!);+ for (let n = 0; n < count; n++) { let v = random(); if (hp) v = hp.run(v); if (lp) v = lp.run(v); buf[n] = v; }+ const level = rmsOf(buf) || 1;+ for (let n = 0; n < count; n++) buf[n]! /= level;+ return buf;+ };+ if (kind === 'room') {+ // Seconds for each band to fall by sixty decibels.+ const long = 0.25 + size * 1.5;+ const bands: [Float32Array, number, number][] = [[banded(null, 420), 0.45, long], [banded(420, 3000), 1, long * 0.8], [banded(3000, null), 1.6, long * 0.4]];+ for (let n = 0; n < count; n++) {+ const t = n / rate;+ const rise = 1 - Math.exp(-t / 0.014);+ let v = 0;+ for (const [buf, loud, falls] of bands) v += buf[n]! * loud * Math.pow(10, (-3 * t) / falls);+ out[n] = v * rise;}- for (const p of passes) {- const y = p.buf[p.at]!;- p.buf[p.at] = sum + y * 0.5;- p.at = (p.at + 1) % p.buf.length;- sum = y - sum;+ const wash = rmsOf(out) * Math.sqrt(count);+ const first = new Float32Array(count);+ for (let e = 0; e < 34; e++) {+ const t = (0.0048 + 0.088 * Math.pow((e + unit()) / 34, 1.5)) * (0.45 + size) * (side ? 1.07 : 1);+ const at = Math.floor(t * rate);+ const loud = (random() < 0 ? -1 : 1) * Math.exp(-t / 0.034) * (0.55 + 0.45 * unit());+ // Later echoes have travelled further and are smeared wider.+ const width = 1 + Math.floor(t * 60);+ for (let n = 0; n < width && at + n < count; n++) first[at + n]! += (loud * (1 - n / width)) / Math.sqrt(width);}- out[n] = sum;+ const firstLevel = rmsOf(first) * Math.sqrt(count) || 1;+ for (let n = 0; n < count; n++) out[n]! += first[n]! * ((0.78 * wash) / firstLevel);+ } else {+ for (const [t, loud, milliseconds, top] of [[0.094, 0.5, 5, 5200], [0.151, 0.4, 8, 3800], [0.212, 0.31, 12, 2700], [0.289, 0.24, 16, 2000]] as const) {+ const length = Math.floor((rate * milliseconds * 4) / 1000);+ const [lp, hp] = [new Biquad('lowpass', 0.6, rate), new Biquad('highpass', 0.6, rate)];+ lp.tune(top); hp.tune(180);+ const slap = new Float32Array(length);+ for (let n = 0; n < length; n++) slap[n] = hp.run(lp.run(random())) * Math.exp(-n / ((rate * milliseconds) / 1000)) * (1 - Math.exp(-n / (rate * 0.0006)));+ const level = rmsOf(slap) * Math.sqrt(length) || 1;+ const at = Math.floor(rate * t * (0.5 + size) * (1 + 0.1 * random() * 0.5));+ const share = (loud * (0.45 + 0.55 * (side ? 1 - unit() : unit()))) / level;+ for (let n = 0; n < length && at + n < count; n++) out[at + n]! += slap[n]! * share;+ }+ const slaps = rmsOf(out) * Math.sqrt(count) || 1;+ const tail = banded(320, 2300);+ const falls = 1 + size * 2;+ let tailSquares = 0;+ for (let n = 0; n < count; n++) {+ const t = n / rate;+ tail[n] = tail[n]! * Math.pow(10, (-3 * t) / falls) * (1 - Math.exp(-t / 0.11));+ tailSquares += tail[n]! * tail[n]!;+ }+ const tailLevel = Math.sqrt(tailSquares) || 1;+ for (let n = 0; n < count; n++) out[n]! += tail[n]! * ((0.5 * slaps) / tailLevel);+ }+ // Let down at its end, and of one energy whatever its size: `mix` then means the same in a closet and a hall.+ const fade = Math.floor(count * 0.08);+ for (let n = 0; n < fade; n++) out[count - 1 - n]! *= n / fade;+ const energy = rmsOf(out) * Math.sqrt(count) || 1;+ for (let n = 0; n < count; n++) out[n]! /= energy;+ return out;+}++interface Strike { at: number; pitch: number; loud: number; pan: number; seed: number }++/** When a layer is struck, and how: once, again by `repeat`, or many times at random by `scatter`. */+function strikesOf(layer: SoundLayer, start: number, seed: number): Strike[] {+ const pan = layer.pan ?? 0;+ if (layer.scatter) {+ const c = layer.scatter;+ const random = noiseOf(seed + 4409);+ const unit = (): number => random() * 0.5 + 0.5;+ const [p0, p1] = c.pitch ?? [1, 1];+ const [g0, g1] = c.gain ?? [1, 1];+ return Array.from({ length: c.count }, (_, k) => {+ const when = Math.pow(unit(), c.early ?? 1);+ return {+ at: start + c.over * when,+ // Between two pitches by ratio, so there are as many strikes in each octave of the range.+ pitch: p0 * Math.pow(p1 / p0, unit()),+ loud: (g0 + (g1 - g0) * unit()) * (1 - (c.fade ?? 0) * when),+ pan: Math.max(-1, Math.min(1, pan + (c.pan ?? 0) * random())),+ seed: seed + k * 131,+ };+ }).sort((a, b) => a.at - b.at);+ }+ const r = layer.repeat;+ const jitter = noiseOf(seed + 7919);+ const out: Strike[] = [];+ let [at, gap] = [start, r?.every ?? 0];+ for (let k = 0; k < (r?.count ?? 1); k++) {+ out.push({ at: at + (k > 0 && r?.jitter ? jitter() * r.jitter : 0), pitch: Math.pow(r?.pitch ?? 1, k), loud: Math.pow(r?.gain ?? 1, k), pan, seed: seed + k * 131 });+ at += gap;+ // A thing bouncing to rest: each gap shorter than the last.+ gap *= r?.faster ?? 1;}return out;}@@ -209,35 +358,39 @@ export function renderSound(source: SoundSource): RenderedSound {source.layers.forEach((layer, index) => {if (layer.mute) return;const start = layer.start ?? 0;- const room = total / rate - start;- const seconds = Math.min(layer.length ?? room, room);+ const space = total / rate - start;+ const seconds = Math.min(layer.length ?? space, space);const where = `layer ${index}${layer.id ? ` "${layer.id}"` : ''}`;if (!(seconds > 0)) { notes.push(`${where} starts at the end of the sound and is not heard`); return; }- if (layer.length !== undefined && layer.length > room + 1e-6 && !layer.repeat) notes.push(`${where} is cut short: it runs ${layer.length} s from ${start} s in a sound of ${source.duration} s`);- const pan = layer.pan ?? 0;- if (pan !== 0) stereo = true;- // Equal power: a sound sent to one side is as loud as one in the middle.- const [gl, gr] = [Math.cos(((pan + 1) * Math.PI) / 4), Math.sin(((pan + 1) * Math.PI) / 4)];- const seed = layer.seed ?? index + 1;- const jitter = noiseOf(seed + 7919);- const times = layer.repeat?.count ?? 1;- let [peak, last] = [0, start];- for (let k = 0; k < times; k++) {- const at = start + k * (layer.repeat?.every ?? 0) + (k > 0 && layer.repeat?.jitter ? jitter() * layer.repeat.jitter : 0);- const from = Math.round(Math.max(0, at) * rate);- if (from >= total) break;+ if (layer.length !== undefined && layer.length > space + 1e-6 && !layer.repeat && !layer.scatter) notes.push(`${where} is cut short: it runs ${layer.length} s from ${start} s in a sound of ${source.duration} s`);+ const wide = layer.source === 'noise' ? layer.wide ?? 0 : 0;+ const strikes = strikesOf(layer, start, layer.seed ?? index + 1);+ if (wide > 0 || strikes.some((s) => s.pan !== 0)) stereo = true;+ let [peak, last, heard] = [0, start, 0];+ for (const s of strikes) {+ const from = Math.round(Math.max(0, s.at) * rate);+ if (from >= total) continue;+ heard++;+ const length = Math.min(seconds, (total - from) / rate);// Each striking has its own noise, as no two footsteps are the same grit.- const hit = strike(layer, Math.min(seconds, (total - from) / rate), rate, Math.pow(layer.repeat?.pitch ?? 1, k), seed + k * 131);- const loud = Math.pow(layer.repeat?.gain ?? 1, k);+ const hit = strike(layer, length, rate, s.pitch, s.seed);+ // The other ear's noise is another noise, by as much as the layer is wide.+ const other = wide > 0 ? strike(layer, length, rate, s.pitch, s.seed + 50021) : null;+ // Equal power: a sound sent to one side is as loud as one in the middle.+ const [gl, gr] = [Math.cos(((s.pan + 1) * Math.PI) / 4), Math.sin(((s.pan + 1) * Math.PI) / 4)];for (let n = 0; n < hit.length && from + n < total; n++) {- const v = hit[n]! * loud;+ const v = hit[n]! * s.loud;left[from + n]! += v * gl;- right[from + n]! += v * gr;+ right[from + n]! += (other ? v * (1 - wide) + other[n]! * s.loud * wide : v) * gr;if (Math.abs(v) > peak) peak = Math.abs(v);}- last = Math.min(total / rate, at + hit.length / rate);+ last = Math.max(last, Math.min(total / rate, s.at + hit.length / rate));}- reports.push({ ...(layer.id ? { id: layer.id } : {}), source: layer.source, from: Math.round(start * 1000) / 1000, to: Math.round(last * 1000) / 1000, peak: Math.round(peak * 1000) / 1000 });+ reports.push({+ ...(layer.id ? { id: layer.id } : {}), source: layer.source, from: Math.round(start * 1000) / 1000, to: Math.round(last * 1000) / 1000,+ peak: Math.round(peak * 1000) / 1000, ...(strikes.length > 1 ? { strikes: heard } : {}),+ });+ if (heard < strikes.length) notes.push(`${where}: ${strikes.length - heard} of its ${strikes.length} strikes fall past the end of the sound and are not heard`);if (peak < 1e-4) notes.push(`${where} makes no sound: its level is nothing throughout`);});@@ -260,10 +413,10 @@ export function renderSound(source: SoundSource): RenderedSound {}}if (source.reverb) {+ // The two ears are answered a little differently, which is what makes a place wide.+ const wet = convolve(channel, placeResponse(rate, source.reverb.size ?? 0.5, source.reverb.kind ?? 'room', c), total);const mix = source.reverb.mix ?? 0.25;- // The two sides are rooms a little different, which is what makes it wide.- const wet = room(channel, rate, source.reverb.size ?? 0.5, c * 23);- for (let n = 0; n < total; n++) channel[n] = channel[n]! * (1 - mix * 0.5) + wet[n]! * mix;+ for (let n = 0; n < total; n++) channel[n] = channel[n]! + wet[n]! * mix * 3;}}diff --git a/pipeline/src/sound/soundSource.ts b/pipeline/src/sound/soundSource.tsindex 72b364803..98cfc25a2 100644--- a/pipeline/src/sound/soundSource.ts+++ b/pipeline/src/sound/soundSource.ts@@ -20,9 +20,10 @@ export const SOUND_RATES = [22050, 44100, 48000] as const;/** One value for the whole of a layer, or [[seconds, value], ...] from the layer's start: a pitch that falls, a filter that opens. */export type SoundCurve = number | readonly (readonly [number, number])[];-export const SOUND_SOURCES = ['sine', 'triangle', 'saw', 'square', 'noise', 'modes'] as const;+export const SOUND_SOURCES = ['sine', 'triangle', 'saw', 'square', 'noise', 'modes', 'impulse'] as const;export type SoundSourceKind = (typeof SOUND_SOURCES)[number];-export const SOUND_FILTERS = ['lowpass', 'highpass', 'bandpass', 'notch'] as const;+export const SOUND_FILTERS = ['lowpass', 'highpass', 'bandpass', 'notch', 'peak'] as const;+export const REVERB_KINDS = ['room', 'open'] as const;export const NOISE_COLORS = ['white', 'pink', 'brown'] as const;export interface SoundFilter {@@ -31,6 +32,8 @@ export interface SoundFilter {freq: SoundCurve;/** How narrow: 0.7 is plain, 5 rings, 20 whistles. Default 0.7. */q?: number;+ /** peak: dB it lifts (or with a minus, cuts) round `freq`, -24..24: the note a barrel, a box or a room adds. */+ gain?: number;}export interface SoundLayer {@@ -38,8 +41,15 @@ export interface SoundLayer {source: SoundSourceKind;/** A tone's pitch in Hz; a curve glides between its points as the ear hears pitch. */freq?: SoundCurve;- /** square: the share of each cycle it is high, 0.05..0.95. Default 0.5. */+ /** square: the share of each cycle it is high, 0.05..0.95. Default 0.5. impulse: seconds its one spike lasts, 0.00002..0.02; a shot's is 0.0002. */width?: number;+ /**+ * noise: only what lies between these two Hz, brought back to the level of the whole. A real bang is several bands+ * of noise that die at different rates, the high ones first, and this is one of them.+ */+ band?: readonly [number, number];+ /** noise: how unlike its two sides are, 0..1. It makes the file stereo, and a wide crack fills the head where a narrow one sits in the middle. */+ wide?: number;/** noise: white is hiss, pink is rain, brown is a rumble. Default white. */color?: (typeof NOISE_COLORS)[number];/** modes: each [Hz, loudness, seconds to die away], the tones a struck thing rings with. */@@ -56,6 +66,8 @@ export interface SoundLayer {release?: number;/** Dies away of itself: seconds to fall to about a third. A hit, a pluck, a drop. */decay?: number;+ /** With `decay`: a share `mix` of it dies more slowly, in `decay` seconds of its own. The body of a bang goes at once and its ring lingers. */+ tail?: { decay: number; mix: number };/** Wavers in pitch: `rate` times a second, `depth` semitones each way. */vibrato?: { rate: number; depth: number };/** Wavers in loudness: `rate` times a second, by `depth` 0..1. */@@ -69,7 +81,14 @@ export interface SoundLayer {/** -1 is left, 1 is right. Default 0. */pan?: number;/** The layer struck again: `count` times in all, `every` seconds apart, each `gain` times as loud and `pitch` times as high as the last, off the beat by up to `jitter` seconds. */- repeat?: { count: number; every: number; gain?: number; pitch?: number; jitter?: number };+ repeat?: { count: number; every: number; gain?: number; pitch?: number; jitter?: number; faster?: number };+ /**+ * The layer struck many times at random: `count` strikes within `over` seconds, crowded toward the start by+ * `early` (1 is even, 2.3 is a crash), each at a pitch between the two of `pitch` times its own, as loud as between+ * the two of `gain`, thrown to either side by up to `pan`, the later ones quieter by `fade`. Breaking glass is four+ * hundred short rings scattered like this; so are gravel, rain, sparks and applause.+ */+ scatter?: { count: number; over: number; early?: number; pitch?: readonly [number, number]; gain?: readonly [number, number]; pan?: number; fade?: number };/** Left out of the sound, kept in the source. */mute?: boolean;}@@ -88,8 +107,12 @@ export interface SoundSource {lowpass?: number;/** A repeat of the whole: `time` seconds later, `feedback` 0..0.95 of each into the next, `mix` 0..1 of it in the sound. */echo?: { time: number; feedback?: number; mix?: number };- /** A room round it: `size` 0..1 from a closet to a hall, `mix` 0..1 of it in the sound. */- reverb?: { size?: number; mix?: number };+ /**+ * A place round it: `size` 0..1 from a closet to a hall, `mix` 0..1 of it in the sound. `kind` "room" is walls+ * close by, with first echoes and a wash whose top dies before its bottom; "open" is a street or a yard: a few+ * distinct slaps off far walls and a long thin tail.+ */+ reverb?: { size?: number; mix?: number; kind?: (typeof REVERB_KINDS)[number] };/** Loudness of the whole. With `normalize` it is how loud the loudest moment is, 1 being full. Default 0.9. */gain?: number;/** false leaves the levels as the layers sum to. Default true: the loudest moment is brought to `gain`. */@@ -113,7 +136,7 @@ function curveProblem(v: unknown, lo: number, hi: number, what: string): stringreturn null;}-const LAYER_FIELDS = ['id', 'source', 'freq', 'width', 'color', 'modes', 'seed', 'start', 'length', 'gain', 'attack', 'release', 'decay', 'vibrato', 'tremolo', 'fm', 'filters', 'drive', 'pan', 'repeat', 'mute'];+const LAYER_FIELDS = ['id', 'source', 'freq', 'width', 'band', 'wide', 'color', 'modes', 'seed', 'start', 'length', 'gain', 'attack', 'release', 'decay', 'tail', 'vibrato', 'tremolo', 'fm', 'filters', 'drive', 'pan', 'repeat', 'scatter', 'mute'];function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>, duration: number): void {const fail = (what: string): never => { throw new Error(`${where}: ${what}`); };@@ -125,13 +148,28 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>,ids.add(l.id as string);}if (!SOUND_SOURCES.includes(l.source as SoundSourceKind)) fail(`source ${JSON.stringify(l.source)} must be one of ${SOUND_SOURCES.join(', ')}`);- const tone = l.source !== 'noise' && l.source !== 'modes';+ const tone = l.source !== 'noise' && l.source !== 'modes' && l.source !== 'impulse';if (tone) {if (l.freq === undefined) fail(`a ${String(l.source)} needs freq, its pitch in Hz`);const bad = curveProblem(l.freq, 10, 20000, 'freq');if (bad) fail(bad);} else if (l.freq !== undefined) fail(`freq is a tone's pitch; a ${String(l.source)} has none (give noise its colour with filters, and modes their own Hz)`);- if (l.width !== undefined && !(l.source === 'square' && between(l.width, 0.05, 0.95))) fail('width is a square\'s, 0.05..0.95');+ if (l.width !== undefined) {+ if (l.source === 'square') { if (!between(l.width, 0.05, 0.95)) fail('a square\'s width is the share of a cycle it is high, 0.05..0.95'); }+ else if (l.source === 'impulse') { if (!between(l.width, 0.00002, 0.02)) fail('an impulse\'s width is seconds, 0.00002..0.02'); }+ else fail('width is a square\'s or an impulse\'s');+ }+ if (l.band !== undefined) {+ const b = l.band as unknown[];+ if (l.source !== 'noise') fail('band is a noise\'s: [low Hz, high Hz]');+ if (!Array.isArray(b) || b.length !== 2 || !between(b[0], 20, 20000) || !between(b[1], 20, 20000) || (b[0] as number) >= (b[1] as number)) fail('band must be [low Hz, high Hz], 20..20000, the first below the second');+ }+ if (l.wide !== undefined && !(l.source === 'noise' && between(l.wide, 0, 1))) fail('wide is a noise\'s, 0..1');+ if (l.tail !== undefined) {+ const t = l.tail as Record<string, unknown> | null;+ if (l.decay === undefined) fail('tail is the slow part of a decay: give decay too');+ if (typeof t !== 'object' || t === null || !(isNum(t.decay) && t.decay > 0) || !between(t.mix, 0, 1) || Object.keys(t).length !== 2) fail('tail must be { decay: seconds above 0, mix: 0..1 }');+ }if (l.color !== undefined && !(l.source === 'noise' && NOISE_COLORS.includes(l.color as never))) fail(`color is a noise's: ${NOISE_COLORS.join(', ')}`);if (l.source === 'modes') {const modes = l.modes;@@ -164,7 +202,8 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>,if (!Array.isArray(l.filters) || l.filters.length > 8) fail('filters must be a list of up to 8');(l.filters as Record<string, unknown>[]).forEach((f, i) => {if (typeof f !== 'object' || f === null) fail(`filter ${i} must be { type, freq, q? }`);- for (const key of Object.keys(f)) if (!['type', 'freq', 'q'].includes(key)) fail(`filter ${i} has unknown "${key}"; it takes type, freq, q`);+ for (const key of Object.keys(f)) if (!['type', 'freq', 'q', 'gain'].includes(key)) fail(`filter ${i} has unknown "${key}"; it takes type, freq, q, gain`);+ if (f.type === 'peak' ? !between(f.gain, -24, 24) : f.gain !== undefined) fail(`filter ${i}: gain is a peak's, in dB, -24..24`);if (!SOUND_FILTERS.includes(f.type as never)) fail(`filter ${i}: type must be one of ${SOUND_FILTERS.join(', ')}`);const bad = curveProblem(f.freq, 20, 20000, `filter ${i}: freq`);if (bad) fail(bad);@@ -176,13 +215,31 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>,if (l.repeat !== undefined) {const r = l.repeat as Record<string, unknown> | null;if (typeof r !== 'object' || r === null) fail('repeat must be { count, every, gain?, pitch?, jitter? }');- for (const key of Object.keys(r!)) if (!['count', 'every', 'gain', 'pitch', 'jitter'].includes(key)) fail(`repeat has unknown "${key}"; it takes count, every, gain, pitch, jitter`);+ for (const key of Object.keys(r!)) if (!['count', 'every', 'gain', 'pitch', 'jitter', 'faster'].includes(key)) fail(`repeat has unknown "${key}"; it takes count, every, gain, pitch, jitter, faster`);+ if (r!.faster !== undefined && !between(r!.faster, 0.2, 1)) fail('repeat.faster is how much shorter each gap is than the last, 0.2..1: a thing bouncing to rest');+ if (l.scatter !== undefined) fail('a layer is struck by repeat or by scatter, not both');if (!Number.isInteger(r!.count) || (r!.count as number) < 2 || (r!.count as number) > 200) fail('repeat.count must be a whole number, 2..200');if (!(isNum(r!.every) && (r!.every as number) > 0)) fail('repeat.every must be seconds above 0');if (r!.gain !== undefined && !between(r!.gain, 0, 2)) fail('repeat.gain must be 0..2');if (r!.pitch !== undefined && !between(r!.pitch, 0.25, 4)) fail('repeat.pitch must be 0.25..4');if (r!.jitter !== undefined && !between(r!.jitter, 0, 1)) fail('repeat.jitter must be 0..1 seconds');}+ if (l.scatter !== undefined) {+ const c = l.scatter as Record<string, unknown> | null;+ if (typeof c !== 'object' || c === null) fail('scatter must be { count, over, early?, pitch?, gain?, pan?, fade? }');+ for (const key of Object.keys(c!)) if (!['count', 'over', 'early', 'pitch', 'gain', 'pan', 'fade'].includes(key)) fail(`scatter has unknown "${key}"; it takes count, over, early, pitch, gain, pan, fade`);+ if (!Number.isInteger(c!.count) || (c!.count as number) < 2 || (c!.count as number) > 2000) fail('scatter.count must be a whole number, 2..2000');+ if (!(isNum(c!.over) && (c!.over as number) > 0)) fail('scatter.over must be seconds above 0');+ if (c!.early !== undefined && !between(c!.early, 0.3, 6)) fail('scatter.early must be 0.3..6');+ const range = (key: string, lo: number, hi: number): void => {+ const v = c![key] as unknown[] | undefined;+ if (v === undefined) return;+ if (!Array.isArray(v) || v.length !== 2 || !between(v[0], lo, hi) || !between(v[1], lo, hi) || (v[0] as number) > (v[1] as number)) fail(`scatter.${key} must be [low, high], ${lo}..${hi}`);+ };+ range('pitch', 0.1, 10);+ range('gain', 0, 2);+ for (const key of ['pan', 'fade']) if (c![key] !== undefined && !between(c![key], 0, 1)) fail(`scatter.${key} must be 0..1`);+ }if (l.mute !== undefined && typeof l.mute !== 'boolean') fail('mute must be true or false');}@@ -209,8 +266,9 @@ export function validateSoundSource(raw: unknown): SoundSource {}if (s.reverb !== undefined) {const r = s.reverb as Record<string, unknown> | null;- if (typeof r !== 'object' || r === null) throw new Error('reverb must be { size?, mix? }');- for (const key of Object.keys(r)) if (!['size', 'mix'].includes(key)) throw new Error(`reverb has unknown "${key}"; it takes size, mix`);+ if (typeof r !== 'object' || r === null) throw new Error('reverb must be { size?, mix?, kind? }');+ for (const key of Object.keys(r)) if (!['size', 'mix', 'kind'].includes(key)) throw new Error(`reverb has unknown "${key}"; it takes size, mix, kind`);+ if (r.kind !== undefined && !REVERB_KINDS.includes(r.kind as never)) throw new Error(`reverb.kind must be one of ${REVERB_KINDS.join(', ')}`);for (const key of ['size', 'mix']) if (r[key] !== undefined && !between(r[key], 0, 1)) throw new Error(`reverb.${key} must be 0..1`);}if (!Array.isArray(s.layers) || s.layers.length === 0) throw new Error('layers must be a list of one or more');diff --git a/pipeline/tests/sound.test.ts b/pipeline/tests/sound.test.tsindex 617da763a..886acca30 100644--- a/pipeline/tests/sound.test.ts+++ b/pipeline/tests/sound.test.ts@@ -218,3 +218,99 @@ describe('a sound source', () => {expect(source.layers[0]!.freq).toBe(300);});});++describe('what makes a made sound pass for a real one', () => {+ const raw = (layers: SoundLayer[], rest: Partial<SoundSource> = {}) => make(layers, { normalize: false, ...rest });++ it('cuts noise to a band and brings it back to the level of the whole', () => {+ const whole = level(raw([{ source: 'noise' }]).channels[0]!, 0.1, 0.9);+ for (const band of [[250, 800], [2500, 6000]] as const) {+ const s = raw([{ source: 'noise', band }]);+ expect(level(s.channels[0]!, 0.1, 0.9)).toBeCloseTo(whole, 1);+ }+ expect(soundBands(raw([{ source: 'noise', band: [2500, 6000] }])).high).toBeGreaterThan(0.95);+ expect(soundBands(raw([{ source: 'noise', band: [40, 150] }])).low).toBeGreaterThan(0.8);+ });++ it('lets a share of a decay linger as a tail', () => {+ const plain = raw([{ source: 'noise', decay: 0.01 }]).channels[0]!;+ const tailed = raw([{ source: 'noise', decay: 0.01, tail: { decay: 0.2, mix: 0.3 } }]).channels[0]!;+ expect(level(plain, 0.3, 0.5)).toBeLessThan(1e-6);+ expect(level(tailed, 0.3, 0.5)).toBeGreaterThan(0.02);+ // The start is the same sound: the tail takes its share, it does not add to it.+ expect(level(tailed, 0, 0.005)).toBeCloseTo(level(plain, 0, 0.005), 1);+ });++ it('makes a spike that is up at once and gone in its width', () => {+ const s = raw([{ source: 'impulse', width: 0.0002 }]).channels[0]!;+ expect(s[0]).toBeCloseTo(1, 5);+ expect(Math.abs(s[30]!)).toBeLessThan(0.1);+ expect(level(s, 0.01, 1)).toBe(0);+ });++ it('lifts what lies round a peak', () => {+ const share = (gain: number) => soundBands(raw([{ source: 'noise', filters: [{ type: 'peak', freq: 600, q: 1.5, gain }] }])).mid;+ expect(share(12)).toBeGreaterThan(share(0) * 1.5);+ expect(share(-12)).toBeLessThan(share(0));+ });++ it('scatters strikes in time and pitch, the same way each time, crowded early when told', () => {+ const scattered = (early: number) => raw([{ source: 'sine', freq: 2000, length: 0.01, decay: 0.002, scatter: { count: 200, over: 0.45, early, pitch: [1, 4], pan: 1 } }]);+ const even = scattered(1), crowded = scattered(3);+ expect(even.layers[0]!.strikes).toBe(200);+ expect(even.channels).toHaveLength(2);+ const mono = (s: typeof even): Float32Array => s.channels[0]!.map((v, i) => v + s.channels[1]![i]!);+ expect(level(mono(even), 0.5, 0.9)).toBeGreaterThan(level(mono(even), 0, 0.4) * 0.75);+ expect(level(mono(crowded), 0.5, 0.9)).toBeLessThan(level(mono(crowded), 0, 0.4) * 0.65);+ expect(Buffer.from(scattered(1).channels[0]!.buffer).equals(Buffer.from(even.channels[0]!.buffer))).toBe(true);+ // Pitches between one and four times 2 kHz: all of it above 2 kHz, none of it a single line.+ expect(soundBands(even).high).toBeGreaterThan(0.95);+ });++ it('bounces: each gap shorter than the last', () => {+ const s = raw([{ source: 'impulse', width: 0.0002, length: 0.002, repeat: { count: 4, every: 0.2, faster: 0.5 } }]).channels[0]!;+ const hits: number[] = [];+ for (let n = 0; n < s.length; n++) if (s[n]! > 0.9) hits.push(n / 44100);+ expect(hits).toHaveLength(4);+ expect(hits[1]! - hits[0]!).toBeCloseTo(0.2, 2);+ expect(hits[2]! - hits[1]!).toBeCloseTo(0.1, 2);+ expect(hits[3]! - hits[2]!).toBeCloseTo(0.05, 2);+ });++ it('gives a wide noise two sides that differ, and a narrow one two that do not', () => {+ const differ = (wide: number): number => {+ const s = raw([{ source: 'noise', wide, pan: 0 }]);+ if (s.channels.length === 1) return 0;+ return level(s.channels[0]!.map((v, i) => v - s.channels[1]![i]!));+ };+ expect(differ(0)).toBe(0);+ expect(differ(0.8)).toBeGreaterThan(differ(0.2) * 2);+ });++ it('puts a sound in a place: a room whose top dies before its bottom, open ground with its slaps', () => {+ const click: SoundLayer = { source: 'impulse', width: 0.0002, length: 0.01 };+ const room = raw([click], { duration: 1.5, reverb: { kind: 'room', size: 0.7, mix: 0.5 } });+ expect(room.channels).toHaveLength(2);+ const part = (from: number, to: number) => soundBands({ ...room, channels: [room.channels[0]!.subarray(Math.floor(from * 44100), Math.floor(to * 44100))] });+ expect(level(room.channels[0]!, 0.3, 0.6)).toBeGreaterThan(1e-4);+ expect(part(0.7, 1.2).high).toBeLessThan(part(0.02, 0.2).high * 0.5);+ const open = raw([click], { duration: 1.5, reverb: { kind: 'open', size: 0.5, mix: 0.5 } }).channels[0]!;+ // Nothing comes back from far walls before the first slap, where a room answers at once.+ expect(level(open, 0.012, 0.05)).toBeLessThan(level(room.channels[0]!, 0.012, 0.05) * 0.5);+ expect(level(open, 0.06, 0.2)).toBeGreaterThan(1e-4);+ });++ it('says what is wrong with the new fields', () => {+ const bad = (layer: unknown, rest: object = {}) => () => validateSoundSource({ duration: 1, layers: [layer], ...rest });+ expect(bad({ source: 'sine', freq: 300, band: [100, 200] })).toThrow(/band is a noise's/);+ expect(bad({ source: 'noise', band: [800, 200] })).toThrow(/band must be \[low Hz, high Hz\]/);+ expect(bad({ source: 'noise', tail: { decay: 0.1, mix: 0.2 } })).toThrow(/tail is the slow part of a decay: give decay too/);+ expect(bad({ source: 'impulse', width: 0.5 })).toThrow(/an impulse's width is seconds/);+ expect(bad({ source: 'noise', filters: [{ type: 'peak', freq: 500 }] })).toThrow(/gain is a peak's, in dB/);+ expect(bad({ source: 'noise', filters: [{ type: 'lowpass', freq: 500, gain: 3 }] })).toThrow(/gain is a peak's, in dB/);+ expect(bad({ source: 'noise', scatter: { count: 5, over: 1 }, repeat: { count: 2, every: 0.1 } })).toThrow(/by repeat or by scatter, not both/);+ expect(bad({ source: 'noise', scatter: { count: 5, over: 1, pitch: [3, 1] } })).toThrow(/scatter\.pitch must be \[low, high\]/);+ expect(bad({ source: 'noise', repeat: { count: 3, every: 0.1, faster: 2 } })).toThrow(/repeat\.faster/);+ expect(bad({ source: 'noise' }, { reverb: { kind: 'cave' } })).toThrow(/reverb\.kind must be one of room, open/);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 30e9a3752..3dc953ae2 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4590,6 +4590,10 @@ export const NOTED = {{"note": "An AI can make a sound effect."},"feat(sound): sound_write, sound_edit and sound_read - an AI makes a sound effect from layers and is answered with the picture of it, its level and where its energy lies":{"note": "An AI can make a sound effect."},+ "feat(sound): a made sound is built as a real one is - noise in bands that each die at their own rate, a tail to a decay, an impulse for the front of a bang, strikes scattered in time and pitch, a bounce, a peak filter, and a place made by convolution with first echoes and a top that dies before its bottom":+ {"note": "An AI can make a sound effect."},+ "feat(sound): sound_write teaches the method - bands of noise behind an impulse, strikes scattered by the hundred, two clicks to a step, and what a real bang looks like in the picture":+ {"note": "An AI can make a sound effect."},"feat(sky): a sky of your own shades the ground under its clouds - defineSkyEffect takes groundShadow and a second function, skyShadow(world, sun), what is left of the light at a world position, and the sky pass multiplies every surface it finds by it, as Sky Atmosphere does with its own clouds":{"note": "A sky of your own shades the ground under its clouds."},"fix(terrain): a colour map and an occlusion map lie the way the heightmap does - Terrain.colorMap, Terrain.occlusionMap and Foliage.colorMap were sampled with their rows turned over, so a picture painted to match a heightmap, a splatmap or a density map came out mirrored north to south under them; an image over an area now has its first row along the least z whoever reads it":